blob: 8f6c0e01e81eab1b627d14d6767abbef1731e203 [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 Moolenaar34b466e2013-11-28 17:41:46 +0100844#ifdef FEAT_SPELL
845 spell_delete_wordlist(); /* delete the internal wordlist */
846#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847#ifdef TEMPDIRNAMES
Bram Moolenaar34b466e2013-11-28 17:41:46 +0100848 vim_deltempdir(); /* delete created temp directory */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849#endif
850}
851
852/*
853 * Close all memfiles for not modified buffers.
854 * Only use just before exiting!
855 */
856 void
857ml_close_notmod()
858{
859 buf_T *buf;
860
861 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
862 if (!bufIsChanged(buf))
863 ml_close(buf, TRUE); /* close all not-modified buffers */
864}
865
866/*
867 * Update the timestamp in the .swp file.
868 * Used when the file has been written.
869 */
870 void
871ml_timestamp(buf)
872 buf_T *buf;
873{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200874 ml_upd_block0(buf, UB_FNAME);
875}
876
877/*
878 * Return FAIL when the ID of "b0p" is wrong.
879 */
880 static int
881ml_check_b0_id(b0p)
882 ZERO_BL *b0p;
883{
884 if (b0p->b0_id[0] != BLOCK0_ID0
885 || (b0p->b0_id[1] != BLOCK0_ID1
886 && b0p->b0_id[1] != BLOCK0_ID1_C0
887 && b0p->b0_id[1] != BLOCK0_ID1_C1)
888 )
889 return FAIL;
890 return OK;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000891}
892
893/*
894 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
895 */
896 static void
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200897ml_upd_block0(buf, what)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000898 buf_T *buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200899 upd_block0_T what;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000900{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 memfile_T *mfp;
902 bhdr_T *hp;
903 ZERO_BL *b0p;
904
905 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
907 return;
908 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200909 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000910 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000912 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200913 if (what == UB_FNAME)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000914 set_b0_fname(b0p, buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200915#ifdef FEAT_CRYPT
916 else if (what == UB_CRYPT)
917 ml_set_b0_crypt(buf, b0p);
918#endif
919 else /* what == UB_SAME_DIR */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000920 set_b0_dir_flag(b0p, buf);
921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 mf_put(mfp, hp, TRUE, FALSE);
923}
924
925/*
926 * Write file name and timestamp into block 0 of a swap file.
927 * Also set buf->b_mtime.
928 * Don't use NameBuff[]!!!
929 */
930 static void
931set_b0_fname(b0p, buf)
932 ZERO_BL *b0p;
933 buf_T *buf;
934{
935 struct stat st;
936
937 if (buf->b_ffname == NULL)
938 b0p->b0_fname[0] = NUL;
939 else
940 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200941#if defined(MSDOS) || defined(MSWIN) || defined(AMIGA)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000942 /* Systems that cannot translate "~user" back into a path: copy the
943 * file name unmodified. Do use slashes instead of backslashes for
944 * portability. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200945 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000946# ifdef BACKSLASH_IN_FILENAME
947 forward_slash(b0p->b0_fname);
948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949#else
950 size_t flen, ulen;
951 char_u uname[B0_UNAME_SIZE];
952
953 /*
954 * For a file under the home directory of the current user, we try to
955 * replace the home directory path with "~user". This helps when
956 * editing the same file on different machines over a network.
957 * First replace home dir path with "~/" with home_replace().
958 * Then insert the user name to get "~user/".
959 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200960 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
961 B0_FNAME_SIZE_CRYPT, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962 if (b0p->b0_fname[0] == '~')
963 {
964 flen = STRLEN(b0p->b0_fname);
965 /* If there is no user name or it is too long, don't use "~/" */
966 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200967 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
968 vim_strncpy(b0p->b0_fname, buf->b_ffname,
969 B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970 else
971 {
972 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
973 mch_memmove(b0p->b0_fname + 1, uname, ulen);
974 }
975 }
976#endif
977 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
978 {
979 long_to_char((long)st.st_mtime, b0p->b0_mtime);
980#ifdef CHECK_INODE
981 long_to_char((long)st.st_ino, b0p->b0_ino);
982#endif
983 buf_store_time(buf, &st, buf->b_ffname);
984 buf->b_mtime_read = buf->b_mtime;
985 }
986 else
987 {
988 long_to_char(0L, b0p->b0_mtime);
989#ifdef CHECK_INODE
990 long_to_char(0L, b0p->b0_ino);
991#endif
992 buf->b_mtime = 0;
993 buf->b_mtime_read = 0;
994 buf->b_orig_size = 0;
995 buf->b_orig_mode = 0;
996 }
997 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000998
999#ifdef FEAT_MBYTE
1000 /* Also add the 'fileencoding' if there is room. */
1001 add_b0_fenc(b0p, curbuf);
1002#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003}
1004
1005/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001006 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1007 * swapfile for "buf" are in the same directory.
1008 * This is fail safe: if we are not sure the directories are equal the flag is
1009 * not set.
1010 */
1011 static void
1012set_b0_dir_flag(b0p, buf)
1013 ZERO_BL *b0p;
1014 buf_T *buf;
1015{
1016 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1017 b0p->b0_flags |= B0_SAME_DIR;
1018 else
1019 b0p->b0_flags &= ~B0_SAME_DIR;
1020}
1021
1022#ifdef FEAT_MBYTE
1023/*
1024 * When there is room, add the 'fileencoding' to block zero.
1025 */
1026 static void
1027add_b0_fenc(b0p, buf)
1028 ZERO_BL *b0p;
1029 buf_T *buf;
1030{
1031 int n;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001032 int size = B0_FNAME_SIZE_NOCRYPT;
1033
1034# ifdef FEAT_CRYPT
1035 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1036 * With encryption it's OK to move elsewhere, the swap file is not
1037 * compatible anyway. */
1038 if (*buf->b_p_key != NUL)
1039 size = B0_FNAME_SIZE_CRYPT;
1040# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001041
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001042 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001043 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001044 b0p->b0_flags &= ~B0_HAS_FENC;
1045 else
1046 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001047 mch_memmove((char *)b0p->b0_fname + size - n,
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001048 (char *)buf->b_p_fenc, (size_t)n);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001049 *(b0p->b0_fname + size - n - 1) = NUL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001050 b0p->b0_flags |= B0_HAS_FENC;
1051 }
1052}
1053#endif
1054
1055
1056/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001057 * Try to recover curbuf from the .swp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 */
1059 void
1060ml_recover()
1061{
1062 buf_T *buf = NULL;
1063 memfile_T *mfp = NULL;
1064 char_u *fname;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001065 char_u *fname_used = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066 bhdr_T *hp = NULL;
1067 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001068 int b0_ff;
1069 char_u *b0_fenc = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001070#ifdef FEAT_CRYPT
1071 int b0_cm = -1;
1072#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 PTR_BL *pp;
1074 DATA_BL *dp;
1075 infoptr_T *ip;
1076 blocknr_T bnum;
1077 int page_count;
1078 struct stat org_stat, swp_stat;
1079 int len;
1080 int directly;
1081 linenr_T lnum;
1082 char_u *p;
1083 int i;
1084 long error;
1085 int cannot_open;
1086 linenr_T line_count;
1087 int has_error;
1088 int idx;
1089 int top;
1090 int txt_start;
1091 off_t size;
1092 int called_from_main;
1093 int serious_error = TRUE;
1094 long mtime;
1095 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001096 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097
1098 recoverymode = TRUE;
1099 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1100 attr = hl_attr(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001101
1102 /*
1103 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
1104 * Otherwise a search is done to find the swap file(s).
1105 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 fname = curbuf->b_fname;
1107 if (fname == NULL) /* When there is no file name */
1108 fname = (char_u *)"";
1109 len = (int)STRLEN(fname);
1110 if (len >= 4 &&
Bram Moolenaare60acc12011-05-10 16:41:25 +02001111#if defined(VMS)
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001112 STRNICMP(fname + len - 4, "_s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113#else
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001114 STRNICMP(fname + len - 4, ".s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115#endif
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001116 == 0
1117 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
1118 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 {
1120 directly = TRUE;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001121 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 }
1123 else
1124 {
1125 directly = FALSE;
1126
1127 /* count the number of matching swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001128 len = recover_names(fname, FALSE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 if (len == 0) /* no swap files found */
1130 {
1131 EMSG2(_("E305: No swap file found for %s"), fname);
1132 goto theend;
1133 }
1134 if (len == 1) /* one swap file found, use it */
1135 i = 1;
1136 else /* several swap files found, choose */
1137 {
1138 /* list the names of the swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001139 (void)recover_names(fname, TRUE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 msg_putchar('\n');
1141 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001142 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 if (i < 1 || i > len)
1144 goto theend;
1145 }
1146 /* get the swap file name that will be used */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001147 (void)recover_names(fname, FALSE, i, &fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001149 if (fname_used == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 goto theend; /* out of memory */
1151
1152 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +00001153 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 getout(1);
1155
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001156 /*
1157 * Allocate a buffer structure for the swap file that is used for recovery.
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001158 * Only the memline and crypt information in it are really used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001159 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1161 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001164 /*
1165 * init fields in memline struct
1166 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1168 buf->b_ml.ml_stack = NULL; /* no stack yet */
1169 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1170 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1171 buf->b_ml.ml_locked = NULL; /* no locked block */
1172 buf->b_ml.ml_flags = 0;
Bram Moolenaar0fe849a2010-07-25 15:11:11 +02001173#ifdef FEAT_CRYPT
1174 buf->b_p_key = empty_option;
1175 buf->b_p_cm = empty_option;
1176#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001178 /*
1179 * open the memfile from the old swap file
1180 */
1181 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1182 mf_open() will consume "fname_used"! */
1183 mfp = mf_open(fname_used, O_RDONLY);
1184 fname_used = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 if (mfp == NULL || mfp->mf_fd < 0)
1186 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001187 if (fname_used != NULL)
1188 EMSG2(_("E306: Cannot open %s"), fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189 goto theend;
1190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001192#ifdef FEAT_CRYPT
1193 mfp->mf_buffer = buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001194#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195
1196 /*
1197 * The page size set in mf_open() might be different from the page size
1198 * used in the swap file, we must get it from block 0. But to read block
1199 * 0 we need a page size. Use the minimal size for block 0 here, it will
1200 * be set to the real value below.
1201 */
1202 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1203
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001204 /*
1205 * try to read block 0
1206 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1208 {
1209 msg_start();
1210 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1211 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001212 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001213 attr | MSG_HIST);
1214 msg_end();
1215 goto theend;
1216 }
1217 b0p = (ZERO_BL *)(hp->bh_data);
1218 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1219 {
1220 msg_start();
1221 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1222 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1223 MSG_HIST);
1224 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1225 msg_end();
1226 goto theend;
1227 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001228 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 {
1230 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1231 goto theend;
1232 }
1233 if (b0_magic_wrong(b0p))
1234 {
1235 msg_start();
1236 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1237#if defined(MSDOS) || defined(MSWIN)
1238 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1239 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1240 attr | MSG_HIST);
1241 else
1242#endif
1243 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1244 attr | MSG_HIST);
1245 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001246 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001247 b0p->b0_fname[0] = NUL;
1248 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1249 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1250 msg_end();
1251 goto theend;
1252 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001253
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001254#ifdef FEAT_CRYPT
1255 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
Bram Moolenaar49771f42010-07-20 17:32:38 +02001256 b0_cm = 0;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001257 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1258 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02001259 b0_cm = 1;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001260 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1261 }
Bram Moolenaar49771f42010-07-20 17:32:38 +02001262 set_crypt_method(buf, b0_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001263#else
1264 if (b0p->b0_id[1] != BLOCK0_ID1)
1265 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001266 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001267 goto theend;
1268 }
1269#endif
1270
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271 /*
1272 * If we guessed the wrong page size, we have to recalculate the
1273 * highest block number in the file.
1274 */
1275 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1276 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001277 unsigned previous_page_size = mfp->mf_page_size;
1278
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001280 if (mfp->mf_page_size < previous_page_size)
1281 {
1282 msg_start();
1283 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1284 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1285 attr | MSG_HIST);
1286 msg_end();
1287 goto theend;
1288 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1290 mfp->mf_blocknr_max = 0; /* no file or empty file */
1291 else
1292 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1293 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001294
1295 /* need to reallocate the memory used to store the data */
1296 p = alloc(mfp->mf_page_size);
1297 if (p == NULL)
1298 goto theend;
1299 mch_memmove(p, hp->bh_data, previous_page_size);
1300 vim_free(hp->bh_data);
1301 hp->bh_data = p;
1302 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 }
1304
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001305 /*
1306 * If .swp file name given directly, use name from swap file for buffer.
1307 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 if (directly)
1309 {
1310 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1311 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1312 goto theend;
1313 }
1314
1315 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001316 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317
1318 if (buf_spname(curbuf) != NULL)
Bram Moolenaare1704ba2012-10-03 18:25:00 +02001319 vim_strncpy(NameBuff, buf_spname(curbuf), MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320 else
1321 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001322 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323 msg_putchar('\n');
1324
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001325 /*
1326 * check date of swap file and original file
1327 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001328 mtime = char_to_long(b0p->b0_mtime);
1329 if (curbuf->b_ffname != NULL
1330 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1331 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1332 && org_stat.st_mtime > swp_stat.st_mtime)
1333 || org_stat.st_mtime != mtime))
1334 {
1335 EMSG(_("E308: Warning: Original file may have been changed"));
1336 }
1337 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001338
1339 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1340 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1341 if (b0p->b0_flags & B0_HAS_FENC)
1342 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001343 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001344
1345#ifdef FEAT_CRYPT
1346 /* Use the same size as in add_b0_fenc(). */
1347 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001348 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001349#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001350 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001351 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001352 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001353 }
1354
Bram Moolenaar071d4272004-06-13 20:20:40 +00001355 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1356 hp = NULL;
1357
1358 /*
1359 * Now that we are sure that the file is going to be recovered, clear the
1360 * contents of the current buffer.
1361 */
1362 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1363 ml_delete((linenr_T)1, FALSE);
1364
1365 /*
1366 * Try reading the original file to obtain the values of 'fileformat',
1367 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001368 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369 */
1370 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001371 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001374#ifdef FEAT_CRYPT
1375 if (b0_cm >= 0)
1376 {
1377 /* Need to ask the user for the crypt key. If this fails we continue
1378 * without a key, will probably get garbage text. */
1379 if (*curbuf->b_p_key != NUL)
1380 {
1381 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1382 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1383 MSG_PUTS(_("\nenter the new crypt key."));
1384 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1385 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1386 }
1387 else
1388 smsg((char_u *)_(need_key_msg), fname_used);
1389 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1390 if (buf->b_p_key == NULL)
1391 buf->b_p_key = curbuf->b_p_key;
1392 else if (*buf->b_p_key == NUL)
1393 {
1394 vim_free(buf->b_p_key);
1395 buf->b_p_key = curbuf->b_p_key;
1396 }
1397 if (buf->b_p_key == NULL)
1398 buf->b_p_key = empty_option;
1399 }
1400#endif
1401
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001402 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1403 if (b0_ff != 0)
1404 set_fileformat(b0_ff - 1, OPT_LOCAL);
1405 if (b0_fenc != NULL)
1406 {
1407 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1408 vim_free(b0_fenc);
1409 }
1410 unchanged(curbuf, TRUE);
1411
Bram Moolenaar071d4272004-06-13 20:20:40 +00001412 bnum = 1; /* start with block 1 */
1413 page_count = 1; /* which is 1 page */
1414 lnum = 0; /* append after line 0 in curbuf */
1415 line_count = 0;
1416 idx = 0; /* start with first index in block 1 */
1417 error = 0;
1418 buf->b_ml.ml_stack_top = 0;
1419 buf->b_ml.ml_stack = NULL;
1420 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1421
1422 if (curbuf->b_ffname == NULL)
1423 cannot_open = TRUE;
1424 else
1425 cannot_open = FALSE;
1426
1427 serious_error = FALSE;
1428 for ( ; !got_int; line_breakcheck())
1429 {
1430 if (hp != NULL)
1431 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1432
1433 /*
1434 * get block
1435 */
1436 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1437 {
1438 if (bnum == 1)
1439 {
1440 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1441 goto theend;
1442 }
1443 ++error;
1444 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1445 (colnr_T)0, TRUE);
1446 }
1447 else /* there is a block */
1448 {
1449 pp = (PTR_BL *)(hp->bh_data);
1450 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1451 {
1452 /* check line count when using pointer block first time */
1453 if (idx == 0 && line_count != 0)
1454 {
1455 for (i = 0; i < (int)pp->pb_count; ++i)
1456 line_count -= pp->pb_pointer[i].pe_line_count;
1457 if (line_count != 0)
1458 {
1459 ++error;
1460 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1461 (colnr_T)0, TRUE);
1462 }
1463 }
1464
1465 if (pp->pb_count == 0)
1466 {
1467 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1468 (colnr_T)0, TRUE);
1469 ++error;
1470 }
1471 else if (idx < (int)pp->pb_count) /* go a block deeper */
1472 {
1473 if (pp->pb_pointer[idx].pe_bnum < 0)
1474 {
1475 /*
1476 * Data block with negative block number.
1477 * Try to read lines from the original file.
1478 * This is slow, but it works.
1479 */
1480 if (!cannot_open)
1481 {
1482 line_count = pp->pb_pointer[idx].pe_line_count;
1483 if (readfile(curbuf->b_ffname, NULL, lnum,
1484 pp->pb_pointer[idx].pe_old_lnum - 1,
1485 line_count, NULL, 0) == FAIL)
1486 cannot_open = TRUE;
1487 else
1488 lnum += line_count;
1489 }
1490 if (cannot_open)
1491 {
1492 ++error;
1493 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1494 (colnr_T)0, TRUE);
1495 }
1496 ++idx; /* get same block again for next index */
1497 continue;
1498 }
1499
1500 /*
1501 * going one block deeper in the tree
1502 */
1503 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1504 {
1505 ++error;
1506 break; /* out of memory */
1507 }
1508 ip = &(buf->b_ml.ml_stack[top]);
1509 ip->ip_bnum = bnum;
1510 ip->ip_index = idx;
1511
1512 bnum = pp->pb_pointer[idx].pe_bnum;
1513 line_count = pp->pb_pointer[idx].pe_line_count;
1514 page_count = pp->pb_pointer[idx].pe_page_count;
Bram Moolenaar986a0032011-06-13 01:07:27 +02001515 idx = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516 continue;
1517 }
1518 }
1519 else /* not a pointer block */
1520 {
1521 dp = (DATA_BL *)(hp->bh_data);
1522 if (dp->db_id != DATA_ID) /* block id wrong */
1523 {
1524 if (bnum == 1)
1525 {
1526 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1527 mfp->mf_fname);
1528 goto theend;
1529 }
1530 ++error;
1531 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1532 (colnr_T)0, TRUE);
1533 }
1534 else
1535 {
1536 /*
1537 * it is a data block
1538 * Append all the lines in this block
1539 */
1540 has_error = FALSE;
1541 /*
1542 * check length of block
1543 * if wrong, use length in pointer block
1544 */
1545 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1546 {
1547 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1548 (colnr_T)0, TRUE);
1549 ++error;
1550 has_error = TRUE;
1551 dp->db_txt_end = page_count * mfp->mf_page_size;
1552 }
1553
1554 /* make sure there is a NUL at the end of the block */
1555 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1556
1557 /*
1558 * check number of lines in block
1559 * if wrong, use count in data block
1560 */
1561 if (line_count != dp->db_line_count)
1562 {
1563 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1564 (colnr_T)0, TRUE);
1565 ++error;
1566 has_error = TRUE;
1567 }
1568
1569 for (i = 0; i < dp->db_line_count; ++i)
1570 {
1571 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001572 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 || txt_start >= (int)dp->db_txt_end)
1574 {
1575 p = (char_u *)"???";
1576 ++error;
1577 }
1578 else
1579 p = (char_u *)dp + txt_start;
1580 ml_append(lnum++, p, (colnr_T)0, TRUE);
1581 }
1582 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001583 ml_append(lnum++, (char_u *)_("???END"),
1584 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 }
1586 }
1587 }
1588
1589 if (buf->b_ml.ml_stack_top == 0) /* finished */
1590 break;
1591
1592 /*
1593 * go one block up in the tree
1594 */
1595 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1596 bnum = ip->ip_bnum;
1597 idx = ip->ip_index + 1; /* go to next index */
1598 page_count = 1;
1599 }
1600
1601 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001602 * Compare the buffer contents with the original file. When they differ
1603 * set the 'modified' flag.
1604 * Lines 1 - lnum are the new contents.
1605 * Lines lnum + 1 to ml_line_count are the original contents.
1606 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001608 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1609 {
1610 /* Recovering an empty file results in two lines and the first line is
1611 * empty. Don't set the modified flag then. */
1612 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1613 {
1614 changed_int();
1615 ++curbuf->b_changedtick;
1616 }
1617 }
1618 else
1619 {
1620 for (idx = 1; idx <= lnum; ++idx)
1621 {
1622 /* Need to copy one line, fetching the other one may flush it. */
1623 p = vim_strsave(ml_get(idx));
1624 i = STRCMP(p, ml_get(idx + lnum));
1625 vim_free(p);
1626 if (i != 0)
1627 {
1628 changed_int();
1629 ++curbuf->b_changedtick;
1630 break;
1631 }
1632 }
1633 }
1634
1635 /*
1636 * Delete the lines from the original file and the dummy line from the
1637 * empty buffer. These will now be after the last line in the buffer.
1638 */
1639 while (curbuf->b_ml.ml_line_count > lnum
1640 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1641 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 curbuf->b_flags |= BF_RECOVERED;
1643
1644 recoverymode = FALSE;
1645 if (got_int)
1646 EMSG(_("E311: Recovery Interrupted"));
1647 else if (error)
1648 {
1649 ++no_wait_return;
1650 MSG(">>>>>>>>>>>>>");
1651 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1652 --no_wait_return;
1653 MSG(_("See \":help E312\" for more information."));
1654 MSG(">>>>>>>>>>>>>");
1655 }
1656 else
1657 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001658 if (curbuf->b_changed)
1659 {
1660 MSG(_("Recovery completed. You should check if everything is OK."));
1661 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1662 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1663 }
1664 else
1665 MSG(_("Recovery completed. Buffer contents equals file contents."));
1666 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667 cmdline_row = msg_row;
1668 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001669#ifdef FEAT_CRYPT
1670 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1671 {
1672 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1673 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1674 }
1675#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 redraw_curbuf_later(NOT_VALID);
1677
1678theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001679 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 recoverymode = FALSE;
1681 if (mfp != NULL)
1682 {
1683 if (hp != NULL)
1684 mf_put(mfp, hp, FALSE, FALSE);
1685 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1686 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001687 if (buf != NULL)
1688 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001689#ifdef FEAT_CRYPT
1690 if (buf->b_p_key != curbuf->b_p_key)
1691 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001692 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001693#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001694 vim_free(buf->b_ml.ml_stack);
1695 vim_free(buf);
1696 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 if (serious_error && called_from_main)
1698 ml_close(curbuf, TRUE);
1699#ifdef FEAT_AUTOCMD
1700 else
1701 {
1702 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1703 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1704 }
1705#endif
1706 return;
1707}
1708
1709/*
1710 * Find the names of swap files in current directory and the directory given
1711 * with the 'directory' option.
1712 *
1713 * Used to:
1714 * - list the swap files for "vim -r"
1715 * - count the number of swap files when recovering
1716 * - list the swap files when recovering
1717 * - find the name of the n'th swap file when recovering
1718 */
1719 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001720recover_names(fname, list, nr, fname_out)
1721 char_u *fname; /* base for swap file name */
1722 int list; /* when TRUE, list the swap file names */
1723 int nr; /* when non-zero, return nr'th swap file name */
1724 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725{
1726 int num_names;
1727 char_u *(names[6]);
1728 char_u *tail;
1729 char_u *p;
1730 int num_files;
1731 int file_count = 0;
1732 char_u **files;
1733 int i;
1734 char_u *dirp;
1735 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001736 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001737#ifdef HAVE_READLINK
1738 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001739#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001740
Bram Moolenaar64354da2010-05-25 21:37:17 +02001741 if (fname != NULL)
1742 {
1743#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001744 /* Expand symlink in the file name, because the swap file is created
1745 * with the actual file instead of with the symlink. */
1746 if (resolve_symlink(fname, fname_buf) == OK)
1747 fname_res = fname_buf;
1748 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001749#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001750 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752
1753 if (list)
1754 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001755 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 msg((char_u *)_("Swap files found:"));
1757 msg_putchar('\n');
1758 }
1759
1760 /*
1761 * Do the loop for every directory in 'directory'.
1762 * First allocate some memory to put the directory name in.
1763 */
1764 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1765 dirp = p_dir;
1766 while (dir_name != NULL && *dirp)
1767 {
1768 /*
1769 * Isolate a directory name from *dirp and put it in dir_name (we know
1770 * it is large enough, so use 31000 for length).
1771 * Advance dirp to next directory name.
1772 */
1773 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1774
1775 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1776 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001777 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 {
1779#ifdef VMS
1780 names[0] = vim_strsave((char_u *)"*_sw%");
1781#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 names[0] = vim_strsave((char_u *)"*.sw?");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001784#if defined(UNIX) || defined(WIN3264)
1785 /* For Unix names starting with a dot are special. MS-Windows
1786 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787 names[1] = vim_strsave((char_u *)".*.sw?");
1788 names[2] = vim_strsave((char_u *)".sw?");
1789 num_names = 3;
1790#else
1791# ifdef VMS
1792 names[1] = vim_strsave((char_u *)".*_sw%");
1793 num_names = 2;
1794# else
1795 num_names = 1;
1796# endif
1797#endif
1798 }
1799 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001800 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 }
1802 else /* check directory dir_name */
1803 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001804 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805 {
1806#ifdef VMS
1807 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1808#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001811#if defined(UNIX) || defined(WIN3264)
1812 /* For Unix names starting with a dot are special. MS-Windows
1813 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1815 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1816 num_names = 3;
1817#else
1818# ifdef VMS
1819 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1820 num_names = 2;
1821# else
1822 num_names = 1;
1823# endif
1824#endif
1825 }
1826 else
1827 {
1828#if defined(UNIX) || defined(WIN3264)
1829 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001830 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 {
1832 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001833 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834 }
1835 else
1836#endif
1837 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001838 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 tail = concat_fnames(dir_name, tail, TRUE);
1840 }
1841 if (tail == NULL)
1842 num_names = 0;
1843 else
1844 {
1845 num_names = recov_file_names(names, tail, FALSE);
1846 vim_free(tail);
1847 }
1848 }
1849 }
1850
1851 /* check for out-of-memory */
1852 for (i = 0; i < num_names; ++i)
1853 {
1854 if (names[i] == NULL)
1855 {
1856 for (i = 0; i < num_names; ++i)
1857 vim_free(names[i]);
1858 num_names = 0;
1859 }
1860 }
1861 if (num_names == 0)
1862 num_files = 0;
1863 else if (expand_wildcards(num_names, names, &num_files, &files,
1864 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1865 num_files = 0;
1866
1867 /*
1868 * When no swap file found, wildcard expansion might have failed (e.g.
1869 * not able to execute the shell).
1870 * Try finding a swap file by simply adding ".swp" to the file name.
1871 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001872 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 {
1874 struct stat st;
1875 char_u *swapname;
1876
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001877 swapname = modname(fname_res,
Bram Moolenaare60acc12011-05-10 16:41:25 +02001878#if defined(VMS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001879 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001881 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001883 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 if (swapname != NULL)
1885 {
1886 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1887 {
1888 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1889 if (files != NULL)
1890 {
1891 files[0] = swapname;
1892 swapname = NULL;
1893 num_files = 1;
1894 }
1895 }
1896 vim_free(swapname);
1897 }
1898 }
1899
1900 /*
1901 * remove swapfile name of the current buffer, it must be ignored
1902 */
1903 if (curbuf->b_ml.ml_mfp != NULL
1904 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1905 {
1906 for (i = 0; i < num_files; ++i)
1907 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1908 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001909 /* Remove the name from files[i]. Move further entries
1910 * down. When the array becomes empty free it here, since
1911 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001913 if (--num_files == 0)
1914 vim_free(files);
1915 else
1916 for ( ; i < num_files; ++i)
1917 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 }
1919 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001920 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 {
1922 file_count += num_files;
1923 if (nr <= file_count)
1924 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001925 *fname_out = vim_strsave(
1926 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927 dirp = (char_u *)""; /* stop searching */
1928 }
1929 }
1930 else if (list)
1931 {
1932 if (dir_name[0] == '.' && dir_name[1] == NUL)
1933 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001934 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 MSG_PUTS(_(" In current directory:\n"));
1936 else
1937 MSG_PUTS(_(" Using specified name:\n"));
1938 }
1939 else
1940 {
1941 MSG_PUTS(_(" In directory "));
1942 msg_home_replace(dir_name);
1943 MSG_PUTS(":\n");
1944 }
1945
1946 if (num_files)
1947 {
1948 for (i = 0; i < num_files; ++i)
1949 {
1950 /* print the swap file name */
1951 msg_outnum((long)++file_count);
1952 MSG_PUTS(". ");
1953 msg_puts(gettail(files[i]));
1954 msg_putchar('\n');
1955 (void)swapfile_info(files[i]);
1956 }
1957 }
1958 else
1959 MSG_PUTS(_(" -- none --\n"));
1960 out_flush();
1961 }
1962 else
1963 file_count += num_files;
1964
1965 for (i = 0; i < num_names; ++i)
1966 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001967 if (num_files > 0)
1968 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969 }
1970 vim_free(dir_name);
1971 return file_count;
1972}
1973
1974#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1975/*
1976 * Append the full path to name with path separators made into percent
1977 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1978 */
1979 static char_u *
1980make_percent_swname(dir, name)
1981 char_u *dir;
1982 char_u *name;
1983{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001984 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985
1986 f = fix_fname(name != NULL ? name : (char_u *) "");
1987 d = NULL;
1988 if (f != NULL)
1989 {
1990 s = alloc((unsigned)(STRLEN(f) + 1));
1991 if (s != NULL)
1992 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001993 STRCPY(s, f);
1994 for (d = s; *d != NUL; mb_ptr_adv(d))
1995 if (vim_ispathsep(*d))
1996 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 d = concat_fnames(dir, s, TRUE);
1998 vim_free(s);
1999 }
2000 vim_free(f);
2001 }
2002 return d;
2003}
2004#endif
2005
2006#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2007static int process_still_running;
2008#endif
2009
2010/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002011 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012 * Returns timestamp (0 when unknown).
2013 */
2014 static time_t
2015swapfile_info(fname)
2016 char_u *fname;
2017{
2018 struct stat st;
2019 int fd;
2020 struct block0 b0;
2021 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002022 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023#ifdef UNIX
2024 char_u uname[B0_UNAME_SIZE];
2025#endif
2026
2027 /* print the swap file date */
2028 if (mch_stat((char *)fname, &st) != -1)
2029 {
2030#ifdef UNIX
2031 /* print name of owner of the file */
2032 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2033 {
2034 MSG_PUTS(_(" owned by: "));
2035 msg_outtrans(uname);
2036 MSG_PUTS(_(" dated: "));
2037 }
2038 else
2039#endif
2040 MSG_PUTS(_(" dated: "));
2041 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002042 p = ctime(&x); /* includes '\n' */
2043 if (p == NULL)
2044 MSG_PUTS("(invalid)\n");
2045 else
2046 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 }
2048
2049 /*
2050 * print the original file name
2051 */
2052 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2053 if (fd >= 0)
2054 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01002055 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 {
2057 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2058 {
2059 MSG_PUTS(_(" [from Vim version 3.0]"));
2060 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002061 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 {
2063 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2064 }
2065 else
2066 {
2067 MSG_PUTS(_(" file name: "));
2068 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002069 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 else
2071 msg_outtrans(b0.b0_fname);
2072
2073 MSG_PUTS(_("\n modified: "));
2074 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2075
2076 if (*(b0.b0_uname) != NUL)
2077 {
2078 MSG_PUTS(_("\n user name: "));
2079 msg_outtrans(b0.b0_uname);
2080 }
2081
2082 if (*(b0.b0_hname) != NUL)
2083 {
2084 if (*(b0.b0_uname) != NUL)
2085 MSG_PUTS(_(" host name: "));
2086 else
2087 MSG_PUTS(_("\n host name: "));
2088 msg_outtrans(b0.b0_hname);
2089 }
2090
2091 if (char_to_long(b0.b0_pid) != 0L)
2092 {
2093 MSG_PUTS(_("\n process ID: "));
2094 msg_outnum(char_to_long(b0.b0_pid));
2095#if defined(UNIX) || defined(__EMX__)
2096 /* EMX kill() not working correctly, it seems */
2097 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2098 {
2099 MSG_PUTS(_(" (still running)"));
2100# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2101 process_still_running = TRUE;
2102# endif
2103 }
2104#endif
2105 }
2106
2107 if (b0_magic_wrong(&b0))
2108 {
2109#if defined(MSDOS) || defined(MSWIN)
2110 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2111 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2112 else
2113#endif
2114 MSG_PUTS(_("\n [not usable on this computer]"));
2115 }
2116 }
2117 }
2118 else
2119 MSG_PUTS(_(" [cannot be read]"));
2120 close(fd);
2121 }
2122 else
2123 MSG_PUTS(_(" [cannot be opened]"));
2124 msg_putchar('\n');
2125
2126 return x;
2127}
2128
2129 static int
2130recov_file_names(names, path, prepend_dot)
2131 char_u **names;
2132 char_u *path;
2133 int prepend_dot;
2134{
2135 int num_names;
2136
2137#ifdef SHORT_FNAME
2138 /*
2139 * (MS-DOS) always short names
2140 */
2141 names[0] = modname(path, (char_u *)".sw?", FALSE);
2142 num_names = 1;
2143#else /* !SHORT_FNAME */
2144 /*
2145 * (Win32 and Win64) never short names, but do prepend a dot.
2146 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2147 * Only use the short name if it is different.
2148 */
2149 char_u *p;
2150 int i;
2151# ifndef WIN3264
2152 int shortname = curbuf->b_shortname;
2153
2154 curbuf->b_shortname = FALSE;
2155# endif
2156
2157 num_names = 0;
2158
2159 /*
2160 * May also add the file name with a dot prepended, for swap file in same
2161 * dir as original file.
2162 */
2163 if (prepend_dot)
2164 {
2165 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2166 if (names[num_names] == NULL)
2167 goto end;
2168 ++num_names;
2169 }
2170
2171 /*
2172 * Form the normal swap file name pattern by appending ".sw?".
2173 */
2174#ifdef VMS
2175 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2176#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178#endif
2179 if (names[num_names] == NULL)
2180 goto end;
2181 if (num_names >= 1) /* check if we have the same name twice */
2182 {
2183 p = names[num_names - 1];
2184 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2185 if (i > 0)
2186 p += i; /* file name has been expanded to full path */
2187
2188 if (STRCMP(p, names[num_names]) != 0)
2189 ++num_names;
2190 else
2191 vim_free(names[num_names]);
2192 }
2193 else
2194 ++num_names;
2195
2196# ifndef WIN3264
2197 /*
2198 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2199 */
2200 curbuf->b_shortname = TRUE;
2201#ifdef VMS
2202 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2203#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205#endif
2206 if (names[num_names] == NULL)
2207 goto end;
2208
2209 /*
2210 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2211 */
2212 p = names[num_names];
2213 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2214 if (i > 0)
2215 p += i; /* file name has been expanded to full path */
2216 if (STRCMP(names[num_names - 1], p) == 0)
2217 vim_free(names[num_names]);
2218 else
2219 ++num_names;
2220# endif
2221
2222end:
2223# ifndef WIN3264
2224 curbuf->b_shortname = shortname;
2225# endif
2226
2227#endif /* !SHORT_FNAME */
2228
2229 return num_names;
2230}
2231
2232/*
2233 * sync all memlines
2234 *
2235 * If 'check_file' is TRUE, check if original file exists and was not changed.
2236 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2237 * always sync at least one block.
2238 */
2239 void
2240ml_sync_all(check_file, check_char)
2241 int check_file;
2242 int check_char;
2243{
2244 buf_T *buf;
2245 struct stat st;
2246
2247 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2248 {
2249 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2250 continue; /* no file */
2251
2252 ml_flush_line(buf); /* flush buffered line */
2253 /* flush locked block */
2254 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2255 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2256 && buf->b_ffname != NULL)
2257 {
2258 /*
2259 * If the original file does not exist anymore or has been changed
2260 * call ml_preserve() to get rid of all negative numbered blocks.
2261 */
2262 if (mch_stat((char *)buf->b_ffname, &st) == -1
2263 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002264 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 {
2266 ml_preserve(buf, FALSE);
2267 did_check_timestamps = FALSE;
2268 need_check_timestamps = TRUE; /* give message later */
2269 }
2270 }
2271 if (buf->b_ml.ml_mfp->mf_dirty)
2272 {
2273 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2274 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2275 if (check_char && ui_char_avail()) /* character available now */
2276 break;
2277 }
2278 }
2279}
2280
2281/*
2282 * sync one buffer, including negative blocks
2283 *
2284 * after this all the blocks are in the swap file
2285 *
2286 * Used for the :preserve command and when the original file has been
2287 * changed or deleted.
2288 *
2289 * when message is TRUE the success of preserving is reported
2290 */
2291 void
2292ml_preserve(buf, message)
2293 buf_T *buf;
2294 int message;
2295{
2296 bhdr_T *hp;
2297 linenr_T lnum;
2298 memfile_T *mfp = buf->b_ml.ml_mfp;
2299 int status;
2300 int got_int_save = got_int;
2301
2302 if (mfp == NULL || mfp->mf_fname == NULL)
2303 {
2304 if (message)
2305 EMSG(_("E313: Cannot preserve, there is no swap file"));
2306 return;
2307 }
2308
2309 /* We only want to stop when interrupted here, not when interrupted
2310 * before. */
2311 got_int = FALSE;
2312
2313 ml_flush_line(buf); /* flush buffered line */
2314 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2315 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2316
2317 /* stack is invalid after mf_sync(.., MFS_ALL) */
2318 buf->b_ml.ml_stack_top = 0;
2319
2320 /*
2321 * Some of the data blocks may have been changed from negative to
2322 * positive block number. In that case the pointer blocks need to be
2323 * updated.
2324 *
2325 * We don't know in which pointer block the references are, so we visit
2326 * all data blocks until there are no more translations to be done (or
2327 * we hit the end of the file, which can only happen in case a write fails,
2328 * e.g. when file system if full).
2329 * ml_find_line() does the work by translating the negative block numbers
2330 * when getting the first line of each data block.
2331 */
2332 if (mf_need_trans(mfp) && !got_int)
2333 {
2334 lnum = 1;
2335 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2336 {
2337 hp = ml_find_line(buf, lnum, ML_FIND);
2338 if (hp == NULL)
2339 {
2340 status = FAIL;
2341 goto theend;
2342 }
2343 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2344 lnum = buf->b_ml.ml_locked_high + 1;
2345 }
2346 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2347 /* sync the updated pointer blocks */
2348 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2349 status = FAIL;
2350 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2351 }
2352theend:
2353 got_int |= got_int_save;
2354
2355 if (message)
2356 {
2357 if (status == OK)
2358 MSG(_("File preserved"));
2359 else
2360 EMSG(_("E314: Preserve failed"));
2361 }
2362}
2363
2364/*
2365 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2366 * until the next call!
2367 * line1 = ml_get(1);
2368 * line2 = ml_get(2); // line1 is now invalid!
2369 * Make a copy of the line if necessary.
2370 */
2371/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002372 * Return a pointer to a (read-only copy of a) line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 *
2374 * On failure an error message is given and IObuff is returned (to avoid
2375 * having to check for error everywhere).
2376 */
2377 char_u *
2378ml_get(lnum)
2379 linenr_T lnum;
2380{
2381 return ml_get_buf(curbuf, lnum, FALSE);
2382}
2383
2384/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002385 * Return pointer to position "pos".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 */
2387 char_u *
2388ml_get_pos(pos)
2389 pos_T *pos;
2390{
2391 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2392}
2393
2394/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002395 * Return pointer to cursor line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 */
2397 char_u *
2398ml_get_curline()
2399{
2400 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2401}
2402
2403/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002404 * Return pointer to cursor position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 */
2406 char_u *
2407ml_get_cursor()
2408{
2409 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2410 curwin->w_cursor.col);
2411}
2412
2413/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002414 * Return a pointer to a line in a specific buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 *
2416 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2417 * changed)
2418 */
2419 char_u *
2420ml_get_buf(buf, lnum, will_change)
2421 buf_T *buf;
2422 linenr_T lnum;
2423 int will_change; /* line will be changed */
2424{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002425 bhdr_T *hp;
2426 DATA_BL *dp;
2427 char_u *ptr;
2428 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429
2430 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2431 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002432 if (recursive == 0)
2433 {
2434 /* Avoid giving this message for a recursive call, may happen when
2435 * the GUI redraws part of the text. */
2436 ++recursive;
2437 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2438 --recursive;
2439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440errorret:
2441 STRCPY(IObuff, "???");
2442 return IObuff;
2443 }
2444 if (lnum <= 0) /* pretend line 0 is line 1 */
2445 lnum = 1;
2446
2447 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2448 return (char_u *)"";
2449
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002450 /*
2451 * See if it is the same line as requested last time.
2452 * Otherwise may need to flush last used line.
2453 * Don't use the last used line when 'swapfile' is reset, need to load all
2454 * blocks.
2455 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002456 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 {
2458 ml_flush_line(buf);
2459
2460 /*
2461 * Find the data block containing the line.
2462 * This also fills the stack with the blocks from the root to the data
2463 * block and releases any locked block.
2464 */
2465 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2466 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002467 if (recursive == 0)
2468 {
2469 /* Avoid giving this message for a recursive call, may happen
2470 * when the GUI redraws part of the text. */
2471 ++recursive;
2472 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2473 --recursive;
2474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 goto errorret;
2476 }
2477
2478 dp = (DATA_BL *)(hp->bh_data);
2479
2480 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2481 buf->b_ml.ml_line_ptr = ptr;
2482 buf->b_ml.ml_line_lnum = lnum;
2483 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2484 }
2485 if (will_change)
2486 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2487
2488 return buf->b_ml.ml_line_ptr;
2489}
2490
2491/*
2492 * Check if a line that was just obtained by a call to ml_get
2493 * is in allocated memory.
2494 */
2495 int
2496ml_line_alloced()
2497{
2498 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2499}
2500
2501/*
2502 * Append a line after lnum (may be 0 to insert a line in front of the file).
2503 * "line" does not need to be allocated, but can't be another line in a
2504 * buffer, unlocking may make it invalid.
2505 *
2506 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2507 * will be set for recovery
2508 * Check: The caller of this function should probably also call
2509 * appended_lines().
2510 *
2511 * return FAIL for failure, OK otherwise
2512 */
2513 int
2514ml_append(lnum, line, len, newfile)
2515 linenr_T lnum; /* append after this line (can be 0) */
2516 char_u *line; /* text of the new line */
2517 colnr_T len; /* length of new line, including NUL, or 0 */
2518 int newfile; /* flag, see above */
2519{
2520 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002521 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 return FAIL;
2523
2524 if (curbuf->b_ml.ml_line_lnum != 0)
2525 ml_flush_line(curbuf);
2526 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2527}
2528
Bram Moolenaara1956f62006-03-12 22:18:00 +00002529#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002530/*
2531 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2532 * a memline.
2533 */
2534 int
2535ml_append_buf(buf, lnum, line, len, newfile)
2536 buf_T *buf;
2537 linenr_T lnum; /* append after this line (can be 0) */
2538 char_u *line; /* text of the new line */
2539 colnr_T len; /* length of new line, including NUL, or 0 */
2540 int newfile; /* flag, see above */
2541{
2542 if (buf->b_ml.ml_mfp == NULL)
2543 return FAIL;
2544
2545 if (buf->b_ml.ml_line_lnum != 0)
2546 ml_flush_line(buf);
2547 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2548}
2549#endif
2550
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 static int
2552ml_append_int(buf, lnum, line, len, newfile, mark)
2553 buf_T *buf;
2554 linenr_T lnum; /* append after this line (can be 0) */
2555 char_u *line; /* text of the new line */
2556 colnr_T len; /* length of line, including NUL, or 0 */
2557 int newfile; /* flag, see above */
2558 int mark; /* mark the new line */
2559{
2560 int i;
2561 int line_count; /* number of indexes in current block */
2562 int offset;
2563 int from, to;
2564 int space_needed; /* space needed for new line */
2565 int page_size;
2566 int page_count;
2567 int db_idx; /* index for lnum in data block */
2568 bhdr_T *hp;
2569 memfile_T *mfp;
2570 DATA_BL *dp;
2571 PTR_BL *pp;
2572 infoptr_T *ip;
2573
2574 /* lnum out of range */
2575 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2576 return FAIL;
2577
2578 if (lowest_marked && lowest_marked > lnum)
2579 lowest_marked = lnum + 1;
2580
2581 if (len == 0)
2582 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2583 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2584
2585 mfp = buf->b_ml.ml_mfp;
2586 page_size = mfp->mf_page_size;
2587
2588/*
2589 * find the data block containing the previous line
2590 * This also fills the stack with the blocks from the root to the data block
2591 * This also releases any locked block.
2592 */
2593 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2594 ML_INSERT)) == NULL)
2595 return FAIL;
2596
2597 buf->b_ml.ml_flags &= ~ML_EMPTY;
2598
2599 if (lnum == 0) /* got line one instead, correct db_idx */
2600 db_idx = -1; /* careful, it is negative! */
2601 else
2602 db_idx = lnum - buf->b_ml.ml_locked_low;
2603 /* get line count before the insertion */
2604 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2605
2606 dp = (DATA_BL *)(hp->bh_data);
2607
2608/*
2609 * If
2610 * - there is not enough room in the current block
2611 * - appending to the last line in the block
2612 * - not appending to the last line in the file
2613 * insert in front of the next block.
2614 */
2615 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2616 && lnum < buf->b_ml.ml_line_count)
2617 {
2618 /*
2619 * Now that the line is not going to be inserted in the block that we
2620 * expected, the line count has to be adjusted in the pointer blocks
2621 * by using ml_locked_lineadd.
2622 */
2623 --(buf->b_ml.ml_locked_lineadd);
2624 --(buf->b_ml.ml_locked_high);
2625 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2626 return FAIL;
2627
2628 db_idx = -1; /* careful, it is negative! */
2629 /* get line count before the insertion */
2630 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2631 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2632
2633 dp = (DATA_BL *)(hp->bh_data);
2634 }
2635
2636 ++buf->b_ml.ml_line_count;
2637
2638 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2639 {
2640/*
2641 * Insert new line in existing data block, or in data block allocated above.
2642 */
2643 dp->db_txt_start -= len;
2644 dp->db_free -= space_needed;
2645 ++(dp->db_line_count);
2646
2647 /*
2648 * move the text of the lines that follow to the front
2649 * adjust the indexes of the lines that follow
2650 */
2651 if (line_count > db_idx + 1) /* if there are following lines */
2652 {
2653 /*
2654 * Offset is the start of the previous line.
2655 * This will become the character just after the new line.
2656 */
2657 if (db_idx < 0)
2658 offset = dp->db_txt_end;
2659 else
2660 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2661 mch_memmove((char *)dp + dp->db_txt_start,
2662 (char *)dp + dp->db_txt_start + len,
2663 (size_t)(offset - (dp->db_txt_start + len)));
2664 for (i = line_count - 1; i > db_idx; --i)
2665 dp->db_index[i + 1] = dp->db_index[i] - len;
2666 dp->db_index[db_idx + 1] = offset - len;
2667 }
2668 else /* add line at the end */
2669 dp->db_index[db_idx + 1] = dp->db_txt_start;
2670
2671 /*
2672 * copy the text into the block
2673 */
2674 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2675 if (mark)
2676 dp->db_index[db_idx + 1] |= DB_MARKED;
2677
2678 /*
2679 * Mark the block dirty.
2680 */
2681 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2682 if (!newfile)
2683 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2684 }
2685 else /* not enough space in data block */
2686 {
2687/*
2688 * If there is not enough room we have to create a new data block and copy some
2689 * lines into it.
2690 * Then we have to insert an entry in the pointer block.
2691 * If this pointer block also is full, we go up another block, and so on, up
2692 * to the root if necessary.
2693 * The line counts in the pointer blocks have already been adjusted by
2694 * ml_find_line().
2695 */
2696 long line_count_left, line_count_right;
2697 int page_count_left, page_count_right;
2698 bhdr_T *hp_left;
2699 bhdr_T *hp_right;
2700 bhdr_T *hp_new;
2701 int lines_moved;
2702 int data_moved = 0; /* init to shut up gcc */
2703 int total_moved = 0; /* init to shut up gcc */
2704 DATA_BL *dp_right, *dp_left;
2705 int stack_idx;
2706 int in_left;
2707 int lineadd;
2708 blocknr_T bnum_left, bnum_right;
2709 linenr_T lnum_left, lnum_right;
2710 int pb_idx;
2711 PTR_BL *pp_new;
2712
2713 /*
2714 * We are going to allocate a new data block. Depending on the
2715 * situation it will be put to the left or right of the existing
2716 * block. If possible we put the new line in the left block and move
2717 * the lines after it to the right block. Otherwise the new line is
2718 * also put in the right block. This method is more efficient when
2719 * inserting a lot of lines at one place.
2720 */
2721 if (db_idx < 0) /* left block is new, right block is existing */
2722 {
2723 lines_moved = 0;
2724 in_left = TRUE;
2725 /* space_needed does not change */
2726 }
2727 else /* left block is existing, right block is new */
2728 {
2729 lines_moved = line_count - db_idx - 1;
2730 if (lines_moved == 0)
2731 in_left = FALSE; /* put new line in right block */
2732 /* space_needed does not change */
2733 else
2734 {
2735 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2736 dp->db_txt_start;
2737 total_moved = data_moved + lines_moved * INDEX_SIZE;
2738 if ((int)dp->db_free + total_moved >= space_needed)
2739 {
2740 in_left = TRUE; /* put new line in left block */
2741 space_needed = total_moved;
2742 }
2743 else
2744 {
2745 in_left = FALSE; /* put new line in right block */
2746 space_needed += total_moved;
2747 }
2748 }
2749 }
2750
2751 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2752 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2753 {
2754 /* correct line counts in pointer blocks */
2755 --(buf->b_ml.ml_locked_lineadd);
2756 --(buf->b_ml.ml_locked_high);
2757 return FAIL;
2758 }
2759 if (db_idx < 0) /* left block is new */
2760 {
2761 hp_left = hp_new;
2762 hp_right = hp;
2763 line_count_left = 0;
2764 line_count_right = line_count;
2765 }
2766 else /* right block is new */
2767 {
2768 hp_left = hp;
2769 hp_right = hp_new;
2770 line_count_left = line_count;
2771 line_count_right = 0;
2772 }
2773 dp_right = (DATA_BL *)(hp_right->bh_data);
2774 dp_left = (DATA_BL *)(hp_left->bh_data);
2775 bnum_left = hp_left->bh_bnum;
2776 bnum_right = hp_right->bh_bnum;
2777 page_count_left = hp_left->bh_page_count;
2778 page_count_right = hp_right->bh_page_count;
2779
2780 /*
2781 * May move the new line into the right/new block.
2782 */
2783 if (!in_left)
2784 {
2785 dp_right->db_txt_start -= len;
2786 dp_right->db_free -= len + INDEX_SIZE;
2787 dp_right->db_index[0] = dp_right->db_txt_start;
2788 if (mark)
2789 dp_right->db_index[0] |= DB_MARKED;
2790
2791 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2792 line, (size_t)len);
2793 ++line_count_right;
2794 }
2795 /*
2796 * may move lines from the left/old block to the right/new one.
2797 */
2798 if (lines_moved)
2799 {
2800 /*
2801 */
2802 dp_right->db_txt_start -= data_moved;
2803 dp_right->db_free -= total_moved;
2804 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2805 (char *)dp_left + dp_left->db_txt_start,
2806 (size_t)data_moved);
2807 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2808 dp_left->db_txt_start += data_moved;
2809 dp_left->db_free += total_moved;
2810
2811 /*
2812 * update indexes in the new block
2813 */
2814 for (to = line_count_right, from = db_idx + 1;
2815 from < line_count_left; ++from, ++to)
2816 dp_right->db_index[to] = dp->db_index[from] + offset;
2817 line_count_right += lines_moved;
2818 line_count_left -= lines_moved;
2819 }
2820
2821 /*
2822 * May move the new line into the left (old or new) block.
2823 */
2824 if (in_left)
2825 {
2826 dp_left->db_txt_start -= len;
2827 dp_left->db_free -= len + INDEX_SIZE;
2828 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2829 if (mark)
2830 dp_left->db_index[line_count_left] |= DB_MARKED;
2831 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2832 line, (size_t)len);
2833 ++line_count_left;
2834 }
2835
2836 if (db_idx < 0) /* left block is new */
2837 {
2838 lnum_left = lnum + 1;
2839 lnum_right = 0;
2840 }
2841 else /* right block is new */
2842 {
2843 lnum_left = 0;
2844 if (in_left)
2845 lnum_right = lnum + 2;
2846 else
2847 lnum_right = lnum + 1;
2848 }
2849 dp_left->db_line_count = line_count_left;
2850 dp_right->db_line_count = line_count_right;
2851
2852 /*
2853 * release the two data blocks
2854 * The new one (hp_new) already has a correct blocknumber.
2855 * The old one (hp, in ml_locked) gets a positive blocknumber if
2856 * we changed it and we are not editing a new file.
2857 */
2858 if (lines_moved || in_left)
2859 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2860 if (!newfile && db_idx >= 0 && in_left)
2861 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2862 mf_put(mfp, hp_new, TRUE, FALSE);
2863
2864 /*
2865 * flush the old data block
2866 * set ml_locked_lineadd to 0, because the updating of the
2867 * pointer blocks is done below
2868 */
2869 lineadd = buf->b_ml.ml_locked_lineadd;
2870 buf->b_ml.ml_locked_lineadd = 0;
2871 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2872
2873 /*
2874 * update pointer blocks for the new data block
2875 */
2876 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2877 --stack_idx)
2878 {
2879 ip = &(buf->b_ml.ml_stack[stack_idx]);
2880 pb_idx = ip->ip_index;
2881 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2882 return FAIL;
2883 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2884 if (pp->pb_id != PTR_ID)
2885 {
2886 EMSG(_("E317: pointer block id wrong 3"));
2887 mf_put(mfp, hp, FALSE, FALSE);
2888 return FAIL;
2889 }
2890 /*
2891 * TODO: If the pointer block is full and we are adding at the end
2892 * try to insert in front of the next block
2893 */
2894 /* block not full, add one entry */
2895 if (pp->pb_count < pp->pb_count_max)
2896 {
2897 if (pb_idx + 1 < (int)pp->pb_count)
2898 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2899 &pp->pb_pointer[pb_idx + 1],
2900 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2901 ++pp->pb_count;
2902 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2903 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2904 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2905 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2906 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2907 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2908
2909 if (lnum_left != 0)
2910 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2911 if (lnum_right != 0)
2912 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2913
2914 mf_put(mfp, hp, TRUE, FALSE);
2915 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2916
2917 if (lineadd)
2918 {
2919 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002920 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 ml_lineadd(buf, lineadd);
2922 /* fix stack itself */
2923 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2924 lineadd;
2925 ++(buf->b_ml.ml_stack_top);
2926 }
2927
2928 /*
2929 * We are finished, break the loop here.
2930 */
2931 break;
2932 }
2933 else /* pointer block full */
2934 {
2935 /*
2936 * split the pointer block
2937 * allocate a new pointer block
2938 * move some of the pointer into the new block
2939 * prepare for updating the parent block
2940 */
2941 for (;;) /* do this twice when splitting block 1 */
2942 {
2943 hp_new = ml_new_ptr(mfp);
2944 if (hp_new == NULL) /* TODO: try to fix tree */
2945 return FAIL;
2946 pp_new = (PTR_BL *)(hp_new->bh_data);
2947
2948 if (hp->bh_bnum != 1)
2949 break;
2950
2951 /*
2952 * if block 1 becomes full the tree is given an extra level
2953 * The pointers from block 1 are moved into the new block.
2954 * block 1 is updated to point to the new block
2955 * then continue to split the new block
2956 */
2957 mch_memmove(pp_new, pp, (size_t)page_size);
2958 pp->pb_count = 1;
2959 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2960 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2961 pp->pb_pointer[0].pe_old_lnum = 1;
2962 pp->pb_pointer[0].pe_page_count = 1;
2963 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2964 hp = hp_new; /* new block is to be split */
2965 pp = pp_new;
2966 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2967 ip->ip_index = 0;
2968 ++stack_idx; /* do block 1 again later */
2969 }
2970 /*
2971 * move the pointers after the current one to the new block
2972 * If there are none, the new entry will be in the new block.
2973 */
2974 total_moved = pp->pb_count - pb_idx - 1;
2975 if (total_moved)
2976 {
2977 mch_memmove(&pp_new->pb_pointer[0],
2978 &pp->pb_pointer[pb_idx + 1],
2979 (size_t)(total_moved) * sizeof(PTR_EN));
2980 pp_new->pb_count = total_moved;
2981 pp->pb_count -= total_moved - 1;
2982 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2983 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2984 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2985 if (lnum_right)
2986 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2987 }
2988 else
2989 {
2990 pp_new->pb_count = 1;
2991 pp_new->pb_pointer[0].pe_bnum = bnum_right;
2992 pp_new->pb_pointer[0].pe_line_count = line_count_right;
2993 pp_new->pb_pointer[0].pe_page_count = page_count_right;
2994 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
2995 }
2996 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2997 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2998 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2999 if (lnum_left)
3000 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3001 lnum_left = 0;
3002 lnum_right = 0;
3003
3004 /*
3005 * recompute line counts
3006 */
3007 line_count_right = 0;
3008 for (i = 0; i < (int)pp_new->pb_count; ++i)
3009 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3010 line_count_left = 0;
3011 for (i = 0; i < (int)pp->pb_count; ++i)
3012 line_count_left += pp->pb_pointer[i].pe_line_count;
3013
3014 bnum_left = hp->bh_bnum;
3015 bnum_right = hp_new->bh_bnum;
3016 page_count_left = 1;
3017 page_count_right = 1;
3018 mf_put(mfp, hp, TRUE, FALSE);
3019 mf_put(mfp, hp_new, TRUE, FALSE);
3020 }
3021 }
3022
3023 /*
3024 * Safety check: fallen out of for loop?
3025 */
3026 if (stack_idx < 0)
3027 {
3028 EMSG(_("E318: Updated too many blocks?"));
3029 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3030 }
3031 }
3032
3033#ifdef FEAT_BYTEOFF
3034 /* The line was inserted below 'lnum' */
3035 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3036#endif
3037#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003038 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039 {
3040 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003041 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003042 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 (char_u *)"\n", 1);
3044 }
3045#endif
3046 return OK;
3047}
3048
3049/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003050 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003052 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053 * copied to allocated memory already.
3054 *
3055 * Check: The caller of this function should probably also call
3056 * changed_lines(), unless update_screen(NOT_VALID) is used.
3057 *
3058 * return FAIL for failure, OK otherwise
3059 */
3060 int
3061ml_replace(lnum, line, copy)
3062 linenr_T lnum;
3063 char_u *line;
3064 int copy;
3065{
3066 if (line == NULL) /* just checking... */
3067 return FAIL;
3068
3069 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003070 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 return FAIL;
3072
3073 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3074 return FAIL;
3075#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003076 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077 {
3078 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003079 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080 }
3081#endif
3082 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3083 ml_flush_line(curbuf); /* flush it */
3084 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3085 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3086 curbuf->b_ml.ml_line_ptr = line;
3087 curbuf->b_ml.ml_line_lnum = lnum;
3088 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3089
3090 return OK;
3091}
3092
3093/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003094 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 *
3096 * Check: The caller of this function should probably also call
3097 * deleted_lines() after this.
3098 *
3099 * return FAIL for failure, OK otherwise
3100 */
3101 int
3102ml_delete(lnum, message)
3103 linenr_T lnum;
3104 int message;
3105{
3106 ml_flush_line(curbuf);
3107 return ml_delete_int(curbuf, lnum, message);
3108}
3109
3110 static int
3111ml_delete_int(buf, lnum, message)
3112 buf_T *buf;
3113 linenr_T lnum;
3114 int message;
3115{
3116 bhdr_T *hp;
3117 memfile_T *mfp;
3118 DATA_BL *dp;
3119 PTR_BL *pp;
3120 infoptr_T *ip;
3121 int count; /* number of entries in block */
3122 int idx;
3123 int stack_idx;
3124 int text_start;
3125 int line_start;
3126 long line_size;
3127 int i;
3128
3129 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3130 return FAIL;
3131
3132 if (lowest_marked && lowest_marked > lnum)
3133 lowest_marked--;
3134
3135/*
3136 * If the file becomes empty the last line is replaced by an empty line.
3137 */
3138 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3139 {
3140 if (message
3141#ifdef FEAT_NETBEANS_INTG
3142 && !netbeansSuppressNoLines
3143#endif
3144 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003145 set_keep_msg((char_u *)_(no_lines_msg), 0);
3146
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003147 /* FEAT_BYTEOFF already handled in there, don't worry 'bout it below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003148 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3149 buf->b_ml.ml_flags |= ML_EMPTY;
3150
3151 return i;
3152 }
3153
3154/*
3155 * find the data block containing the line
3156 * This also fills the stack with the blocks from the root to the data block
3157 * This also releases any locked block.
3158 */
3159 mfp = buf->b_ml.ml_mfp;
3160 if (mfp == NULL)
3161 return FAIL;
3162
3163 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3164 return FAIL;
3165
3166 dp = (DATA_BL *)(hp->bh_data);
3167 /* compute line count before the delete */
3168 count = (long)(buf->b_ml.ml_locked_high)
3169 - (long)(buf->b_ml.ml_locked_low) + 2;
3170 idx = lnum - buf->b_ml.ml_locked_low;
3171
3172 --buf->b_ml.ml_line_count;
3173
3174 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3175 if (idx == 0) /* first line in block, text at the end */
3176 line_size = dp->db_txt_end - line_start;
3177 else
3178 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3179
3180#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003181 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003182 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183#endif
3184
3185/*
3186 * special case: If there is only one line in the data block it becomes empty.
3187 * Then we have to remove the entry, pointing to this data block, from the
3188 * pointer block. If this pointer block also becomes empty, we go up another
3189 * block, and so on, up to the root if necessary.
3190 * The line counts in the pointer blocks have already been adjusted by
3191 * ml_find_line().
3192 */
3193 if (count == 1)
3194 {
3195 mf_free(mfp, hp); /* free the data block */
3196 buf->b_ml.ml_locked = NULL;
3197
Bram Moolenaare60acc12011-05-10 16:41:25 +02003198 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3199 --stack_idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 {
3201 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3202 ip = &(buf->b_ml.ml_stack[stack_idx]);
3203 idx = ip->ip_index;
3204 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3205 return FAIL;
3206 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3207 if (pp->pb_id != PTR_ID)
3208 {
3209 EMSG(_("E317: pointer block id wrong 4"));
3210 mf_put(mfp, hp, FALSE, FALSE);
3211 return FAIL;
3212 }
3213 count = --(pp->pb_count);
3214 if (count == 0) /* the pointer block becomes empty! */
3215 mf_free(mfp, hp);
3216 else
3217 {
3218 if (count != idx) /* move entries after the deleted one */
3219 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3220 (size_t)(count - idx) * sizeof(PTR_EN));
3221 mf_put(mfp, hp, TRUE, FALSE);
3222
3223 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003224 /* fix line count for rest of blocks in the stack */
3225 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 {
3227 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3228 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003229 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 }
3231 ++(buf->b_ml.ml_stack_top);
3232
3233 break;
3234 }
3235 }
3236 CHECK(stack_idx < 0, _("deleted block 1?"));
3237 }
3238 else
3239 {
3240 /*
3241 * delete the text by moving the next lines forwards
3242 */
3243 text_start = dp->db_txt_start;
3244 mch_memmove((char *)dp + text_start + line_size,
3245 (char *)dp + text_start, (size_t)(line_start - text_start));
3246
3247 /*
3248 * delete the index by moving the next indexes backwards
3249 * Adjust the indexes for the text movement.
3250 */
3251 for (i = idx; i < count - 1; ++i)
3252 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3253
3254 dp->db_free += line_size + INDEX_SIZE;
3255 dp->db_txt_start += line_size;
3256 --(dp->db_line_count);
3257
3258 /*
3259 * mark the block dirty and make sure it is in the file (for recovery)
3260 */
3261 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3262 }
3263
3264#ifdef FEAT_BYTEOFF
3265 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3266#endif
3267 return OK;
3268}
3269
3270/*
3271 * set the B_MARKED flag for line 'lnum'
3272 */
3273 void
3274ml_setmarked(lnum)
3275 linenr_T lnum;
3276{
3277 bhdr_T *hp;
3278 DATA_BL *dp;
3279 /* invalid line number */
3280 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3281 || curbuf->b_ml.ml_mfp == NULL)
3282 return; /* give error message? */
3283
3284 if (lowest_marked == 0 || lowest_marked > lnum)
3285 lowest_marked = lnum;
3286
3287 /*
3288 * find the data block containing the line
3289 * This also fills the stack with the blocks from the root to the data block
3290 * This also releases any locked block.
3291 */
3292 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3293 return; /* give error message? */
3294
3295 dp = (DATA_BL *)(hp->bh_data);
3296 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3297 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3298}
3299
3300/*
3301 * find the first line with its B_MARKED flag set
3302 */
3303 linenr_T
3304ml_firstmarked()
3305{
3306 bhdr_T *hp;
3307 DATA_BL *dp;
3308 linenr_T lnum;
3309 int i;
3310
3311 if (curbuf->b_ml.ml_mfp == NULL)
3312 return (linenr_T) 0;
3313
3314 /*
3315 * The search starts with lowest_marked line. This is the last line where
3316 * a mark was found, adjusted by inserting/deleting lines.
3317 */
3318 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3319 {
3320 /*
3321 * Find the data block containing the line.
3322 * This also fills the stack with the blocks from the root to the data
3323 * block This also releases any locked block.
3324 */
3325 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3326 return (linenr_T)0; /* give error message? */
3327
3328 dp = (DATA_BL *)(hp->bh_data);
3329
3330 for (i = lnum - curbuf->b_ml.ml_locked_low;
3331 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3332 if ((dp->db_index[i]) & DB_MARKED)
3333 {
3334 (dp->db_index[i]) &= DB_INDEX_MASK;
3335 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3336 lowest_marked = lnum + 1;
3337 return lnum;
3338 }
3339 }
3340
3341 return (linenr_T) 0;
3342}
3343
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344/*
3345 * clear all DB_MARKED flags
3346 */
3347 void
3348ml_clearmarked()
3349{
3350 bhdr_T *hp;
3351 DATA_BL *dp;
3352 linenr_T lnum;
3353 int i;
3354
3355 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3356 return;
3357
3358 /*
3359 * The search starts with line lowest_marked.
3360 */
3361 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3362 {
3363 /*
3364 * Find the data block containing the line.
3365 * This also fills the stack with the blocks from the root to the data
3366 * block and releases any locked block.
3367 */
3368 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3369 return; /* give error message? */
3370
3371 dp = (DATA_BL *)(hp->bh_data);
3372
3373 for (i = lnum - curbuf->b_ml.ml_locked_low;
3374 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3375 if ((dp->db_index[i]) & DB_MARKED)
3376 {
3377 (dp->db_index[i]) &= DB_INDEX_MASK;
3378 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3379 }
3380 }
3381
3382 lowest_marked = 0;
3383 return;
3384}
3385
3386/*
3387 * flush ml_line if necessary
3388 */
3389 static void
3390ml_flush_line(buf)
3391 buf_T *buf;
3392{
3393 bhdr_T *hp;
3394 DATA_BL *dp;
3395 linenr_T lnum;
3396 char_u *new_line;
3397 char_u *old_line;
3398 colnr_T new_len;
3399 int old_len;
3400 int extra;
3401 int idx;
3402 int start;
3403 int count;
3404 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003405 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406
3407 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3408 return; /* nothing to do */
3409
3410 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3411 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003412 /* This code doesn't work recursively, but Netbeans may call back here
3413 * when obtaining the cursor position. */
3414 if (entered)
3415 return;
3416 entered = TRUE;
3417
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418 lnum = buf->b_ml.ml_line_lnum;
3419 new_line = buf->b_ml.ml_line_ptr;
3420
3421 hp = ml_find_line(buf, lnum, ML_FIND);
3422 if (hp == NULL)
3423 EMSGN(_("E320: Cannot find line %ld"), lnum);
3424 else
3425 {
3426 dp = (DATA_BL *)(hp->bh_data);
3427 idx = lnum - buf->b_ml.ml_locked_low;
3428 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3429 old_line = (char_u *)dp + start;
3430 if (idx == 0) /* line is last in block */
3431 old_len = dp->db_txt_end - start;
3432 else /* text of previous line follows */
3433 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3434 new_len = (colnr_T)STRLEN(new_line) + 1;
3435 extra = new_len - old_len; /* negative if lines gets smaller */
3436
3437 /*
3438 * if new line fits in data block, replace directly
3439 */
3440 if ((int)dp->db_free >= extra)
3441 {
3442 /* if the length changes and there are following lines */
3443 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3444 if (extra != 0 && idx < count - 1)
3445 {
3446 /* move text of following lines */
3447 mch_memmove((char *)dp + dp->db_txt_start - extra,
3448 (char *)dp + dp->db_txt_start,
3449 (size_t)(start - dp->db_txt_start));
3450
3451 /* adjust pointers of this and following lines */
3452 for (i = idx + 1; i < count; ++i)
3453 dp->db_index[i] -= extra;
3454 }
3455 dp->db_index[idx] -= extra;
3456
3457 /* adjust free space */
3458 dp->db_free -= extra;
3459 dp->db_txt_start -= extra;
3460
3461 /* copy new line into the data block */
3462 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3463 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3464#ifdef FEAT_BYTEOFF
3465 /* The else case is already covered by the insert and delete */
3466 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3467#endif
3468 }
3469 else
3470 {
3471 /*
3472 * Cannot do it in one data block: Delete and append.
3473 * Append first, because ml_delete_int() cannot delete the
3474 * last line in a buffer, which causes trouble for a buffer
3475 * that has only one line.
3476 * Don't forget to copy the mark!
3477 */
3478 /* How about handling errors??? */
3479 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3480 (dp->db_index[idx] & DB_MARKED));
3481 (void)ml_delete_int(buf, lnum, FALSE);
3482 }
3483 }
3484 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003485
3486 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487 }
3488
3489 buf->b_ml.ml_line_lnum = 0;
3490}
3491
3492/*
3493 * create a new, empty, data block
3494 */
3495 static bhdr_T *
3496ml_new_data(mfp, negative, page_count)
3497 memfile_T *mfp;
3498 int negative;
3499 int page_count;
3500{
3501 bhdr_T *hp;
3502 DATA_BL *dp;
3503
3504 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3505 return NULL;
3506
3507 dp = (DATA_BL *)(hp->bh_data);
3508 dp->db_id = DATA_ID;
3509 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3510 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3511 dp->db_line_count = 0;
3512
3513 return hp;
3514}
3515
3516/*
3517 * create a new, empty, pointer block
3518 */
3519 static bhdr_T *
3520ml_new_ptr(mfp)
3521 memfile_T *mfp;
3522{
3523 bhdr_T *hp;
3524 PTR_BL *pp;
3525
3526 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3527 return NULL;
3528
3529 pp = (PTR_BL *)(hp->bh_data);
3530 pp->pb_id = PTR_ID;
3531 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003532 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3533 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534
3535 return hp;
3536}
3537
3538/*
3539 * lookup line 'lnum' in a memline
3540 *
3541 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3542 * if ML_FLUSH only flush a locked block
3543 * if ML_FIND just find the line
3544 *
3545 * If the block was found it is locked and put in ml_locked.
3546 * The stack is updated to lead to the locked block. The ip_high field in
3547 * the stack is updated to reflect the last line in the block AFTER the
3548 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003549 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 *
3551 * return: NULL for failure, pointer to block header otherwise
3552 */
3553 static bhdr_T *
3554ml_find_line(buf, lnum, action)
3555 buf_T *buf;
3556 linenr_T lnum;
3557 int action;
3558{
3559 DATA_BL *dp;
3560 PTR_BL *pp;
3561 infoptr_T *ip;
3562 bhdr_T *hp;
3563 memfile_T *mfp;
3564 linenr_T t;
3565 blocknr_T bnum, bnum2;
3566 int dirty;
3567 linenr_T low, high;
3568 int top;
3569 int page_count;
3570 int idx;
3571
3572 mfp = buf->b_ml.ml_mfp;
3573
3574 /*
3575 * If there is a locked block check if the wanted line is in it.
3576 * If not, flush and release the locked block.
3577 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3578 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003579 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 */
3581 if (buf->b_ml.ml_locked)
3582 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003583 if (ML_SIMPLE(action)
3584 && buf->b_ml.ml_locked_low <= lnum
3585 && buf->b_ml.ml_locked_high >= lnum
3586 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003588 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589 if (action == ML_INSERT)
3590 {
3591 ++(buf->b_ml.ml_locked_lineadd);
3592 ++(buf->b_ml.ml_locked_high);
3593 }
3594 else if (action == ML_DELETE)
3595 {
3596 --(buf->b_ml.ml_locked_lineadd);
3597 --(buf->b_ml.ml_locked_high);
3598 }
3599 return (buf->b_ml.ml_locked);
3600 }
3601
3602 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3603 buf->b_ml.ml_flags & ML_LOCKED_POS);
3604 buf->b_ml.ml_locked = NULL;
3605
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003606 /*
3607 * If lines have been added or deleted in the locked block, need to
3608 * update the line count in pointer blocks.
3609 */
3610 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3612 }
3613
3614 if (action == ML_FLUSH) /* nothing else to do */
3615 return NULL;
3616
3617 bnum = 1; /* start at the root of the tree */
3618 page_count = 1;
3619 low = 1;
3620 high = buf->b_ml.ml_line_count;
3621
3622 if (action == ML_FIND) /* first try stack entries */
3623 {
3624 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3625 {
3626 ip = &(buf->b_ml.ml_stack[top]);
3627 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3628 {
3629 bnum = ip->ip_bnum;
3630 low = ip->ip_low;
3631 high = ip->ip_high;
3632 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3633 break;
3634 }
3635 }
3636 if (top < 0)
3637 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3638 }
3639 else /* ML_DELETE or ML_INSERT */
3640 buf->b_ml.ml_stack_top = 0; /* start at the root */
3641
3642/*
3643 * search downwards in the tree until a data block is found
3644 */
3645 for (;;)
3646 {
3647 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3648 goto error_noblock;
3649
3650 /*
3651 * update high for insert/delete
3652 */
3653 if (action == ML_INSERT)
3654 ++high;
3655 else if (action == ML_DELETE)
3656 --high;
3657
3658 dp = (DATA_BL *)(hp->bh_data);
3659 if (dp->db_id == DATA_ID) /* data block */
3660 {
3661 buf->b_ml.ml_locked = hp;
3662 buf->b_ml.ml_locked_low = low;
3663 buf->b_ml.ml_locked_high = high;
3664 buf->b_ml.ml_locked_lineadd = 0;
3665 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3666 return hp;
3667 }
3668
3669 pp = (PTR_BL *)(dp); /* must be pointer block */
3670 if (pp->pb_id != PTR_ID)
3671 {
3672 EMSG(_("E317: pointer block id wrong"));
3673 goto error_block;
3674 }
3675
3676 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3677 goto error_block;
3678 ip = &(buf->b_ml.ml_stack[top]);
3679 ip->ip_bnum = bnum;
3680 ip->ip_low = low;
3681 ip->ip_high = high;
3682 ip->ip_index = -1; /* index not known yet */
3683
3684 dirty = FALSE;
3685 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3686 {
3687 t = pp->pb_pointer[idx].pe_line_count;
3688 CHECK(t == 0, _("pe_line_count is zero"));
3689 if ((low += t) > lnum)
3690 {
3691 ip->ip_index = idx;
3692 bnum = pp->pb_pointer[idx].pe_bnum;
3693 page_count = pp->pb_pointer[idx].pe_page_count;
3694 high = low - 1;
3695 low -= t;
3696
3697 /*
3698 * a negative block number may have been changed
3699 */
3700 if (bnum < 0)
3701 {
3702 bnum2 = mf_trans_del(mfp, bnum);
3703 if (bnum != bnum2)
3704 {
3705 bnum = bnum2;
3706 pp->pb_pointer[idx].pe_bnum = bnum;
3707 dirty = TRUE;
3708 }
3709 }
3710
3711 break;
3712 }
3713 }
3714 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3715 {
3716 if (lnum > buf->b_ml.ml_line_count)
3717 EMSGN(_("E322: line number out of range: %ld past the end"),
3718 lnum - buf->b_ml.ml_line_count);
3719
3720 else
3721 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3722 goto error_block;
3723 }
3724 if (action == ML_DELETE)
3725 {
3726 pp->pb_pointer[idx].pe_line_count--;
3727 dirty = TRUE;
3728 }
3729 else if (action == ML_INSERT)
3730 {
3731 pp->pb_pointer[idx].pe_line_count++;
3732 dirty = TRUE;
3733 }
3734 mf_put(mfp, hp, dirty, FALSE);
3735 }
3736
3737error_block:
3738 mf_put(mfp, hp, FALSE, FALSE);
3739error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003740 /*
3741 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3742 * the incremented/decremented line counts, because there won't be a line
3743 * inserted/deleted after all.
3744 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 if (action == ML_DELETE)
3746 ml_lineadd(buf, 1);
3747 else if (action == ML_INSERT)
3748 ml_lineadd(buf, -1);
3749 buf->b_ml.ml_stack_top = 0;
3750 return NULL;
3751}
3752
3753/*
3754 * add an entry to the info pointer stack
3755 *
3756 * return -1 for failure, number of the new entry otherwise
3757 */
3758 static int
3759ml_add_stack(buf)
3760 buf_T *buf;
3761{
3762 int top;
3763 infoptr_T *newstack;
3764
3765 top = buf->b_ml.ml_stack_top;
3766
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003767 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768 if (top == buf->b_ml.ml_stack_size)
3769 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003770 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771
3772 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3773 (buf->b_ml.ml_stack_size + STACK_INCR));
3774 if (newstack == NULL)
3775 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003776 mch_memmove(newstack, buf->b_ml.ml_stack,
3777 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 vim_free(buf->b_ml.ml_stack);
3779 buf->b_ml.ml_stack = newstack;
3780 buf->b_ml.ml_stack_size += STACK_INCR;
3781 }
3782
3783 buf->b_ml.ml_stack_top++;
3784 return top;
3785}
3786
3787/*
3788 * Update the pointer blocks on the stack for inserted/deleted lines.
3789 * The stack itself is also updated.
3790 *
3791 * When a insert/delete line action fails, the line is not inserted/deleted,
3792 * but the pointer blocks have already been updated. That is fixed here by
3793 * walking through the stack.
3794 *
3795 * Count is the number of lines added, negative if lines have been deleted.
3796 */
3797 static void
3798ml_lineadd(buf, count)
3799 buf_T *buf;
3800 int count;
3801{
3802 int idx;
3803 infoptr_T *ip;
3804 PTR_BL *pp;
3805 memfile_T *mfp = buf->b_ml.ml_mfp;
3806 bhdr_T *hp;
3807
3808 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3809 {
3810 ip = &(buf->b_ml.ml_stack[idx]);
3811 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3812 break;
3813 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3814 if (pp->pb_id != PTR_ID)
3815 {
3816 mf_put(mfp, hp, FALSE, FALSE);
3817 EMSG(_("E317: pointer block id wrong 2"));
3818 break;
3819 }
3820 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3821 ip->ip_high += count;
3822 mf_put(mfp, hp, TRUE, FALSE);
3823 }
3824}
3825
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003826#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003827/*
3828 * Resolve a symlink in the last component of a file name.
3829 * Note that f_resolve() does it for every part of the path, we don't do that
3830 * here.
3831 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3832 * Otherwise returns FAIL.
3833 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003834 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003835resolve_symlink(fname, buf)
3836 char_u *fname;
3837 char_u *buf;
3838{
3839 char_u tmp[MAXPATHL];
3840 int ret;
3841 int depth = 0;
3842
3843 if (fname == NULL)
3844 return FAIL;
3845
3846 /* Put the result so far in tmp[], starting with the original name. */
3847 vim_strncpy(tmp, fname, MAXPATHL - 1);
3848
3849 for (;;)
3850 {
3851 /* Limit symlink depth to 100, catch recursive loops. */
3852 if (++depth == 100)
3853 {
3854 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3855 return FAIL;
3856 }
3857
3858 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3859 if (ret <= 0)
3860 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003861 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003862 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003863 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003864 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003865 * call to vim_FullName(). */
3866 if (depth == 1)
3867 return FAIL;
3868
3869 /* Use the resolved name in tmp[]. */
3870 break;
3871 }
3872
3873 /* There must be some error reading links, use original name. */
3874 return FAIL;
3875 }
3876 buf[ret] = NUL;
3877
3878 /*
3879 * Check whether the symlink is relative or absolute.
3880 * If it's relative, build a new path based on the directory
3881 * portion of the filename (if any) and the path the symlink
3882 * points to.
3883 */
3884 if (mch_isFullName(buf))
3885 STRCPY(tmp, buf);
3886 else
3887 {
3888 char_u *tail;
3889
3890 tail = gettail(tmp);
3891 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3892 return FAIL;
3893 STRCPY(tail, buf);
3894 }
3895 }
3896
3897 /*
3898 * Try to resolve the full name of the file so that the swapfile name will
3899 * be consistent even when opening a relative symlink from different
3900 * working directories.
3901 */
3902 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3903}
3904#endif
3905
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003907 * Make swap file name out of the file name and a directory name.
3908 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003910 char_u *
3911makeswapname(fname, ffname, buf, dir_name)
3912 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003913 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 buf_T *buf;
3915 char_u *dir_name;
3916{
3917 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003918 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003919#ifdef HAVE_READLINK
3920 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003921#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003922
3923#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3924 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003925 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 { /* Ends with '//', Use Full path */
3927 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003928 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 {
3930 r = modname(s, (char_u *)".swp", FALSE);
3931 vim_free(s);
3932 }
3933 return r;
3934 }
3935#endif
3936
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003937#ifdef HAVE_READLINK
3938 /* Expand symlink in the file name, so that we put the swap file with the
3939 * actual file instead of with the symlink. */
3940 if (resolve_symlink(fname, fname_buf) == OK)
3941 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003942#endif
3943
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 r = buf_modname(
3945#ifdef SHORT_FNAME
3946 TRUE,
3947#else
3948 (buf->b_p_sn || buf->b_shortname),
3949#endif
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003950 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 (char_u *)
Bram Moolenaare60acc12011-05-10 16:41:25 +02003952#if defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953 "_swp",
3954#else
3955 ".swp",
3956#endif
3957#ifdef SHORT_FNAME /* always 8.3 file name */
3958 FALSE
3959#else
3960 /* Prepend a '.' to the swap file name for the current directory. */
3961 dir_name[0] == '.' && dir_name[1] == NUL
3962#endif
3963 );
3964 if (r == NULL) /* out of memory */
3965 return NULL;
3966
3967 s = get_file_in_dir(r, dir_name);
3968 vim_free(r);
3969 return s;
3970}
3971
3972/*
3973 * Get file name to use for swap file or backup file.
3974 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3975 * option "dname".
3976 * - If "dname" is ".", return "fname" (swap file in dir of file).
3977 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3978 * relative to dir of file).
3979 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
3980 * dir).
3981 *
3982 * The return value is an allocated string and can be NULL.
3983 */
3984 char_u *
3985get_file_in_dir(fname, dname)
3986 char_u *fname;
3987 char_u *dname; /* don't use "dirname", it is a global for Alpha */
3988{
3989 char_u *t;
3990 char_u *tail;
3991 char_u *retval;
3992 int save_char;
3993
3994 tail = gettail(fname);
3995
3996 if (dname[0] == '.' && dname[1] == NUL)
3997 retval = vim_strsave(fname);
3998 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
3999 {
4000 if (tail == fname) /* no path before file name */
4001 retval = concat_fnames(dname + 2, tail, TRUE);
4002 else
4003 {
4004 save_char = *tail;
4005 *tail = NUL;
4006 t = concat_fnames(fname, dname + 2, TRUE);
4007 *tail = save_char;
4008 if (t == NULL) /* out of memory */
4009 retval = NULL;
4010 else
4011 {
4012 retval = concat_fnames(t, tail, TRUE);
4013 vim_free(t);
4014 }
4015 }
4016 }
4017 else
4018 retval = concat_fnames(dname, tail, TRUE);
4019
Bram Moolenaar69c35002013-11-04 02:54:12 +01004020#ifdef WIN3264
4021 if (retval != NULL)
4022 for (t = gettail(retval); *t != NUL; mb_ptr_adv(t))
4023 if (*t == ':')
4024 *t = '%';
4025#endif
4026
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027 return retval;
4028}
4029
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004030static void attention_message __ARGS((buf_T *buf, char_u *fname));
4031
4032/*
4033 * Print the ATTENTION message: info about an existing swap file.
4034 */
4035 static void
4036attention_message(buf, fname)
4037 buf_T *buf; /* buffer being edited */
4038 char_u *fname; /* swap file name */
4039{
4040 struct stat st;
4041 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004042 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004043
4044 ++no_wait_return;
4045 (void)EMSG(_("E325: ATTENTION"));
4046 MSG_PUTS(_("\nFound a swap file by the name \""));
4047 msg_home_replace(fname);
4048 MSG_PUTS("\"\n");
4049 sx = swapfile_info(fname);
4050 MSG_PUTS(_("While opening file \""));
4051 msg_outtrans(buf->b_fname);
4052 MSG_PUTS("\"\n");
4053 if (mch_stat((char *)buf->b_fname, &st) != -1)
4054 {
4055 MSG_PUTS(_(" dated: "));
4056 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004057 p = ctime(&x); /* includes '\n' */
4058 if (p == NULL)
4059 MSG_PUTS("(invalid)\n");
4060 else
4061 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004062 if (sx != 0 && x > sx)
4063 MSG_PUTS(_(" NEWER than swap file!\n"));
4064 }
4065 /* Some of these messages are long to allow translation to
4066 * other languages. */
Bram Moolenaarc41fc712011-02-15 11:57:04 +01004067 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."));
4068 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4069 MSG_PUTS(_("(2) An edit session for this file crashed.\n"));
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004070 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4071 msg_outtrans(buf->b_fname);
4072 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4073 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4074 msg_outtrans(fname);
4075 MSG_PUTS(_("\"\n to avoid this message.\n"));
4076 cmdline_row = msg_row;
4077 --no_wait_return;
4078}
4079
4080#ifdef FEAT_AUTOCMD
4081static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4082
4083/*
4084 * Trigger the SwapExists autocommands.
4085 * Returns a value for equivalent to do_dialog() (see below):
4086 * 0: still need to ask for a choice
4087 * 1: open read-only
4088 * 2: edit anyway
4089 * 3: recover
4090 * 4: delete it
4091 * 5: quit
4092 * 6: abort
4093 */
4094 static int
4095do_swapexists(buf, fname)
4096 buf_T *buf;
4097 char_u *fname;
4098{
4099 set_vim_var_string(VV_SWAPNAME, fname, -1);
4100 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4101
4102 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004103 * edited. Disallow changing directory here. */
4104 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004105 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004106 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004107
4108 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4109
4110 switch (*get_vim_var_str(VV_SWAPCHOICE))
4111 {
4112 case 'o': return 1;
4113 case 'e': return 2;
4114 case 'r': return 3;
4115 case 'd': return 4;
4116 case 'q': return 5;
4117 case 'a': return 6;
4118 }
4119
4120 return 0;
4121}
4122#endif
4123
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124/*
4125 * Find out what name to use for the swap file for buffer 'buf'.
4126 *
4127 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004128 * Returns the name in allocated memory or NULL.
Bram Moolenaarf541c362011-10-26 11:44:18 +02004129 * When out of memory "dirp" is set to NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 *
4131 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004132 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004133 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 */
4135 static char_u *
4136findswapname(buf, dirp, old_fname)
4137 buf_T *buf;
4138 char_u **dirp; /* pointer to list of directories */
4139 char_u *old_fname; /* don't give warning for this file name */
4140{
4141 char_u *fname;
4142 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 char_u *dir_name;
4144#ifdef AMIGA
4145 BPTR fh;
4146#endif
4147#ifndef SHORT_FNAME
4148 int r;
4149#endif
Bram Moolenaar69c35002013-11-04 02:54:12 +01004150 char_u *buf_fname = buf->b_fname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151
4152#if !defined(SHORT_FNAME) \
Bram Moolenaar69c35002013-11-04 02:54:12 +01004153 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154# define CREATE_DUMMY_FILE
4155 FILE *dummyfd = NULL;
4156
Bram Moolenaar69c35002013-11-04 02:54:12 +01004157# ifdef WIN3264
4158 if (buf_fname != NULL && !mch_isFullName(buf_fname)
4159 && vim_strchr(gettail(buf_fname), ':'))
4160 {
4161 char_u *t;
4162
4163 buf_fname = vim_strsave(buf_fname);
4164 if (buf_fname == NULL)
4165 buf_fname = buf->b_fname;
4166 else
4167 for (t = gettail(buf_fname); *t != NUL; mb_ptr_adv(t))
4168 if (*t == ':')
4169 *t = '%';
4170 }
4171# endif
4172
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004173 /*
4174 * If we start editing a new file, e.g. "test.doc", which resides on an
4175 * MSDOS compatible filesystem, it is possible that the file
4176 * "test.doc.swp" which we create will be exactly the same file. To avoid
4177 * this problem we temporarily create "test.doc". Don't do this when the
4178 * check below for a 8.3 file name is used.
4179 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004180 if (!(buf->b_p_sn || buf->b_shortname) && buf_fname != NULL
4181 && mch_getperm(buf_fname) < 0)
4182 dummyfd = mch_fopen((char *)buf_fname, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183#endif
4184
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004185 /*
4186 * Isolate a directory name from *dirp and put it in dir_name.
4187 * First allocate some memory to put the directory name in.
4188 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
Bram Moolenaarf541c362011-10-26 11:44:18 +02004190 if (dir_name == NULL)
4191 *dirp = NULL;
4192 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 (void)copy_option_part(dirp, dir_name, 31000, ",");
4194
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004195 /*
4196 * we try different names until we find one that does not exist yet
4197 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 if (dir_name == NULL) /* out of memory */
4199 fname = NULL;
4200 else
Bram Moolenaar69c35002013-11-04 02:54:12 +01004201 fname = makeswapname(buf_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202
4203 for (;;)
4204 {
4205 if (fname == NULL) /* must be out of memory */
4206 break;
4207 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4208 {
4209 vim_free(fname);
4210 fname = NULL;
4211 break;
4212 }
4213#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4214/*
4215 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4216 * file names. If this is the first try and the swap file name does not fit in
4217 * 8.3, detect if this is the case, set shortname and try again.
4218 */
4219 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4220 && !(buf->b_p_sn || buf->b_shortname))
4221 {
4222 char_u *tail;
4223 char_u *fname2;
4224 struct stat s1, s2;
4225 int f1, f2;
4226 int created1 = FALSE, created2 = FALSE;
4227 int same = FALSE;
4228
4229 /*
4230 * Check if swapfile name does not fit in 8.3:
4231 * It either contains two dots, is longer than 8 chars, or starts
4232 * with a dot.
4233 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004234 tail = gettail(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 if ( vim_strchr(tail, '.') != NULL
4236 || STRLEN(tail) > (size_t)8
4237 || *gettail(fname) == '.')
4238 {
4239 fname2 = alloc(n + 2);
4240 if (fname2 != NULL)
4241 {
4242 STRCPY(fname2, fname);
4243 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4244 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4245 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4246 */
4247 if (vim_strchr(tail, '.') != NULL)
4248 fname2[n - 1] = 'x';
4249 else if (*gettail(fname) == '.')
4250 {
4251 fname2[n] = 'x';
4252 fname2[n + 1] = NUL;
4253 }
4254 else
4255 fname2[n - 5] += 1;
4256 /*
4257 * may need to create the files to be able to use mch_stat()
4258 */
4259 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4260 if (f1 < 0)
4261 {
4262 f1 = mch_open_rw((char *)fname,
4263 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4264#if defined(OS2)
4265 if (f1 < 0 && errno == ENOENT)
4266 same = TRUE;
4267#endif
4268 created1 = TRUE;
4269 }
4270 if (f1 >= 0)
4271 {
4272 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4273 if (f2 < 0)
4274 {
4275 f2 = mch_open_rw((char *)fname2,
4276 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4277 created2 = TRUE;
4278 }
4279 if (f2 >= 0)
4280 {
4281 /*
4282 * Both files exist now. If mch_stat() returns the
4283 * same device and inode they are the same file.
4284 */
4285 if (mch_fstat(f1, &s1) != -1
4286 && mch_fstat(f2, &s2) != -1
4287 && s1.st_dev == s2.st_dev
4288 && s1.st_ino == s2.st_ino)
4289 same = TRUE;
4290 close(f2);
4291 if (created2)
4292 mch_remove(fname2);
4293 }
4294 close(f1);
4295 if (created1)
4296 mch_remove(fname);
4297 }
4298 vim_free(fname2);
4299 if (same)
4300 {
4301 buf->b_shortname = TRUE;
4302 vim_free(fname);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004303 fname = makeswapname(buf_fname, buf->b_ffname,
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004304 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 continue; /* try again with b_shortname set */
4306 }
4307 }
4308 }
4309 }
4310#endif
4311 /*
4312 * check if the swapfile already exists
4313 */
4314 if (mch_getperm(fname) < 0) /* it does not exist */
4315 {
4316#ifdef HAVE_LSTAT
4317 struct stat sb;
4318
4319 /*
4320 * Extra security check: When a swap file is a symbolic link, this
4321 * is most likely a symlink attack.
4322 */
4323 if (mch_lstat((char *)fname, &sb) < 0)
4324#else
4325# ifdef AMIGA
4326 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4327 /*
4328 * on the Amiga mch_getperm() will return -1 when the file exists
4329 * but is being used by another program. This happens if you edit
4330 * a file twice.
4331 */
4332 if (fh != (BPTR)NULL) /* can open file, OK */
4333 {
4334 Close(fh);
4335 mch_remove(fname);
4336 break;
4337 }
4338 if (IoErr() != ERROR_OBJECT_IN_USE
4339 && IoErr() != ERROR_OBJECT_EXISTS)
4340# endif
4341#endif
4342 break;
4343 }
4344
4345 /*
4346 * A file name equal to old_fname is OK to use.
4347 */
4348 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4349 break;
4350
4351 /*
4352 * get here when file already exists
4353 */
4354 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4355 {
4356#ifndef SHORT_FNAME
4357 /*
4358 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4359 * and file.doc are the same file. To guess if this problem is
4360 * present try if file.doc.swx exists. If it does, we set
4361 * buf->b_shortname and try file_doc.swp (dots replaced by
4362 * underscores for this file), and try again. If it doesn't we
4363 * assume that "file.doc.swp" already exists.
4364 */
4365 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4366 {
4367 fname[n - 1] = 'x';
4368 r = mch_getperm(fname); /* try "file.swx" */
4369 fname[n - 1] = 'p';
4370 if (r >= 0) /* "file.swx" seems to exist */
4371 {
4372 buf->b_shortname = TRUE;
4373 vim_free(fname);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004374 fname = makeswapname(buf_fname, buf->b_ffname,
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004375 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 continue; /* try again with '.' replaced with '_' */
4377 }
4378 }
4379#endif
4380 /*
4381 * If we get here the ".swp" file really exists.
4382 * Give an error message, unless recovering, no file name, we are
4383 * viewing a help file or when the path of the file is different
4384 * (happens when all .swp files are in one directory).
4385 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004386 if (!recoverymode && buf_fname != NULL
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004387 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388 {
4389 int fd;
4390 struct block0 b0;
4391 int differ = FALSE;
4392
4393 /*
4394 * Try to read block 0 from the swap file to get the original
4395 * file name (and inode number).
4396 */
4397 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4398 if (fd >= 0)
4399 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004400 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 {
4402 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004403 * If the swapfile has the same directory as the
4404 * buffer don't compare the directory names, they can
4405 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004407 if (b0.b0_flags & B0_SAME_DIR)
4408 {
4409 if (fnamecmp(gettail(buf->b_ffname),
4410 gettail(b0.b0_fname)) != 0
4411 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004412 {
4413#ifdef CHECK_INODE
4414 /* Symlinks may point to the same file even
4415 * when the name differs, need to check the
4416 * inode too. */
4417 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4418 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4419 char_to_long(b0.b0_ino)))
4420#endif
4421 differ = TRUE;
4422 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004423 }
4424 else
4425 {
4426 /*
4427 * The name in the swap file may be
4428 * "~user/path/file". Expand it first.
4429 */
4430 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004432 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004433 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004434 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004436 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4437 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004440 }
4441 close(fd);
4442 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443
4444 /* give the ATTENTION message when there is an old swap file
4445 * for the current file, and the buffer was not recovered. */
4446 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4447 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4448 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004449#if defined(HAS_SWAP_EXISTS_ACTION)
4450 int choice = 0;
4451#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452#ifdef CREATE_DUMMY_FILE
4453 int did_use_dummy = FALSE;
4454
4455 /* Avoid getting a warning for the file being created
4456 * outside of Vim, it was created at the start of this
4457 * function. Delete the file now, because Vim might exit
4458 * here if the window is closed. */
4459 if (dummyfd != NULL)
4460 {
4461 fclose(dummyfd);
4462 dummyfd = NULL;
Bram Moolenaar69c35002013-11-04 02:54:12 +01004463 mch_remove(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 did_use_dummy = TRUE;
4465 }
4466#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467
4468#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4469 process_still_running = FALSE;
4470#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004471#ifdef FEAT_AUTOCMD
4472 /*
4473 * If there is an SwapExists autocommand and we can handle
4474 * the response, trigger it. It may return 0 to ask the
4475 * user anyway.
4476 */
4477 if (swap_exists_action != SEA_NONE
Bram Moolenaar69c35002013-11-04 02:54:12 +01004478 && has_autocmd(EVENT_SWAPEXISTS, buf_fname, buf))
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004479 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004481 if (choice == 0)
4482#endif
4483 {
4484#ifdef FEAT_GUI
4485 /* If we are supposed to start the GUI but it wasn't
4486 * completely started yet, start it now. This makes
4487 * the messages displayed in the Vim window when
4488 * loading a session from the .gvimrc file. */
4489 if (gui.starting && !gui.in_use)
4490 gui_start();
4491#endif
4492 /* Show info about the existing swap file. */
4493 attention_message(buf, fname);
4494
4495 /* We don't want a 'q' typed at the more-prompt
4496 * interrupt loading a file. */
4497 got_int = FALSE;
4498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499
4500#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004501 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 {
4503 char_u *name;
4504
4505 name = alloc((unsigned)(STRLEN(fname)
4506 + STRLEN(_("Swap file \""))
4507 + STRLEN(_("\" already exists!")) + 5));
4508 if (name != NULL)
4509 {
4510 STRCPY(name, _("Swap file \""));
4511 home_replace(NULL, fname, name + STRLEN(name),
4512 1000, TRUE);
4513 STRCAT(name, _("\" already exists!"));
4514 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004515 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 (char_u *)_("VIM - ATTENTION"),
4517 name == NULL
4518 ? (char_u *)_("Swap file already exists!")
4519 : name,
4520# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4521 process_still_running
4522 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4523# endif
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004524 (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 +00004525
4526# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4527 if (process_still_running && choice >= 4)
4528 choice++; /* Skip missing "Delete it" button */
4529# endif
4530 vim_free(name);
4531
4532 /* pretend screen didn't scroll, need redraw anyway */
4533 msg_scrolled = 0;
4534 redraw_all_later(NOT_VALID);
4535 }
4536#endif
4537
4538#if defined(HAS_SWAP_EXISTS_ACTION)
4539 if (choice > 0)
4540 {
4541 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 {
4543 case 1:
4544 buf->b_p_ro = TRUE;
4545 break;
4546 case 2:
4547 break;
4548 case 3:
4549 swap_exists_action = SEA_RECOVER;
4550 break;
4551 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004552 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004553 break;
4554 case 5:
4555 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 break;
4557 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004558 swap_exists_action = SEA_QUIT;
4559 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 break;
4561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562
4563 /* If the file was deleted this fname can be used. */
4564 if (mch_getperm(fname) < 0)
4565 break;
4566 }
4567 else
4568#endif
4569 {
4570 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004571 if (msg_silent == 0)
4572 /* call wait_return() later */
4573 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574 }
4575
4576#ifdef CREATE_DUMMY_FILE
4577 /* Going to try another name, need the dummy file again. */
4578 if (did_use_dummy)
Bram Moolenaar69c35002013-11-04 02:54:12 +01004579 dummyfd = mch_fopen((char *)buf_fname, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580#endif
4581 }
4582 }
4583 }
4584
4585 /*
4586 * Change the ".swp" extension to find another file that can be used.
4587 * First decrement the last char: ".swo", ".swn", etc.
4588 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004589 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004590 */
4591 if (fname[n - 1] == 'a') /* ".s?a" */
4592 {
4593 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4594 {
4595 EMSG(_("E326: Too many swap files found"));
4596 vim_free(fname);
4597 fname = NULL;
4598 break;
4599 }
4600 --fname[n - 2]; /* ".svz", ".suz", etc. */
4601 fname[n - 1] = 'z' + 1;
4602 }
4603 --fname[n - 1]; /* ".swo", ".swn", etc. */
4604 }
4605
4606 vim_free(dir_name);
4607#ifdef CREATE_DUMMY_FILE
4608 if (dummyfd != NULL) /* file has been created temporarily */
4609 {
4610 fclose(dummyfd);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004611 mch_remove(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612 }
4613#endif
Bram Moolenaar69c35002013-11-04 02:54:12 +01004614#ifdef WIN3264
4615 if (buf_fname != buf->b_fname)
4616 vim_free(buf_fname);
4617#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 return fname;
4619}
4620
4621 static int
4622b0_magic_wrong(b0p)
4623 ZERO_BL *b0p;
4624{
4625 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4626 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4627 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4628 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4629}
4630
4631#ifdef CHECK_INODE
4632/*
4633 * Compare current file name with file name from swap file.
4634 * Try to use inode numbers when possible.
4635 * Return non-zero when files are different.
4636 *
4637 * When comparing file names a few things have to be taken into consideration:
4638 * - When working over a network the full path of a file depends on the host.
4639 * We check the inode number if possible. It is not 100% reliable though,
4640 * because the device number cannot be used over a network.
4641 * - When a file does not exist yet (editing a new file) there is no inode
4642 * number.
4643 * - The file name in a swap file may not be valid on the current host. The
4644 * "~user" form is used whenever possible to avoid this.
4645 *
4646 * This is getting complicated, let's make a table:
4647 *
4648 * ino_c ino_s fname_c fname_s differ =
4649 *
4650 * both files exist -> compare inode numbers:
4651 * != 0 != 0 X X ino_c != ino_s
4652 *
4653 * inode number(s) unknown, file names available -> compare file names
4654 * == 0 X OK OK fname_c != fname_s
4655 * X == 0 OK OK fname_c != fname_s
4656 *
4657 * current file doesn't exist, file for swap file exist, file name(s) not
4658 * available -> probably different
4659 * == 0 != 0 FAIL X TRUE
4660 * == 0 != 0 X FAIL TRUE
4661 *
4662 * current file exists, inode for swap unknown, file name(s) not
4663 * available -> probably different
4664 * != 0 == 0 FAIL X TRUE
4665 * != 0 == 0 X FAIL TRUE
4666 *
4667 * current file doesn't exist, inode for swap unknown, one file name not
4668 * available -> probably different
4669 * == 0 == 0 FAIL OK TRUE
4670 * == 0 == 0 OK FAIL TRUE
4671 *
4672 * current file doesn't exist, inode for swap unknown, both file names not
4673 * available -> probably same file
4674 * == 0 == 0 FAIL FAIL FALSE
4675 *
4676 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4677 * can't be changed without making the block 0 incompatible with 32 bit
4678 * versions.
4679 */
4680
4681 static int
4682fnamecmp_ino(fname_c, fname_s, ino_block0)
4683 char_u *fname_c; /* current file name */
4684 char_u *fname_s; /* file name from swap file */
4685 long ino_block0;
4686{
4687 struct stat st;
4688 ino_t ino_c = 0; /* ino of current file */
4689 ino_t ino_s; /* ino of file from swap file */
4690 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4691 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4692 int retval_c; /* flag: buf_c valid */
4693 int retval_s; /* flag: buf_s valid */
4694
4695 if (mch_stat((char *)fname_c, &st) == 0)
4696 ino_c = (ino_t)st.st_ino;
4697
4698 /*
4699 * First we try to get the inode from the file name, because the inode in
4700 * the swap file may be outdated. If that fails (e.g. this path is not
4701 * valid on this machine), use the inode from block 0.
4702 */
4703 if (mch_stat((char *)fname_s, &st) == 0)
4704 ino_s = (ino_t)st.st_ino;
4705 else
4706 ino_s = (ino_t)ino_block0;
4707
4708 if (ino_c && ino_s)
4709 return (ino_c != ino_s);
4710
4711 /*
4712 * One of the inode numbers is unknown, try a forced vim_FullName() and
4713 * compare the file names.
4714 */
4715 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4716 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4717 if (retval_c == OK && retval_s == OK)
4718 return (STRCMP(buf_c, buf_s) != 0);
4719
4720 /*
4721 * Can't compare inodes or file names, guess that the files are different,
4722 * unless both appear not to exist at all.
4723 */
4724 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4725 return FALSE;
4726 return TRUE;
4727}
4728#endif /* CHECK_INODE */
4729
4730/*
4731 * Move a long integer into a four byte character array.
4732 * Used for machine independency in block zero.
4733 */
4734 static void
4735long_to_char(n, s)
4736 long n;
4737 char_u *s;
4738{
4739 s[0] = (char_u)(n & 0xff);
4740 n = (unsigned)n >> 8;
4741 s[1] = (char_u)(n & 0xff);
4742 n = (unsigned)n >> 8;
4743 s[2] = (char_u)(n & 0xff);
4744 n = (unsigned)n >> 8;
4745 s[3] = (char_u)(n & 0xff);
4746}
4747
4748 static long
4749char_to_long(s)
4750 char_u *s;
4751{
4752 long retval;
4753
4754 retval = s[3];
4755 retval <<= 8;
4756 retval |= s[2];
4757 retval <<= 8;
4758 retval |= s[1];
4759 retval <<= 8;
4760 retval |= s[0];
4761
4762 return retval;
4763}
4764
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004765/*
4766 * Set the flags in the first block of the swap file:
4767 * - file is modified or not: buf->b_changed
4768 * - 'fileformat'
4769 * - 'fileencoding'
4770 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004772ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774{
4775 bhdr_T *hp;
4776 ZERO_BL *b0p;
4777
4778 if (!buf->b_ml.ml_mfp)
4779 return;
4780 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4781 {
4782 if (hp->bh_bnum == 0)
4783 {
4784 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004785 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4786 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4787 | (get_fileformat(buf) + 1);
4788#ifdef FEAT_MBYTE
4789 add_b0_fenc(b0p, buf);
4790#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791 hp->bh_flags |= BH_DIRTY;
4792 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4793 break;
4794 }
4795 }
4796}
4797
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004798#if defined(FEAT_CRYPT) || defined(PROTO)
4799/*
4800 * If "data" points to a data block encrypt the text in it and return a copy
4801 * in allocated memory. Return NULL when out of memory.
4802 * Otherwise return "data".
4803 */
4804 char_u *
4805ml_encrypt_data(mfp, data, offset, size)
4806 memfile_T *mfp;
4807 char_u *data;
4808 off_t offset;
4809 unsigned size;
4810{
4811 DATA_BL *dp = (DATA_BL *)data;
4812 char_u *head_end;
4813 char_u *text_start;
4814 char_u *new_data;
4815 int text_len;
4816
4817 if (dp->db_id != DATA_ID)
4818 return data;
4819
4820 new_data = (char_u *)alloc(size);
4821 if (new_data == NULL)
4822 return NULL;
4823 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4824 text_start = (char_u *)dp + dp->db_txt_start;
4825 text_len = size - dp->db_txt_start;
4826
4827 /* Copy the header and the text. */
4828 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4829
4830 /* Encrypt the text. */
4831 crypt_push_state();
4832 ml_crypt_prepare(mfp, offset, FALSE);
4833 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4834 crypt_pop_state();
4835
4836 /* Clear the gap. */
4837 if (head_end < text_start)
4838 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4839
4840 return new_data;
4841}
4842
4843/*
4844 * Decrypt the text in "data" if it points to a data block.
4845 */
4846 void
4847ml_decrypt_data(mfp, data, offset, size)
4848 memfile_T *mfp;
4849 char_u *data;
4850 off_t offset;
4851 unsigned size;
4852{
4853 DATA_BL *dp = (DATA_BL *)data;
4854 char_u *head_end;
4855 char_u *text_start;
4856 int text_len;
4857
4858 if (dp->db_id == DATA_ID)
4859 {
4860 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4861 text_start = (char_u *)dp + dp->db_txt_start;
4862 text_len = dp->db_txt_end - dp->db_txt_start;
4863
4864 if (head_end > text_start || dp->db_txt_start > size
4865 || dp->db_txt_end > size)
4866 return; /* data was messed up */
4867
4868 /* Decrypt the text in place. */
4869 crypt_push_state();
4870 ml_crypt_prepare(mfp, offset, TRUE);
4871 crypt_decode(text_start, text_len);
4872 crypt_pop_state();
4873 }
4874}
4875
4876/*
4877 * Prepare for encryption/decryption, using the key, seed and offset.
4878 */
4879 static void
4880ml_crypt_prepare(mfp, offset, reading)
4881 memfile_T *mfp;
4882 off_t offset;
4883 int reading;
4884{
4885 buf_T *buf = mfp->mf_buffer;
4886 char_u salt[50];
4887 int method;
4888 char_u *key;
4889 char_u *seed;
4890
4891 if (reading && mfp->mf_old_key != NULL)
4892 {
4893 /* Reading back blocks with the previous key/method/seed. */
4894 method = mfp->mf_old_cm;
4895 key = mfp->mf_old_key;
4896 seed = mfp->mf_old_seed;
4897 }
4898 else
4899 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02004900 method = get_crypt_method(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004901 key = buf->b_p_key;
4902 seed = mfp->mf_seed;
4903 }
4904
4905 use_crypt_method = method; /* select pkzip or blowfish */
4906 if (method == 0)
4907 {
4908 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4909 crypt_init_keys(salt);
4910 }
4911 else
4912 {
4913 /* Using blowfish, add salt and seed. We use the byte offset of the
4914 * block for the salt. */
4915 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004916 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaar4d504a32014-02-11 15:23:32 +01004917 bf_cfb_init(seed, MF_SEED_LEN);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004918 }
4919}
4920
4921#endif
4922
4923
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924#if defined(FEAT_BYTEOFF) || defined(PROTO)
4925
4926#define MLCS_MAXL 800 /* max no of lines in chunk */
4927#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4928
4929/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004930 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4932 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4933 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4934 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4935 */
4936 static void
4937ml_updatechunk(buf, line, len, updtype)
4938 buf_T *buf;
4939 linenr_T line;
4940 long len;
4941 int updtype;
4942{
4943 static buf_T *ml_upd_lastbuf = NULL;
4944 static linenr_T ml_upd_lastline;
4945 static linenr_T ml_upd_lastcurline;
4946 static int ml_upd_lastcurix;
4947
4948 linenr_T curline = ml_upd_lastcurline;
4949 int curix = ml_upd_lastcurix;
4950 long size;
4951 chunksize_T *curchnk;
4952 int rest;
4953 bhdr_T *hp;
4954 DATA_BL *dp;
4955
4956 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4957 return;
4958 if (buf->b_ml.ml_chunksize == NULL)
4959 {
4960 buf->b_ml.ml_chunksize = (chunksize_T *)
4961 alloc((unsigned)sizeof(chunksize_T) * 100);
4962 if (buf->b_ml.ml_chunksize == NULL)
4963 {
4964 buf->b_ml.ml_usedchunks = -1;
4965 return;
4966 }
4967 buf->b_ml.ml_numchunks = 100;
4968 buf->b_ml.ml_usedchunks = 1;
4969 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4970 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4971 }
4972
4973 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4974 {
4975 /*
4976 * First line in empty buffer from ml_flush_line() -- reset
4977 */
4978 buf->b_ml.ml_usedchunks = 1;
4979 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4980 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4981 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4982 return;
4983 }
4984
4985 /*
4986 * Find chunk that our line belongs to, curline will be at start of the
4987 * chunk.
4988 */
4989 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4990 || updtype != ML_CHNK_ADDLINE)
4991 {
4992 for (curline = 1, curix = 0;
4993 curix < buf->b_ml.ml_usedchunks - 1
4994 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4995 curix++)
4996 {
4997 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4998 }
4999 }
5000 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
5001 && curix < buf->b_ml.ml_usedchunks - 1)
5002 {
5003 /* Adjust cached curix & curline */
5004 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5005 curix++;
5006 }
5007 curchnk = buf->b_ml.ml_chunksize + curix;
5008
5009 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00005010 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011 curchnk->mlcs_totalsize += len;
5012 if (updtype == ML_CHNK_ADDLINE)
5013 {
5014 curchnk->mlcs_numlines++;
5015
5016 /* May resize here so we don't have to do it in both cases below */
5017 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5018 {
5019 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5020 buf->b_ml.ml_chunksize = (chunksize_T *)
5021 vim_realloc(buf->b_ml.ml_chunksize,
5022 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5023 if (buf->b_ml.ml_chunksize == NULL)
5024 {
5025 /* Hmmmm, Give up on offset for this buffer */
5026 buf->b_ml.ml_usedchunks = -1;
5027 return;
5028 }
5029 }
5030
5031 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5032 {
5033 int count; /* number of entries in block */
5034 int idx;
5035 int text_end;
5036 int linecnt;
5037
5038 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5039 buf->b_ml.ml_chunksize + curix,
5040 (buf->b_ml.ml_usedchunks - curix) *
5041 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005042 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 size = 0;
5044 linecnt = 0;
5045 while (curline < buf->b_ml.ml_line_count
5046 && linecnt < MLCS_MINL)
5047 {
5048 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5049 {
5050 buf->b_ml.ml_usedchunks = -1;
5051 return;
5052 }
5053 dp = (DATA_BL *)(hp->bh_data);
5054 count = (long)(buf->b_ml.ml_locked_high) -
5055 (long)(buf->b_ml.ml_locked_low) + 1;
5056 idx = curline - buf->b_ml.ml_locked_low;
5057 curline = buf->b_ml.ml_locked_high + 1;
5058 if (idx == 0)/* first line in block, text at the end */
5059 text_end = dp->db_txt_end;
5060 else
5061 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5062 /* Compute index of last line to use in this MEMLINE */
5063 rest = count - idx;
5064 if (linecnt + rest > MLCS_MINL)
5065 {
5066 idx += MLCS_MINL - linecnt - 1;
5067 linecnt = MLCS_MINL;
5068 }
5069 else
5070 {
5071 idx = count - 1;
5072 linecnt += rest;
5073 }
5074 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5075 }
5076 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5077 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5078 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5079 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5080 buf->b_ml.ml_usedchunks++;
5081 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5082 return;
5083 }
5084 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5085 && curix == buf->b_ml.ml_usedchunks - 1
5086 && buf->b_ml.ml_line_count - line <= 1)
5087 {
5088 /*
5089 * We are in the last chunk and it is cheap to crate a new one
5090 * after this. Do it now to avoid the loop above later on
5091 */
5092 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5093 buf->b_ml.ml_usedchunks++;
5094 if (line == buf->b_ml.ml_line_count)
5095 {
5096 curchnk->mlcs_numlines = 0;
5097 curchnk->mlcs_totalsize = 0;
5098 }
5099 else
5100 {
5101 /*
5102 * Line is just prior to last, move count for last
5103 * This is the common case when loading a new file
5104 */
5105 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5106 if (hp == NULL)
5107 {
5108 buf->b_ml.ml_usedchunks = -1;
5109 return;
5110 }
5111 dp = (DATA_BL *)(hp->bh_data);
5112 if (dp->db_line_count == 1)
5113 rest = dp->db_txt_end - dp->db_txt_start;
5114 else
5115 rest =
5116 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5117 - dp->db_txt_start;
5118 curchnk->mlcs_totalsize = rest;
5119 curchnk->mlcs_numlines = 1;
5120 curchnk[-1].mlcs_totalsize -= rest;
5121 curchnk[-1].mlcs_numlines -= 1;
5122 }
5123 }
5124 }
5125 else if (updtype == ML_CHNK_DELLINE)
5126 {
5127 curchnk->mlcs_numlines--;
5128 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5129 if (curix < (buf->b_ml.ml_usedchunks - 1)
5130 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5131 <= MLCS_MINL)
5132 {
5133 curix++;
5134 curchnk = buf->b_ml.ml_chunksize + curix;
5135 }
5136 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5137 {
5138 buf->b_ml.ml_usedchunks--;
5139 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5140 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5141 return;
5142 }
5143 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5144 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5145 > MLCS_MINL))
5146 {
5147 return;
5148 }
5149
5150 /* Collapse chunks */
5151 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5152 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5153 buf->b_ml.ml_usedchunks--;
5154 if (curix < buf->b_ml.ml_usedchunks)
5155 {
5156 mch_memmove(buf->b_ml.ml_chunksize + curix,
5157 buf->b_ml.ml_chunksize + curix + 1,
5158 (buf->b_ml.ml_usedchunks - curix) *
5159 sizeof(chunksize_T));
5160 }
5161 return;
5162 }
5163 ml_upd_lastbuf = buf;
5164 ml_upd_lastline = line;
5165 ml_upd_lastcurline = curline;
5166 ml_upd_lastcurix = curix;
5167}
5168
5169/*
5170 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005171 * Find line with offset if "lnum" is 0; return remaining offset in offp
5172 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 * return -1 if information is not available
5174 */
5175 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005176ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005178 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179 long *offp;
5180{
5181 linenr_T curline;
5182 int curix;
5183 long size;
5184 bhdr_T *hp;
5185 DATA_BL *dp;
5186 int count; /* number of entries in block */
5187 int idx;
5188 int start_idx;
5189 int text_end;
5190 long offset;
5191 int len;
5192 int ffdos = (get_fileformat(buf) == EOL_DOS);
5193 int extra = 0;
5194
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005195 /* take care of cached line first */
5196 ml_flush_line(curbuf);
5197
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 if (buf->b_ml.ml_usedchunks == -1
5199 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005200 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201 return -1;
5202
5203 if (offp == NULL)
5204 offset = 0;
5205 else
5206 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005207 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5209 /*
5210 * Find the last chunk before the one containing our line. Last chunk is
5211 * special because it will never qualify
5212 */
5213 curline = 1;
5214 curix = size = 0;
5215 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005216 && ((lnum != 0
5217 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 || (offset != 0
5219 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5220 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5221 {
5222 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5223 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5224 if (offset && ffdos)
5225 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5226 curix++;
5227 }
5228
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005229 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005230 {
5231 if (curline > buf->b_ml.ml_line_count
5232 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5233 return -1;
5234 dp = (DATA_BL *)(hp->bh_data);
5235 count = (long)(buf->b_ml.ml_locked_high) -
5236 (long)(buf->b_ml.ml_locked_low) + 1;
5237 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5238 if (idx == 0)/* first line in block, text at the end */
5239 text_end = dp->db_txt_end;
5240 else
5241 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5242 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005243 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005245 if (curline + (count - idx) >= lnum)
5246 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005247 else
5248 idx = count - 1;
5249 }
5250 else
5251 {
5252 extra = 0;
5253 while (offset >= size
5254 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5255 + ffdos)
5256 {
5257 if (ffdos)
5258 size++;
5259 if (idx == count - 1)
5260 {
5261 extra = 1;
5262 break;
5263 }
5264 idx++;
5265 }
5266 }
5267 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5268 size += len;
5269 if (offset != 0 && size >= offset)
5270 {
5271 if (size + ffdos == offset)
5272 *offp = 0;
5273 else if (idx == start_idx)
5274 *offp = offset - size + len;
5275 else
5276 *offp = offset - size + len
5277 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5278 curline += idx - start_idx + extra;
5279 if (curline > buf->b_ml.ml_line_count)
5280 return -1; /* exactly one byte beyond the end */
5281 return curline;
5282 }
5283 curline = buf->b_ml.ml_locked_high + 1;
5284 }
5285
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005286 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005287 {
5288 /* Count extra CR characters. */
5289 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005290 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005291
5292 /* Don't count the last line break if 'bin' and 'noeol'. */
5293 if (buf->b_p_bin && !buf->b_p_eol)
5294 size -= ffdos + 1;
5295 }
5296
Bram Moolenaar071d4272004-06-13 20:20:40 +00005297 return size;
5298}
5299
5300/*
5301 * Goto byte in buffer with offset 'cnt'.
5302 */
5303 void
5304goto_byte(cnt)
5305 long cnt;
5306{
5307 long boff = cnt;
5308 linenr_T lnum;
5309
5310 ml_flush_line(curbuf); /* cached line may be dirty */
5311 setpcmark();
5312 if (boff)
5313 --boff;
5314 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5315 if (lnum < 1) /* past the end */
5316 {
5317 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5318 curwin->w_curswant = MAXCOL;
5319 coladvance((colnr_T)MAXCOL);
5320 }
5321 else
5322 {
5323 curwin->w_cursor.lnum = lnum;
5324 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005325# ifdef FEAT_VIRTUALEDIT
5326 curwin->w_cursor.coladd = 0;
5327# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328 curwin->w_set_curswant = TRUE;
5329 }
5330 check_cursor();
5331
5332# ifdef FEAT_MBYTE
5333 /* Make sure the cursor is on the first byte of a multi-byte char. */
5334 if (has_mbyte)
5335 mb_adjust_cursor();
5336# endif
5337}
5338#endif