blob: 2f08557f825b5f7e09155c221d450232f72c1594 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
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 */
11/* #define CHECK(c, s) if (c) EMSG(s) */
12#define CHECK(c, s)
13
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 Moolenaar071d4272004-06-13 20:20:40 +000066
67/*
68 * pointer to a block, used in a pointer block
69 */
70struct pointer_entry
71{
72 blocknr_T pe_bnum; /* block number */
73 linenr_T pe_line_count; /* number of lines in this branch */
74 linenr_T pe_old_lnum; /* lnum for this block (for recovery) */
75 int pe_page_count; /* number of pages in block pe_bnum */
76};
77
78/*
79 * A pointer block contains a list of branches in the tree.
80 */
81struct pointer_block
82{
83 short_u pb_id; /* ID for pointer block: PTR_ID */
Bram Moolenaar20a825a2010-05-31 21:27:30 +020084 short_u pb_count; /* number of pointers in this block */
Bram Moolenaar071d4272004-06-13 20:20:40 +000085 short_u pb_count_max; /* maximum value for pb_count */
86 PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer)
87 * followed by empty space until end of page */
88};
89
90/*
91 * A data block is a leaf in the tree.
92 *
93 * The text of the lines is at the end of the block. The text of the first line
94 * in the block is put at the end, the text of the second line in front of it,
95 * etc. Thus the order of the lines is the opposite of the line number.
96 */
97struct data_block
98{
99 short_u db_id; /* ID for data block: DATA_ID */
100 unsigned db_free; /* free space available */
101 unsigned db_txt_start; /* byte where text starts */
102 unsigned db_txt_end; /* byte just after data block */
103 linenr_T db_line_count; /* number of lines in this block */
104 unsigned db_index[1]; /* index for start of line (actually bigger)
105 * followed by empty space upto db_txt_start
106 * followed by the text in the lines until
107 * end of page */
108};
109
110/*
111 * The low bits of db_index hold the actual index. The topmost bit is
112 * used for the global command to be able to mark a line.
113 * This method is not clean, but otherwise there would be at least one extra
114 * byte used for each line.
115 * The mark has to be in this place to keep it with the correct line when other
116 * lines are inserted or deleted.
117 */
118#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
119#define DB_INDEX_MASK (~DB_MARKED)
120
121#define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */
122#define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */
123
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000124#define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200125#define B0_FNAME_SIZE_NOCRYPT 898 /* 2 bytes used for other things */
126#define B0_FNAME_SIZE_CRYPT 890 /* 10 bytes used for other things */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000127#define B0_UNAME_SIZE 40
128#define B0_HNAME_SIZE 40
Bram Moolenaar071d4272004-06-13 20:20:40 +0000129/*
130 * Restrict the numbers to 32 bits, otherwise most compilers will complain.
131 * This won't detect a 64 bit machine that only swaps a byte in the top 32
132 * bits, but that is crazy anyway.
133 */
134#define B0_MAGIC_LONG 0x30313233L
135#define B0_MAGIC_INT 0x20212223L
136#define B0_MAGIC_SHORT 0x10111213L
137#define B0_MAGIC_CHAR 0x55
138
139/*
140 * Block zero holds all info about the swap file.
141 *
142 * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
143 * swap files unusable!
144 *
145 * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
146 *
Bram Moolenaarbae0c162007-05-10 19:30:25 +0000147 * This block is built up of single bytes, to make it portable across
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148 * different machines. b0_magic_* is used to check the byte order and size of
149 * variables, because the rest of the swap file is not portable.
150 */
151struct block0
152{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200153 char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1,
154 * BLOCK0_ID1_C0, BLOCK0_ID1_C1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155 char_u b0_version[10]; /* Vim version string */
156 char_u b0_page_size[4];/* number of bytes per page */
157 char_u b0_mtime[4]; /* last modification time of file */
158 char_u b0_ino[4]; /* inode of b0_fname */
159 char_u b0_pid[4]; /* process id of creator (or 0) */
160 char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */
161 char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000162 char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163 long b0_magic_long; /* check for byte order of long */
164 int b0_magic_int; /* check for byte order of int */
165 short b0_magic_short; /* check for byte order of short */
166 char_u b0_magic_char; /* check for last char */
167};
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000168
169/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000170 * Note: b0_dirty and b0_flags are put at the end of the file name. For very
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000171 * long file names in older versions of Vim they are invalid.
172 * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
173 * when there is room, for very long file names it's omitted.
174 */
175#define B0_DIRTY 0x55
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200176#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000177
178/*
179 * The b0_flags field is new in Vim 7.0.
180 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200181#define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2]
182
183/*
184 * Crypt seed goes here, 8 bytes. New in Vim 7.3.
185 * Without encryption these bytes may be used for 'fenc'.
186 */
187#define b0_seed b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000188
189/* The lowest two bits contain the fileformat. Zero means it's not set
190 * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
191 * EOL_MAC + 1. */
192#define B0_FF_MASK 3
193
194/* Swap file is in directory of edited file. Used to find the file from
195 * different mount points. */
196#define B0_SAME_DIR 4
197
198/* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
199 * When empty there is only the NUL. */
200#define B0_HAS_FENC 8
Bram Moolenaar071d4272004-06-13 20:20:40 +0000201
202#define STACK_INCR 5 /* nr of entries added to ml_stack at a time */
203
204/*
205 * The line number where the first mark may be is remembered.
206 * If it is 0 there are no marks at all.
207 * (always used for the current buffer only, no buffer change possible while
208 * executing a global command).
209 */
210static linenr_T lowest_marked = 0;
211
212/*
213 * arguments for ml_find_line()
214 */
215#define ML_DELETE 0x11 /* delete line */
216#define ML_INSERT 0x12 /* insert line */
217#define ML_FIND 0x13 /* just find the line */
218#define ML_FLUSH 0x02 /* flush locked block */
219#define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */
220
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200221/* argument for ml_upd_block0() */
222typedef enum {
223 UB_FNAME = 0 /* update timestamp and filename */
224 , UB_SAME_DIR /* update the B0_SAME_DIR flag */
225 , UB_CRYPT /* update crypt key */
226} upd_block0_T;
227
228#ifdef FEAT_CRYPT
229static void ml_set_b0_crypt __ARGS((buf_T *buf, ZERO_BL *b0p));
230#endif
231static int ml_check_b0_id __ARGS((ZERO_BL *b0p));
232static void ml_upd_block0 __ARGS((buf_T *buf, upd_block0_T what));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000233static void set_b0_fname __ARGS((ZERO_BL *, buf_T *buf));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000234static void set_b0_dir_flag __ARGS((ZERO_BL *b0p, buf_T *buf));
235#ifdef FEAT_MBYTE
236static void add_b0_fenc __ARGS((ZERO_BL *b0p, buf_T *buf));
237#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238static time_t swapfile_info __ARGS((char_u *));
239static int recov_file_names __ARGS((char_u **, char_u *, int prepend_dot));
240static int ml_append_int __ARGS((buf_T *, linenr_T, char_u *, colnr_T, int, int));
241static int ml_delete_int __ARGS((buf_T *, linenr_T, int));
242static char_u *findswapname __ARGS((buf_T *, char_u **, char_u *));
243static void ml_flush_line __ARGS((buf_T *));
244static bhdr_T *ml_new_data __ARGS((memfile_T *, int, int));
245static bhdr_T *ml_new_ptr __ARGS((memfile_T *));
246static bhdr_T *ml_find_line __ARGS((buf_T *, linenr_T, int));
247static int ml_add_stack __ARGS((buf_T *));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000248static void ml_lineadd __ARGS((buf_T *, int));
249static int b0_magic_wrong __ARGS((ZERO_BL *));
250#ifdef CHECK_INODE
251static int fnamecmp_ino __ARGS((char_u *, char_u *, long));
252#endif
253static void long_to_char __ARGS((long, char_u *));
254static long char_to_long __ARGS((char_u *));
255#if defined(UNIX) || defined(WIN3264)
256static char_u *make_percent_swname __ARGS((char_u *dir, char_u *name));
257#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200258#ifdef FEAT_CRYPT
259static void ml_crypt_prepare __ARGS((memfile_T *mfp, off_t offset, int reading));
260#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000261#ifdef FEAT_BYTEOFF
262static void ml_updatechunk __ARGS((buf_T *buf, long line, long len, int updtype));
263#endif
264
265/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000266 * Open a new memline for "buf".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000267 *
Bram Moolenaar4770d092006-01-12 23:22:24 +0000268 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000269 */
270 int
Bram Moolenaar4770d092006-01-12 23:22:24 +0000271ml_open(buf)
272 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000273{
274 memfile_T *mfp;
275 bhdr_T *hp = NULL;
276 ZERO_BL *b0p;
277 PTR_BL *pp;
278 DATA_BL *dp;
279
Bram Moolenaar4770d092006-01-12 23:22:24 +0000280 /*
281 * init fields in memline struct
282 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200283 buf->b_ml.ml_stack_size = 0; /* no stack yet */
Bram Moolenaar4770d092006-01-12 23:22:24 +0000284 buf->b_ml.ml_stack = NULL; /* no stack yet */
285 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
286 buf->b_ml.ml_locked = NULL; /* no cached block */
287 buf->b_ml.ml_line_lnum = 0; /* no cached line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000288#ifdef FEAT_BYTEOFF
Bram Moolenaar4770d092006-01-12 23:22:24 +0000289 buf->b_ml.ml_chunksize = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000290#endif
291
Bram Moolenaar4770d092006-01-12 23:22:24 +0000292 /*
293 * When 'updatecount' is non-zero swap file may be opened later.
294 */
295 if (p_uc && buf->b_p_swf)
296 buf->b_may_swap = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297 else
Bram Moolenaar4770d092006-01-12 23:22:24 +0000298 buf->b_may_swap = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000299
Bram Moolenaar4770d092006-01-12 23:22:24 +0000300 /*
301 * Open the memfile. No swap file is created yet.
302 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 mfp = mf_open(NULL, 0);
304 if (mfp == NULL)
305 goto error;
306
Bram Moolenaar4770d092006-01-12 23:22:24 +0000307 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200308#ifdef FEAT_CRYPT
309 mfp->mf_buffer = buf;
310#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000311 buf->b_ml.ml_flags = ML_EMPTY;
312 buf->b_ml.ml_line_count = 1;
Bram Moolenaar592e0a22004-07-03 16:05:59 +0000313#ifdef FEAT_LINEBREAK
314 curwin->w_nrwidth_line_count = 0;
315#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316
317#if defined(MSDOS) && !defined(DJGPP)
318 /* for 16 bit MS-DOS create a swapfile now, because we run out of
319 * memory very quickly */
320 if (p_uc != 0)
Bram Moolenaar4770d092006-01-12 23:22:24 +0000321 ml_open_file(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322#endif
323
324/*
325 * fill block0 struct and write page 0
326 */
327 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
328 goto error;
329 if (hp->bh_bnum != 0)
330 {
331 EMSG(_("E298: Didn't get block nr 0?"));
332 goto error;
333 }
334 b0p = (ZERO_BL *)(hp->bh_data);
335
336 b0p->b0_id[0] = BLOCK0_ID0;
337 b0p->b0_id[1] = BLOCK0_ID1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 b0p->b0_magic_long = (long)B0_MAGIC_LONG;
339 b0p->b0_magic_int = (int)B0_MAGIC_INT;
340 b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
341 b0p->b0_magic_char = B0_MAGIC_CHAR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000342 STRNCPY(b0p->b0_version, "VIM ", 4);
343 STRNCPY(b0p->b0_version + 4, Version, 6);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000345
Bram Moolenaar76b92b22006-03-24 22:46:53 +0000346#ifdef FEAT_SPELL
347 if (!buf->b_spell)
348#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000349 {
350 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
351 b0p->b0_flags = get_fileformat(buf) + 1;
352 set_b0_fname(b0p, buf);
353 (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
354 b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
355 mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
356 b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
357 long_to_char(mch_get_pid(), b0p->b0_pid);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200358#ifdef FEAT_CRYPT
359 if (*buf->b_p_key != NUL)
360 ml_set_b0_crypt(buf, b0p);
361#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000363
364 /*
365 * Always sync block number 0 to disk, so we can check the file name in
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200366 * the swap file in findswapname(). Don't do this for a help files or
367 * a spell buffer though.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368 * Only works when there's a swapfile, otherwise it's done when the file
369 * is created.
370 */
371 mf_put(mfp, hp, TRUE, FALSE);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000372 if (!buf->b_help && !B_SPELL(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373 (void)mf_sync(mfp, 0);
374
Bram Moolenaar4770d092006-01-12 23:22:24 +0000375 /*
376 * Fill in root pointer block and write page 1.
377 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000378 if ((hp = ml_new_ptr(mfp)) == NULL)
379 goto error;
380 if (hp->bh_bnum != 1)
381 {
382 EMSG(_("E298: Didn't get block nr 1?"));
383 goto error;
384 }
385 pp = (PTR_BL *)(hp->bh_data);
386 pp->pb_count = 1;
387 pp->pb_pointer[0].pe_bnum = 2;
388 pp->pb_pointer[0].pe_page_count = 1;
389 pp->pb_pointer[0].pe_old_lnum = 1;
390 pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */
391 mf_put(mfp, hp, TRUE, FALSE);
392
Bram Moolenaar4770d092006-01-12 23:22:24 +0000393 /*
394 * Allocate first data block and create an empty line 1.
395 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000396 if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
397 goto error;
398 if (hp->bh_bnum != 2)
399 {
400 EMSG(_("E298: Didn't get block nr 2?"));
401 goto error;
402 }
403
404 dp = (DATA_BL *)(hp->bh_data);
405 dp->db_index[0] = --dp->db_txt_start; /* at end of block */
406 dp->db_free -= 1 + INDEX_SIZE;
407 dp->db_line_count = 1;
Bram Moolenaarf05da212009-11-17 16:13:15 +0000408 *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409
410 return OK;
411
412error:
413 if (mfp != NULL)
414 {
415 if (hp)
416 mf_put(mfp, hp, FALSE, FALSE);
417 mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */
418 }
Bram Moolenaar4770d092006-01-12 23:22:24 +0000419 buf->b_ml.ml_mfp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420 return FAIL;
421}
422
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200423#if defined(FEAT_CRYPT) || defined(PROTO)
424/*
425 * Prepare encryption for "buf" with block 0 "b0p".
426 */
427 static void
428ml_set_b0_crypt(buf, b0p)
429 buf_T *buf;
430 ZERO_BL *b0p;
431{
432 if (*buf->b_p_key == NUL)
433 b0p->b0_id[1] = BLOCK0_ID1;
434 else
435 {
Bram Moolenaar49771f42010-07-20 17:32:38 +0200436 if (get_crypt_method(buf) == 0)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200437 b0p->b0_id[1] = BLOCK0_ID1_C0;
438 else
439 {
440 b0p->b0_id[1] = BLOCK0_ID1_C1;
441 /* Generate a seed and store it in block 0 and in the memfile. */
442 sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0);
443 mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
444 }
445 }
446}
447
448/*
449 * Called after the crypt key or 'cryptmethod' was changed for "buf".
450 * Will apply this to the swapfile.
451 * "old_key" is the previous key. It is equal to buf->b_p_key when
452 * 'cryptmethod' is changed.
Bram Moolenaar49771f42010-07-20 17:32:38 +0200453 * "old_cm" is the previous 'cryptmethod'. It is equal to the current
454 * 'cryptmethod' when 'key' is changed.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200455 */
456 void
457ml_set_crypt_key(buf, old_key, old_cm)
458 buf_T *buf;
459 char_u *old_key;
460 int old_cm;
461{
462 memfile_T *mfp = buf->b_ml.ml_mfp;
463 bhdr_T *hp;
464 int page_count;
465 int idx;
466 long error;
467 infoptr_T *ip;
468 PTR_BL *pp;
469 DATA_BL *dp;
470 blocknr_T bnum;
471 int top;
472
Bram Moolenaar3832c462010-08-04 15:32:46 +0200473 if (mfp == NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200474 return; /* no memfile yet, nothing to do */
475
476 /* Set the key, method and seed to be used for reading, these must be the
477 * old values. */
478 mfp->mf_old_key = old_key;
479 mfp->mf_old_cm = old_cm;
480 if (old_cm > 0)
481 mch_memmove(mfp->mf_old_seed, mfp->mf_seed, MF_SEED_LEN);
482
483 /* Update block 0 with the crypt flag and may set a new seed. */
484 ml_upd_block0(buf, UB_CRYPT);
485
486 if (mfp->mf_infile_count > 2)
487 {
488 /*
489 * Need to read back all data blocks from disk, decrypt them with the
490 * old key/method and mark them to be written. The algorithm is
491 * similar to what happens in ml_recover(), but we skip negative block
492 * numbers.
493 */
494 ml_flush_line(buf); /* flush buffered line */
495 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
496
497 hp = NULL;
498 bnum = 1; /* start with block 1 */
499 page_count = 1; /* which is 1 page */
500 idx = 0; /* start with first index in block 1 */
501 error = 0;
502 buf->b_ml.ml_stack_top = 0;
Bram Moolenaare242b832010-06-24 05:39:03 +0200503 vim_free(buf->b_ml.ml_stack);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200504 buf->b_ml.ml_stack = NULL;
505 buf->b_ml.ml_stack_size = 0; /* no stack yet */
506
507 for ( ; !got_int; line_breakcheck())
508 {
509 if (hp != NULL)
510 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
511
512 /* get the block (pointer or data) */
513 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
514 {
515 if (bnum == 1)
516 break;
517 ++error;
518 }
519 else
520 {
521 pp = (PTR_BL *)(hp->bh_data);
522 if (pp->pb_id == PTR_ID) /* it is a pointer block */
523 {
524 if (pp->pb_count == 0)
525 {
526 /* empty block? */
527 ++error;
528 }
529 else if (idx < (int)pp->pb_count) /* go a block deeper */
530 {
531 if (pp->pb_pointer[idx].pe_bnum < 0)
532 {
533 /* Skip data block with negative block number. */
534 ++idx; /* get same block again for next index */
535 continue;
536 }
537
538 /* going one block deeper in the tree, new entry in
539 * stack */
540 if ((top = ml_add_stack(buf)) < 0)
541 {
542 ++error;
543 break; /* out of memory */
544 }
545 ip = &(buf->b_ml.ml_stack[top]);
546 ip->ip_bnum = bnum;
547 ip->ip_index = idx;
548
549 bnum = pp->pb_pointer[idx].pe_bnum;
550 page_count = pp->pb_pointer[idx].pe_page_count;
551 continue;
552 }
553 }
554 else /* not a pointer block */
555 {
556 dp = (DATA_BL *)(hp->bh_data);
557 if (dp->db_id != DATA_ID) /* block id wrong */
558 ++error;
559 else
560 {
561 /* It is a data block, need to write it back to disk. */
562 mf_put(mfp, hp, TRUE, FALSE);
563 hp = NULL;
564 }
565 }
566 }
567
568 if (buf->b_ml.ml_stack_top == 0) /* finished */
569 break;
570
571 /* go one block up in the tree */
572 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
573 bnum = ip->ip_bnum;
574 idx = ip->ip_index + 1; /* go to next index */
575 page_count = 1;
576 }
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +0100577
578 if (error > 0)
579 EMSG(_("E843: Error while updating swap file crypt"));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200580 }
581
582 mfp->mf_old_key = NULL;
583}
584#endif
585
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586/*
587 * ml_setname() is called when the file name of "buf" has been changed.
588 * It may rename the swap file.
589 */
590 void
591ml_setname(buf)
592 buf_T *buf;
593{
594 int success = FALSE;
595 memfile_T *mfp;
596 char_u *fname;
597 char_u *dirp;
598#if defined(MSDOS) || defined(MSWIN)
599 char_u *p;
600#endif
601
602 mfp = buf->b_ml.ml_mfp;
603 if (mfp->mf_fd < 0) /* there is no swap file yet */
604 {
605 /*
606 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
607 * For help files we will make a swap file now.
608 */
609 if (p_uc != 0)
610 ml_open_file(buf); /* create a swap file */
611 return;
612 }
613
614 /*
615 * Try all directories in the 'directory' option.
616 */
617 dirp = p_dir;
618 for (;;)
619 {
620 if (*dirp == NUL) /* tried all directories, fail */
621 break;
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000622 fname = findswapname(buf, &dirp, mfp->mf_fname);
623 /* alloc's fname */
Bram Moolenaarf541c362011-10-26 11:44:18 +0200624 if (dirp == NULL) /* out of memory */
625 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 if (fname == NULL) /* no file name found for this dir */
627 continue;
628
629#if defined(MSDOS) || defined(MSWIN)
630 /*
631 * Set full pathname for swap file now, because a ":!cd dir" may
632 * change directory without us knowing it.
633 */
634 p = FullName_save(fname, FALSE);
635 vim_free(fname);
636 fname = p;
637 if (fname == NULL)
638 continue;
639#endif
640 /* if the file name is the same we don't have to do anything */
641 if (fnamecmp(fname, mfp->mf_fname) == 0)
642 {
643 vim_free(fname);
644 success = TRUE;
645 break;
646 }
647 /* need to close the swap file before renaming */
648 if (mfp->mf_fd >= 0)
649 {
650 close(mfp->mf_fd);
651 mfp->mf_fd = -1;
652 }
653
654 /* try to rename the swap file */
655 if (vim_rename(mfp->mf_fname, fname) == 0)
656 {
657 success = TRUE;
658 vim_free(mfp->mf_fname);
659 mfp->mf_fname = fname;
660 vim_free(mfp->mf_ffname);
661#if defined(MSDOS) || defined(MSWIN)
662 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
663#else
664 mf_set_ffname(mfp);
665#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200666 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667 break;
668 }
669 vim_free(fname); /* this fname didn't work, try another */
670 }
671
672 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
673 {
674 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
675 if (mfp->mf_fd < 0)
676 {
677 /* could not (re)open the swap file, what can we do???? */
678 EMSG(_("E301: Oops, lost the swap file!!!"));
679 return;
680 }
Bram Moolenaarf05da212009-11-17 16:13:15 +0000681#ifdef HAVE_FD_CLOEXEC
682 {
683 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
684 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
685 fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
686 }
687#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 }
689 if (!success)
690 EMSG(_("E302: Could not rename swap file"));
691}
692
693/*
694 * Open a file for the memfile for all buffers that are not readonly or have
695 * been modified.
696 * Used when 'updatecount' changes from zero to non-zero.
697 */
698 void
699ml_open_files()
700{
701 buf_T *buf;
702
703 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
704 if (!buf->b_p_ro || buf->b_changed)
705 ml_open_file(buf);
706}
707
708/*
709 * Open a swap file for an existing memfile, if there is no swap file yet.
710 * If we are unable to find a file name, mf_fname will be NULL
711 * and the memfile will be in memory only (no recovery possible).
712 */
713 void
714ml_open_file(buf)
715 buf_T *buf;
716{
717 memfile_T *mfp;
718 char_u *fname;
719 char_u *dirp;
720
721 mfp = buf->b_ml.ml_mfp;
722 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf)
723 return; /* nothing to do */
724
Bram Moolenaara1956f62006-03-12 22:18:00 +0000725#ifdef FEAT_SPELL
Bram Moolenaar4770d092006-01-12 23:22:24 +0000726 /* For a spell buffer use a temp file name. */
727 if (buf->b_spell)
728 {
729 fname = vim_tempname('s');
730 if (fname != NULL)
731 (void)mf_open_file(mfp, fname); /* consumes fname! */
732 buf->b_may_swap = FALSE;
733 return;
734 }
735#endif
736
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 /*
738 * Try all directories in 'directory' option.
739 */
740 dirp = p_dir;
741 for (;;)
742 {
743 if (*dirp == NUL)
744 break;
Bram Moolenaare242b832010-06-24 05:39:03 +0200745 /* There is a small chance that between choosing the swap file name
746 * and creating it, another Vim creates the file. In that case the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 * creation will fail and we will use another directory. */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000748 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
Bram Moolenaarf541c362011-10-26 11:44:18 +0200749 if (dirp == NULL)
750 break; /* out of memory */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751 if (fname == NULL)
752 continue;
753 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
754 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200755#if defined(MSDOS) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756 /*
757 * set full pathname for swap file now, because a ":!cd dir" may
758 * change directory without us knowing it.
759 */
760 mf_fullname(mfp);
761#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200762 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000763
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 /* Flush block zero, so others can read it */
765 if (mf_sync(mfp, MFS_ZERO) == OK)
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000766 {
767 /* Mark all blocks that should be in the swapfile as dirty.
768 * Needed for when the 'swapfile' option was reset, so that
769 * the swap file was deleted, and then on again. */
770 mf_set_dirty(mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 break;
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000772 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 /* Writing block 0 failed: close the file and try another dir */
774 mf_close_file(buf, FALSE);
775 }
776 }
777
778 if (mfp->mf_fname == NULL) /* Failed! */
779 {
780 need_wait_return = TRUE; /* call wait_return later */
781 ++no_wait_return;
782 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
Bram Moolenaare1704ba2012-10-03 18:25:00 +0200783 buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784 --no_wait_return;
785 }
786
787 /* don't try to open a swap file again */
788 buf->b_may_swap = FALSE;
789}
790
791/*
792 * If still need to create a swap file, and starting to edit a not-readonly
793 * file, or reading into an existing buffer, create a swap file now.
794 */
795 void
796check_need_swap(newfile)
797 int newfile; /* reading file into new buffer */
798{
799 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
800 ml_open_file(curbuf);
801}
802
803/*
804 * Close memline for buffer 'buf'.
805 * If 'del_file' is TRUE, delete the swap file
806 */
807 void
808ml_close(buf, del_file)
809 buf_T *buf;
810 int del_file;
811{
812 if (buf->b_ml.ml_mfp == NULL) /* not open */
813 return;
814 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
815 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
816 vim_free(buf->b_ml.ml_line_ptr);
817 vim_free(buf->b_ml.ml_stack);
818#ifdef FEAT_BYTEOFF
819 vim_free(buf->b_ml.ml_chunksize);
820 buf->b_ml.ml_chunksize = NULL;
821#endif
822 buf->b_ml.ml_mfp = NULL;
823
824 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
825 * this buffer is loaded. */
826 buf->b_flags &= ~BF_RECOVERED;
827}
828
829/*
830 * Close all existing memlines and memfiles.
831 * Only used when exiting.
832 * When 'del_file' is TRUE, delete the memfiles.
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000833 * But don't delete files that were ":preserve"d when we are POSIX compatible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834 */
835 void
836ml_close_all(del_file)
837 int del_file;
838{
839 buf_T *buf;
840
841 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000842 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
843 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000844#ifdef TEMPDIRNAMES
845 vim_deltempdir(); /* delete created temp directory */
846#endif
847}
848
849/*
850 * Close all memfiles for not modified buffers.
851 * Only use just before exiting!
852 */
853 void
854ml_close_notmod()
855{
856 buf_T *buf;
857
858 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
859 if (!bufIsChanged(buf))
860 ml_close(buf, TRUE); /* close all not-modified buffers */
861}
862
863/*
864 * Update the timestamp in the .swp file.
865 * Used when the file has been written.
866 */
867 void
868ml_timestamp(buf)
869 buf_T *buf;
870{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200871 ml_upd_block0(buf, UB_FNAME);
872}
873
874/*
875 * Return FAIL when the ID of "b0p" is wrong.
876 */
877 static int
878ml_check_b0_id(b0p)
879 ZERO_BL *b0p;
880{
881 if (b0p->b0_id[0] != BLOCK0_ID0
882 || (b0p->b0_id[1] != BLOCK0_ID1
883 && b0p->b0_id[1] != BLOCK0_ID1_C0
884 && b0p->b0_id[1] != BLOCK0_ID1_C1)
885 )
886 return FAIL;
887 return OK;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000888}
889
890/*
891 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
892 */
893 static void
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200894ml_upd_block0(buf, what)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000895 buf_T *buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200896 upd_block0_T what;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000897{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 memfile_T *mfp;
899 bhdr_T *hp;
900 ZERO_BL *b0p;
901
902 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
904 return;
905 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200906 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000907 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000909 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200910 if (what == UB_FNAME)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000911 set_b0_fname(b0p, buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200912#ifdef FEAT_CRYPT
913 else if (what == UB_CRYPT)
914 ml_set_b0_crypt(buf, b0p);
915#endif
916 else /* what == UB_SAME_DIR */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000917 set_b0_dir_flag(b0p, buf);
918 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919 mf_put(mfp, hp, TRUE, FALSE);
920}
921
922/*
923 * Write file name and timestamp into block 0 of a swap file.
924 * Also set buf->b_mtime.
925 * Don't use NameBuff[]!!!
926 */
927 static void
928set_b0_fname(b0p, buf)
929 ZERO_BL *b0p;
930 buf_T *buf;
931{
932 struct stat st;
933
934 if (buf->b_ffname == NULL)
935 b0p->b0_fname[0] = NUL;
936 else
937 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200938#if defined(MSDOS) || defined(MSWIN) || defined(AMIGA)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000939 /* Systems that cannot translate "~user" back into a path: copy the
940 * file name unmodified. Do use slashes instead of backslashes for
941 * portability. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200942 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000943# ifdef BACKSLASH_IN_FILENAME
944 forward_slash(b0p->b0_fname);
945# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946#else
947 size_t flen, ulen;
948 char_u uname[B0_UNAME_SIZE];
949
950 /*
951 * For a file under the home directory of the current user, we try to
952 * replace the home directory path with "~user". This helps when
953 * editing the same file on different machines over a network.
954 * First replace home dir path with "~/" with home_replace().
955 * Then insert the user name to get "~user/".
956 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200957 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
958 B0_FNAME_SIZE_CRYPT, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 if (b0p->b0_fname[0] == '~')
960 {
961 flen = STRLEN(b0p->b0_fname);
962 /* If there is no user name or it is too long, don't use "~/" */
963 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200964 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
965 vim_strncpy(b0p->b0_fname, buf->b_ffname,
966 B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 else
968 {
969 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
970 mch_memmove(b0p->b0_fname + 1, uname, ulen);
971 }
972 }
973#endif
974 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
975 {
976 long_to_char((long)st.st_mtime, b0p->b0_mtime);
977#ifdef CHECK_INODE
978 long_to_char((long)st.st_ino, b0p->b0_ino);
979#endif
980 buf_store_time(buf, &st, buf->b_ffname);
981 buf->b_mtime_read = buf->b_mtime;
982 }
983 else
984 {
985 long_to_char(0L, b0p->b0_mtime);
986#ifdef CHECK_INODE
987 long_to_char(0L, b0p->b0_ino);
988#endif
989 buf->b_mtime = 0;
990 buf->b_mtime_read = 0;
991 buf->b_orig_size = 0;
992 buf->b_orig_mode = 0;
993 }
994 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000995
996#ifdef FEAT_MBYTE
997 /* Also add the 'fileencoding' if there is room. */
998 add_b0_fenc(b0p, curbuf);
999#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000}
1001
1002/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001003 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1004 * swapfile for "buf" are in the same directory.
1005 * This is fail safe: if we are not sure the directories are equal the flag is
1006 * not set.
1007 */
1008 static void
1009set_b0_dir_flag(b0p, buf)
1010 ZERO_BL *b0p;
1011 buf_T *buf;
1012{
1013 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1014 b0p->b0_flags |= B0_SAME_DIR;
1015 else
1016 b0p->b0_flags &= ~B0_SAME_DIR;
1017}
1018
1019#ifdef FEAT_MBYTE
1020/*
1021 * When there is room, add the 'fileencoding' to block zero.
1022 */
1023 static void
1024add_b0_fenc(b0p, buf)
1025 ZERO_BL *b0p;
1026 buf_T *buf;
1027{
1028 int n;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001029 int size = B0_FNAME_SIZE_NOCRYPT;
1030
1031# ifdef FEAT_CRYPT
1032 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1033 * With encryption it's OK to move elsewhere, the swap file is not
1034 * compatible anyway. */
1035 if (*buf->b_p_key != NUL)
1036 size = B0_FNAME_SIZE_CRYPT;
1037# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001038
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001039 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001040 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001041 b0p->b0_flags &= ~B0_HAS_FENC;
1042 else
1043 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001044 mch_memmove((char *)b0p->b0_fname + size - n,
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001045 (char *)buf->b_p_fenc, (size_t)n);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001046 *(b0p->b0_fname + size - n - 1) = NUL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001047 b0p->b0_flags |= B0_HAS_FENC;
1048 }
1049}
1050#endif
1051
1052
1053/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001054 * Try to recover curbuf from the .swp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 */
1056 void
1057ml_recover()
1058{
1059 buf_T *buf = NULL;
1060 memfile_T *mfp = NULL;
1061 char_u *fname;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001062 char_u *fname_used = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 bhdr_T *hp = NULL;
1064 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001065 int b0_ff;
1066 char_u *b0_fenc = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001067#ifdef FEAT_CRYPT
1068 int b0_cm = -1;
1069#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070 PTR_BL *pp;
1071 DATA_BL *dp;
1072 infoptr_T *ip;
1073 blocknr_T bnum;
1074 int page_count;
1075 struct stat org_stat, swp_stat;
1076 int len;
1077 int directly;
1078 linenr_T lnum;
1079 char_u *p;
1080 int i;
1081 long error;
1082 int cannot_open;
1083 linenr_T line_count;
1084 int has_error;
1085 int idx;
1086 int top;
1087 int txt_start;
1088 off_t size;
1089 int called_from_main;
1090 int serious_error = TRUE;
1091 long mtime;
1092 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001093 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094
1095 recoverymode = TRUE;
1096 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1097 attr = hl_attr(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001098
1099 /*
1100 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
1101 * Otherwise a search is done to find the swap file(s).
1102 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 fname = curbuf->b_fname;
1104 if (fname == NULL) /* When there is no file name */
1105 fname = (char_u *)"";
1106 len = (int)STRLEN(fname);
1107 if (len >= 4 &&
Bram Moolenaare60acc12011-05-10 16:41:25 +02001108#if defined(VMS)
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001109 STRNICMP(fname + len - 4, "_s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110#else
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001111 STRNICMP(fname + len - 4, ".s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112#endif
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001113 == 0
1114 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
1115 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 {
1117 directly = TRUE;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001118 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 }
1120 else
1121 {
1122 directly = FALSE;
1123
1124 /* count the number of matching swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001125 len = recover_names(fname, FALSE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126 if (len == 0) /* no swap files found */
1127 {
1128 EMSG2(_("E305: No swap file found for %s"), fname);
1129 goto theend;
1130 }
1131 if (len == 1) /* one swap file found, use it */
1132 i = 1;
1133 else /* several swap files found, choose */
1134 {
1135 /* list the names of the swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001136 (void)recover_names(fname, TRUE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137 msg_putchar('\n');
1138 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001139 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 if (i < 1 || i > len)
1141 goto theend;
1142 }
1143 /* get the swap file name that will be used */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001144 (void)recover_names(fname, FALSE, i, &fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001146 if (fname_used == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147 goto theend; /* out of memory */
1148
1149 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +00001150 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 getout(1);
1152
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001153 /*
1154 * Allocate a buffer structure for the swap file that is used for recovery.
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001155 * Only the memline and crypt information in it are really used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001156 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1158 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001159 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001161 /*
1162 * init fields in memline struct
1163 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1165 buf->b_ml.ml_stack = NULL; /* no stack yet */
1166 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1167 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1168 buf->b_ml.ml_locked = NULL; /* no locked block */
1169 buf->b_ml.ml_flags = 0;
Bram Moolenaar0fe849a2010-07-25 15:11:11 +02001170#ifdef FEAT_CRYPT
1171 buf->b_p_key = empty_option;
1172 buf->b_p_cm = empty_option;
1173#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001174
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001175 /*
1176 * open the memfile from the old swap file
1177 */
1178 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1179 mf_open() will consume "fname_used"! */
1180 mfp = mf_open(fname_used, O_RDONLY);
1181 fname_used = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 if (mfp == NULL || mfp->mf_fd < 0)
1183 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001184 if (fname_used != NULL)
1185 EMSG2(_("E306: Cannot open %s"), fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186 goto theend;
1187 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001189#ifdef FEAT_CRYPT
1190 mfp->mf_buffer = buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001191#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192
1193 /*
1194 * The page size set in mf_open() might be different from the page size
1195 * used in the swap file, we must get it from block 0. But to read block
1196 * 0 we need a page size. Use the minimal size for block 0 here, it will
1197 * be set to the real value below.
1198 */
1199 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1200
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001201 /*
1202 * try to read block 0
1203 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1205 {
1206 msg_start();
1207 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1208 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001209 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 attr | MSG_HIST);
1211 msg_end();
1212 goto theend;
1213 }
1214 b0p = (ZERO_BL *)(hp->bh_data);
1215 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1216 {
1217 msg_start();
1218 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1219 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1220 MSG_HIST);
1221 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1222 msg_end();
1223 goto theend;
1224 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001225 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 {
1227 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1228 goto theend;
1229 }
1230 if (b0_magic_wrong(b0p))
1231 {
1232 msg_start();
1233 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1234#if defined(MSDOS) || defined(MSWIN)
1235 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1236 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1237 attr | MSG_HIST);
1238 else
1239#endif
1240 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1241 attr | MSG_HIST);
1242 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001243 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244 b0p->b0_fname[0] = NUL;
1245 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1246 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1247 msg_end();
1248 goto theend;
1249 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001250
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001251#ifdef FEAT_CRYPT
1252 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
Bram Moolenaar49771f42010-07-20 17:32:38 +02001253 b0_cm = 0;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001254 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1255 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02001256 b0_cm = 1;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001257 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1258 }
Bram Moolenaar49771f42010-07-20 17:32:38 +02001259 set_crypt_method(buf, b0_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001260#else
1261 if (b0p->b0_id[1] != BLOCK0_ID1)
1262 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001263 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001264 goto theend;
1265 }
1266#endif
1267
Bram Moolenaar071d4272004-06-13 20:20:40 +00001268 /*
1269 * If we guessed the wrong page size, we have to recalculate the
1270 * highest block number in the file.
1271 */
1272 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1273 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001274 unsigned previous_page_size = mfp->mf_page_size;
1275
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001277 if (mfp->mf_page_size < previous_page_size)
1278 {
1279 msg_start();
1280 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1281 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1282 attr | MSG_HIST);
1283 msg_end();
1284 goto theend;
1285 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1287 mfp->mf_blocknr_max = 0; /* no file or empty file */
1288 else
1289 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1290 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001291
1292 /* need to reallocate the memory used to store the data */
1293 p = alloc(mfp->mf_page_size);
1294 if (p == NULL)
1295 goto theend;
1296 mch_memmove(p, hp->bh_data, previous_page_size);
1297 vim_free(hp->bh_data);
1298 hp->bh_data = p;
1299 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001300 }
1301
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001302 /*
1303 * If .swp file name given directly, use name from swap file for buffer.
1304 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305 if (directly)
1306 {
1307 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1308 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1309 goto theend;
1310 }
1311
1312 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001313 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
1315 if (buf_spname(curbuf) != NULL)
Bram Moolenaare1704ba2012-10-03 18:25:00 +02001316 vim_strncpy(NameBuff, buf_spname(curbuf), MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317 else
1318 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001319 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320 msg_putchar('\n');
1321
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001322 /*
1323 * check date of swap file and original file
1324 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001325 mtime = char_to_long(b0p->b0_mtime);
1326 if (curbuf->b_ffname != NULL
1327 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1328 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1329 && org_stat.st_mtime > swp_stat.st_mtime)
1330 || org_stat.st_mtime != mtime))
1331 {
1332 EMSG(_("E308: Warning: Original file may have been changed"));
1333 }
1334 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001335
1336 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1337 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1338 if (b0p->b0_flags & B0_HAS_FENC)
1339 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001340 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001341
1342#ifdef FEAT_CRYPT
1343 /* Use the same size as in add_b0_fenc(). */
1344 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001345 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001346#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001347 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001348 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001349 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001350 }
1351
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1353 hp = NULL;
1354
1355 /*
1356 * Now that we are sure that the file is going to be recovered, clear the
1357 * contents of the current buffer.
1358 */
1359 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1360 ml_delete((linenr_T)1, FALSE);
1361
1362 /*
1363 * Try reading the original file to obtain the values of 'fileformat',
1364 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001365 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001366 */
1367 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001368 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001371#ifdef FEAT_CRYPT
1372 if (b0_cm >= 0)
1373 {
1374 /* Need to ask the user for the crypt key. If this fails we continue
1375 * without a key, will probably get garbage text. */
1376 if (*curbuf->b_p_key != NUL)
1377 {
1378 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1379 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1380 MSG_PUTS(_("\nenter the new crypt key."));
1381 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1382 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1383 }
1384 else
1385 smsg((char_u *)_(need_key_msg), fname_used);
1386 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1387 if (buf->b_p_key == NULL)
1388 buf->b_p_key = curbuf->b_p_key;
1389 else if (*buf->b_p_key == NUL)
1390 {
1391 vim_free(buf->b_p_key);
1392 buf->b_p_key = curbuf->b_p_key;
1393 }
1394 if (buf->b_p_key == NULL)
1395 buf->b_p_key = empty_option;
1396 }
1397#endif
1398
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001399 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1400 if (b0_ff != 0)
1401 set_fileformat(b0_ff - 1, OPT_LOCAL);
1402 if (b0_fenc != NULL)
1403 {
1404 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1405 vim_free(b0_fenc);
1406 }
1407 unchanged(curbuf, TRUE);
1408
Bram Moolenaar071d4272004-06-13 20:20:40 +00001409 bnum = 1; /* start with block 1 */
1410 page_count = 1; /* which is 1 page */
1411 lnum = 0; /* append after line 0 in curbuf */
1412 line_count = 0;
1413 idx = 0; /* start with first index in block 1 */
1414 error = 0;
1415 buf->b_ml.ml_stack_top = 0;
1416 buf->b_ml.ml_stack = NULL;
1417 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1418
1419 if (curbuf->b_ffname == NULL)
1420 cannot_open = TRUE;
1421 else
1422 cannot_open = FALSE;
1423
1424 serious_error = FALSE;
1425 for ( ; !got_int; line_breakcheck())
1426 {
1427 if (hp != NULL)
1428 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1429
1430 /*
1431 * get block
1432 */
1433 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1434 {
1435 if (bnum == 1)
1436 {
1437 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1438 goto theend;
1439 }
1440 ++error;
1441 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1442 (colnr_T)0, TRUE);
1443 }
1444 else /* there is a block */
1445 {
1446 pp = (PTR_BL *)(hp->bh_data);
1447 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1448 {
1449 /* check line count when using pointer block first time */
1450 if (idx == 0 && line_count != 0)
1451 {
1452 for (i = 0; i < (int)pp->pb_count; ++i)
1453 line_count -= pp->pb_pointer[i].pe_line_count;
1454 if (line_count != 0)
1455 {
1456 ++error;
1457 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1458 (colnr_T)0, TRUE);
1459 }
1460 }
1461
1462 if (pp->pb_count == 0)
1463 {
1464 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1465 (colnr_T)0, TRUE);
1466 ++error;
1467 }
1468 else if (idx < (int)pp->pb_count) /* go a block deeper */
1469 {
1470 if (pp->pb_pointer[idx].pe_bnum < 0)
1471 {
1472 /*
1473 * Data block with negative block number.
1474 * Try to read lines from the original file.
1475 * This is slow, but it works.
1476 */
1477 if (!cannot_open)
1478 {
1479 line_count = pp->pb_pointer[idx].pe_line_count;
1480 if (readfile(curbuf->b_ffname, NULL, lnum,
1481 pp->pb_pointer[idx].pe_old_lnum - 1,
1482 line_count, NULL, 0) == FAIL)
1483 cannot_open = TRUE;
1484 else
1485 lnum += line_count;
1486 }
1487 if (cannot_open)
1488 {
1489 ++error;
1490 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1491 (colnr_T)0, TRUE);
1492 }
1493 ++idx; /* get same block again for next index */
1494 continue;
1495 }
1496
1497 /*
1498 * going one block deeper in the tree
1499 */
1500 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1501 {
1502 ++error;
1503 break; /* out of memory */
1504 }
1505 ip = &(buf->b_ml.ml_stack[top]);
1506 ip->ip_bnum = bnum;
1507 ip->ip_index = idx;
1508
1509 bnum = pp->pb_pointer[idx].pe_bnum;
1510 line_count = pp->pb_pointer[idx].pe_line_count;
1511 page_count = pp->pb_pointer[idx].pe_page_count;
Bram Moolenaar986a0032011-06-13 01:07:27 +02001512 idx = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 continue;
1514 }
1515 }
1516 else /* not a pointer block */
1517 {
1518 dp = (DATA_BL *)(hp->bh_data);
1519 if (dp->db_id != DATA_ID) /* block id wrong */
1520 {
1521 if (bnum == 1)
1522 {
1523 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1524 mfp->mf_fname);
1525 goto theend;
1526 }
1527 ++error;
1528 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1529 (colnr_T)0, TRUE);
1530 }
1531 else
1532 {
1533 /*
1534 * it is a data block
1535 * Append all the lines in this block
1536 */
1537 has_error = FALSE;
1538 /*
1539 * check length of block
1540 * if wrong, use length in pointer block
1541 */
1542 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1543 {
1544 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1545 (colnr_T)0, TRUE);
1546 ++error;
1547 has_error = TRUE;
1548 dp->db_txt_end = page_count * mfp->mf_page_size;
1549 }
1550
1551 /* make sure there is a NUL at the end of the block */
1552 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1553
1554 /*
1555 * check number of lines in block
1556 * if wrong, use count in data block
1557 */
1558 if (line_count != dp->db_line_count)
1559 {
1560 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1561 (colnr_T)0, TRUE);
1562 ++error;
1563 has_error = TRUE;
1564 }
1565
1566 for (i = 0; i < dp->db_line_count; ++i)
1567 {
1568 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001569 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 || txt_start >= (int)dp->db_txt_end)
1571 {
1572 p = (char_u *)"???";
1573 ++error;
1574 }
1575 else
1576 p = (char_u *)dp + txt_start;
1577 ml_append(lnum++, p, (colnr_T)0, TRUE);
1578 }
1579 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001580 ml_append(lnum++, (char_u *)_("???END"),
1581 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 }
1583 }
1584 }
1585
1586 if (buf->b_ml.ml_stack_top == 0) /* finished */
1587 break;
1588
1589 /*
1590 * go one block up in the tree
1591 */
1592 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1593 bnum = ip->ip_bnum;
1594 idx = ip->ip_index + 1; /* go to next index */
1595 page_count = 1;
1596 }
1597
1598 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001599 * Compare the buffer contents with the original file. When they differ
1600 * set the 'modified' flag.
1601 * Lines 1 - lnum are the new contents.
1602 * Lines lnum + 1 to ml_line_count are the original contents.
1603 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001605 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1606 {
1607 /* Recovering an empty file results in two lines and the first line is
1608 * empty. Don't set the modified flag then. */
1609 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1610 {
1611 changed_int();
1612 ++curbuf->b_changedtick;
1613 }
1614 }
1615 else
1616 {
1617 for (idx = 1; idx <= lnum; ++idx)
1618 {
1619 /* Need to copy one line, fetching the other one may flush it. */
1620 p = vim_strsave(ml_get(idx));
1621 i = STRCMP(p, ml_get(idx + lnum));
1622 vim_free(p);
1623 if (i != 0)
1624 {
1625 changed_int();
1626 ++curbuf->b_changedtick;
1627 break;
1628 }
1629 }
1630 }
1631
1632 /*
1633 * Delete the lines from the original file and the dummy line from the
1634 * empty buffer. These will now be after the last line in the buffer.
1635 */
1636 while (curbuf->b_ml.ml_line_count > lnum
1637 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1638 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 curbuf->b_flags |= BF_RECOVERED;
1640
1641 recoverymode = FALSE;
1642 if (got_int)
1643 EMSG(_("E311: Recovery Interrupted"));
1644 else if (error)
1645 {
1646 ++no_wait_return;
1647 MSG(">>>>>>>>>>>>>");
1648 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1649 --no_wait_return;
1650 MSG(_("See \":help E312\" for more information."));
1651 MSG(">>>>>>>>>>>>>");
1652 }
1653 else
1654 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001655 if (curbuf->b_changed)
1656 {
1657 MSG(_("Recovery completed. You should check if everything is OK."));
1658 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1659 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1660 }
1661 else
1662 MSG(_("Recovery completed. Buffer contents equals file contents."));
1663 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 cmdline_row = msg_row;
1665 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001666#ifdef FEAT_CRYPT
1667 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1668 {
1669 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1670 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1671 }
1672#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 redraw_curbuf_later(NOT_VALID);
1674
1675theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001676 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 recoverymode = FALSE;
1678 if (mfp != NULL)
1679 {
1680 if (hp != NULL)
1681 mf_put(mfp, hp, FALSE, FALSE);
1682 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1683 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001684 if (buf != NULL)
1685 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001686#ifdef FEAT_CRYPT
1687 if (buf->b_p_key != curbuf->b_p_key)
1688 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001689 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001690#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001691 vim_free(buf->b_ml.ml_stack);
1692 vim_free(buf);
1693 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 if (serious_error && called_from_main)
1695 ml_close(curbuf, TRUE);
1696#ifdef FEAT_AUTOCMD
1697 else
1698 {
1699 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1700 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1701 }
1702#endif
1703 return;
1704}
1705
1706/*
1707 * Find the names of swap files in current directory and the directory given
1708 * with the 'directory' option.
1709 *
1710 * Used to:
1711 * - list the swap files for "vim -r"
1712 * - count the number of swap files when recovering
1713 * - list the swap files when recovering
1714 * - find the name of the n'th swap file when recovering
1715 */
1716 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001717recover_names(fname, list, nr, fname_out)
1718 char_u *fname; /* base for swap file name */
1719 int list; /* when TRUE, list the swap file names */
1720 int nr; /* when non-zero, return nr'th swap file name */
1721 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722{
1723 int num_names;
1724 char_u *(names[6]);
1725 char_u *tail;
1726 char_u *p;
1727 int num_files;
1728 int file_count = 0;
1729 char_u **files;
1730 int i;
1731 char_u *dirp;
1732 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001733 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001734#ifdef HAVE_READLINK
1735 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001736#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001737
Bram Moolenaar64354da2010-05-25 21:37:17 +02001738 if (fname != NULL)
1739 {
1740#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001741 /* Expand symlink in the file name, because the swap file is created
1742 * with the actual file instead of with the symlink. */
1743 if (resolve_symlink(fname, fname_buf) == OK)
1744 fname_res = fname_buf;
1745 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001746#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001747 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749
1750 if (list)
1751 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001752 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 msg((char_u *)_("Swap files found:"));
1754 msg_putchar('\n');
1755 }
1756
1757 /*
1758 * Do the loop for every directory in 'directory'.
1759 * First allocate some memory to put the directory name in.
1760 */
1761 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1762 dirp = p_dir;
1763 while (dir_name != NULL && *dirp)
1764 {
1765 /*
1766 * Isolate a directory name from *dirp and put it in dir_name (we know
1767 * it is large enough, so use 31000 for length).
1768 * Advance dirp to next directory name.
1769 */
1770 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1771
1772 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1773 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001774 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 {
1776#ifdef VMS
1777 names[0] = vim_strsave((char_u *)"*_sw%");
1778#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 names[0] = vim_strsave((char_u *)"*.sw?");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001781#if defined(UNIX) || defined(WIN3264)
1782 /* For Unix names starting with a dot are special. MS-Windows
1783 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001784 names[1] = vim_strsave((char_u *)".*.sw?");
1785 names[2] = vim_strsave((char_u *)".sw?");
1786 num_names = 3;
1787#else
1788# ifdef VMS
1789 names[1] = vim_strsave((char_u *)".*_sw%");
1790 num_names = 2;
1791# else
1792 num_names = 1;
1793# endif
1794#endif
1795 }
1796 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001797 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 }
1799 else /* check directory dir_name */
1800 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001801 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 {
1803#ifdef VMS
1804 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1805#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001808#if defined(UNIX) || defined(WIN3264)
1809 /* For Unix names starting with a dot are special. MS-Windows
1810 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1812 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1813 num_names = 3;
1814#else
1815# ifdef VMS
1816 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1817 num_names = 2;
1818# else
1819 num_names = 1;
1820# endif
1821#endif
1822 }
1823 else
1824 {
1825#if defined(UNIX) || defined(WIN3264)
1826 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001827 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828 {
1829 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001830 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 }
1832 else
1833#endif
1834 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001835 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 tail = concat_fnames(dir_name, tail, TRUE);
1837 }
1838 if (tail == NULL)
1839 num_names = 0;
1840 else
1841 {
1842 num_names = recov_file_names(names, tail, FALSE);
1843 vim_free(tail);
1844 }
1845 }
1846 }
1847
1848 /* check for out-of-memory */
1849 for (i = 0; i < num_names; ++i)
1850 {
1851 if (names[i] == NULL)
1852 {
1853 for (i = 0; i < num_names; ++i)
1854 vim_free(names[i]);
1855 num_names = 0;
1856 }
1857 }
1858 if (num_names == 0)
1859 num_files = 0;
1860 else if (expand_wildcards(num_names, names, &num_files, &files,
1861 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1862 num_files = 0;
1863
1864 /*
1865 * When no swap file found, wildcard expansion might have failed (e.g.
1866 * not able to execute the shell).
1867 * Try finding a swap file by simply adding ".swp" to the file name.
1868 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001869 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 {
1871 struct stat st;
1872 char_u *swapname;
1873
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001874 swapname = modname(fname_res,
Bram Moolenaare60acc12011-05-10 16:41:25 +02001875#if defined(VMS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001876 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001878 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001880 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 if (swapname != NULL)
1882 {
1883 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1884 {
1885 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1886 if (files != NULL)
1887 {
1888 files[0] = swapname;
1889 swapname = NULL;
1890 num_files = 1;
1891 }
1892 }
1893 vim_free(swapname);
1894 }
1895 }
1896
1897 /*
1898 * remove swapfile name of the current buffer, it must be ignored
1899 */
1900 if (curbuf->b_ml.ml_mfp != NULL
1901 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1902 {
1903 for (i = 0; i < num_files; ++i)
1904 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1905 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001906 /* Remove the name from files[i]. Move further entries
1907 * down. When the array becomes empty free it here, since
1908 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001910 if (--num_files == 0)
1911 vim_free(files);
1912 else
1913 for ( ; i < num_files; ++i)
1914 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 }
1916 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001917 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 {
1919 file_count += num_files;
1920 if (nr <= file_count)
1921 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001922 *fname_out = vim_strsave(
1923 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 dirp = (char_u *)""; /* stop searching */
1925 }
1926 }
1927 else if (list)
1928 {
1929 if (dir_name[0] == '.' && dir_name[1] == NUL)
1930 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001931 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 MSG_PUTS(_(" In current directory:\n"));
1933 else
1934 MSG_PUTS(_(" Using specified name:\n"));
1935 }
1936 else
1937 {
1938 MSG_PUTS(_(" In directory "));
1939 msg_home_replace(dir_name);
1940 MSG_PUTS(":\n");
1941 }
1942
1943 if (num_files)
1944 {
1945 for (i = 0; i < num_files; ++i)
1946 {
1947 /* print the swap file name */
1948 msg_outnum((long)++file_count);
1949 MSG_PUTS(". ");
1950 msg_puts(gettail(files[i]));
1951 msg_putchar('\n');
1952 (void)swapfile_info(files[i]);
1953 }
1954 }
1955 else
1956 MSG_PUTS(_(" -- none --\n"));
1957 out_flush();
1958 }
1959 else
1960 file_count += num_files;
1961
1962 for (i = 0; i < num_names; ++i)
1963 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001964 if (num_files > 0)
1965 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 }
1967 vim_free(dir_name);
1968 return file_count;
1969}
1970
1971#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1972/*
1973 * Append the full path to name with path separators made into percent
1974 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1975 */
1976 static char_u *
1977make_percent_swname(dir, name)
1978 char_u *dir;
1979 char_u *name;
1980{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001981 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001982
1983 f = fix_fname(name != NULL ? name : (char_u *) "");
1984 d = NULL;
1985 if (f != NULL)
1986 {
1987 s = alloc((unsigned)(STRLEN(f) + 1));
1988 if (s != NULL)
1989 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001990 STRCPY(s, f);
1991 for (d = s; *d != NUL; mb_ptr_adv(d))
1992 if (vim_ispathsep(*d))
1993 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 d = concat_fnames(dir, s, TRUE);
1995 vim_free(s);
1996 }
1997 vim_free(f);
1998 }
1999 return d;
2000}
2001#endif
2002
2003#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2004static int process_still_running;
2005#endif
2006
2007/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002008 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009 * Returns timestamp (0 when unknown).
2010 */
2011 static time_t
2012swapfile_info(fname)
2013 char_u *fname;
2014{
2015 struct stat st;
2016 int fd;
2017 struct block0 b0;
2018 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002019 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020#ifdef UNIX
2021 char_u uname[B0_UNAME_SIZE];
2022#endif
2023
2024 /* print the swap file date */
2025 if (mch_stat((char *)fname, &st) != -1)
2026 {
2027#ifdef UNIX
2028 /* print name of owner of the file */
2029 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2030 {
2031 MSG_PUTS(_(" owned by: "));
2032 msg_outtrans(uname);
2033 MSG_PUTS(_(" dated: "));
2034 }
2035 else
2036#endif
2037 MSG_PUTS(_(" dated: "));
2038 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002039 p = ctime(&x); /* includes '\n' */
2040 if (p == NULL)
2041 MSG_PUTS("(invalid)\n");
2042 else
2043 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044 }
2045
2046 /*
2047 * print the original file name
2048 */
2049 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2050 if (fd >= 0)
2051 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01002052 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 {
2054 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2055 {
2056 MSG_PUTS(_(" [from Vim version 3.0]"));
2057 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002058 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 {
2060 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2061 }
2062 else
2063 {
2064 MSG_PUTS(_(" file name: "));
2065 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002066 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 else
2068 msg_outtrans(b0.b0_fname);
2069
2070 MSG_PUTS(_("\n modified: "));
2071 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2072
2073 if (*(b0.b0_uname) != NUL)
2074 {
2075 MSG_PUTS(_("\n user name: "));
2076 msg_outtrans(b0.b0_uname);
2077 }
2078
2079 if (*(b0.b0_hname) != NUL)
2080 {
2081 if (*(b0.b0_uname) != NUL)
2082 MSG_PUTS(_(" host name: "));
2083 else
2084 MSG_PUTS(_("\n host name: "));
2085 msg_outtrans(b0.b0_hname);
2086 }
2087
2088 if (char_to_long(b0.b0_pid) != 0L)
2089 {
2090 MSG_PUTS(_("\n process ID: "));
2091 msg_outnum(char_to_long(b0.b0_pid));
2092#if defined(UNIX) || defined(__EMX__)
2093 /* EMX kill() not working correctly, it seems */
2094 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2095 {
2096 MSG_PUTS(_(" (still running)"));
2097# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2098 process_still_running = TRUE;
2099# endif
2100 }
2101#endif
2102 }
2103
2104 if (b0_magic_wrong(&b0))
2105 {
2106#if defined(MSDOS) || defined(MSWIN)
2107 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2108 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2109 else
2110#endif
2111 MSG_PUTS(_("\n [not usable on this computer]"));
2112 }
2113 }
2114 }
2115 else
2116 MSG_PUTS(_(" [cannot be read]"));
2117 close(fd);
2118 }
2119 else
2120 MSG_PUTS(_(" [cannot be opened]"));
2121 msg_putchar('\n');
2122
2123 return x;
2124}
2125
2126 static int
2127recov_file_names(names, path, prepend_dot)
2128 char_u **names;
2129 char_u *path;
2130 int prepend_dot;
2131{
2132 int num_names;
2133
2134#ifdef SHORT_FNAME
2135 /*
2136 * (MS-DOS) always short names
2137 */
2138 names[0] = modname(path, (char_u *)".sw?", FALSE);
2139 num_names = 1;
2140#else /* !SHORT_FNAME */
2141 /*
2142 * (Win32 and Win64) never short names, but do prepend a dot.
2143 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2144 * Only use the short name if it is different.
2145 */
2146 char_u *p;
2147 int i;
2148# ifndef WIN3264
2149 int shortname = curbuf->b_shortname;
2150
2151 curbuf->b_shortname = FALSE;
2152# endif
2153
2154 num_names = 0;
2155
2156 /*
2157 * May also add the file name with a dot prepended, for swap file in same
2158 * dir as original file.
2159 */
2160 if (prepend_dot)
2161 {
2162 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2163 if (names[num_names] == NULL)
2164 goto end;
2165 ++num_names;
2166 }
2167
2168 /*
2169 * Form the normal swap file name pattern by appending ".sw?".
2170 */
2171#ifdef VMS
2172 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2173#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175#endif
2176 if (names[num_names] == NULL)
2177 goto end;
2178 if (num_names >= 1) /* check if we have the same name twice */
2179 {
2180 p = names[num_names - 1];
2181 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2182 if (i > 0)
2183 p += i; /* file name has been expanded to full path */
2184
2185 if (STRCMP(p, names[num_names]) != 0)
2186 ++num_names;
2187 else
2188 vim_free(names[num_names]);
2189 }
2190 else
2191 ++num_names;
2192
2193# ifndef WIN3264
2194 /*
2195 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2196 */
2197 curbuf->b_shortname = TRUE;
2198#ifdef VMS
2199 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2200#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202#endif
2203 if (names[num_names] == NULL)
2204 goto end;
2205
2206 /*
2207 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2208 */
2209 p = names[num_names];
2210 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2211 if (i > 0)
2212 p += i; /* file name has been expanded to full path */
2213 if (STRCMP(names[num_names - 1], p) == 0)
2214 vim_free(names[num_names]);
2215 else
2216 ++num_names;
2217# endif
2218
2219end:
2220# ifndef WIN3264
2221 curbuf->b_shortname = shortname;
2222# endif
2223
2224#endif /* !SHORT_FNAME */
2225
2226 return num_names;
2227}
2228
2229/*
2230 * sync all memlines
2231 *
2232 * If 'check_file' is TRUE, check if original file exists and was not changed.
2233 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2234 * always sync at least one block.
2235 */
2236 void
2237ml_sync_all(check_file, check_char)
2238 int check_file;
2239 int check_char;
2240{
2241 buf_T *buf;
2242 struct stat st;
2243
2244 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2245 {
2246 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2247 continue; /* no file */
2248
2249 ml_flush_line(buf); /* flush buffered line */
2250 /* flush locked block */
2251 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2252 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2253 && buf->b_ffname != NULL)
2254 {
2255 /*
2256 * If the original file does not exist anymore or has been changed
2257 * call ml_preserve() to get rid of all negative numbered blocks.
2258 */
2259 if (mch_stat((char *)buf->b_ffname, &st) == -1
2260 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002261 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 {
2263 ml_preserve(buf, FALSE);
2264 did_check_timestamps = FALSE;
2265 need_check_timestamps = TRUE; /* give message later */
2266 }
2267 }
2268 if (buf->b_ml.ml_mfp->mf_dirty)
2269 {
2270 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2271 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2272 if (check_char && ui_char_avail()) /* character available now */
2273 break;
2274 }
2275 }
2276}
2277
2278/*
2279 * sync one buffer, including negative blocks
2280 *
2281 * after this all the blocks are in the swap file
2282 *
2283 * Used for the :preserve command and when the original file has been
2284 * changed or deleted.
2285 *
2286 * when message is TRUE the success of preserving is reported
2287 */
2288 void
2289ml_preserve(buf, message)
2290 buf_T *buf;
2291 int message;
2292{
2293 bhdr_T *hp;
2294 linenr_T lnum;
2295 memfile_T *mfp = buf->b_ml.ml_mfp;
2296 int status;
2297 int got_int_save = got_int;
2298
2299 if (mfp == NULL || mfp->mf_fname == NULL)
2300 {
2301 if (message)
2302 EMSG(_("E313: Cannot preserve, there is no swap file"));
2303 return;
2304 }
2305
2306 /* We only want to stop when interrupted here, not when interrupted
2307 * before. */
2308 got_int = FALSE;
2309
2310 ml_flush_line(buf); /* flush buffered line */
2311 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2312 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2313
2314 /* stack is invalid after mf_sync(.., MFS_ALL) */
2315 buf->b_ml.ml_stack_top = 0;
2316
2317 /*
2318 * Some of the data blocks may have been changed from negative to
2319 * positive block number. In that case the pointer blocks need to be
2320 * updated.
2321 *
2322 * We don't know in which pointer block the references are, so we visit
2323 * all data blocks until there are no more translations to be done (or
2324 * we hit the end of the file, which can only happen in case a write fails,
2325 * e.g. when file system if full).
2326 * ml_find_line() does the work by translating the negative block numbers
2327 * when getting the first line of each data block.
2328 */
2329 if (mf_need_trans(mfp) && !got_int)
2330 {
2331 lnum = 1;
2332 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2333 {
2334 hp = ml_find_line(buf, lnum, ML_FIND);
2335 if (hp == NULL)
2336 {
2337 status = FAIL;
2338 goto theend;
2339 }
2340 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2341 lnum = buf->b_ml.ml_locked_high + 1;
2342 }
2343 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2344 /* sync the updated pointer blocks */
2345 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2346 status = FAIL;
2347 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2348 }
2349theend:
2350 got_int |= got_int_save;
2351
2352 if (message)
2353 {
2354 if (status == OK)
2355 MSG(_("File preserved"));
2356 else
2357 EMSG(_("E314: Preserve failed"));
2358 }
2359}
2360
2361/*
2362 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2363 * until the next call!
2364 * line1 = ml_get(1);
2365 * line2 = ml_get(2); // line1 is now invalid!
2366 * Make a copy of the line if necessary.
2367 */
2368/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002369 * Return a pointer to a (read-only copy of a) line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 *
2371 * On failure an error message is given and IObuff is returned (to avoid
2372 * having to check for error everywhere).
2373 */
2374 char_u *
2375ml_get(lnum)
2376 linenr_T lnum;
2377{
2378 return ml_get_buf(curbuf, lnum, FALSE);
2379}
2380
2381/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002382 * Return pointer to position "pos".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 */
2384 char_u *
2385ml_get_pos(pos)
2386 pos_T *pos;
2387{
2388 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2389}
2390
2391/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002392 * Return pointer to cursor line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393 */
2394 char_u *
2395ml_get_curline()
2396{
2397 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2398}
2399
2400/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002401 * Return pointer to cursor position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 */
2403 char_u *
2404ml_get_cursor()
2405{
2406 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2407 curwin->w_cursor.col);
2408}
2409
2410/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002411 * Return a pointer to a line in a specific buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002412 *
2413 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2414 * changed)
2415 */
2416 char_u *
2417ml_get_buf(buf, lnum, will_change)
2418 buf_T *buf;
2419 linenr_T lnum;
2420 int will_change; /* line will be changed */
2421{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002422 bhdr_T *hp;
2423 DATA_BL *dp;
2424 char_u *ptr;
2425 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426
2427 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2428 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002429 if (recursive == 0)
2430 {
2431 /* Avoid giving this message for a recursive call, may happen when
2432 * the GUI redraws part of the text. */
2433 ++recursive;
2434 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2435 --recursive;
2436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437errorret:
2438 STRCPY(IObuff, "???");
2439 return IObuff;
2440 }
2441 if (lnum <= 0) /* pretend line 0 is line 1 */
2442 lnum = 1;
2443
2444 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2445 return (char_u *)"";
2446
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002447 /*
2448 * See if it is the same line as requested last time.
2449 * Otherwise may need to flush last used line.
2450 * Don't use the last used line when 'swapfile' is reset, need to load all
2451 * blocks.
2452 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002453 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 {
2455 ml_flush_line(buf);
2456
2457 /*
2458 * Find the data block containing the line.
2459 * This also fills the stack with the blocks from the root to the data
2460 * block and releases any locked block.
2461 */
2462 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2463 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002464 if (recursive == 0)
2465 {
2466 /* Avoid giving this message for a recursive call, may happen
2467 * when the GUI redraws part of the text. */
2468 ++recursive;
2469 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2470 --recursive;
2471 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 goto errorret;
2473 }
2474
2475 dp = (DATA_BL *)(hp->bh_data);
2476
2477 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2478 buf->b_ml.ml_line_ptr = ptr;
2479 buf->b_ml.ml_line_lnum = lnum;
2480 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2481 }
2482 if (will_change)
2483 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2484
2485 return buf->b_ml.ml_line_ptr;
2486}
2487
2488/*
2489 * Check if a line that was just obtained by a call to ml_get
2490 * is in allocated memory.
2491 */
2492 int
2493ml_line_alloced()
2494{
2495 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2496}
2497
2498/*
2499 * Append a line after lnum (may be 0 to insert a line in front of the file).
2500 * "line" does not need to be allocated, but can't be another line in a
2501 * buffer, unlocking may make it invalid.
2502 *
2503 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2504 * will be set for recovery
2505 * Check: The caller of this function should probably also call
2506 * appended_lines().
2507 *
2508 * return FAIL for failure, OK otherwise
2509 */
2510 int
2511ml_append(lnum, line, len, newfile)
2512 linenr_T lnum; /* append after this line (can be 0) */
2513 char_u *line; /* text of the new line */
2514 colnr_T len; /* length of new line, including NUL, or 0 */
2515 int newfile; /* flag, see above */
2516{
2517 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002518 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 return FAIL;
2520
2521 if (curbuf->b_ml.ml_line_lnum != 0)
2522 ml_flush_line(curbuf);
2523 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2524}
2525
Bram Moolenaara1956f62006-03-12 22:18:00 +00002526#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002527/*
2528 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2529 * a memline.
2530 */
2531 int
2532ml_append_buf(buf, lnum, line, len, newfile)
2533 buf_T *buf;
2534 linenr_T lnum; /* append after this line (can be 0) */
2535 char_u *line; /* text of the new line */
2536 colnr_T len; /* length of new line, including NUL, or 0 */
2537 int newfile; /* flag, see above */
2538{
2539 if (buf->b_ml.ml_mfp == NULL)
2540 return FAIL;
2541
2542 if (buf->b_ml.ml_line_lnum != 0)
2543 ml_flush_line(buf);
2544 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2545}
2546#endif
2547
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 static int
2549ml_append_int(buf, lnum, line, len, newfile, mark)
2550 buf_T *buf;
2551 linenr_T lnum; /* append after this line (can be 0) */
2552 char_u *line; /* text of the new line */
2553 colnr_T len; /* length of line, including NUL, or 0 */
2554 int newfile; /* flag, see above */
2555 int mark; /* mark the new line */
2556{
2557 int i;
2558 int line_count; /* number of indexes in current block */
2559 int offset;
2560 int from, to;
2561 int space_needed; /* space needed for new line */
2562 int page_size;
2563 int page_count;
2564 int db_idx; /* index for lnum in data block */
2565 bhdr_T *hp;
2566 memfile_T *mfp;
2567 DATA_BL *dp;
2568 PTR_BL *pp;
2569 infoptr_T *ip;
2570
2571 /* lnum out of range */
2572 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2573 return FAIL;
2574
2575 if (lowest_marked && lowest_marked > lnum)
2576 lowest_marked = lnum + 1;
2577
2578 if (len == 0)
2579 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2580 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2581
2582 mfp = buf->b_ml.ml_mfp;
2583 page_size = mfp->mf_page_size;
2584
2585/*
2586 * find the data block containing the previous line
2587 * This also fills the stack with the blocks from the root to the data block
2588 * This also releases any locked block.
2589 */
2590 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2591 ML_INSERT)) == NULL)
2592 return FAIL;
2593
2594 buf->b_ml.ml_flags &= ~ML_EMPTY;
2595
2596 if (lnum == 0) /* got line one instead, correct db_idx */
2597 db_idx = -1; /* careful, it is negative! */
2598 else
2599 db_idx = lnum - buf->b_ml.ml_locked_low;
2600 /* get line count before the insertion */
2601 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2602
2603 dp = (DATA_BL *)(hp->bh_data);
2604
2605/*
2606 * If
2607 * - there is not enough room in the current block
2608 * - appending to the last line in the block
2609 * - not appending to the last line in the file
2610 * insert in front of the next block.
2611 */
2612 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2613 && lnum < buf->b_ml.ml_line_count)
2614 {
2615 /*
2616 * Now that the line is not going to be inserted in the block that we
2617 * expected, the line count has to be adjusted in the pointer blocks
2618 * by using ml_locked_lineadd.
2619 */
2620 --(buf->b_ml.ml_locked_lineadd);
2621 --(buf->b_ml.ml_locked_high);
2622 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2623 return FAIL;
2624
2625 db_idx = -1; /* careful, it is negative! */
2626 /* get line count before the insertion */
2627 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2628 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2629
2630 dp = (DATA_BL *)(hp->bh_data);
2631 }
2632
2633 ++buf->b_ml.ml_line_count;
2634
2635 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2636 {
2637/*
2638 * Insert new line in existing data block, or in data block allocated above.
2639 */
2640 dp->db_txt_start -= len;
2641 dp->db_free -= space_needed;
2642 ++(dp->db_line_count);
2643
2644 /*
2645 * move the text of the lines that follow to the front
2646 * adjust the indexes of the lines that follow
2647 */
2648 if (line_count > db_idx + 1) /* if there are following lines */
2649 {
2650 /*
2651 * Offset is the start of the previous line.
2652 * This will become the character just after the new line.
2653 */
2654 if (db_idx < 0)
2655 offset = dp->db_txt_end;
2656 else
2657 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2658 mch_memmove((char *)dp + dp->db_txt_start,
2659 (char *)dp + dp->db_txt_start + len,
2660 (size_t)(offset - (dp->db_txt_start + len)));
2661 for (i = line_count - 1; i > db_idx; --i)
2662 dp->db_index[i + 1] = dp->db_index[i] - len;
2663 dp->db_index[db_idx + 1] = offset - len;
2664 }
2665 else /* add line at the end */
2666 dp->db_index[db_idx + 1] = dp->db_txt_start;
2667
2668 /*
2669 * copy the text into the block
2670 */
2671 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2672 if (mark)
2673 dp->db_index[db_idx + 1] |= DB_MARKED;
2674
2675 /*
2676 * Mark the block dirty.
2677 */
2678 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2679 if (!newfile)
2680 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2681 }
2682 else /* not enough space in data block */
2683 {
2684/*
2685 * If there is not enough room we have to create a new data block and copy some
2686 * lines into it.
2687 * Then we have to insert an entry in the pointer block.
2688 * If this pointer block also is full, we go up another block, and so on, up
2689 * to the root if necessary.
2690 * The line counts in the pointer blocks have already been adjusted by
2691 * ml_find_line().
2692 */
2693 long line_count_left, line_count_right;
2694 int page_count_left, page_count_right;
2695 bhdr_T *hp_left;
2696 bhdr_T *hp_right;
2697 bhdr_T *hp_new;
2698 int lines_moved;
2699 int data_moved = 0; /* init to shut up gcc */
2700 int total_moved = 0; /* init to shut up gcc */
2701 DATA_BL *dp_right, *dp_left;
2702 int stack_idx;
2703 int in_left;
2704 int lineadd;
2705 blocknr_T bnum_left, bnum_right;
2706 linenr_T lnum_left, lnum_right;
2707 int pb_idx;
2708 PTR_BL *pp_new;
2709
2710 /*
2711 * We are going to allocate a new data block. Depending on the
2712 * situation it will be put to the left or right of the existing
2713 * block. If possible we put the new line in the left block and move
2714 * the lines after it to the right block. Otherwise the new line is
2715 * also put in the right block. This method is more efficient when
2716 * inserting a lot of lines at one place.
2717 */
2718 if (db_idx < 0) /* left block is new, right block is existing */
2719 {
2720 lines_moved = 0;
2721 in_left = TRUE;
2722 /* space_needed does not change */
2723 }
2724 else /* left block is existing, right block is new */
2725 {
2726 lines_moved = line_count - db_idx - 1;
2727 if (lines_moved == 0)
2728 in_left = FALSE; /* put new line in right block */
2729 /* space_needed does not change */
2730 else
2731 {
2732 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2733 dp->db_txt_start;
2734 total_moved = data_moved + lines_moved * INDEX_SIZE;
2735 if ((int)dp->db_free + total_moved >= space_needed)
2736 {
2737 in_left = TRUE; /* put new line in left block */
2738 space_needed = total_moved;
2739 }
2740 else
2741 {
2742 in_left = FALSE; /* put new line in right block */
2743 space_needed += total_moved;
2744 }
2745 }
2746 }
2747
2748 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2749 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2750 {
2751 /* correct line counts in pointer blocks */
2752 --(buf->b_ml.ml_locked_lineadd);
2753 --(buf->b_ml.ml_locked_high);
2754 return FAIL;
2755 }
2756 if (db_idx < 0) /* left block is new */
2757 {
2758 hp_left = hp_new;
2759 hp_right = hp;
2760 line_count_left = 0;
2761 line_count_right = line_count;
2762 }
2763 else /* right block is new */
2764 {
2765 hp_left = hp;
2766 hp_right = hp_new;
2767 line_count_left = line_count;
2768 line_count_right = 0;
2769 }
2770 dp_right = (DATA_BL *)(hp_right->bh_data);
2771 dp_left = (DATA_BL *)(hp_left->bh_data);
2772 bnum_left = hp_left->bh_bnum;
2773 bnum_right = hp_right->bh_bnum;
2774 page_count_left = hp_left->bh_page_count;
2775 page_count_right = hp_right->bh_page_count;
2776
2777 /*
2778 * May move the new line into the right/new block.
2779 */
2780 if (!in_left)
2781 {
2782 dp_right->db_txt_start -= len;
2783 dp_right->db_free -= len + INDEX_SIZE;
2784 dp_right->db_index[0] = dp_right->db_txt_start;
2785 if (mark)
2786 dp_right->db_index[0] |= DB_MARKED;
2787
2788 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2789 line, (size_t)len);
2790 ++line_count_right;
2791 }
2792 /*
2793 * may move lines from the left/old block to the right/new one.
2794 */
2795 if (lines_moved)
2796 {
2797 /*
2798 */
2799 dp_right->db_txt_start -= data_moved;
2800 dp_right->db_free -= total_moved;
2801 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2802 (char *)dp_left + dp_left->db_txt_start,
2803 (size_t)data_moved);
2804 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2805 dp_left->db_txt_start += data_moved;
2806 dp_left->db_free += total_moved;
2807
2808 /*
2809 * update indexes in the new block
2810 */
2811 for (to = line_count_right, from = db_idx + 1;
2812 from < line_count_left; ++from, ++to)
2813 dp_right->db_index[to] = dp->db_index[from] + offset;
2814 line_count_right += lines_moved;
2815 line_count_left -= lines_moved;
2816 }
2817
2818 /*
2819 * May move the new line into the left (old or new) block.
2820 */
2821 if (in_left)
2822 {
2823 dp_left->db_txt_start -= len;
2824 dp_left->db_free -= len + INDEX_SIZE;
2825 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2826 if (mark)
2827 dp_left->db_index[line_count_left] |= DB_MARKED;
2828 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2829 line, (size_t)len);
2830 ++line_count_left;
2831 }
2832
2833 if (db_idx < 0) /* left block is new */
2834 {
2835 lnum_left = lnum + 1;
2836 lnum_right = 0;
2837 }
2838 else /* right block is new */
2839 {
2840 lnum_left = 0;
2841 if (in_left)
2842 lnum_right = lnum + 2;
2843 else
2844 lnum_right = lnum + 1;
2845 }
2846 dp_left->db_line_count = line_count_left;
2847 dp_right->db_line_count = line_count_right;
2848
2849 /*
2850 * release the two data blocks
2851 * The new one (hp_new) already has a correct blocknumber.
2852 * The old one (hp, in ml_locked) gets a positive blocknumber if
2853 * we changed it and we are not editing a new file.
2854 */
2855 if (lines_moved || in_left)
2856 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2857 if (!newfile && db_idx >= 0 && in_left)
2858 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2859 mf_put(mfp, hp_new, TRUE, FALSE);
2860
2861 /*
2862 * flush the old data block
2863 * set ml_locked_lineadd to 0, because the updating of the
2864 * pointer blocks is done below
2865 */
2866 lineadd = buf->b_ml.ml_locked_lineadd;
2867 buf->b_ml.ml_locked_lineadd = 0;
2868 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2869
2870 /*
2871 * update pointer blocks for the new data block
2872 */
2873 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2874 --stack_idx)
2875 {
2876 ip = &(buf->b_ml.ml_stack[stack_idx]);
2877 pb_idx = ip->ip_index;
2878 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2879 return FAIL;
2880 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2881 if (pp->pb_id != PTR_ID)
2882 {
2883 EMSG(_("E317: pointer block id wrong 3"));
2884 mf_put(mfp, hp, FALSE, FALSE);
2885 return FAIL;
2886 }
2887 /*
2888 * TODO: If the pointer block is full and we are adding at the end
2889 * try to insert in front of the next block
2890 */
2891 /* block not full, add one entry */
2892 if (pp->pb_count < pp->pb_count_max)
2893 {
2894 if (pb_idx + 1 < (int)pp->pb_count)
2895 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2896 &pp->pb_pointer[pb_idx + 1],
2897 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2898 ++pp->pb_count;
2899 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2900 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2901 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2902 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2903 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2904 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2905
2906 if (lnum_left != 0)
2907 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2908 if (lnum_right != 0)
2909 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2910
2911 mf_put(mfp, hp, TRUE, FALSE);
2912 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2913
2914 if (lineadd)
2915 {
2916 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002917 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 ml_lineadd(buf, lineadd);
2919 /* fix stack itself */
2920 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2921 lineadd;
2922 ++(buf->b_ml.ml_stack_top);
2923 }
2924
2925 /*
2926 * We are finished, break the loop here.
2927 */
2928 break;
2929 }
2930 else /* pointer block full */
2931 {
2932 /*
2933 * split the pointer block
2934 * allocate a new pointer block
2935 * move some of the pointer into the new block
2936 * prepare for updating the parent block
2937 */
2938 for (;;) /* do this twice when splitting block 1 */
2939 {
2940 hp_new = ml_new_ptr(mfp);
2941 if (hp_new == NULL) /* TODO: try to fix tree */
2942 return FAIL;
2943 pp_new = (PTR_BL *)(hp_new->bh_data);
2944
2945 if (hp->bh_bnum != 1)
2946 break;
2947
2948 /*
2949 * if block 1 becomes full the tree is given an extra level
2950 * The pointers from block 1 are moved into the new block.
2951 * block 1 is updated to point to the new block
2952 * then continue to split the new block
2953 */
2954 mch_memmove(pp_new, pp, (size_t)page_size);
2955 pp->pb_count = 1;
2956 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2957 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2958 pp->pb_pointer[0].pe_old_lnum = 1;
2959 pp->pb_pointer[0].pe_page_count = 1;
2960 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2961 hp = hp_new; /* new block is to be split */
2962 pp = pp_new;
2963 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2964 ip->ip_index = 0;
2965 ++stack_idx; /* do block 1 again later */
2966 }
2967 /*
2968 * move the pointers after the current one to the new block
2969 * If there are none, the new entry will be in the new block.
2970 */
2971 total_moved = pp->pb_count - pb_idx - 1;
2972 if (total_moved)
2973 {
2974 mch_memmove(&pp_new->pb_pointer[0],
2975 &pp->pb_pointer[pb_idx + 1],
2976 (size_t)(total_moved) * sizeof(PTR_EN));
2977 pp_new->pb_count = total_moved;
2978 pp->pb_count -= total_moved - 1;
2979 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2980 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2981 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2982 if (lnum_right)
2983 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2984 }
2985 else
2986 {
2987 pp_new->pb_count = 1;
2988 pp_new->pb_pointer[0].pe_bnum = bnum_right;
2989 pp_new->pb_pointer[0].pe_line_count = line_count_right;
2990 pp_new->pb_pointer[0].pe_page_count = page_count_right;
2991 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
2992 }
2993 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2994 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2995 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2996 if (lnum_left)
2997 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2998 lnum_left = 0;
2999 lnum_right = 0;
3000
3001 /*
3002 * recompute line counts
3003 */
3004 line_count_right = 0;
3005 for (i = 0; i < (int)pp_new->pb_count; ++i)
3006 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3007 line_count_left = 0;
3008 for (i = 0; i < (int)pp->pb_count; ++i)
3009 line_count_left += pp->pb_pointer[i].pe_line_count;
3010
3011 bnum_left = hp->bh_bnum;
3012 bnum_right = hp_new->bh_bnum;
3013 page_count_left = 1;
3014 page_count_right = 1;
3015 mf_put(mfp, hp, TRUE, FALSE);
3016 mf_put(mfp, hp_new, TRUE, FALSE);
3017 }
3018 }
3019
3020 /*
3021 * Safety check: fallen out of for loop?
3022 */
3023 if (stack_idx < 0)
3024 {
3025 EMSG(_("E318: Updated too many blocks?"));
3026 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3027 }
3028 }
3029
3030#ifdef FEAT_BYTEOFF
3031 /* The line was inserted below 'lnum' */
3032 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3033#endif
3034#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003035 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036 {
3037 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003038 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003039 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 (char_u *)"\n", 1);
3041 }
3042#endif
3043 return OK;
3044}
3045
3046/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003047 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003049 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050 * copied to allocated memory already.
3051 *
3052 * Check: The caller of this function should probably also call
3053 * changed_lines(), unless update_screen(NOT_VALID) is used.
3054 *
3055 * return FAIL for failure, OK otherwise
3056 */
3057 int
3058ml_replace(lnum, line, copy)
3059 linenr_T lnum;
3060 char_u *line;
3061 int copy;
3062{
3063 if (line == NULL) /* just checking... */
3064 return FAIL;
3065
3066 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003067 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 return FAIL;
3069
3070 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3071 return FAIL;
3072#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003073 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 {
3075 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003076 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077 }
3078#endif
3079 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3080 ml_flush_line(curbuf); /* flush it */
3081 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3082 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3083 curbuf->b_ml.ml_line_ptr = line;
3084 curbuf->b_ml.ml_line_lnum = lnum;
3085 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3086
3087 return OK;
3088}
3089
3090/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003091 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092 *
3093 * Check: The caller of this function should probably also call
3094 * deleted_lines() after this.
3095 *
3096 * return FAIL for failure, OK otherwise
3097 */
3098 int
3099ml_delete(lnum, message)
3100 linenr_T lnum;
3101 int message;
3102{
3103 ml_flush_line(curbuf);
3104 return ml_delete_int(curbuf, lnum, message);
3105}
3106
3107 static int
3108ml_delete_int(buf, lnum, message)
3109 buf_T *buf;
3110 linenr_T lnum;
3111 int message;
3112{
3113 bhdr_T *hp;
3114 memfile_T *mfp;
3115 DATA_BL *dp;
3116 PTR_BL *pp;
3117 infoptr_T *ip;
3118 int count; /* number of entries in block */
3119 int idx;
3120 int stack_idx;
3121 int text_start;
3122 int line_start;
3123 long line_size;
3124 int i;
3125
3126 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3127 return FAIL;
3128
3129 if (lowest_marked && lowest_marked > lnum)
3130 lowest_marked--;
3131
3132/*
3133 * If the file becomes empty the last line is replaced by an empty line.
3134 */
3135 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3136 {
3137 if (message
3138#ifdef FEAT_NETBEANS_INTG
3139 && !netbeansSuppressNoLines
3140#endif
3141 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003142 set_keep_msg((char_u *)_(no_lines_msg), 0);
3143
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003144 /* FEAT_BYTEOFF already handled in there, don't worry 'bout it below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3146 buf->b_ml.ml_flags |= ML_EMPTY;
3147
3148 return i;
3149 }
3150
3151/*
3152 * find the data block containing the line
3153 * This also fills the stack with the blocks from the root to the data block
3154 * This also releases any locked block.
3155 */
3156 mfp = buf->b_ml.ml_mfp;
3157 if (mfp == NULL)
3158 return FAIL;
3159
3160 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3161 return FAIL;
3162
3163 dp = (DATA_BL *)(hp->bh_data);
3164 /* compute line count before the delete */
3165 count = (long)(buf->b_ml.ml_locked_high)
3166 - (long)(buf->b_ml.ml_locked_low) + 2;
3167 idx = lnum - buf->b_ml.ml_locked_low;
3168
3169 --buf->b_ml.ml_line_count;
3170
3171 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3172 if (idx == 0) /* first line in block, text at the end */
3173 line_size = dp->db_txt_end - line_start;
3174 else
3175 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3176
3177#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003178 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003179 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180#endif
3181
3182/*
3183 * special case: If there is only one line in the data block it becomes empty.
3184 * Then we have to remove the entry, pointing to this data block, from the
3185 * pointer block. If this pointer block also becomes empty, we go up another
3186 * block, and so on, up to the root if necessary.
3187 * The line counts in the pointer blocks have already been adjusted by
3188 * ml_find_line().
3189 */
3190 if (count == 1)
3191 {
3192 mf_free(mfp, hp); /* free the data block */
3193 buf->b_ml.ml_locked = NULL;
3194
Bram Moolenaare60acc12011-05-10 16:41:25 +02003195 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3196 --stack_idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 {
3198 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3199 ip = &(buf->b_ml.ml_stack[stack_idx]);
3200 idx = ip->ip_index;
3201 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3202 return FAIL;
3203 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3204 if (pp->pb_id != PTR_ID)
3205 {
3206 EMSG(_("E317: pointer block id wrong 4"));
3207 mf_put(mfp, hp, FALSE, FALSE);
3208 return FAIL;
3209 }
3210 count = --(pp->pb_count);
3211 if (count == 0) /* the pointer block becomes empty! */
3212 mf_free(mfp, hp);
3213 else
3214 {
3215 if (count != idx) /* move entries after the deleted one */
3216 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3217 (size_t)(count - idx) * sizeof(PTR_EN));
3218 mf_put(mfp, hp, TRUE, FALSE);
3219
3220 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003221 /* fix line count for rest of blocks in the stack */
3222 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 {
3224 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3225 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003226 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227 }
3228 ++(buf->b_ml.ml_stack_top);
3229
3230 break;
3231 }
3232 }
3233 CHECK(stack_idx < 0, _("deleted block 1?"));
3234 }
3235 else
3236 {
3237 /*
3238 * delete the text by moving the next lines forwards
3239 */
3240 text_start = dp->db_txt_start;
3241 mch_memmove((char *)dp + text_start + line_size,
3242 (char *)dp + text_start, (size_t)(line_start - text_start));
3243
3244 /*
3245 * delete the index by moving the next indexes backwards
3246 * Adjust the indexes for the text movement.
3247 */
3248 for (i = idx; i < count - 1; ++i)
3249 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3250
3251 dp->db_free += line_size + INDEX_SIZE;
3252 dp->db_txt_start += line_size;
3253 --(dp->db_line_count);
3254
3255 /*
3256 * mark the block dirty and make sure it is in the file (for recovery)
3257 */
3258 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3259 }
3260
3261#ifdef FEAT_BYTEOFF
3262 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3263#endif
3264 return OK;
3265}
3266
3267/*
3268 * set the B_MARKED flag for line 'lnum'
3269 */
3270 void
3271ml_setmarked(lnum)
3272 linenr_T lnum;
3273{
3274 bhdr_T *hp;
3275 DATA_BL *dp;
3276 /* invalid line number */
3277 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3278 || curbuf->b_ml.ml_mfp == NULL)
3279 return; /* give error message? */
3280
3281 if (lowest_marked == 0 || lowest_marked > lnum)
3282 lowest_marked = lnum;
3283
3284 /*
3285 * find the data block containing the line
3286 * This also fills the stack with the blocks from the root to the data block
3287 * This also releases any locked block.
3288 */
3289 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3290 return; /* give error message? */
3291
3292 dp = (DATA_BL *)(hp->bh_data);
3293 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3294 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3295}
3296
3297/*
3298 * find the first line with its B_MARKED flag set
3299 */
3300 linenr_T
3301ml_firstmarked()
3302{
3303 bhdr_T *hp;
3304 DATA_BL *dp;
3305 linenr_T lnum;
3306 int i;
3307
3308 if (curbuf->b_ml.ml_mfp == NULL)
3309 return (linenr_T) 0;
3310
3311 /*
3312 * The search starts with lowest_marked line. This is the last line where
3313 * a mark was found, adjusted by inserting/deleting lines.
3314 */
3315 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3316 {
3317 /*
3318 * Find the data block containing the line.
3319 * This also fills the stack with the blocks from the root to the data
3320 * block This also releases any locked block.
3321 */
3322 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3323 return (linenr_T)0; /* give error message? */
3324
3325 dp = (DATA_BL *)(hp->bh_data);
3326
3327 for (i = lnum - curbuf->b_ml.ml_locked_low;
3328 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3329 if ((dp->db_index[i]) & DB_MARKED)
3330 {
3331 (dp->db_index[i]) &= DB_INDEX_MASK;
3332 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3333 lowest_marked = lnum + 1;
3334 return lnum;
3335 }
3336 }
3337
3338 return (linenr_T) 0;
3339}
3340
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341/*
3342 * clear all DB_MARKED flags
3343 */
3344 void
3345ml_clearmarked()
3346{
3347 bhdr_T *hp;
3348 DATA_BL *dp;
3349 linenr_T lnum;
3350 int i;
3351
3352 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3353 return;
3354
3355 /*
3356 * The search starts with line lowest_marked.
3357 */
3358 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3359 {
3360 /*
3361 * Find the data block containing the line.
3362 * This also fills the stack with the blocks from the root to the data
3363 * block and releases any locked block.
3364 */
3365 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3366 return; /* give error message? */
3367
3368 dp = (DATA_BL *)(hp->bh_data);
3369
3370 for (i = lnum - curbuf->b_ml.ml_locked_low;
3371 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3372 if ((dp->db_index[i]) & DB_MARKED)
3373 {
3374 (dp->db_index[i]) &= DB_INDEX_MASK;
3375 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3376 }
3377 }
3378
3379 lowest_marked = 0;
3380 return;
3381}
3382
3383/*
3384 * flush ml_line if necessary
3385 */
3386 static void
3387ml_flush_line(buf)
3388 buf_T *buf;
3389{
3390 bhdr_T *hp;
3391 DATA_BL *dp;
3392 linenr_T lnum;
3393 char_u *new_line;
3394 char_u *old_line;
3395 colnr_T new_len;
3396 int old_len;
3397 int extra;
3398 int idx;
3399 int start;
3400 int count;
3401 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003402 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403
3404 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3405 return; /* nothing to do */
3406
3407 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3408 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003409 /* This code doesn't work recursively, but Netbeans may call back here
3410 * when obtaining the cursor position. */
3411 if (entered)
3412 return;
3413 entered = TRUE;
3414
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 lnum = buf->b_ml.ml_line_lnum;
3416 new_line = buf->b_ml.ml_line_ptr;
3417
3418 hp = ml_find_line(buf, lnum, ML_FIND);
3419 if (hp == NULL)
3420 EMSGN(_("E320: Cannot find line %ld"), lnum);
3421 else
3422 {
3423 dp = (DATA_BL *)(hp->bh_data);
3424 idx = lnum - buf->b_ml.ml_locked_low;
3425 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3426 old_line = (char_u *)dp + start;
3427 if (idx == 0) /* line is last in block */
3428 old_len = dp->db_txt_end - start;
3429 else /* text of previous line follows */
3430 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3431 new_len = (colnr_T)STRLEN(new_line) + 1;
3432 extra = new_len - old_len; /* negative if lines gets smaller */
3433
3434 /*
3435 * if new line fits in data block, replace directly
3436 */
3437 if ((int)dp->db_free >= extra)
3438 {
3439 /* if the length changes and there are following lines */
3440 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3441 if (extra != 0 && idx < count - 1)
3442 {
3443 /* move text of following lines */
3444 mch_memmove((char *)dp + dp->db_txt_start - extra,
3445 (char *)dp + dp->db_txt_start,
3446 (size_t)(start - dp->db_txt_start));
3447
3448 /* adjust pointers of this and following lines */
3449 for (i = idx + 1; i < count; ++i)
3450 dp->db_index[i] -= extra;
3451 }
3452 dp->db_index[idx] -= extra;
3453
3454 /* adjust free space */
3455 dp->db_free -= extra;
3456 dp->db_txt_start -= extra;
3457
3458 /* copy new line into the data block */
3459 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3460 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3461#ifdef FEAT_BYTEOFF
3462 /* The else case is already covered by the insert and delete */
3463 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3464#endif
3465 }
3466 else
3467 {
3468 /*
3469 * Cannot do it in one data block: Delete and append.
3470 * Append first, because ml_delete_int() cannot delete the
3471 * last line in a buffer, which causes trouble for a buffer
3472 * that has only one line.
3473 * Don't forget to copy the mark!
3474 */
3475 /* How about handling errors??? */
3476 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3477 (dp->db_index[idx] & DB_MARKED));
3478 (void)ml_delete_int(buf, lnum, FALSE);
3479 }
3480 }
3481 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003482
3483 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003484 }
3485
3486 buf->b_ml.ml_line_lnum = 0;
3487}
3488
3489/*
3490 * create a new, empty, data block
3491 */
3492 static bhdr_T *
3493ml_new_data(mfp, negative, page_count)
3494 memfile_T *mfp;
3495 int negative;
3496 int page_count;
3497{
3498 bhdr_T *hp;
3499 DATA_BL *dp;
3500
3501 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3502 return NULL;
3503
3504 dp = (DATA_BL *)(hp->bh_data);
3505 dp->db_id = DATA_ID;
3506 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3507 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3508 dp->db_line_count = 0;
3509
3510 return hp;
3511}
3512
3513/*
3514 * create a new, empty, pointer block
3515 */
3516 static bhdr_T *
3517ml_new_ptr(mfp)
3518 memfile_T *mfp;
3519{
3520 bhdr_T *hp;
3521 PTR_BL *pp;
3522
3523 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3524 return NULL;
3525
3526 pp = (PTR_BL *)(hp->bh_data);
3527 pp->pb_id = PTR_ID;
3528 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003529 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3530 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531
3532 return hp;
3533}
3534
3535/*
3536 * lookup line 'lnum' in a memline
3537 *
3538 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3539 * if ML_FLUSH only flush a locked block
3540 * if ML_FIND just find the line
3541 *
3542 * If the block was found it is locked and put in ml_locked.
3543 * The stack is updated to lead to the locked block. The ip_high field in
3544 * the stack is updated to reflect the last line in the block AFTER the
3545 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003546 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 *
3548 * return: NULL for failure, pointer to block header otherwise
3549 */
3550 static bhdr_T *
3551ml_find_line(buf, lnum, action)
3552 buf_T *buf;
3553 linenr_T lnum;
3554 int action;
3555{
3556 DATA_BL *dp;
3557 PTR_BL *pp;
3558 infoptr_T *ip;
3559 bhdr_T *hp;
3560 memfile_T *mfp;
3561 linenr_T t;
3562 blocknr_T bnum, bnum2;
3563 int dirty;
3564 linenr_T low, high;
3565 int top;
3566 int page_count;
3567 int idx;
3568
3569 mfp = buf->b_ml.ml_mfp;
3570
3571 /*
3572 * If there is a locked block check if the wanted line is in it.
3573 * If not, flush and release the locked block.
3574 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3575 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003576 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 */
3578 if (buf->b_ml.ml_locked)
3579 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003580 if (ML_SIMPLE(action)
3581 && buf->b_ml.ml_locked_low <= lnum
3582 && buf->b_ml.ml_locked_high >= lnum
3583 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003585 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586 if (action == ML_INSERT)
3587 {
3588 ++(buf->b_ml.ml_locked_lineadd);
3589 ++(buf->b_ml.ml_locked_high);
3590 }
3591 else if (action == ML_DELETE)
3592 {
3593 --(buf->b_ml.ml_locked_lineadd);
3594 --(buf->b_ml.ml_locked_high);
3595 }
3596 return (buf->b_ml.ml_locked);
3597 }
3598
3599 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3600 buf->b_ml.ml_flags & ML_LOCKED_POS);
3601 buf->b_ml.ml_locked = NULL;
3602
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003603 /*
3604 * If lines have been added or deleted in the locked block, need to
3605 * update the line count in pointer blocks.
3606 */
3607 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3609 }
3610
3611 if (action == ML_FLUSH) /* nothing else to do */
3612 return NULL;
3613
3614 bnum = 1; /* start at the root of the tree */
3615 page_count = 1;
3616 low = 1;
3617 high = buf->b_ml.ml_line_count;
3618
3619 if (action == ML_FIND) /* first try stack entries */
3620 {
3621 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3622 {
3623 ip = &(buf->b_ml.ml_stack[top]);
3624 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3625 {
3626 bnum = ip->ip_bnum;
3627 low = ip->ip_low;
3628 high = ip->ip_high;
3629 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3630 break;
3631 }
3632 }
3633 if (top < 0)
3634 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3635 }
3636 else /* ML_DELETE or ML_INSERT */
3637 buf->b_ml.ml_stack_top = 0; /* start at the root */
3638
3639/*
3640 * search downwards in the tree until a data block is found
3641 */
3642 for (;;)
3643 {
3644 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3645 goto error_noblock;
3646
3647 /*
3648 * update high for insert/delete
3649 */
3650 if (action == ML_INSERT)
3651 ++high;
3652 else if (action == ML_DELETE)
3653 --high;
3654
3655 dp = (DATA_BL *)(hp->bh_data);
3656 if (dp->db_id == DATA_ID) /* data block */
3657 {
3658 buf->b_ml.ml_locked = hp;
3659 buf->b_ml.ml_locked_low = low;
3660 buf->b_ml.ml_locked_high = high;
3661 buf->b_ml.ml_locked_lineadd = 0;
3662 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3663 return hp;
3664 }
3665
3666 pp = (PTR_BL *)(dp); /* must be pointer block */
3667 if (pp->pb_id != PTR_ID)
3668 {
3669 EMSG(_("E317: pointer block id wrong"));
3670 goto error_block;
3671 }
3672
3673 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3674 goto error_block;
3675 ip = &(buf->b_ml.ml_stack[top]);
3676 ip->ip_bnum = bnum;
3677 ip->ip_low = low;
3678 ip->ip_high = high;
3679 ip->ip_index = -1; /* index not known yet */
3680
3681 dirty = FALSE;
3682 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3683 {
3684 t = pp->pb_pointer[idx].pe_line_count;
3685 CHECK(t == 0, _("pe_line_count is zero"));
3686 if ((low += t) > lnum)
3687 {
3688 ip->ip_index = idx;
3689 bnum = pp->pb_pointer[idx].pe_bnum;
3690 page_count = pp->pb_pointer[idx].pe_page_count;
3691 high = low - 1;
3692 low -= t;
3693
3694 /*
3695 * a negative block number may have been changed
3696 */
3697 if (bnum < 0)
3698 {
3699 bnum2 = mf_trans_del(mfp, bnum);
3700 if (bnum != bnum2)
3701 {
3702 bnum = bnum2;
3703 pp->pb_pointer[idx].pe_bnum = bnum;
3704 dirty = TRUE;
3705 }
3706 }
3707
3708 break;
3709 }
3710 }
3711 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3712 {
3713 if (lnum > buf->b_ml.ml_line_count)
3714 EMSGN(_("E322: line number out of range: %ld past the end"),
3715 lnum - buf->b_ml.ml_line_count);
3716
3717 else
3718 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3719 goto error_block;
3720 }
3721 if (action == ML_DELETE)
3722 {
3723 pp->pb_pointer[idx].pe_line_count--;
3724 dirty = TRUE;
3725 }
3726 else if (action == ML_INSERT)
3727 {
3728 pp->pb_pointer[idx].pe_line_count++;
3729 dirty = TRUE;
3730 }
3731 mf_put(mfp, hp, dirty, FALSE);
3732 }
3733
3734error_block:
3735 mf_put(mfp, hp, FALSE, FALSE);
3736error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003737 /*
3738 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3739 * the incremented/decremented line counts, because there won't be a line
3740 * inserted/deleted after all.
3741 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 if (action == ML_DELETE)
3743 ml_lineadd(buf, 1);
3744 else if (action == ML_INSERT)
3745 ml_lineadd(buf, -1);
3746 buf->b_ml.ml_stack_top = 0;
3747 return NULL;
3748}
3749
3750/*
3751 * add an entry to the info pointer stack
3752 *
3753 * return -1 for failure, number of the new entry otherwise
3754 */
3755 static int
3756ml_add_stack(buf)
3757 buf_T *buf;
3758{
3759 int top;
3760 infoptr_T *newstack;
3761
3762 top = buf->b_ml.ml_stack_top;
3763
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003764 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 if (top == buf->b_ml.ml_stack_size)
3766 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003767 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768
3769 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3770 (buf->b_ml.ml_stack_size + STACK_INCR));
3771 if (newstack == NULL)
3772 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003773 mch_memmove(newstack, buf->b_ml.ml_stack,
3774 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 vim_free(buf->b_ml.ml_stack);
3776 buf->b_ml.ml_stack = newstack;
3777 buf->b_ml.ml_stack_size += STACK_INCR;
3778 }
3779
3780 buf->b_ml.ml_stack_top++;
3781 return top;
3782}
3783
3784/*
3785 * Update the pointer blocks on the stack for inserted/deleted lines.
3786 * The stack itself is also updated.
3787 *
3788 * When a insert/delete line action fails, the line is not inserted/deleted,
3789 * but the pointer blocks have already been updated. That is fixed here by
3790 * walking through the stack.
3791 *
3792 * Count is the number of lines added, negative if lines have been deleted.
3793 */
3794 static void
3795ml_lineadd(buf, count)
3796 buf_T *buf;
3797 int count;
3798{
3799 int idx;
3800 infoptr_T *ip;
3801 PTR_BL *pp;
3802 memfile_T *mfp = buf->b_ml.ml_mfp;
3803 bhdr_T *hp;
3804
3805 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3806 {
3807 ip = &(buf->b_ml.ml_stack[idx]);
3808 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3809 break;
3810 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3811 if (pp->pb_id != PTR_ID)
3812 {
3813 mf_put(mfp, hp, FALSE, FALSE);
3814 EMSG(_("E317: pointer block id wrong 2"));
3815 break;
3816 }
3817 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3818 ip->ip_high += count;
3819 mf_put(mfp, hp, TRUE, FALSE);
3820 }
3821}
3822
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003823#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003824/*
3825 * Resolve a symlink in the last component of a file name.
3826 * Note that f_resolve() does it for every part of the path, we don't do that
3827 * here.
3828 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3829 * Otherwise returns FAIL.
3830 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003831 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003832resolve_symlink(fname, buf)
3833 char_u *fname;
3834 char_u *buf;
3835{
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 *
3908makeswapname(fname, ffname, buf, dir_name)
3909 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003910 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 buf_T *buf;
3912 char_u *dir_name;
3913{
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 */
3921 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003922 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 { /* Ends with '//', Use Full path */
3924 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003925 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 {
3927 r = modname(s, (char_u *)".swp", FALSE);
3928 vim_free(s);
3929 }
3930 return r;
3931 }
3932#endif
3933
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003934#ifdef HAVE_READLINK
3935 /* Expand symlink in the file name, so that we put the swap file with the
3936 * actual file instead of with the symlink. */
3937 if (resolve_symlink(fname, fname_buf) == OK)
3938 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003939#endif
3940
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941 r = buf_modname(
3942#ifdef SHORT_FNAME
3943 TRUE,
3944#else
3945 (buf->b_p_sn || buf->b_shortname),
3946#endif
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003947 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 (char_u *)
Bram Moolenaare60acc12011-05-10 16:41:25 +02003949#if defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 "_swp",
3951#else
3952 ".swp",
3953#endif
3954#ifdef SHORT_FNAME /* always 8.3 file name */
3955 FALSE
3956#else
3957 /* Prepend a '.' to the swap file name for the current directory. */
3958 dir_name[0] == '.' && dir_name[1] == NUL
3959#endif
3960 );
3961 if (r == NULL) /* out of memory */
3962 return NULL;
3963
3964 s = get_file_in_dir(r, dir_name);
3965 vim_free(r);
3966 return s;
3967}
3968
3969/*
3970 * Get file name to use for swap file or backup file.
3971 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3972 * option "dname".
3973 * - If "dname" is ".", return "fname" (swap file in dir of file).
3974 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3975 * relative to dir of file).
3976 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
3977 * dir).
3978 *
3979 * The return value is an allocated string and can be NULL.
3980 */
3981 char_u *
3982get_file_in_dir(fname, dname)
3983 char_u *fname;
3984 char_u *dname; /* don't use "dirname", it is a global for Alpha */
3985{
3986 char_u *t;
3987 char_u *tail;
3988 char_u *retval;
3989 int save_char;
3990
3991 tail = gettail(fname);
3992
3993 if (dname[0] == '.' && dname[1] == NUL)
3994 retval = vim_strsave(fname);
3995 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
3996 {
3997 if (tail == fname) /* no path before file name */
3998 retval = concat_fnames(dname + 2, tail, TRUE);
3999 else
4000 {
4001 save_char = *tail;
4002 *tail = NUL;
4003 t = concat_fnames(fname, dname + 2, TRUE);
4004 *tail = save_char;
4005 if (t == NULL) /* out of memory */
4006 retval = NULL;
4007 else
4008 {
4009 retval = concat_fnames(t, tail, TRUE);
4010 vim_free(t);
4011 }
4012 }
4013 }
4014 else
4015 retval = concat_fnames(dname, tail, TRUE);
4016
Bram Moolenaar69c35002013-11-04 02:54:12 +01004017#ifdef WIN3264
4018 if (retval != NULL)
4019 for (t = gettail(retval); *t != NUL; mb_ptr_adv(t))
4020 if (*t == ':')
4021 *t = '%';
4022#endif
4023
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024 return retval;
4025}
4026
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004027static void attention_message __ARGS((buf_T *buf, char_u *fname));
4028
4029/*
4030 * Print the ATTENTION message: info about an existing swap file.
4031 */
4032 static void
4033attention_message(buf, fname)
4034 buf_T *buf; /* buffer being edited */
4035 char_u *fname; /* swap file name */
4036{
4037 struct stat st;
4038 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004039 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004040
4041 ++no_wait_return;
4042 (void)EMSG(_("E325: ATTENTION"));
4043 MSG_PUTS(_("\nFound a swap file by the name \""));
4044 msg_home_replace(fname);
4045 MSG_PUTS("\"\n");
4046 sx = swapfile_info(fname);
4047 MSG_PUTS(_("While opening file \""));
4048 msg_outtrans(buf->b_fname);
4049 MSG_PUTS("\"\n");
4050 if (mch_stat((char *)buf->b_fname, &st) != -1)
4051 {
4052 MSG_PUTS(_(" dated: "));
4053 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004054 p = ctime(&x); /* includes '\n' */
4055 if (p == NULL)
4056 MSG_PUTS("(invalid)\n");
4057 else
4058 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004059 if (sx != 0 && x > sx)
4060 MSG_PUTS(_(" NEWER than swap file!\n"));
4061 }
4062 /* Some of these messages are long to allow translation to
4063 * other languages. */
Bram Moolenaarc41fc712011-02-15 11:57:04 +01004064 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."));
4065 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4066 MSG_PUTS(_("(2) An edit session for this file crashed.\n"));
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004067 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4068 msg_outtrans(buf->b_fname);
4069 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4070 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4071 msg_outtrans(fname);
4072 MSG_PUTS(_("\"\n to avoid this message.\n"));
4073 cmdline_row = msg_row;
4074 --no_wait_return;
4075}
4076
4077#ifdef FEAT_AUTOCMD
4078static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4079
4080/*
4081 * Trigger the SwapExists autocommands.
4082 * Returns a value for equivalent to do_dialog() (see below):
4083 * 0: still need to ask for a choice
4084 * 1: open read-only
4085 * 2: edit anyway
4086 * 3: recover
4087 * 4: delete it
4088 * 5: quit
4089 * 6: abort
4090 */
4091 static int
4092do_swapexists(buf, fname)
4093 buf_T *buf;
4094 char_u *fname;
4095{
4096 set_vim_var_string(VV_SWAPNAME, fname, -1);
4097 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4098
4099 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004100 * edited. Disallow changing directory here. */
4101 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004102 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004103 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004104
4105 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4106
4107 switch (*get_vim_var_str(VV_SWAPCHOICE))
4108 {
4109 case 'o': return 1;
4110 case 'e': return 2;
4111 case 'r': return 3;
4112 case 'd': return 4;
4113 case 'q': return 5;
4114 case 'a': return 6;
4115 }
4116
4117 return 0;
4118}
4119#endif
4120
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121/*
4122 * Find out what name to use for the swap file for buffer 'buf'.
4123 *
4124 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004125 * Returns the name in allocated memory or NULL.
Bram Moolenaarf541c362011-10-26 11:44:18 +02004126 * When out of memory "dirp" is set to NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 *
4128 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004129 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004130 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 */
4132 static char_u *
4133findswapname(buf, dirp, old_fname)
4134 buf_T *buf;
4135 char_u **dirp; /* pointer to list of directories */
4136 char_u *old_fname; /* don't give warning for this file name */
4137{
4138 char_u *fname;
4139 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 char_u *dir_name;
4141#ifdef AMIGA
4142 BPTR fh;
4143#endif
4144#ifndef SHORT_FNAME
4145 int r;
4146#endif
Bram Moolenaar69c35002013-11-04 02:54:12 +01004147 char_u *buf_fname = buf->b_fname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148
4149#if !defined(SHORT_FNAME) \
Bram Moolenaar69c35002013-11-04 02:54:12 +01004150 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151# define CREATE_DUMMY_FILE
4152 FILE *dummyfd = NULL;
4153
Bram Moolenaar69c35002013-11-04 02:54:12 +01004154# ifdef WIN3264
4155 if (buf_fname != NULL && !mch_isFullName(buf_fname)
4156 && vim_strchr(gettail(buf_fname), ':'))
4157 {
4158 char_u *t;
4159
4160 buf_fname = vim_strsave(buf_fname);
4161 if (buf_fname == NULL)
4162 buf_fname = buf->b_fname;
4163 else
4164 for (t = gettail(buf_fname); *t != NUL; mb_ptr_adv(t))
4165 if (*t == ':')
4166 *t = '%';
4167 }
4168# endif
4169
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004170 /*
4171 * If we start editing a new file, e.g. "test.doc", which resides on an
4172 * MSDOS compatible filesystem, it is possible that the file
4173 * "test.doc.swp" which we create will be exactly the same file. To avoid
4174 * this problem we temporarily create "test.doc". Don't do this when the
4175 * check below for a 8.3 file name is used.
4176 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004177 if (!(buf->b_p_sn || buf->b_shortname) && buf_fname != NULL
4178 && mch_getperm(buf_fname) < 0)
4179 dummyfd = mch_fopen((char *)buf_fname, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180#endif
4181
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004182 /*
4183 * Isolate a directory name from *dirp and put it in dir_name.
4184 * First allocate some memory to put the directory name in.
4185 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
Bram Moolenaarf541c362011-10-26 11:44:18 +02004187 if (dir_name == NULL)
4188 *dirp = NULL;
4189 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 (void)copy_option_part(dirp, dir_name, 31000, ",");
4191
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004192 /*
4193 * we try different names until we find one that does not exist yet
4194 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195 if (dir_name == NULL) /* out of memory */
4196 fname = NULL;
4197 else
Bram Moolenaar69c35002013-11-04 02:54:12 +01004198 fname = makeswapname(buf_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199
4200 for (;;)
4201 {
4202 if (fname == NULL) /* must be out of memory */
4203 break;
4204 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4205 {
4206 vim_free(fname);
4207 fname = NULL;
4208 break;
4209 }
4210#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4211/*
4212 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4213 * file names. If this is the first try and the swap file name does not fit in
4214 * 8.3, detect if this is the case, set shortname and try again.
4215 */
4216 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4217 && !(buf->b_p_sn || buf->b_shortname))
4218 {
4219 char_u *tail;
4220 char_u *fname2;
4221 struct stat s1, s2;
4222 int f1, f2;
4223 int created1 = FALSE, created2 = FALSE;
4224 int same = FALSE;
4225
4226 /*
4227 * Check if swapfile name does not fit in 8.3:
4228 * It either contains two dots, is longer than 8 chars, or starts
4229 * with a dot.
4230 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004231 tail = gettail(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232 if ( vim_strchr(tail, '.') != NULL
4233 || STRLEN(tail) > (size_t)8
4234 || *gettail(fname) == '.')
4235 {
4236 fname2 = alloc(n + 2);
4237 if (fname2 != NULL)
4238 {
4239 STRCPY(fname2, fname);
4240 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4241 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4242 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4243 */
4244 if (vim_strchr(tail, '.') != NULL)
4245 fname2[n - 1] = 'x';
4246 else if (*gettail(fname) == '.')
4247 {
4248 fname2[n] = 'x';
4249 fname2[n + 1] = NUL;
4250 }
4251 else
4252 fname2[n - 5] += 1;
4253 /*
4254 * may need to create the files to be able to use mch_stat()
4255 */
4256 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4257 if (f1 < 0)
4258 {
4259 f1 = mch_open_rw((char *)fname,
4260 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4261#if defined(OS2)
4262 if (f1 < 0 && errno == ENOENT)
4263 same = TRUE;
4264#endif
4265 created1 = TRUE;
4266 }
4267 if (f1 >= 0)
4268 {
4269 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4270 if (f2 < 0)
4271 {
4272 f2 = mch_open_rw((char *)fname2,
4273 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4274 created2 = TRUE;
4275 }
4276 if (f2 >= 0)
4277 {
4278 /*
4279 * Both files exist now. If mch_stat() returns the
4280 * same device and inode they are the same file.
4281 */
4282 if (mch_fstat(f1, &s1) != -1
4283 && mch_fstat(f2, &s2) != -1
4284 && s1.st_dev == s2.st_dev
4285 && s1.st_ino == s2.st_ino)
4286 same = TRUE;
4287 close(f2);
4288 if (created2)
4289 mch_remove(fname2);
4290 }
4291 close(f1);
4292 if (created1)
4293 mch_remove(fname);
4294 }
4295 vim_free(fname2);
4296 if (same)
4297 {
4298 buf->b_shortname = TRUE;
4299 vim_free(fname);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004300 fname = makeswapname(buf_fname, buf->b_ffname,
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004301 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 continue; /* try again with b_shortname set */
4303 }
4304 }
4305 }
4306 }
4307#endif
4308 /*
4309 * check if the swapfile already exists
4310 */
4311 if (mch_getperm(fname) < 0) /* it does not exist */
4312 {
4313#ifdef HAVE_LSTAT
4314 struct stat sb;
4315
4316 /*
4317 * Extra security check: When a swap file is a symbolic link, this
4318 * is most likely a symlink attack.
4319 */
4320 if (mch_lstat((char *)fname, &sb) < 0)
4321#else
4322# ifdef AMIGA
4323 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4324 /*
4325 * on the Amiga mch_getperm() will return -1 when the file exists
4326 * but is being used by another program. This happens if you edit
4327 * a file twice.
4328 */
4329 if (fh != (BPTR)NULL) /* can open file, OK */
4330 {
4331 Close(fh);
4332 mch_remove(fname);
4333 break;
4334 }
4335 if (IoErr() != ERROR_OBJECT_IN_USE
4336 && IoErr() != ERROR_OBJECT_EXISTS)
4337# endif
4338#endif
4339 break;
4340 }
4341
4342 /*
4343 * A file name equal to old_fname is OK to use.
4344 */
4345 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4346 break;
4347
4348 /*
4349 * get here when file already exists
4350 */
4351 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4352 {
4353#ifndef SHORT_FNAME
4354 /*
4355 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4356 * and file.doc are the same file. To guess if this problem is
4357 * present try if file.doc.swx exists. If it does, we set
4358 * buf->b_shortname and try file_doc.swp (dots replaced by
4359 * underscores for this file), and try again. If it doesn't we
4360 * assume that "file.doc.swp" already exists.
4361 */
4362 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4363 {
4364 fname[n - 1] = 'x';
4365 r = mch_getperm(fname); /* try "file.swx" */
4366 fname[n - 1] = 'p';
4367 if (r >= 0) /* "file.swx" seems to exist */
4368 {
4369 buf->b_shortname = TRUE;
4370 vim_free(fname);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004371 fname = makeswapname(buf_fname, buf->b_ffname,
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004372 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004373 continue; /* try again with '.' replaced with '_' */
4374 }
4375 }
4376#endif
4377 /*
4378 * If we get here the ".swp" file really exists.
4379 * Give an error message, unless recovering, no file name, we are
4380 * viewing a help file or when the path of the file is different
4381 * (happens when all .swp files are in one directory).
4382 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004383 if (!recoverymode && buf_fname != NULL
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004384 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004385 {
4386 int fd;
4387 struct block0 b0;
4388 int differ = FALSE;
4389
4390 /*
4391 * Try to read block 0 from the swap file to get the original
4392 * file name (and inode number).
4393 */
4394 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4395 if (fd >= 0)
4396 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004397 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398 {
4399 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004400 * If the swapfile has the same directory as the
4401 * buffer don't compare the directory names, they can
4402 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004404 if (b0.b0_flags & B0_SAME_DIR)
4405 {
4406 if (fnamecmp(gettail(buf->b_ffname),
4407 gettail(b0.b0_fname)) != 0
4408 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004409 {
4410#ifdef CHECK_INODE
4411 /* Symlinks may point to the same file even
4412 * when the name differs, need to check the
4413 * inode too. */
4414 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4415 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4416 char_to_long(b0.b0_ino)))
4417#endif
4418 differ = TRUE;
4419 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004420 }
4421 else
4422 {
4423 /*
4424 * The name in the swap file may be
4425 * "~user/path/file". Expand it first.
4426 */
4427 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004429 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004430 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004431 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004433 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4434 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 }
4438 close(fd);
4439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440
4441 /* give the ATTENTION message when there is an old swap file
4442 * for the current file, and the buffer was not recovered. */
4443 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4444 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4445 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004446#if defined(HAS_SWAP_EXISTS_ACTION)
4447 int choice = 0;
4448#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449#ifdef CREATE_DUMMY_FILE
4450 int did_use_dummy = FALSE;
4451
4452 /* Avoid getting a warning for the file being created
4453 * outside of Vim, it was created at the start of this
4454 * function. Delete the file now, because Vim might exit
4455 * here if the window is closed. */
4456 if (dummyfd != NULL)
4457 {
4458 fclose(dummyfd);
4459 dummyfd = NULL;
Bram Moolenaar69c35002013-11-04 02:54:12 +01004460 mch_remove(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 did_use_dummy = TRUE;
4462 }
4463#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464
4465#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4466 process_still_running = FALSE;
4467#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004468#ifdef FEAT_AUTOCMD
4469 /*
4470 * If there is an SwapExists autocommand and we can handle
4471 * the response, trigger it. It may return 0 to ask the
4472 * user anyway.
4473 */
4474 if (swap_exists_action != SEA_NONE
Bram Moolenaar69c35002013-11-04 02:54:12 +01004475 && has_autocmd(EVENT_SWAPEXISTS, buf_fname, buf))
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004476 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004478 if (choice == 0)
4479#endif
4480 {
4481#ifdef FEAT_GUI
4482 /* If we are supposed to start the GUI but it wasn't
4483 * completely started yet, start it now. This makes
4484 * the messages displayed in the Vim window when
4485 * loading a session from the .gvimrc file. */
4486 if (gui.starting && !gui.in_use)
4487 gui_start();
4488#endif
4489 /* Show info about the existing swap file. */
4490 attention_message(buf, fname);
4491
4492 /* We don't want a 'q' typed at the more-prompt
4493 * interrupt loading a file. */
4494 got_int = FALSE;
4495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496
4497#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004498 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499 {
4500 char_u *name;
4501
4502 name = alloc((unsigned)(STRLEN(fname)
4503 + STRLEN(_("Swap file \""))
4504 + STRLEN(_("\" already exists!")) + 5));
4505 if (name != NULL)
4506 {
4507 STRCPY(name, _("Swap file \""));
4508 home_replace(NULL, fname, name + STRLEN(name),
4509 1000, TRUE);
4510 STRCAT(name, _("\" already exists!"));
4511 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004512 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513 (char_u *)_("VIM - ATTENTION"),
4514 name == NULL
4515 ? (char_u *)_("Swap file already exists!")
4516 : name,
4517# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4518 process_still_running
4519 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4520# endif
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004521 (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 +00004522
4523# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4524 if (process_still_running && choice >= 4)
4525 choice++; /* Skip missing "Delete it" button */
4526# endif
4527 vim_free(name);
4528
4529 /* pretend screen didn't scroll, need redraw anyway */
4530 msg_scrolled = 0;
4531 redraw_all_later(NOT_VALID);
4532 }
4533#endif
4534
4535#if defined(HAS_SWAP_EXISTS_ACTION)
4536 if (choice > 0)
4537 {
4538 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 {
4540 case 1:
4541 buf->b_p_ro = TRUE;
4542 break;
4543 case 2:
4544 break;
4545 case 3:
4546 swap_exists_action = SEA_RECOVER;
4547 break;
4548 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004549 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 break;
4551 case 5:
4552 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 break;
4554 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004555 swap_exists_action = SEA_QUIT;
4556 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 break;
4558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004559
4560 /* If the file was deleted this fname can be used. */
4561 if (mch_getperm(fname) < 0)
4562 break;
4563 }
4564 else
4565#endif
4566 {
4567 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004568 if (msg_silent == 0)
4569 /* call wait_return() later */
4570 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 }
4572
4573#ifdef CREATE_DUMMY_FILE
4574 /* Going to try another name, need the dummy file again. */
4575 if (did_use_dummy)
Bram Moolenaar69c35002013-11-04 02:54:12 +01004576 dummyfd = mch_fopen((char *)buf_fname, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577#endif
4578 }
4579 }
4580 }
4581
4582 /*
4583 * Change the ".swp" extension to find another file that can be used.
4584 * First decrement the last char: ".swo", ".swn", etc.
4585 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004586 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 */
4588 if (fname[n - 1] == 'a') /* ".s?a" */
4589 {
4590 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4591 {
4592 EMSG(_("E326: Too many swap files found"));
4593 vim_free(fname);
4594 fname = NULL;
4595 break;
4596 }
4597 --fname[n - 2]; /* ".svz", ".suz", etc. */
4598 fname[n - 1] = 'z' + 1;
4599 }
4600 --fname[n - 1]; /* ".swo", ".swn", etc. */
4601 }
4602
4603 vim_free(dir_name);
4604#ifdef CREATE_DUMMY_FILE
4605 if (dummyfd != NULL) /* file has been created temporarily */
4606 {
4607 fclose(dummyfd);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004608 mch_remove(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609 }
4610#endif
Bram Moolenaar69c35002013-11-04 02:54:12 +01004611#ifdef WIN3264
4612 if (buf_fname != buf->b_fname)
4613 vim_free(buf_fname);
4614#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 return fname;
4616}
4617
4618 static int
4619b0_magic_wrong(b0p)
4620 ZERO_BL *b0p;
4621{
4622 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4623 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4624 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4625 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4626}
4627
4628#ifdef CHECK_INODE
4629/*
4630 * Compare current file name with file name from swap file.
4631 * Try to use inode numbers when possible.
4632 * Return non-zero when files are different.
4633 *
4634 * When comparing file names a few things have to be taken into consideration:
4635 * - When working over a network the full path of a file depends on the host.
4636 * We check the inode number if possible. It is not 100% reliable though,
4637 * because the device number cannot be used over a network.
4638 * - When a file does not exist yet (editing a new file) there is no inode
4639 * number.
4640 * - The file name in a swap file may not be valid on the current host. The
4641 * "~user" form is used whenever possible to avoid this.
4642 *
4643 * This is getting complicated, let's make a table:
4644 *
4645 * ino_c ino_s fname_c fname_s differ =
4646 *
4647 * both files exist -> compare inode numbers:
4648 * != 0 != 0 X X ino_c != ino_s
4649 *
4650 * inode number(s) unknown, file names available -> compare file names
4651 * == 0 X OK OK fname_c != fname_s
4652 * X == 0 OK OK fname_c != fname_s
4653 *
4654 * current file doesn't exist, file for swap file exist, file name(s) not
4655 * available -> probably different
4656 * == 0 != 0 FAIL X TRUE
4657 * == 0 != 0 X FAIL TRUE
4658 *
4659 * current file exists, inode for swap unknown, file name(s) not
4660 * available -> probably different
4661 * != 0 == 0 FAIL X TRUE
4662 * != 0 == 0 X FAIL TRUE
4663 *
4664 * current file doesn't exist, inode for swap unknown, one file name not
4665 * available -> probably different
4666 * == 0 == 0 FAIL OK TRUE
4667 * == 0 == 0 OK FAIL TRUE
4668 *
4669 * current file doesn't exist, inode for swap unknown, both file names not
4670 * available -> probably same file
4671 * == 0 == 0 FAIL FAIL FALSE
4672 *
4673 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4674 * can't be changed without making the block 0 incompatible with 32 bit
4675 * versions.
4676 */
4677
4678 static int
4679fnamecmp_ino(fname_c, fname_s, ino_block0)
4680 char_u *fname_c; /* current file name */
4681 char_u *fname_s; /* file name from swap file */
4682 long ino_block0;
4683{
4684 struct stat st;
4685 ino_t ino_c = 0; /* ino of current file */
4686 ino_t ino_s; /* ino of file from swap file */
4687 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4688 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4689 int retval_c; /* flag: buf_c valid */
4690 int retval_s; /* flag: buf_s valid */
4691
4692 if (mch_stat((char *)fname_c, &st) == 0)
4693 ino_c = (ino_t)st.st_ino;
4694
4695 /*
4696 * First we try to get the inode from the file name, because the inode in
4697 * the swap file may be outdated. If that fails (e.g. this path is not
4698 * valid on this machine), use the inode from block 0.
4699 */
4700 if (mch_stat((char *)fname_s, &st) == 0)
4701 ino_s = (ino_t)st.st_ino;
4702 else
4703 ino_s = (ino_t)ino_block0;
4704
4705 if (ino_c && ino_s)
4706 return (ino_c != ino_s);
4707
4708 /*
4709 * One of the inode numbers is unknown, try a forced vim_FullName() and
4710 * compare the file names.
4711 */
4712 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4713 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4714 if (retval_c == OK && retval_s == OK)
4715 return (STRCMP(buf_c, buf_s) != 0);
4716
4717 /*
4718 * Can't compare inodes or file names, guess that the files are different,
4719 * unless both appear not to exist at all.
4720 */
4721 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4722 return FALSE;
4723 return TRUE;
4724}
4725#endif /* CHECK_INODE */
4726
4727/*
4728 * Move a long integer into a four byte character array.
4729 * Used for machine independency in block zero.
4730 */
4731 static void
4732long_to_char(n, s)
4733 long n;
4734 char_u *s;
4735{
4736 s[0] = (char_u)(n & 0xff);
4737 n = (unsigned)n >> 8;
4738 s[1] = (char_u)(n & 0xff);
4739 n = (unsigned)n >> 8;
4740 s[2] = (char_u)(n & 0xff);
4741 n = (unsigned)n >> 8;
4742 s[3] = (char_u)(n & 0xff);
4743}
4744
4745 static long
4746char_to_long(s)
4747 char_u *s;
4748{
4749 long retval;
4750
4751 retval = s[3];
4752 retval <<= 8;
4753 retval |= s[2];
4754 retval <<= 8;
4755 retval |= s[1];
4756 retval <<= 8;
4757 retval |= s[0];
4758
4759 return retval;
4760}
4761
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004762/*
4763 * Set the flags in the first block of the swap file:
4764 * - file is modified or not: buf->b_changed
4765 * - 'fileformat'
4766 * - 'fileencoding'
4767 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004769ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771{
4772 bhdr_T *hp;
4773 ZERO_BL *b0p;
4774
4775 if (!buf->b_ml.ml_mfp)
4776 return;
4777 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4778 {
4779 if (hp->bh_bnum == 0)
4780 {
4781 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004782 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4783 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4784 | (get_fileformat(buf) + 1);
4785#ifdef FEAT_MBYTE
4786 add_b0_fenc(b0p, buf);
4787#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 hp->bh_flags |= BH_DIRTY;
4789 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4790 break;
4791 }
4792 }
4793}
4794
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004795#if defined(FEAT_CRYPT) || defined(PROTO)
4796/*
4797 * If "data" points to a data block encrypt the text in it and return a copy
4798 * in allocated memory. Return NULL when out of memory.
4799 * Otherwise return "data".
4800 */
4801 char_u *
4802ml_encrypt_data(mfp, data, offset, size)
4803 memfile_T *mfp;
4804 char_u *data;
4805 off_t offset;
4806 unsigned size;
4807{
4808 DATA_BL *dp = (DATA_BL *)data;
4809 char_u *head_end;
4810 char_u *text_start;
4811 char_u *new_data;
4812 int text_len;
4813
4814 if (dp->db_id != DATA_ID)
4815 return data;
4816
4817 new_data = (char_u *)alloc(size);
4818 if (new_data == NULL)
4819 return NULL;
4820 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4821 text_start = (char_u *)dp + dp->db_txt_start;
4822 text_len = size - dp->db_txt_start;
4823
4824 /* Copy the header and the text. */
4825 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4826
4827 /* Encrypt the text. */
4828 crypt_push_state();
4829 ml_crypt_prepare(mfp, offset, FALSE);
4830 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4831 crypt_pop_state();
4832
4833 /* Clear the gap. */
4834 if (head_end < text_start)
4835 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4836
4837 return new_data;
4838}
4839
4840/*
4841 * Decrypt the text in "data" if it points to a data block.
4842 */
4843 void
4844ml_decrypt_data(mfp, data, offset, size)
4845 memfile_T *mfp;
4846 char_u *data;
4847 off_t offset;
4848 unsigned size;
4849{
4850 DATA_BL *dp = (DATA_BL *)data;
4851 char_u *head_end;
4852 char_u *text_start;
4853 int text_len;
4854
4855 if (dp->db_id == DATA_ID)
4856 {
4857 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4858 text_start = (char_u *)dp + dp->db_txt_start;
4859 text_len = dp->db_txt_end - dp->db_txt_start;
4860
4861 if (head_end > text_start || dp->db_txt_start > size
4862 || dp->db_txt_end > size)
4863 return; /* data was messed up */
4864
4865 /* Decrypt the text in place. */
4866 crypt_push_state();
4867 ml_crypt_prepare(mfp, offset, TRUE);
4868 crypt_decode(text_start, text_len);
4869 crypt_pop_state();
4870 }
4871}
4872
4873/*
4874 * Prepare for encryption/decryption, using the key, seed and offset.
4875 */
4876 static void
4877ml_crypt_prepare(mfp, offset, reading)
4878 memfile_T *mfp;
4879 off_t offset;
4880 int reading;
4881{
4882 buf_T *buf = mfp->mf_buffer;
4883 char_u salt[50];
4884 int method;
4885 char_u *key;
4886 char_u *seed;
4887
4888 if (reading && mfp->mf_old_key != NULL)
4889 {
4890 /* Reading back blocks with the previous key/method/seed. */
4891 method = mfp->mf_old_cm;
4892 key = mfp->mf_old_key;
4893 seed = mfp->mf_old_seed;
4894 }
4895 else
4896 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02004897 method = get_crypt_method(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004898 key = buf->b_p_key;
4899 seed = mfp->mf_seed;
4900 }
4901
4902 use_crypt_method = method; /* select pkzip or blowfish */
4903 if (method == 0)
4904 {
4905 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4906 crypt_init_keys(salt);
4907 }
4908 else
4909 {
4910 /* Using blowfish, add salt and seed. We use the byte offset of the
4911 * block for the salt. */
4912 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004913 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004914 bf_ofb_init(seed, MF_SEED_LEN);
4915 }
4916}
4917
4918#endif
4919
4920
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921#if defined(FEAT_BYTEOFF) || defined(PROTO)
4922
4923#define MLCS_MAXL 800 /* max no of lines in chunk */
4924#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4925
4926/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004927 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4929 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4930 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4931 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4932 */
4933 static void
4934ml_updatechunk(buf, line, len, updtype)
4935 buf_T *buf;
4936 linenr_T line;
4937 long len;
4938 int updtype;
4939{
4940 static buf_T *ml_upd_lastbuf = NULL;
4941 static linenr_T ml_upd_lastline;
4942 static linenr_T ml_upd_lastcurline;
4943 static int ml_upd_lastcurix;
4944
4945 linenr_T curline = ml_upd_lastcurline;
4946 int curix = ml_upd_lastcurix;
4947 long size;
4948 chunksize_T *curchnk;
4949 int rest;
4950 bhdr_T *hp;
4951 DATA_BL *dp;
4952
4953 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4954 return;
4955 if (buf->b_ml.ml_chunksize == NULL)
4956 {
4957 buf->b_ml.ml_chunksize = (chunksize_T *)
4958 alloc((unsigned)sizeof(chunksize_T) * 100);
4959 if (buf->b_ml.ml_chunksize == NULL)
4960 {
4961 buf->b_ml.ml_usedchunks = -1;
4962 return;
4963 }
4964 buf->b_ml.ml_numchunks = 100;
4965 buf->b_ml.ml_usedchunks = 1;
4966 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4967 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4968 }
4969
4970 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4971 {
4972 /*
4973 * First line in empty buffer from ml_flush_line() -- reset
4974 */
4975 buf->b_ml.ml_usedchunks = 1;
4976 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4977 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4978 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4979 return;
4980 }
4981
4982 /*
4983 * Find chunk that our line belongs to, curline will be at start of the
4984 * chunk.
4985 */
4986 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4987 || updtype != ML_CHNK_ADDLINE)
4988 {
4989 for (curline = 1, curix = 0;
4990 curix < buf->b_ml.ml_usedchunks - 1
4991 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4992 curix++)
4993 {
4994 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4995 }
4996 }
4997 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
4998 && curix < buf->b_ml.ml_usedchunks - 1)
4999 {
5000 /* Adjust cached curix & curline */
5001 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5002 curix++;
5003 }
5004 curchnk = buf->b_ml.ml_chunksize + curix;
5005
5006 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00005007 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 curchnk->mlcs_totalsize += len;
5009 if (updtype == ML_CHNK_ADDLINE)
5010 {
5011 curchnk->mlcs_numlines++;
5012
5013 /* May resize here so we don't have to do it in both cases below */
5014 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5015 {
5016 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5017 buf->b_ml.ml_chunksize = (chunksize_T *)
5018 vim_realloc(buf->b_ml.ml_chunksize,
5019 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5020 if (buf->b_ml.ml_chunksize == NULL)
5021 {
5022 /* Hmmmm, Give up on offset for this buffer */
5023 buf->b_ml.ml_usedchunks = -1;
5024 return;
5025 }
5026 }
5027
5028 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5029 {
5030 int count; /* number of entries in block */
5031 int idx;
5032 int text_end;
5033 int linecnt;
5034
5035 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5036 buf->b_ml.ml_chunksize + curix,
5037 (buf->b_ml.ml_usedchunks - curix) *
5038 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005039 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 size = 0;
5041 linecnt = 0;
5042 while (curline < buf->b_ml.ml_line_count
5043 && linecnt < MLCS_MINL)
5044 {
5045 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5046 {
5047 buf->b_ml.ml_usedchunks = -1;
5048 return;
5049 }
5050 dp = (DATA_BL *)(hp->bh_data);
5051 count = (long)(buf->b_ml.ml_locked_high) -
5052 (long)(buf->b_ml.ml_locked_low) + 1;
5053 idx = curline - buf->b_ml.ml_locked_low;
5054 curline = buf->b_ml.ml_locked_high + 1;
5055 if (idx == 0)/* first line in block, text at the end */
5056 text_end = dp->db_txt_end;
5057 else
5058 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5059 /* Compute index of last line to use in this MEMLINE */
5060 rest = count - idx;
5061 if (linecnt + rest > MLCS_MINL)
5062 {
5063 idx += MLCS_MINL - linecnt - 1;
5064 linecnt = MLCS_MINL;
5065 }
5066 else
5067 {
5068 idx = count - 1;
5069 linecnt += rest;
5070 }
5071 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5072 }
5073 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5074 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5075 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5076 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5077 buf->b_ml.ml_usedchunks++;
5078 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5079 return;
5080 }
5081 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5082 && curix == buf->b_ml.ml_usedchunks - 1
5083 && buf->b_ml.ml_line_count - line <= 1)
5084 {
5085 /*
5086 * We are in the last chunk and it is cheap to crate a new one
5087 * after this. Do it now to avoid the loop above later on
5088 */
5089 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5090 buf->b_ml.ml_usedchunks++;
5091 if (line == buf->b_ml.ml_line_count)
5092 {
5093 curchnk->mlcs_numlines = 0;
5094 curchnk->mlcs_totalsize = 0;
5095 }
5096 else
5097 {
5098 /*
5099 * Line is just prior to last, move count for last
5100 * This is the common case when loading a new file
5101 */
5102 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5103 if (hp == NULL)
5104 {
5105 buf->b_ml.ml_usedchunks = -1;
5106 return;
5107 }
5108 dp = (DATA_BL *)(hp->bh_data);
5109 if (dp->db_line_count == 1)
5110 rest = dp->db_txt_end - dp->db_txt_start;
5111 else
5112 rest =
5113 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5114 - dp->db_txt_start;
5115 curchnk->mlcs_totalsize = rest;
5116 curchnk->mlcs_numlines = 1;
5117 curchnk[-1].mlcs_totalsize -= rest;
5118 curchnk[-1].mlcs_numlines -= 1;
5119 }
5120 }
5121 }
5122 else if (updtype == ML_CHNK_DELLINE)
5123 {
5124 curchnk->mlcs_numlines--;
5125 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5126 if (curix < (buf->b_ml.ml_usedchunks - 1)
5127 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5128 <= MLCS_MINL)
5129 {
5130 curix++;
5131 curchnk = buf->b_ml.ml_chunksize + curix;
5132 }
5133 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5134 {
5135 buf->b_ml.ml_usedchunks--;
5136 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5137 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5138 return;
5139 }
5140 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5141 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5142 > MLCS_MINL))
5143 {
5144 return;
5145 }
5146
5147 /* Collapse chunks */
5148 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5149 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5150 buf->b_ml.ml_usedchunks--;
5151 if (curix < buf->b_ml.ml_usedchunks)
5152 {
5153 mch_memmove(buf->b_ml.ml_chunksize + curix,
5154 buf->b_ml.ml_chunksize + curix + 1,
5155 (buf->b_ml.ml_usedchunks - curix) *
5156 sizeof(chunksize_T));
5157 }
5158 return;
5159 }
5160 ml_upd_lastbuf = buf;
5161 ml_upd_lastline = line;
5162 ml_upd_lastcurline = curline;
5163 ml_upd_lastcurix = curix;
5164}
5165
5166/*
5167 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005168 * Find line with offset if "lnum" is 0; return remaining offset in offp
5169 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005170 * return -1 if information is not available
5171 */
5172 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005173ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005175 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 long *offp;
5177{
5178 linenr_T curline;
5179 int curix;
5180 long size;
5181 bhdr_T *hp;
5182 DATA_BL *dp;
5183 int count; /* number of entries in block */
5184 int idx;
5185 int start_idx;
5186 int text_end;
5187 long offset;
5188 int len;
5189 int ffdos = (get_fileformat(buf) == EOL_DOS);
5190 int extra = 0;
5191
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005192 /* take care of cached line first */
5193 ml_flush_line(curbuf);
5194
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 if (buf->b_ml.ml_usedchunks == -1
5196 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005197 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 return -1;
5199
5200 if (offp == NULL)
5201 offset = 0;
5202 else
5203 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005204 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5206 /*
5207 * Find the last chunk before the one containing our line. Last chunk is
5208 * special because it will never qualify
5209 */
5210 curline = 1;
5211 curix = size = 0;
5212 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005213 && ((lnum != 0
5214 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 || (offset != 0
5216 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5217 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5218 {
5219 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5220 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5221 if (offset && ffdos)
5222 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5223 curix++;
5224 }
5225
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005226 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 {
5228 if (curline > buf->b_ml.ml_line_count
5229 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5230 return -1;
5231 dp = (DATA_BL *)(hp->bh_data);
5232 count = (long)(buf->b_ml.ml_locked_high) -
5233 (long)(buf->b_ml.ml_locked_low) + 1;
5234 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5235 if (idx == 0)/* first line in block, text at the end */
5236 text_end = dp->db_txt_end;
5237 else
5238 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5239 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005240 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005242 if (curline + (count - idx) >= lnum)
5243 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244 else
5245 idx = count - 1;
5246 }
5247 else
5248 {
5249 extra = 0;
5250 while (offset >= size
5251 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5252 + ffdos)
5253 {
5254 if (ffdos)
5255 size++;
5256 if (idx == count - 1)
5257 {
5258 extra = 1;
5259 break;
5260 }
5261 idx++;
5262 }
5263 }
5264 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5265 size += len;
5266 if (offset != 0 && size >= offset)
5267 {
5268 if (size + ffdos == offset)
5269 *offp = 0;
5270 else if (idx == start_idx)
5271 *offp = offset - size + len;
5272 else
5273 *offp = offset - size + len
5274 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5275 curline += idx - start_idx + extra;
5276 if (curline > buf->b_ml.ml_line_count)
5277 return -1; /* exactly one byte beyond the end */
5278 return curline;
5279 }
5280 curline = buf->b_ml.ml_locked_high + 1;
5281 }
5282
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005283 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005284 {
5285 /* Count extra CR characters. */
5286 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005287 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005288
5289 /* Don't count the last line break if 'bin' and 'noeol'. */
5290 if (buf->b_p_bin && !buf->b_p_eol)
5291 size -= ffdos + 1;
5292 }
5293
Bram Moolenaar071d4272004-06-13 20:20:40 +00005294 return size;
5295}
5296
5297/*
5298 * Goto byte in buffer with offset 'cnt'.
5299 */
5300 void
5301goto_byte(cnt)
5302 long cnt;
5303{
5304 long boff = cnt;
5305 linenr_T lnum;
5306
5307 ml_flush_line(curbuf); /* cached line may be dirty */
5308 setpcmark();
5309 if (boff)
5310 --boff;
5311 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5312 if (lnum < 1) /* past the end */
5313 {
5314 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5315 curwin->w_curswant = MAXCOL;
5316 coladvance((colnr_T)MAXCOL);
5317 }
5318 else
5319 {
5320 curwin->w_cursor.lnum = lnum;
5321 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005322# ifdef FEAT_VIRTUALEDIT
5323 curwin->w_cursor.coladd = 0;
5324# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005325 curwin->w_set_curswant = TRUE;
5326 }
5327 check_cursor();
5328
5329# ifdef FEAT_MBYTE
5330 /* Make sure the cursor is on the first byte of a multi-byte char. */
5331 if (has_mbyte)
5332 mb_adjust_cursor();
5333# endif
5334}
5335#endif