blob: 547b55089278f4e5a8898a165217499ce9a0088e [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 Moolenaar071d4272004-06-13 20:20:40 +0000624 if (fname == NULL) /* no file name found for this dir */
625 continue;
626
627#if defined(MSDOS) || defined(MSWIN)
628 /*
629 * Set full pathname for swap file now, because a ":!cd dir" may
630 * change directory without us knowing it.
631 */
632 p = FullName_save(fname, FALSE);
633 vim_free(fname);
634 fname = p;
635 if (fname == NULL)
636 continue;
637#endif
638 /* if the file name is the same we don't have to do anything */
639 if (fnamecmp(fname, mfp->mf_fname) == 0)
640 {
641 vim_free(fname);
642 success = TRUE;
643 break;
644 }
645 /* need to close the swap file before renaming */
646 if (mfp->mf_fd >= 0)
647 {
648 close(mfp->mf_fd);
649 mfp->mf_fd = -1;
650 }
651
652 /* try to rename the swap file */
653 if (vim_rename(mfp->mf_fname, fname) == 0)
654 {
655 success = TRUE;
656 vim_free(mfp->mf_fname);
657 mfp->mf_fname = fname;
658 vim_free(mfp->mf_ffname);
659#if defined(MSDOS) || defined(MSWIN)
660 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
661#else
662 mf_set_ffname(mfp);
663#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200664 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 break;
666 }
667 vim_free(fname); /* this fname didn't work, try another */
668 }
669
670 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
671 {
672 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
673 if (mfp->mf_fd < 0)
674 {
675 /* could not (re)open the swap file, what can we do???? */
676 EMSG(_("E301: Oops, lost the swap file!!!"));
677 return;
678 }
Bram Moolenaarf05da212009-11-17 16:13:15 +0000679#ifdef HAVE_FD_CLOEXEC
680 {
681 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
682 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
683 fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
684 }
685#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686 }
687 if (!success)
688 EMSG(_("E302: Could not rename swap file"));
689}
690
691/*
692 * Open a file for the memfile for all buffers that are not readonly or have
693 * been modified.
694 * Used when 'updatecount' changes from zero to non-zero.
695 */
696 void
697ml_open_files()
698{
699 buf_T *buf;
700
701 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
702 if (!buf->b_p_ro || buf->b_changed)
703 ml_open_file(buf);
704}
705
706/*
707 * Open a swap file for an existing memfile, if there is no swap file yet.
708 * If we are unable to find a file name, mf_fname will be NULL
709 * and the memfile will be in memory only (no recovery possible).
710 */
711 void
712ml_open_file(buf)
713 buf_T *buf;
714{
715 memfile_T *mfp;
716 char_u *fname;
717 char_u *dirp;
718
719 mfp = buf->b_ml.ml_mfp;
720 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf)
721 return; /* nothing to do */
722
Bram Moolenaara1956f62006-03-12 22:18:00 +0000723#ifdef FEAT_SPELL
Bram Moolenaar4770d092006-01-12 23:22:24 +0000724 /* For a spell buffer use a temp file name. */
725 if (buf->b_spell)
726 {
727 fname = vim_tempname('s');
728 if (fname != NULL)
729 (void)mf_open_file(mfp, fname); /* consumes fname! */
730 buf->b_may_swap = FALSE;
731 return;
732 }
733#endif
734
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 /*
736 * Try all directories in 'directory' option.
737 */
738 dirp = p_dir;
739 for (;;)
740 {
741 if (*dirp == NUL)
742 break;
Bram Moolenaare242b832010-06-24 05:39:03 +0200743 /* There is a small chance that between choosing the swap file name
744 * and creating it, another Vim creates the file. In that case the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745 * creation will fail and we will use another directory. */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000746 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 if (fname == NULL)
748 continue;
749 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
750 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200751#if defined(MSDOS) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752 /*
753 * set full pathname for swap file now, because a ":!cd dir" may
754 * change directory without us knowing it.
755 */
756 mf_fullname(mfp);
757#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200758 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000759
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 /* Flush block zero, so others can read it */
761 if (mf_sync(mfp, MFS_ZERO) == OK)
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000762 {
763 /* Mark all blocks that should be in the swapfile as dirty.
764 * Needed for when the 'swapfile' option was reset, so that
765 * the swap file was deleted, and then on again. */
766 mf_set_dirty(mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000767 break;
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 /* Writing block 0 failed: close the file and try another dir */
770 mf_close_file(buf, FALSE);
771 }
772 }
773
774 if (mfp->mf_fname == NULL) /* Failed! */
775 {
776 need_wait_return = TRUE; /* call wait_return later */
777 ++no_wait_return;
778 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
779 buf_spname(buf) != NULL
780 ? (char_u *)buf_spname(buf)
781 : buf->b_fname);
782 --no_wait_return;
783 }
784
785 /* don't try to open a swap file again */
786 buf->b_may_swap = FALSE;
787}
788
789/*
790 * If still need to create a swap file, and starting to edit a not-readonly
791 * file, or reading into an existing buffer, create a swap file now.
792 */
793 void
794check_need_swap(newfile)
795 int newfile; /* reading file into new buffer */
796{
797 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
798 ml_open_file(curbuf);
799}
800
801/*
802 * Close memline for buffer 'buf'.
803 * If 'del_file' is TRUE, delete the swap file
804 */
805 void
806ml_close(buf, del_file)
807 buf_T *buf;
808 int del_file;
809{
810 if (buf->b_ml.ml_mfp == NULL) /* not open */
811 return;
812 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
813 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
814 vim_free(buf->b_ml.ml_line_ptr);
815 vim_free(buf->b_ml.ml_stack);
816#ifdef FEAT_BYTEOFF
817 vim_free(buf->b_ml.ml_chunksize);
818 buf->b_ml.ml_chunksize = NULL;
819#endif
820 buf->b_ml.ml_mfp = NULL;
821
822 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
823 * this buffer is loaded. */
824 buf->b_flags &= ~BF_RECOVERED;
825}
826
827/*
828 * Close all existing memlines and memfiles.
829 * Only used when exiting.
830 * When 'del_file' is TRUE, delete the memfiles.
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000831 * But don't delete files that were ":preserve"d when we are POSIX compatible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832 */
833 void
834ml_close_all(del_file)
835 int del_file;
836{
837 buf_T *buf;
838
839 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000840 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
841 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000842#ifdef TEMPDIRNAMES
843 vim_deltempdir(); /* delete created temp directory */
844#endif
845}
846
847/*
848 * Close all memfiles for not modified buffers.
849 * Only use just before exiting!
850 */
851 void
852ml_close_notmod()
853{
854 buf_T *buf;
855
856 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
857 if (!bufIsChanged(buf))
858 ml_close(buf, TRUE); /* close all not-modified buffers */
859}
860
861/*
862 * Update the timestamp in the .swp file.
863 * Used when the file has been written.
864 */
865 void
866ml_timestamp(buf)
867 buf_T *buf;
868{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200869 ml_upd_block0(buf, UB_FNAME);
870}
871
872/*
873 * Return FAIL when the ID of "b0p" is wrong.
874 */
875 static int
876ml_check_b0_id(b0p)
877 ZERO_BL *b0p;
878{
879 if (b0p->b0_id[0] != BLOCK0_ID0
880 || (b0p->b0_id[1] != BLOCK0_ID1
881 && b0p->b0_id[1] != BLOCK0_ID1_C0
882 && b0p->b0_id[1] != BLOCK0_ID1_C1)
883 )
884 return FAIL;
885 return OK;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000886}
887
888/*
889 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
890 */
891 static void
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200892ml_upd_block0(buf, what)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000893 buf_T *buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200894 upd_block0_T what;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000895{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 memfile_T *mfp;
897 bhdr_T *hp;
898 ZERO_BL *b0p;
899
900 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
902 return;
903 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200904 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000905 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000907 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200908 if (what == UB_FNAME)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000909 set_b0_fname(b0p, buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200910#ifdef FEAT_CRYPT
911 else if (what == UB_CRYPT)
912 ml_set_b0_crypt(buf, b0p);
913#endif
914 else /* what == UB_SAME_DIR */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000915 set_b0_dir_flag(b0p, buf);
916 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917 mf_put(mfp, hp, TRUE, FALSE);
918}
919
920/*
921 * Write file name and timestamp into block 0 of a swap file.
922 * Also set buf->b_mtime.
923 * Don't use NameBuff[]!!!
924 */
925 static void
926set_b0_fname(b0p, buf)
927 ZERO_BL *b0p;
928 buf_T *buf;
929{
930 struct stat st;
931
932 if (buf->b_ffname == NULL)
933 b0p->b0_fname[0] = NUL;
934 else
935 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200936#if defined(MSDOS) || defined(MSWIN) || defined(AMIGA)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000937 /* Systems that cannot translate "~user" back into a path: copy the
938 * file name unmodified. Do use slashes instead of backslashes for
939 * portability. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200940 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000941# ifdef BACKSLASH_IN_FILENAME
942 forward_slash(b0p->b0_fname);
943# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944#else
945 size_t flen, ulen;
946 char_u uname[B0_UNAME_SIZE];
947
948 /*
949 * For a file under the home directory of the current user, we try to
950 * replace the home directory path with "~user". This helps when
951 * editing the same file on different machines over a network.
952 * First replace home dir path with "~/" with home_replace().
953 * Then insert the user name to get "~user/".
954 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200955 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
956 B0_FNAME_SIZE_CRYPT, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957 if (b0p->b0_fname[0] == '~')
958 {
959 flen = STRLEN(b0p->b0_fname);
960 /* If there is no user name or it is too long, don't use "~/" */
961 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200962 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
963 vim_strncpy(b0p->b0_fname, buf->b_ffname,
964 B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 else
966 {
967 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
968 mch_memmove(b0p->b0_fname + 1, uname, ulen);
969 }
970 }
971#endif
972 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
973 {
974 long_to_char((long)st.st_mtime, b0p->b0_mtime);
975#ifdef CHECK_INODE
976 long_to_char((long)st.st_ino, b0p->b0_ino);
977#endif
978 buf_store_time(buf, &st, buf->b_ffname);
979 buf->b_mtime_read = buf->b_mtime;
980 }
981 else
982 {
983 long_to_char(0L, b0p->b0_mtime);
984#ifdef CHECK_INODE
985 long_to_char(0L, b0p->b0_ino);
986#endif
987 buf->b_mtime = 0;
988 buf->b_mtime_read = 0;
989 buf->b_orig_size = 0;
990 buf->b_orig_mode = 0;
991 }
992 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000993
994#ifdef FEAT_MBYTE
995 /* Also add the 'fileencoding' if there is room. */
996 add_b0_fenc(b0p, curbuf);
997#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998}
999
1000/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001001 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1002 * swapfile for "buf" are in the same directory.
1003 * This is fail safe: if we are not sure the directories are equal the flag is
1004 * not set.
1005 */
1006 static void
1007set_b0_dir_flag(b0p, buf)
1008 ZERO_BL *b0p;
1009 buf_T *buf;
1010{
1011 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1012 b0p->b0_flags |= B0_SAME_DIR;
1013 else
1014 b0p->b0_flags &= ~B0_SAME_DIR;
1015}
1016
1017#ifdef FEAT_MBYTE
1018/*
1019 * When there is room, add the 'fileencoding' to block zero.
1020 */
1021 static void
1022add_b0_fenc(b0p, buf)
1023 ZERO_BL *b0p;
1024 buf_T *buf;
1025{
1026 int n;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001027 int size = B0_FNAME_SIZE_NOCRYPT;
1028
1029# ifdef FEAT_CRYPT
1030 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1031 * With encryption it's OK to move elsewhere, the swap file is not
1032 * compatible anyway. */
1033 if (*buf->b_p_key != NUL)
1034 size = B0_FNAME_SIZE_CRYPT;
1035# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001036
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001037 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001038 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001039 b0p->b0_flags &= ~B0_HAS_FENC;
1040 else
1041 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001042 mch_memmove((char *)b0p->b0_fname + size - n,
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001043 (char *)buf->b_p_fenc, (size_t)n);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001044 *(b0p->b0_fname + size - n - 1) = NUL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001045 b0p->b0_flags |= B0_HAS_FENC;
1046 }
1047}
1048#endif
1049
1050
1051/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001052 * Try to recover curbuf from the .swp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 */
1054 void
1055ml_recover()
1056{
1057 buf_T *buf = NULL;
1058 memfile_T *mfp = NULL;
1059 char_u *fname;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001060 char_u *fname_used = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 bhdr_T *hp = NULL;
1062 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001063 int b0_ff;
1064 char_u *b0_fenc = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001065#ifdef FEAT_CRYPT
1066 int b0_cm = -1;
1067#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 PTR_BL *pp;
1069 DATA_BL *dp;
1070 infoptr_T *ip;
1071 blocknr_T bnum;
1072 int page_count;
1073 struct stat org_stat, swp_stat;
1074 int len;
1075 int directly;
1076 linenr_T lnum;
1077 char_u *p;
1078 int i;
1079 long error;
1080 int cannot_open;
1081 linenr_T line_count;
1082 int has_error;
1083 int idx;
1084 int top;
1085 int txt_start;
1086 off_t size;
1087 int called_from_main;
1088 int serious_error = TRUE;
1089 long mtime;
1090 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001091 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092
1093 recoverymode = TRUE;
1094 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1095 attr = hl_attr(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001096
1097 /*
1098 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
1099 * Otherwise a search is done to find the swap file(s).
1100 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 fname = curbuf->b_fname;
1102 if (fname == NULL) /* When there is no file name */
1103 fname = (char_u *)"";
1104 len = (int)STRLEN(fname);
1105 if (len >= 4 &&
Bram Moolenaare60acc12011-05-10 16:41:25 +02001106#if defined(VMS)
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001107 STRNICMP(fname + len - 4, "_s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108#else
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001109 STRNICMP(fname + len - 4, ".s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110#endif
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001111 == 0
1112 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
1113 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 {
1115 directly = TRUE;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001116 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001117 }
1118 else
1119 {
1120 directly = FALSE;
1121
1122 /* count the number of matching swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001123 len = recover_names(fname, FALSE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 if (len == 0) /* no swap files found */
1125 {
1126 EMSG2(_("E305: No swap file found for %s"), fname);
1127 goto theend;
1128 }
1129 if (len == 1) /* one swap file found, use it */
1130 i = 1;
1131 else /* several swap files found, choose */
1132 {
1133 /* list the names of the swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001134 (void)recover_names(fname, TRUE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135 msg_putchar('\n');
1136 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001137 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001138 if (i < 1 || i > len)
1139 goto theend;
1140 }
1141 /* get the swap file name that will be used */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001142 (void)recover_names(fname, FALSE, i, &fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001144 if (fname_used == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145 goto theend; /* out of memory */
1146
1147 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +00001148 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149 getout(1);
1150
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001151 /*
1152 * Allocate a buffer structure for the swap file that is used for recovery.
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001153 * Only the memline and crypt information in it are really used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001154 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001155 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1156 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001159 /*
1160 * init fields in memline struct
1161 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1163 buf->b_ml.ml_stack = NULL; /* no stack yet */
1164 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1165 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1166 buf->b_ml.ml_locked = NULL; /* no locked block */
1167 buf->b_ml.ml_flags = 0;
Bram Moolenaar0fe849a2010-07-25 15:11:11 +02001168#ifdef FEAT_CRYPT
1169 buf->b_p_key = empty_option;
1170 buf->b_p_cm = empty_option;
1171#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001173 /*
1174 * open the memfile from the old swap file
1175 */
1176 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1177 mf_open() will consume "fname_used"! */
1178 mfp = mf_open(fname_used, O_RDONLY);
1179 fname_used = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180 if (mfp == NULL || mfp->mf_fd < 0)
1181 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001182 if (fname_used != NULL)
1183 EMSG2(_("E306: Cannot open %s"), fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184 goto theend;
1185 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001187#ifdef FEAT_CRYPT
1188 mfp->mf_buffer = buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001189#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190
1191 /*
1192 * The page size set in mf_open() might be different from the page size
1193 * used in the swap file, we must get it from block 0. But to read block
1194 * 0 we need a page size. Use the minimal size for block 0 here, it will
1195 * be set to the real value below.
1196 */
1197 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1198
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001199 /*
1200 * try to read block 0
1201 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1203 {
1204 msg_start();
1205 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1206 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001207 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 attr | MSG_HIST);
1209 msg_end();
1210 goto theend;
1211 }
1212 b0p = (ZERO_BL *)(hp->bh_data);
1213 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1214 {
1215 msg_start();
1216 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1217 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1218 MSG_HIST);
1219 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1220 msg_end();
1221 goto theend;
1222 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001223 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224 {
1225 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1226 goto theend;
1227 }
1228 if (b0_magic_wrong(b0p))
1229 {
1230 msg_start();
1231 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1232#if defined(MSDOS) || defined(MSWIN)
1233 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1234 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1235 attr | MSG_HIST);
1236 else
1237#endif
1238 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1239 attr | MSG_HIST);
1240 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001241 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242 b0p->b0_fname[0] = NUL;
1243 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1244 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1245 msg_end();
1246 goto theend;
1247 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001248
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001249#ifdef FEAT_CRYPT
1250 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
Bram Moolenaar49771f42010-07-20 17:32:38 +02001251 b0_cm = 0;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001252 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1253 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02001254 b0_cm = 1;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001255 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1256 }
Bram Moolenaar49771f42010-07-20 17:32:38 +02001257 set_crypt_method(buf, b0_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001258#else
1259 if (b0p->b0_id[1] != BLOCK0_ID1)
1260 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001261 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001262 goto theend;
1263 }
1264#endif
1265
Bram Moolenaar071d4272004-06-13 20:20:40 +00001266 /*
1267 * If we guessed the wrong page size, we have to recalculate the
1268 * highest block number in the file.
1269 */
1270 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1271 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001272 unsigned previous_page_size = mfp->mf_page_size;
1273
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001275 if (mfp->mf_page_size < previous_page_size)
1276 {
1277 msg_start();
1278 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1279 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1280 attr | MSG_HIST);
1281 msg_end();
1282 goto theend;
1283 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001284 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1285 mfp->mf_blocknr_max = 0; /* no file or empty file */
1286 else
1287 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1288 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001289
1290 /* need to reallocate the memory used to store the data */
1291 p = alloc(mfp->mf_page_size);
1292 if (p == NULL)
1293 goto theend;
1294 mch_memmove(p, hp->bh_data, previous_page_size);
1295 vim_free(hp->bh_data);
1296 hp->bh_data = p;
1297 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298 }
1299
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001300 /*
1301 * If .swp file name given directly, use name from swap file for buffer.
1302 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 if (directly)
1304 {
1305 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1306 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1307 goto theend;
1308 }
1309
1310 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001311 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312
1313 if (buf_spname(curbuf) != NULL)
1314 STRCPY(NameBuff, buf_spname(curbuf));
1315 else
1316 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001317 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318 msg_putchar('\n');
1319
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001320 /*
1321 * check date of swap file and original file
1322 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323 mtime = char_to_long(b0p->b0_mtime);
1324 if (curbuf->b_ffname != NULL
1325 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1326 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1327 && org_stat.st_mtime > swp_stat.st_mtime)
1328 || org_stat.st_mtime != mtime))
1329 {
1330 EMSG(_("E308: Warning: Original file may have been changed"));
1331 }
1332 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001333
1334 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1335 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1336 if (b0p->b0_flags & B0_HAS_FENC)
1337 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001338 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001339
1340#ifdef FEAT_CRYPT
1341 /* Use the same size as in add_b0_fenc(). */
1342 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001343 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001344#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001345 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001346 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001347 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001348 }
1349
Bram Moolenaar071d4272004-06-13 20:20:40 +00001350 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1351 hp = NULL;
1352
1353 /*
1354 * Now that we are sure that the file is going to be recovered, clear the
1355 * contents of the current buffer.
1356 */
1357 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1358 ml_delete((linenr_T)1, FALSE);
1359
1360 /*
1361 * Try reading the original file to obtain the values of 'fileformat',
1362 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001363 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 */
1365 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001366 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001369#ifdef FEAT_CRYPT
1370 if (b0_cm >= 0)
1371 {
1372 /* Need to ask the user for the crypt key. If this fails we continue
1373 * without a key, will probably get garbage text. */
1374 if (*curbuf->b_p_key != NUL)
1375 {
1376 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1377 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1378 MSG_PUTS(_("\nenter the new crypt key."));
1379 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1380 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1381 }
1382 else
1383 smsg((char_u *)_(need_key_msg), fname_used);
1384 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1385 if (buf->b_p_key == NULL)
1386 buf->b_p_key = curbuf->b_p_key;
1387 else if (*buf->b_p_key == NUL)
1388 {
1389 vim_free(buf->b_p_key);
1390 buf->b_p_key = curbuf->b_p_key;
1391 }
1392 if (buf->b_p_key == NULL)
1393 buf->b_p_key = empty_option;
1394 }
1395#endif
1396
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001397 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1398 if (b0_ff != 0)
1399 set_fileformat(b0_ff - 1, OPT_LOCAL);
1400 if (b0_fenc != NULL)
1401 {
1402 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1403 vim_free(b0_fenc);
1404 }
1405 unchanged(curbuf, TRUE);
1406
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407 bnum = 1; /* start with block 1 */
1408 page_count = 1; /* which is 1 page */
1409 lnum = 0; /* append after line 0 in curbuf */
1410 line_count = 0;
1411 idx = 0; /* start with first index in block 1 */
1412 error = 0;
1413 buf->b_ml.ml_stack_top = 0;
1414 buf->b_ml.ml_stack = NULL;
1415 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1416
1417 if (curbuf->b_ffname == NULL)
1418 cannot_open = TRUE;
1419 else
1420 cannot_open = FALSE;
1421
1422 serious_error = FALSE;
1423 for ( ; !got_int; line_breakcheck())
1424 {
1425 if (hp != NULL)
1426 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1427
1428 /*
1429 * get block
1430 */
1431 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1432 {
1433 if (bnum == 1)
1434 {
1435 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1436 goto theend;
1437 }
1438 ++error;
1439 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1440 (colnr_T)0, TRUE);
1441 }
1442 else /* there is a block */
1443 {
1444 pp = (PTR_BL *)(hp->bh_data);
1445 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1446 {
1447 /* check line count when using pointer block first time */
1448 if (idx == 0 && line_count != 0)
1449 {
1450 for (i = 0; i < (int)pp->pb_count; ++i)
1451 line_count -= pp->pb_pointer[i].pe_line_count;
1452 if (line_count != 0)
1453 {
1454 ++error;
1455 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1456 (colnr_T)0, TRUE);
1457 }
1458 }
1459
1460 if (pp->pb_count == 0)
1461 {
1462 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1463 (colnr_T)0, TRUE);
1464 ++error;
1465 }
1466 else if (idx < (int)pp->pb_count) /* go a block deeper */
1467 {
1468 if (pp->pb_pointer[idx].pe_bnum < 0)
1469 {
1470 /*
1471 * Data block with negative block number.
1472 * Try to read lines from the original file.
1473 * This is slow, but it works.
1474 */
1475 if (!cannot_open)
1476 {
1477 line_count = pp->pb_pointer[idx].pe_line_count;
1478 if (readfile(curbuf->b_ffname, NULL, lnum,
1479 pp->pb_pointer[idx].pe_old_lnum - 1,
1480 line_count, NULL, 0) == FAIL)
1481 cannot_open = TRUE;
1482 else
1483 lnum += line_count;
1484 }
1485 if (cannot_open)
1486 {
1487 ++error;
1488 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1489 (colnr_T)0, TRUE);
1490 }
1491 ++idx; /* get same block again for next index */
1492 continue;
1493 }
1494
1495 /*
1496 * going one block deeper in the tree
1497 */
1498 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1499 {
1500 ++error;
1501 break; /* out of memory */
1502 }
1503 ip = &(buf->b_ml.ml_stack[top]);
1504 ip->ip_bnum = bnum;
1505 ip->ip_index = idx;
1506
1507 bnum = pp->pb_pointer[idx].pe_bnum;
1508 line_count = pp->pb_pointer[idx].pe_line_count;
1509 page_count = pp->pb_pointer[idx].pe_page_count;
1510 continue;
1511 }
1512 }
1513 else /* not a pointer block */
1514 {
1515 dp = (DATA_BL *)(hp->bh_data);
1516 if (dp->db_id != DATA_ID) /* block id wrong */
1517 {
1518 if (bnum == 1)
1519 {
1520 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1521 mfp->mf_fname);
1522 goto theend;
1523 }
1524 ++error;
1525 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1526 (colnr_T)0, TRUE);
1527 }
1528 else
1529 {
1530 /*
1531 * it is a data block
1532 * Append all the lines in this block
1533 */
1534 has_error = FALSE;
1535 /*
1536 * check length of block
1537 * if wrong, use length in pointer block
1538 */
1539 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1540 {
1541 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1542 (colnr_T)0, TRUE);
1543 ++error;
1544 has_error = TRUE;
1545 dp->db_txt_end = page_count * mfp->mf_page_size;
1546 }
1547
1548 /* make sure there is a NUL at the end of the block */
1549 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1550
1551 /*
1552 * check number of lines in block
1553 * if wrong, use count in data block
1554 */
1555 if (line_count != dp->db_line_count)
1556 {
1557 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1558 (colnr_T)0, TRUE);
1559 ++error;
1560 has_error = TRUE;
1561 }
1562
1563 for (i = 0; i < dp->db_line_count; ++i)
1564 {
1565 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001566 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 || txt_start >= (int)dp->db_txt_end)
1568 {
1569 p = (char_u *)"???";
1570 ++error;
1571 }
1572 else
1573 p = (char_u *)dp + txt_start;
1574 ml_append(lnum++, p, (colnr_T)0, TRUE);
1575 }
1576 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001577 ml_append(lnum++, (char_u *)_("???END"),
1578 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579 }
1580 }
1581 }
1582
1583 if (buf->b_ml.ml_stack_top == 0) /* finished */
1584 break;
1585
1586 /*
1587 * go one block up in the tree
1588 */
1589 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1590 bnum = ip->ip_bnum;
1591 idx = ip->ip_index + 1; /* go to next index */
1592 page_count = 1;
1593 }
1594
1595 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001596 * Compare the buffer contents with the original file. When they differ
1597 * set the 'modified' flag.
1598 * Lines 1 - lnum are the new contents.
1599 * Lines lnum + 1 to ml_line_count are the original contents.
1600 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001602 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1603 {
1604 /* Recovering an empty file results in two lines and the first line is
1605 * empty. Don't set the modified flag then. */
1606 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1607 {
1608 changed_int();
1609 ++curbuf->b_changedtick;
1610 }
1611 }
1612 else
1613 {
1614 for (idx = 1; idx <= lnum; ++idx)
1615 {
1616 /* Need to copy one line, fetching the other one may flush it. */
1617 p = vim_strsave(ml_get(idx));
1618 i = STRCMP(p, ml_get(idx + lnum));
1619 vim_free(p);
1620 if (i != 0)
1621 {
1622 changed_int();
1623 ++curbuf->b_changedtick;
1624 break;
1625 }
1626 }
1627 }
1628
1629 /*
1630 * Delete the lines from the original file and the dummy line from the
1631 * empty buffer. These will now be after the last line in the buffer.
1632 */
1633 while (curbuf->b_ml.ml_line_count > lnum
1634 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1635 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 curbuf->b_flags |= BF_RECOVERED;
1637
1638 recoverymode = FALSE;
1639 if (got_int)
1640 EMSG(_("E311: Recovery Interrupted"));
1641 else if (error)
1642 {
1643 ++no_wait_return;
1644 MSG(">>>>>>>>>>>>>");
1645 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1646 --no_wait_return;
1647 MSG(_("See \":help E312\" for more information."));
1648 MSG(">>>>>>>>>>>>>");
1649 }
1650 else
1651 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001652 if (curbuf->b_changed)
1653 {
1654 MSG(_("Recovery completed. You should check if everything is OK."));
1655 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1656 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1657 }
1658 else
1659 MSG(_("Recovery completed. Buffer contents equals file contents."));
1660 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 cmdline_row = msg_row;
1662 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001663#ifdef FEAT_CRYPT
1664 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1665 {
1666 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1667 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1668 }
1669#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670 redraw_curbuf_later(NOT_VALID);
1671
1672theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001673 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 recoverymode = FALSE;
1675 if (mfp != NULL)
1676 {
1677 if (hp != NULL)
1678 mf_put(mfp, hp, FALSE, FALSE);
1679 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1680 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001681 if (buf != NULL)
1682 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001683#ifdef FEAT_CRYPT
1684 if (buf->b_p_key != curbuf->b_p_key)
1685 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001686 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001687#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001688 vim_free(buf->b_ml.ml_stack);
1689 vim_free(buf);
1690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 if (serious_error && called_from_main)
1692 ml_close(curbuf, TRUE);
1693#ifdef FEAT_AUTOCMD
1694 else
1695 {
1696 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1697 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1698 }
1699#endif
1700 return;
1701}
1702
1703/*
1704 * Find the names of swap files in current directory and the directory given
1705 * with the 'directory' option.
1706 *
1707 * Used to:
1708 * - list the swap files for "vim -r"
1709 * - count the number of swap files when recovering
1710 * - list the swap files when recovering
1711 * - find the name of the n'th swap file when recovering
1712 */
1713 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001714recover_names(fname, list, nr, fname_out)
1715 char_u *fname; /* base for swap file name */
1716 int list; /* when TRUE, list the swap file names */
1717 int nr; /* when non-zero, return nr'th swap file name */
1718 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719{
1720 int num_names;
1721 char_u *(names[6]);
1722 char_u *tail;
1723 char_u *p;
1724 int num_files;
1725 int file_count = 0;
1726 char_u **files;
1727 int i;
1728 char_u *dirp;
1729 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001730 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001731#ifdef HAVE_READLINK
1732 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001733#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001734
Bram Moolenaar64354da2010-05-25 21:37:17 +02001735 if (fname != NULL)
1736 {
1737#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001738 /* Expand symlink in the file name, because the swap file is created
1739 * with the actual file instead of with the symlink. */
1740 if (resolve_symlink(fname, fname_buf) == OK)
1741 fname_res = fname_buf;
1742 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001743#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001744 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746
1747 if (list)
1748 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001749 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750 msg((char_u *)_("Swap files found:"));
1751 msg_putchar('\n');
1752 }
1753
1754 /*
1755 * Do the loop for every directory in 'directory'.
1756 * First allocate some memory to put the directory name in.
1757 */
1758 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1759 dirp = p_dir;
1760 while (dir_name != NULL && *dirp)
1761 {
1762 /*
1763 * Isolate a directory name from *dirp and put it in dir_name (we know
1764 * it is large enough, so use 31000 for length).
1765 * Advance dirp to next directory name.
1766 */
1767 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1768
1769 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1770 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001771 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772 {
1773#ifdef VMS
1774 names[0] = vim_strsave((char_u *)"*_sw%");
1775#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776 names[0] = vim_strsave((char_u *)"*.sw?");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001778#if defined(UNIX) || defined(WIN3264)
1779 /* For Unix names starting with a dot are special. MS-Windows
1780 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 names[1] = vim_strsave((char_u *)".*.sw?");
1782 names[2] = vim_strsave((char_u *)".sw?");
1783 num_names = 3;
1784#else
1785# ifdef VMS
1786 names[1] = vim_strsave((char_u *)".*_sw%");
1787 num_names = 2;
1788# else
1789 num_names = 1;
1790# endif
1791#endif
1792 }
1793 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001794 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 }
1796 else /* check directory dir_name */
1797 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001798 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 {
1800#ifdef VMS
1801 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1802#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001805#if defined(UNIX) || defined(WIN3264)
1806 /* For Unix names starting with a dot are special. MS-Windows
1807 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1809 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1810 num_names = 3;
1811#else
1812# ifdef VMS
1813 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1814 num_names = 2;
1815# else
1816 num_names = 1;
1817# endif
1818#endif
1819 }
1820 else
1821 {
1822#if defined(UNIX) || defined(WIN3264)
1823 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001824 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 {
1826 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001827 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828 }
1829 else
1830#endif
1831 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001832 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 tail = concat_fnames(dir_name, tail, TRUE);
1834 }
1835 if (tail == NULL)
1836 num_names = 0;
1837 else
1838 {
1839 num_names = recov_file_names(names, tail, FALSE);
1840 vim_free(tail);
1841 }
1842 }
1843 }
1844
1845 /* check for out-of-memory */
1846 for (i = 0; i < num_names; ++i)
1847 {
1848 if (names[i] == NULL)
1849 {
1850 for (i = 0; i < num_names; ++i)
1851 vim_free(names[i]);
1852 num_names = 0;
1853 }
1854 }
1855 if (num_names == 0)
1856 num_files = 0;
1857 else if (expand_wildcards(num_names, names, &num_files, &files,
1858 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1859 num_files = 0;
1860
1861 /*
1862 * When no swap file found, wildcard expansion might have failed (e.g.
1863 * not able to execute the shell).
1864 * Try finding a swap file by simply adding ".swp" to the file name.
1865 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001866 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 {
1868 struct stat st;
1869 char_u *swapname;
1870
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001871 swapname = modname(fname_res,
Bram Moolenaare60acc12011-05-10 16:41:25 +02001872#if defined(VMS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001873 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001875 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001877 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 if (swapname != NULL)
1879 {
1880 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1881 {
1882 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1883 if (files != NULL)
1884 {
1885 files[0] = swapname;
1886 swapname = NULL;
1887 num_files = 1;
1888 }
1889 }
1890 vim_free(swapname);
1891 }
1892 }
1893
1894 /*
1895 * remove swapfile name of the current buffer, it must be ignored
1896 */
1897 if (curbuf->b_ml.ml_mfp != NULL
1898 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1899 {
1900 for (i = 0; i < num_files; ++i)
1901 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1902 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001903 /* Remove the name from files[i]. Move further entries
1904 * down. When the array becomes empty free it here, since
1905 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001907 if (--num_files == 0)
1908 vim_free(files);
1909 else
1910 for ( ; i < num_files; ++i)
1911 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 }
1913 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001914 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 {
1916 file_count += num_files;
1917 if (nr <= file_count)
1918 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001919 *fname_out = vim_strsave(
1920 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 dirp = (char_u *)""; /* stop searching */
1922 }
1923 }
1924 else if (list)
1925 {
1926 if (dir_name[0] == '.' && dir_name[1] == NUL)
1927 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001928 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 MSG_PUTS(_(" In current directory:\n"));
1930 else
1931 MSG_PUTS(_(" Using specified name:\n"));
1932 }
1933 else
1934 {
1935 MSG_PUTS(_(" In directory "));
1936 msg_home_replace(dir_name);
1937 MSG_PUTS(":\n");
1938 }
1939
1940 if (num_files)
1941 {
1942 for (i = 0; i < num_files; ++i)
1943 {
1944 /* print the swap file name */
1945 msg_outnum((long)++file_count);
1946 MSG_PUTS(". ");
1947 msg_puts(gettail(files[i]));
1948 msg_putchar('\n');
1949 (void)swapfile_info(files[i]);
1950 }
1951 }
1952 else
1953 MSG_PUTS(_(" -- none --\n"));
1954 out_flush();
1955 }
1956 else
1957 file_count += num_files;
1958
1959 for (i = 0; i < num_names; ++i)
1960 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001961 if (num_files > 0)
1962 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 }
1964 vim_free(dir_name);
1965 return file_count;
1966}
1967
1968#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1969/*
1970 * Append the full path to name with path separators made into percent
1971 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1972 */
1973 static char_u *
1974make_percent_swname(dir, name)
1975 char_u *dir;
1976 char_u *name;
1977{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001978 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979
1980 f = fix_fname(name != NULL ? name : (char_u *) "");
1981 d = NULL;
1982 if (f != NULL)
1983 {
1984 s = alloc((unsigned)(STRLEN(f) + 1));
1985 if (s != NULL)
1986 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001987 STRCPY(s, f);
1988 for (d = s; *d != NUL; mb_ptr_adv(d))
1989 if (vim_ispathsep(*d))
1990 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00001991 d = concat_fnames(dir, s, TRUE);
1992 vim_free(s);
1993 }
1994 vim_free(f);
1995 }
1996 return d;
1997}
1998#endif
1999
2000#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2001static int process_still_running;
2002#endif
2003
2004/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002005 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 * Returns timestamp (0 when unknown).
2007 */
2008 static time_t
2009swapfile_info(fname)
2010 char_u *fname;
2011{
2012 struct stat st;
2013 int fd;
2014 struct block0 b0;
2015 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002016 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017#ifdef UNIX
2018 char_u uname[B0_UNAME_SIZE];
2019#endif
2020
2021 /* print the swap file date */
2022 if (mch_stat((char *)fname, &st) != -1)
2023 {
2024#ifdef UNIX
2025 /* print name of owner of the file */
2026 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2027 {
2028 MSG_PUTS(_(" owned by: "));
2029 msg_outtrans(uname);
2030 MSG_PUTS(_(" dated: "));
2031 }
2032 else
2033#endif
2034 MSG_PUTS(_(" dated: "));
2035 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002036 p = ctime(&x); /* includes '\n' */
2037 if (p == NULL)
2038 MSG_PUTS("(invalid)\n");
2039 else
2040 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 }
2042
2043 /*
2044 * print the original file name
2045 */
2046 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2047 if (fd >= 0)
2048 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01002049 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050 {
2051 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2052 {
2053 MSG_PUTS(_(" [from Vim version 3.0]"));
2054 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002055 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056 {
2057 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2058 }
2059 else
2060 {
2061 MSG_PUTS(_(" file name: "));
2062 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002063 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 else
2065 msg_outtrans(b0.b0_fname);
2066
2067 MSG_PUTS(_("\n modified: "));
2068 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2069
2070 if (*(b0.b0_uname) != NUL)
2071 {
2072 MSG_PUTS(_("\n user name: "));
2073 msg_outtrans(b0.b0_uname);
2074 }
2075
2076 if (*(b0.b0_hname) != NUL)
2077 {
2078 if (*(b0.b0_uname) != NUL)
2079 MSG_PUTS(_(" host name: "));
2080 else
2081 MSG_PUTS(_("\n host name: "));
2082 msg_outtrans(b0.b0_hname);
2083 }
2084
2085 if (char_to_long(b0.b0_pid) != 0L)
2086 {
2087 MSG_PUTS(_("\n process ID: "));
2088 msg_outnum(char_to_long(b0.b0_pid));
2089#if defined(UNIX) || defined(__EMX__)
2090 /* EMX kill() not working correctly, it seems */
2091 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2092 {
2093 MSG_PUTS(_(" (still running)"));
2094# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2095 process_still_running = TRUE;
2096# endif
2097 }
2098#endif
2099 }
2100
2101 if (b0_magic_wrong(&b0))
2102 {
2103#if defined(MSDOS) || defined(MSWIN)
2104 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2105 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2106 else
2107#endif
2108 MSG_PUTS(_("\n [not usable on this computer]"));
2109 }
2110 }
2111 }
2112 else
2113 MSG_PUTS(_(" [cannot be read]"));
2114 close(fd);
2115 }
2116 else
2117 MSG_PUTS(_(" [cannot be opened]"));
2118 msg_putchar('\n');
2119
2120 return x;
2121}
2122
2123 static int
2124recov_file_names(names, path, prepend_dot)
2125 char_u **names;
2126 char_u *path;
2127 int prepend_dot;
2128{
2129 int num_names;
2130
2131#ifdef SHORT_FNAME
2132 /*
2133 * (MS-DOS) always short names
2134 */
2135 names[0] = modname(path, (char_u *)".sw?", FALSE);
2136 num_names = 1;
2137#else /* !SHORT_FNAME */
2138 /*
2139 * (Win32 and Win64) never short names, but do prepend a dot.
2140 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2141 * Only use the short name if it is different.
2142 */
2143 char_u *p;
2144 int i;
2145# ifndef WIN3264
2146 int shortname = curbuf->b_shortname;
2147
2148 curbuf->b_shortname = FALSE;
2149# endif
2150
2151 num_names = 0;
2152
2153 /*
2154 * May also add the file name with a dot prepended, for swap file in same
2155 * dir as original file.
2156 */
2157 if (prepend_dot)
2158 {
2159 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2160 if (names[num_names] == NULL)
2161 goto end;
2162 ++num_names;
2163 }
2164
2165 /*
2166 * Form the normal swap file name pattern by appending ".sw?".
2167 */
2168#ifdef VMS
2169 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2170#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172#endif
2173 if (names[num_names] == NULL)
2174 goto end;
2175 if (num_names >= 1) /* check if we have the same name twice */
2176 {
2177 p = names[num_names - 1];
2178 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2179 if (i > 0)
2180 p += i; /* file name has been expanded to full path */
2181
2182 if (STRCMP(p, names[num_names]) != 0)
2183 ++num_names;
2184 else
2185 vim_free(names[num_names]);
2186 }
2187 else
2188 ++num_names;
2189
2190# ifndef WIN3264
2191 /*
2192 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2193 */
2194 curbuf->b_shortname = TRUE;
2195#ifdef VMS
2196 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2197#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199#endif
2200 if (names[num_names] == NULL)
2201 goto end;
2202
2203 /*
2204 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2205 */
2206 p = names[num_names];
2207 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2208 if (i > 0)
2209 p += i; /* file name has been expanded to full path */
2210 if (STRCMP(names[num_names - 1], p) == 0)
2211 vim_free(names[num_names]);
2212 else
2213 ++num_names;
2214# endif
2215
2216end:
2217# ifndef WIN3264
2218 curbuf->b_shortname = shortname;
2219# endif
2220
2221#endif /* !SHORT_FNAME */
2222
2223 return num_names;
2224}
2225
2226/*
2227 * sync all memlines
2228 *
2229 * If 'check_file' is TRUE, check if original file exists and was not changed.
2230 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2231 * always sync at least one block.
2232 */
2233 void
2234ml_sync_all(check_file, check_char)
2235 int check_file;
2236 int check_char;
2237{
2238 buf_T *buf;
2239 struct stat st;
2240
2241 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2242 {
2243 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2244 continue; /* no file */
2245
2246 ml_flush_line(buf); /* flush buffered line */
2247 /* flush locked block */
2248 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2249 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2250 && buf->b_ffname != NULL)
2251 {
2252 /*
2253 * If the original file does not exist anymore or has been changed
2254 * call ml_preserve() to get rid of all negative numbered blocks.
2255 */
2256 if (mch_stat((char *)buf->b_ffname, &st) == -1
2257 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002258 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 {
2260 ml_preserve(buf, FALSE);
2261 did_check_timestamps = FALSE;
2262 need_check_timestamps = TRUE; /* give message later */
2263 }
2264 }
2265 if (buf->b_ml.ml_mfp->mf_dirty)
2266 {
2267 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2268 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2269 if (check_char && ui_char_avail()) /* character available now */
2270 break;
2271 }
2272 }
2273}
2274
2275/*
2276 * sync one buffer, including negative blocks
2277 *
2278 * after this all the blocks are in the swap file
2279 *
2280 * Used for the :preserve command and when the original file has been
2281 * changed or deleted.
2282 *
2283 * when message is TRUE the success of preserving is reported
2284 */
2285 void
2286ml_preserve(buf, message)
2287 buf_T *buf;
2288 int message;
2289{
2290 bhdr_T *hp;
2291 linenr_T lnum;
2292 memfile_T *mfp = buf->b_ml.ml_mfp;
2293 int status;
2294 int got_int_save = got_int;
2295
2296 if (mfp == NULL || mfp->mf_fname == NULL)
2297 {
2298 if (message)
2299 EMSG(_("E313: Cannot preserve, there is no swap file"));
2300 return;
2301 }
2302
2303 /* We only want to stop when interrupted here, not when interrupted
2304 * before. */
2305 got_int = FALSE;
2306
2307 ml_flush_line(buf); /* flush buffered line */
2308 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2309 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2310
2311 /* stack is invalid after mf_sync(.., MFS_ALL) */
2312 buf->b_ml.ml_stack_top = 0;
2313
2314 /*
2315 * Some of the data blocks may have been changed from negative to
2316 * positive block number. In that case the pointer blocks need to be
2317 * updated.
2318 *
2319 * We don't know in which pointer block the references are, so we visit
2320 * all data blocks until there are no more translations to be done (or
2321 * we hit the end of the file, which can only happen in case a write fails,
2322 * e.g. when file system if full).
2323 * ml_find_line() does the work by translating the negative block numbers
2324 * when getting the first line of each data block.
2325 */
2326 if (mf_need_trans(mfp) && !got_int)
2327 {
2328 lnum = 1;
2329 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2330 {
2331 hp = ml_find_line(buf, lnum, ML_FIND);
2332 if (hp == NULL)
2333 {
2334 status = FAIL;
2335 goto theend;
2336 }
2337 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2338 lnum = buf->b_ml.ml_locked_high + 1;
2339 }
2340 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2341 /* sync the updated pointer blocks */
2342 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2343 status = FAIL;
2344 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2345 }
2346theend:
2347 got_int |= got_int_save;
2348
2349 if (message)
2350 {
2351 if (status == OK)
2352 MSG(_("File preserved"));
2353 else
2354 EMSG(_("E314: Preserve failed"));
2355 }
2356}
2357
2358/*
2359 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2360 * until the next call!
2361 * line1 = ml_get(1);
2362 * line2 = ml_get(2); // line1 is now invalid!
2363 * Make a copy of the line if necessary.
2364 */
2365/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002366 * Return a pointer to a (read-only copy of a) line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 *
2368 * On failure an error message is given and IObuff is returned (to avoid
2369 * having to check for error everywhere).
2370 */
2371 char_u *
2372ml_get(lnum)
2373 linenr_T lnum;
2374{
2375 return ml_get_buf(curbuf, lnum, FALSE);
2376}
2377
2378/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002379 * Return pointer to position "pos".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 */
2381 char_u *
2382ml_get_pos(pos)
2383 pos_T *pos;
2384{
2385 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2386}
2387
2388/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002389 * Return pointer to cursor line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 */
2391 char_u *
2392ml_get_curline()
2393{
2394 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2395}
2396
2397/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002398 * Return pointer to cursor position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 */
2400 char_u *
2401ml_get_cursor()
2402{
2403 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2404 curwin->w_cursor.col);
2405}
2406
2407/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002408 * Return a pointer to a line in a specific buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 *
2410 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2411 * changed)
2412 */
2413 char_u *
2414ml_get_buf(buf, lnum, will_change)
2415 buf_T *buf;
2416 linenr_T lnum;
2417 int will_change; /* line will be changed */
2418{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002419 bhdr_T *hp;
2420 DATA_BL *dp;
2421 char_u *ptr;
2422 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423
2424 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2425 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002426 if (recursive == 0)
2427 {
2428 /* Avoid giving this message for a recursive call, may happen when
2429 * the GUI redraws part of the text. */
2430 ++recursive;
2431 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2432 --recursive;
2433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434errorret:
2435 STRCPY(IObuff, "???");
2436 return IObuff;
2437 }
2438 if (lnum <= 0) /* pretend line 0 is line 1 */
2439 lnum = 1;
2440
2441 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2442 return (char_u *)"";
2443
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002444 /*
2445 * See if it is the same line as requested last time.
2446 * Otherwise may need to flush last used line.
2447 * Don't use the last used line when 'swapfile' is reset, need to load all
2448 * blocks.
2449 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002450 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 {
2452 ml_flush_line(buf);
2453
2454 /*
2455 * Find the data block containing the line.
2456 * This also fills the stack with the blocks from the root to the data
2457 * block and releases any locked block.
2458 */
2459 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2460 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002461 if (recursive == 0)
2462 {
2463 /* Avoid giving this message for a recursive call, may happen
2464 * when the GUI redraws part of the text. */
2465 ++recursive;
2466 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2467 --recursive;
2468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469 goto errorret;
2470 }
2471
2472 dp = (DATA_BL *)(hp->bh_data);
2473
2474 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2475 buf->b_ml.ml_line_ptr = ptr;
2476 buf->b_ml.ml_line_lnum = lnum;
2477 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2478 }
2479 if (will_change)
2480 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2481
2482 return buf->b_ml.ml_line_ptr;
2483}
2484
2485/*
2486 * Check if a line that was just obtained by a call to ml_get
2487 * is in allocated memory.
2488 */
2489 int
2490ml_line_alloced()
2491{
2492 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2493}
2494
2495/*
2496 * Append a line after lnum (may be 0 to insert a line in front of the file).
2497 * "line" does not need to be allocated, but can't be another line in a
2498 * buffer, unlocking may make it invalid.
2499 *
2500 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2501 * will be set for recovery
2502 * Check: The caller of this function should probably also call
2503 * appended_lines().
2504 *
2505 * return FAIL for failure, OK otherwise
2506 */
2507 int
2508ml_append(lnum, line, len, newfile)
2509 linenr_T lnum; /* append after this line (can be 0) */
2510 char_u *line; /* text of the new line */
2511 colnr_T len; /* length of new line, including NUL, or 0 */
2512 int newfile; /* flag, see above */
2513{
2514 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002515 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 return FAIL;
2517
2518 if (curbuf->b_ml.ml_line_lnum != 0)
2519 ml_flush_line(curbuf);
2520 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2521}
2522
Bram Moolenaara1956f62006-03-12 22:18:00 +00002523#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002524/*
2525 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2526 * a memline.
2527 */
2528 int
2529ml_append_buf(buf, lnum, line, len, newfile)
2530 buf_T *buf;
2531 linenr_T lnum; /* append after this line (can be 0) */
2532 char_u *line; /* text of the new line */
2533 colnr_T len; /* length of new line, including NUL, or 0 */
2534 int newfile; /* flag, see above */
2535{
2536 if (buf->b_ml.ml_mfp == NULL)
2537 return FAIL;
2538
2539 if (buf->b_ml.ml_line_lnum != 0)
2540 ml_flush_line(buf);
2541 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2542}
2543#endif
2544
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 static int
2546ml_append_int(buf, lnum, line, len, newfile, mark)
2547 buf_T *buf;
2548 linenr_T lnum; /* append after this line (can be 0) */
2549 char_u *line; /* text of the new line */
2550 colnr_T len; /* length of line, including NUL, or 0 */
2551 int newfile; /* flag, see above */
2552 int mark; /* mark the new line */
2553{
2554 int i;
2555 int line_count; /* number of indexes in current block */
2556 int offset;
2557 int from, to;
2558 int space_needed; /* space needed for new line */
2559 int page_size;
2560 int page_count;
2561 int db_idx; /* index for lnum in data block */
2562 bhdr_T *hp;
2563 memfile_T *mfp;
2564 DATA_BL *dp;
2565 PTR_BL *pp;
2566 infoptr_T *ip;
2567
2568 /* lnum out of range */
2569 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2570 return FAIL;
2571
2572 if (lowest_marked && lowest_marked > lnum)
2573 lowest_marked = lnum + 1;
2574
2575 if (len == 0)
2576 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2577 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2578
2579 mfp = buf->b_ml.ml_mfp;
2580 page_size = mfp->mf_page_size;
2581
2582/*
2583 * find the data block containing the previous line
2584 * This also fills the stack with the blocks from the root to the data block
2585 * This also releases any locked block.
2586 */
2587 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2588 ML_INSERT)) == NULL)
2589 return FAIL;
2590
2591 buf->b_ml.ml_flags &= ~ML_EMPTY;
2592
2593 if (lnum == 0) /* got line one instead, correct db_idx */
2594 db_idx = -1; /* careful, it is negative! */
2595 else
2596 db_idx = lnum - buf->b_ml.ml_locked_low;
2597 /* get line count before the insertion */
2598 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2599
2600 dp = (DATA_BL *)(hp->bh_data);
2601
2602/*
2603 * If
2604 * - there is not enough room in the current block
2605 * - appending to the last line in the block
2606 * - not appending to the last line in the file
2607 * insert in front of the next block.
2608 */
2609 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2610 && lnum < buf->b_ml.ml_line_count)
2611 {
2612 /*
2613 * Now that the line is not going to be inserted in the block that we
2614 * expected, the line count has to be adjusted in the pointer blocks
2615 * by using ml_locked_lineadd.
2616 */
2617 --(buf->b_ml.ml_locked_lineadd);
2618 --(buf->b_ml.ml_locked_high);
2619 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2620 return FAIL;
2621
2622 db_idx = -1; /* careful, it is negative! */
2623 /* get line count before the insertion */
2624 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2625 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2626
2627 dp = (DATA_BL *)(hp->bh_data);
2628 }
2629
2630 ++buf->b_ml.ml_line_count;
2631
2632 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2633 {
2634/*
2635 * Insert new line in existing data block, or in data block allocated above.
2636 */
2637 dp->db_txt_start -= len;
2638 dp->db_free -= space_needed;
2639 ++(dp->db_line_count);
2640
2641 /*
2642 * move the text of the lines that follow to the front
2643 * adjust the indexes of the lines that follow
2644 */
2645 if (line_count > db_idx + 1) /* if there are following lines */
2646 {
2647 /*
2648 * Offset is the start of the previous line.
2649 * This will become the character just after the new line.
2650 */
2651 if (db_idx < 0)
2652 offset = dp->db_txt_end;
2653 else
2654 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2655 mch_memmove((char *)dp + dp->db_txt_start,
2656 (char *)dp + dp->db_txt_start + len,
2657 (size_t)(offset - (dp->db_txt_start + len)));
2658 for (i = line_count - 1; i > db_idx; --i)
2659 dp->db_index[i + 1] = dp->db_index[i] - len;
2660 dp->db_index[db_idx + 1] = offset - len;
2661 }
2662 else /* add line at the end */
2663 dp->db_index[db_idx + 1] = dp->db_txt_start;
2664
2665 /*
2666 * copy the text into the block
2667 */
2668 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2669 if (mark)
2670 dp->db_index[db_idx + 1] |= DB_MARKED;
2671
2672 /*
2673 * Mark the block dirty.
2674 */
2675 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2676 if (!newfile)
2677 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2678 }
2679 else /* not enough space in data block */
2680 {
2681/*
2682 * If there is not enough room we have to create a new data block and copy some
2683 * lines into it.
2684 * Then we have to insert an entry in the pointer block.
2685 * If this pointer block also is full, we go up another block, and so on, up
2686 * to the root if necessary.
2687 * The line counts in the pointer blocks have already been adjusted by
2688 * ml_find_line().
2689 */
2690 long line_count_left, line_count_right;
2691 int page_count_left, page_count_right;
2692 bhdr_T *hp_left;
2693 bhdr_T *hp_right;
2694 bhdr_T *hp_new;
2695 int lines_moved;
2696 int data_moved = 0; /* init to shut up gcc */
2697 int total_moved = 0; /* init to shut up gcc */
2698 DATA_BL *dp_right, *dp_left;
2699 int stack_idx;
2700 int in_left;
2701 int lineadd;
2702 blocknr_T bnum_left, bnum_right;
2703 linenr_T lnum_left, lnum_right;
2704 int pb_idx;
2705 PTR_BL *pp_new;
2706
2707 /*
2708 * We are going to allocate a new data block. Depending on the
2709 * situation it will be put to the left or right of the existing
2710 * block. If possible we put the new line in the left block and move
2711 * the lines after it to the right block. Otherwise the new line is
2712 * also put in the right block. This method is more efficient when
2713 * inserting a lot of lines at one place.
2714 */
2715 if (db_idx < 0) /* left block is new, right block is existing */
2716 {
2717 lines_moved = 0;
2718 in_left = TRUE;
2719 /* space_needed does not change */
2720 }
2721 else /* left block is existing, right block is new */
2722 {
2723 lines_moved = line_count - db_idx - 1;
2724 if (lines_moved == 0)
2725 in_left = FALSE; /* put new line in right block */
2726 /* space_needed does not change */
2727 else
2728 {
2729 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2730 dp->db_txt_start;
2731 total_moved = data_moved + lines_moved * INDEX_SIZE;
2732 if ((int)dp->db_free + total_moved >= space_needed)
2733 {
2734 in_left = TRUE; /* put new line in left block */
2735 space_needed = total_moved;
2736 }
2737 else
2738 {
2739 in_left = FALSE; /* put new line in right block */
2740 space_needed += total_moved;
2741 }
2742 }
2743 }
2744
2745 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2746 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2747 {
2748 /* correct line counts in pointer blocks */
2749 --(buf->b_ml.ml_locked_lineadd);
2750 --(buf->b_ml.ml_locked_high);
2751 return FAIL;
2752 }
2753 if (db_idx < 0) /* left block is new */
2754 {
2755 hp_left = hp_new;
2756 hp_right = hp;
2757 line_count_left = 0;
2758 line_count_right = line_count;
2759 }
2760 else /* right block is new */
2761 {
2762 hp_left = hp;
2763 hp_right = hp_new;
2764 line_count_left = line_count;
2765 line_count_right = 0;
2766 }
2767 dp_right = (DATA_BL *)(hp_right->bh_data);
2768 dp_left = (DATA_BL *)(hp_left->bh_data);
2769 bnum_left = hp_left->bh_bnum;
2770 bnum_right = hp_right->bh_bnum;
2771 page_count_left = hp_left->bh_page_count;
2772 page_count_right = hp_right->bh_page_count;
2773
2774 /*
2775 * May move the new line into the right/new block.
2776 */
2777 if (!in_left)
2778 {
2779 dp_right->db_txt_start -= len;
2780 dp_right->db_free -= len + INDEX_SIZE;
2781 dp_right->db_index[0] = dp_right->db_txt_start;
2782 if (mark)
2783 dp_right->db_index[0] |= DB_MARKED;
2784
2785 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2786 line, (size_t)len);
2787 ++line_count_right;
2788 }
2789 /*
2790 * may move lines from the left/old block to the right/new one.
2791 */
2792 if (lines_moved)
2793 {
2794 /*
2795 */
2796 dp_right->db_txt_start -= data_moved;
2797 dp_right->db_free -= total_moved;
2798 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2799 (char *)dp_left + dp_left->db_txt_start,
2800 (size_t)data_moved);
2801 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2802 dp_left->db_txt_start += data_moved;
2803 dp_left->db_free += total_moved;
2804
2805 /*
2806 * update indexes in the new block
2807 */
2808 for (to = line_count_right, from = db_idx + 1;
2809 from < line_count_left; ++from, ++to)
2810 dp_right->db_index[to] = dp->db_index[from] + offset;
2811 line_count_right += lines_moved;
2812 line_count_left -= lines_moved;
2813 }
2814
2815 /*
2816 * May move the new line into the left (old or new) block.
2817 */
2818 if (in_left)
2819 {
2820 dp_left->db_txt_start -= len;
2821 dp_left->db_free -= len + INDEX_SIZE;
2822 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2823 if (mark)
2824 dp_left->db_index[line_count_left] |= DB_MARKED;
2825 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2826 line, (size_t)len);
2827 ++line_count_left;
2828 }
2829
2830 if (db_idx < 0) /* left block is new */
2831 {
2832 lnum_left = lnum + 1;
2833 lnum_right = 0;
2834 }
2835 else /* right block is new */
2836 {
2837 lnum_left = 0;
2838 if (in_left)
2839 lnum_right = lnum + 2;
2840 else
2841 lnum_right = lnum + 1;
2842 }
2843 dp_left->db_line_count = line_count_left;
2844 dp_right->db_line_count = line_count_right;
2845
2846 /*
2847 * release the two data blocks
2848 * The new one (hp_new) already has a correct blocknumber.
2849 * The old one (hp, in ml_locked) gets a positive blocknumber if
2850 * we changed it and we are not editing a new file.
2851 */
2852 if (lines_moved || in_left)
2853 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2854 if (!newfile && db_idx >= 0 && in_left)
2855 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2856 mf_put(mfp, hp_new, TRUE, FALSE);
2857
2858 /*
2859 * flush the old data block
2860 * set ml_locked_lineadd to 0, because the updating of the
2861 * pointer blocks is done below
2862 */
2863 lineadd = buf->b_ml.ml_locked_lineadd;
2864 buf->b_ml.ml_locked_lineadd = 0;
2865 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2866
2867 /*
2868 * update pointer blocks for the new data block
2869 */
2870 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2871 --stack_idx)
2872 {
2873 ip = &(buf->b_ml.ml_stack[stack_idx]);
2874 pb_idx = ip->ip_index;
2875 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2876 return FAIL;
2877 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2878 if (pp->pb_id != PTR_ID)
2879 {
2880 EMSG(_("E317: pointer block id wrong 3"));
2881 mf_put(mfp, hp, FALSE, FALSE);
2882 return FAIL;
2883 }
2884 /*
2885 * TODO: If the pointer block is full and we are adding at the end
2886 * try to insert in front of the next block
2887 */
2888 /* block not full, add one entry */
2889 if (pp->pb_count < pp->pb_count_max)
2890 {
2891 if (pb_idx + 1 < (int)pp->pb_count)
2892 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2893 &pp->pb_pointer[pb_idx + 1],
2894 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2895 ++pp->pb_count;
2896 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2897 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2898 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2899 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2900 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2901 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2902
2903 if (lnum_left != 0)
2904 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2905 if (lnum_right != 0)
2906 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2907
2908 mf_put(mfp, hp, TRUE, FALSE);
2909 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2910
2911 if (lineadd)
2912 {
2913 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002914 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 ml_lineadd(buf, lineadd);
2916 /* fix stack itself */
2917 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2918 lineadd;
2919 ++(buf->b_ml.ml_stack_top);
2920 }
2921
2922 /*
2923 * We are finished, break the loop here.
2924 */
2925 break;
2926 }
2927 else /* pointer block full */
2928 {
2929 /*
2930 * split the pointer block
2931 * allocate a new pointer block
2932 * move some of the pointer into the new block
2933 * prepare for updating the parent block
2934 */
2935 for (;;) /* do this twice when splitting block 1 */
2936 {
2937 hp_new = ml_new_ptr(mfp);
2938 if (hp_new == NULL) /* TODO: try to fix tree */
2939 return FAIL;
2940 pp_new = (PTR_BL *)(hp_new->bh_data);
2941
2942 if (hp->bh_bnum != 1)
2943 break;
2944
2945 /*
2946 * if block 1 becomes full the tree is given an extra level
2947 * The pointers from block 1 are moved into the new block.
2948 * block 1 is updated to point to the new block
2949 * then continue to split the new block
2950 */
2951 mch_memmove(pp_new, pp, (size_t)page_size);
2952 pp->pb_count = 1;
2953 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2954 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2955 pp->pb_pointer[0].pe_old_lnum = 1;
2956 pp->pb_pointer[0].pe_page_count = 1;
2957 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2958 hp = hp_new; /* new block is to be split */
2959 pp = pp_new;
2960 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2961 ip->ip_index = 0;
2962 ++stack_idx; /* do block 1 again later */
2963 }
2964 /*
2965 * move the pointers after the current one to the new block
2966 * If there are none, the new entry will be in the new block.
2967 */
2968 total_moved = pp->pb_count - pb_idx - 1;
2969 if (total_moved)
2970 {
2971 mch_memmove(&pp_new->pb_pointer[0],
2972 &pp->pb_pointer[pb_idx + 1],
2973 (size_t)(total_moved) * sizeof(PTR_EN));
2974 pp_new->pb_count = total_moved;
2975 pp->pb_count -= total_moved - 1;
2976 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2977 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2978 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2979 if (lnum_right)
2980 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2981 }
2982 else
2983 {
2984 pp_new->pb_count = 1;
2985 pp_new->pb_pointer[0].pe_bnum = bnum_right;
2986 pp_new->pb_pointer[0].pe_line_count = line_count_right;
2987 pp_new->pb_pointer[0].pe_page_count = page_count_right;
2988 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
2989 }
2990 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2991 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2992 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2993 if (lnum_left)
2994 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2995 lnum_left = 0;
2996 lnum_right = 0;
2997
2998 /*
2999 * recompute line counts
3000 */
3001 line_count_right = 0;
3002 for (i = 0; i < (int)pp_new->pb_count; ++i)
3003 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3004 line_count_left = 0;
3005 for (i = 0; i < (int)pp->pb_count; ++i)
3006 line_count_left += pp->pb_pointer[i].pe_line_count;
3007
3008 bnum_left = hp->bh_bnum;
3009 bnum_right = hp_new->bh_bnum;
3010 page_count_left = 1;
3011 page_count_right = 1;
3012 mf_put(mfp, hp, TRUE, FALSE);
3013 mf_put(mfp, hp_new, TRUE, FALSE);
3014 }
3015 }
3016
3017 /*
3018 * Safety check: fallen out of for loop?
3019 */
3020 if (stack_idx < 0)
3021 {
3022 EMSG(_("E318: Updated too many blocks?"));
3023 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3024 }
3025 }
3026
3027#ifdef FEAT_BYTEOFF
3028 /* The line was inserted below 'lnum' */
3029 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3030#endif
3031#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003032 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003033 {
3034 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003035 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003036 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037 (char_u *)"\n", 1);
3038 }
3039#endif
3040 return OK;
3041}
3042
3043/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003044 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003045 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003046 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 * copied to allocated memory already.
3048 *
3049 * Check: The caller of this function should probably also call
3050 * changed_lines(), unless update_screen(NOT_VALID) is used.
3051 *
3052 * return FAIL for failure, OK otherwise
3053 */
3054 int
3055ml_replace(lnum, line, copy)
3056 linenr_T lnum;
3057 char_u *line;
3058 int copy;
3059{
3060 if (line == NULL) /* just checking... */
3061 return FAIL;
3062
3063 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003064 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 return FAIL;
3066
3067 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3068 return FAIL;
3069#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003070 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 {
3072 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003073 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 }
3075#endif
3076 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3077 ml_flush_line(curbuf); /* flush it */
3078 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3079 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3080 curbuf->b_ml.ml_line_ptr = line;
3081 curbuf->b_ml.ml_line_lnum = lnum;
3082 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3083
3084 return OK;
3085}
3086
3087/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003088 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 *
3090 * Check: The caller of this function should probably also call
3091 * deleted_lines() after this.
3092 *
3093 * return FAIL for failure, OK otherwise
3094 */
3095 int
3096ml_delete(lnum, message)
3097 linenr_T lnum;
3098 int message;
3099{
3100 ml_flush_line(curbuf);
3101 return ml_delete_int(curbuf, lnum, message);
3102}
3103
3104 static int
3105ml_delete_int(buf, lnum, message)
3106 buf_T *buf;
3107 linenr_T lnum;
3108 int message;
3109{
3110 bhdr_T *hp;
3111 memfile_T *mfp;
3112 DATA_BL *dp;
3113 PTR_BL *pp;
3114 infoptr_T *ip;
3115 int count; /* number of entries in block */
3116 int idx;
3117 int stack_idx;
3118 int text_start;
3119 int line_start;
3120 long line_size;
3121 int i;
3122
3123 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3124 return FAIL;
3125
3126 if (lowest_marked && lowest_marked > lnum)
3127 lowest_marked--;
3128
3129/*
3130 * If the file becomes empty the last line is replaced by an empty line.
3131 */
3132 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3133 {
3134 if (message
3135#ifdef FEAT_NETBEANS_INTG
3136 && !netbeansSuppressNoLines
3137#endif
3138 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003139 set_keep_msg((char_u *)_(no_lines_msg), 0);
3140
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
3142 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3143 buf->b_ml.ml_flags |= ML_EMPTY;
3144
3145 return i;
3146 }
3147
3148/*
3149 * find the data block containing the line
3150 * This also fills the stack with the blocks from the root to the data block
3151 * This also releases any locked block.
3152 */
3153 mfp = buf->b_ml.ml_mfp;
3154 if (mfp == NULL)
3155 return FAIL;
3156
3157 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3158 return FAIL;
3159
3160 dp = (DATA_BL *)(hp->bh_data);
3161 /* compute line count before the delete */
3162 count = (long)(buf->b_ml.ml_locked_high)
3163 - (long)(buf->b_ml.ml_locked_low) + 2;
3164 idx = lnum - buf->b_ml.ml_locked_low;
3165
3166 --buf->b_ml.ml_line_count;
3167
3168 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3169 if (idx == 0) /* first line in block, text at the end */
3170 line_size = dp->db_txt_end - line_start;
3171 else
3172 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3173
3174#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003175 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003176 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177#endif
3178
3179/*
3180 * special case: If there is only one line in the data block it becomes empty.
3181 * Then we have to remove the entry, pointing to this data block, from the
3182 * pointer block. If this pointer block also becomes empty, we go up another
3183 * block, and so on, up to the root if necessary.
3184 * The line counts in the pointer blocks have already been adjusted by
3185 * ml_find_line().
3186 */
3187 if (count == 1)
3188 {
3189 mf_free(mfp, hp); /* free the data block */
3190 buf->b_ml.ml_locked = NULL;
3191
Bram Moolenaare60acc12011-05-10 16:41:25 +02003192 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3193 --stack_idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 {
3195 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3196 ip = &(buf->b_ml.ml_stack[stack_idx]);
3197 idx = ip->ip_index;
3198 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3199 return FAIL;
3200 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3201 if (pp->pb_id != PTR_ID)
3202 {
3203 EMSG(_("E317: pointer block id wrong 4"));
3204 mf_put(mfp, hp, FALSE, FALSE);
3205 return FAIL;
3206 }
3207 count = --(pp->pb_count);
3208 if (count == 0) /* the pointer block becomes empty! */
3209 mf_free(mfp, hp);
3210 else
3211 {
3212 if (count != idx) /* move entries after the deleted one */
3213 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3214 (size_t)(count - idx) * sizeof(PTR_EN));
3215 mf_put(mfp, hp, TRUE, FALSE);
3216
3217 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003218 /* fix line count for rest of blocks in the stack */
3219 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220 {
3221 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3222 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003223 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224 }
3225 ++(buf->b_ml.ml_stack_top);
3226
3227 break;
3228 }
3229 }
3230 CHECK(stack_idx < 0, _("deleted block 1?"));
3231 }
3232 else
3233 {
3234 /*
3235 * delete the text by moving the next lines forwards
3236 */
3237 text_start = dp->db_txt_start;
3238 mch_memmove((char *)dp + text_start + line_size,
3239 (char *)dp + text_start, (size_t)(line_start - text_start));
3240
3241 /*
3242 * delete the index by moving the next indexes backwards
3243 * Adjust the indexes for the text movement.
3244 */
3245 for (i = idx; i < count - 1; ++i)
3246 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3247
3248 dp->db_free += line_size + INDEX_SIZE;
3249 dp->db_txt_start += line_size;
3250 --(dp->db_line_count);
3251
3252 /*
3253 * mark the block dirty and make sure it is in the file (for recovery)
3254 */
3255 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3256 }
3257
3258#ifdef FEAT_BYTEOFF
3259 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3260#endif
3261 return OK;
3262}
3263
3264/*
3265 * set the B_MARKED flag for line 'lnum'
3266 */
3267 void
3268ml_setmarked(lnum)
3269 linenr_T lnum;
3270{
3271 bhdr_T *hp;
3272 DATA_BL *dp;
3273 /* invalid line number */
3274 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3275 || curbuf->b_ml.ml_mfp == NULL)
3276 return; /* give error message? */
3277
3278 if (lowest_marked == 0 || lowest_marked > lnum)
3279 lowest_marked = lnum;
3280
3281 /*
3282 * find the data block containing the line
3283 * This also fills the stack with the blocks from the root to the data block
3284 * This also releases any locked block.
3285 */
3286 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3287 return; /* give error message? */
3288
3289 dp = (DATA_BL *)(hp->bh_data);
3290 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3291 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3292}
3293
3294/*
3295 * find the first line with its B_MARKED flag set
3296 */
3297 linenr_T
3298ml_firstmarked()
3299{
3300 bhdr_T *hp;
3301 DATA_BL *dp;
3302 linenr_T lnum;
3303 int i;
3304
3305 if (curbuf->b_ml.ml_mfp == NULL)
3306 return (linenr_T) 0;
3307
3308 /*
3309 * The search starts with lowest_marked line. This is the last line where
3310 * a mark was found, adjusted by inserting/deleting lines.
3311 */
3312 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3313 {
3314 /*
3315 * Find the data block containing the line.
3316 * This also fills the stack with the blocks from the root to the data
3317 * block This also releases any locked block.
3318 */
3319 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3320 return (linenr_T)0; /* give error message? */
3321
3322 dp = (DATA_BL *)(hp->bh_data);
3323
3324 for (i = lnum - curbuf->b_ml.ml_locked_low;
3325 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3326 if ((dp->db_index[i]) & DB_MARKED)
3327 {
3328 (dp->db_index[i]) &= DB_INDEX_MASK;
3329 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3330 lowest_marked = lnum + 1;
3331 return lnum;
3332 }
3333 }
3334
3335 return (linenr_T) 0;
3336}
3337
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338/*
3339 * clear all DB_MARKED flags
3340 */
3341 void
3342ml_clearmarked()
3343{
3344 bhdr_T *hp;
3345 DATA_BL *dp;
3346 linenr_T lnum;
3347 int i;
3348
3349 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3350 return;
3351
3352 /*
3353 * The search starts with line lowest_marked.
3354 */
3355 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3356 {
3357 /*
3358 * Find the data block containing the line.
3359 * This also fills the stack with the blocks from the root to the data
3360 * block and releases any locked block.
3361 */
3362 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3363 return; /* give error message? */
3364
3365 dp = (DATA_BL *)(hp->bh_data);
3366
3367 for (i = lnum - curbuf->b_ml.ml_locked_low;
3368 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3369 if ((dp->db_index[i]) & DB_MARKED)
3370 {
3371 (dp->db_index[i]) &= DB_INDEX_MASK;
3372 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3373 }
3374 }
3375
3376 lowest_marked = 0;
3377 return;
3378}
3379
3380/*
3381 * flush ml_line if necessary
3382 */
3383 static void
3384ml_flush_line(buf)
3385 buf_T *buf;
3386{
3387 bhdr_T *hp;
3388 DATA_BL *dp;
3389 linenr_T lnum;
3390 char_u *new_line;
3391 char_u *old_line;
3392 colnr_T new_len;
3393 int old_len;
3394 int extra;
3395 int idx;
3396 int start;
3397 int count;
3398 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003399 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400
3401 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3402 return; /* nothing to do */
3403
3404 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3405 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003406 /* This code doesn't work recursively, but Netbeans may call back here
3407 * when obtaining the cursor position. */
3408 if (entered)
3409 return;
3410 entered = TRUE;
3411
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412 lnum = buf->b_ml.ml_line_lnum;
3413 new_line = buf->b_ml.ml_line_ptr;
3414
3415 hp = ml_find_line(buf, lnum, ML_FIND);
3416 if (hp == NULL)
3417 EMSGN(_("E320: Cannot find line %ld"), lnum);
3418 else
3419 {
3420 dp = (DATA_BL *)(hp->bh_data);
3421 idx = lnum - buf->b_ml.ml_locked_low;
3422 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3423 old_line = (char_u *)dp + start;
3424 if (idx == 0) /* line is last in block */
3425 old_len = dp->db_txt_end - start;
3426 else /* text of previous line follows */
3427 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3428 new_len = (colnr_T)STRLEN(new_line) + 1;
3429 extra = new_len - old_len; /* negative if lines gets smaller */
3430
3431 /*
3432 * if new line fits in data block, replace directly
3433 */
3434 if ((int)dp->db_free >= extra)
3435 {
3436 /* if the length changes and there are following lines */
3437 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3438 if (extra != 0 && idx < count - 1)
3439 {
3440 /* move text of following lines */
3441 mch_memmove((char *)dp + dp->db_txt_start - extra,
3442 (char *)dp + dp->db_txt_start,
3443 (size_t)(start - dp->db_txt_start));
3444
3445 /* adjust pointers of this and following lines */
3446 for (i = idx + 1; i < count; ++i)
3447 dp->db_index[i] -= extra;
3448 }
3449 dp->db_index[idx] -= extra;
3450
3451 /* adjust free space */
3452 dp->db_free -= extra;
3453 dp->db_txt_start -= extra;
3454
3455 /* copy new line into the data block */
3456 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3457 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3458#ifdef FEAT_BYTEOFF
3459 /* The else case is already covered by the insert and delete */
3460 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3461#endif
3462 }
3463 else
3464 {
3465 /*
3466 * Cannot do it in one data block: Delete and append.
3467 * Append first, because ml_delete_int() cannot delete the
3468 * last line in a buffer, which causes trouble for a buffer
3469 * that has only one line.
3470 * Don't forget to copy the mark!
3471 */
3472 /* How about handling errors??? */
3473 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3474 (dp->db_index[idx] & DB_MARKED));
3475 (void)ml_delete_int(buf, lnum, FALSE);
3476 }
3477 }
3478 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003479
3480 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 }
3482
3483 buf->b_ml.ml_line_lnum = 0;
3484}
3485
3486/*
3487 * create a new, empty, data block
3488 */
3489 static bhdr_T *
3490ml_new_data(mfp, negative, page_count)
3491 memfile_T *mfp;
3492 int negative;
3493 int page_count;
3494{
3495 bhdr_T *hp;
3496 DATA_BL *dp;
3497
3498 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3499 return NULL;
3500
3501 dp = (DATA_BL *)(hp->bh_data);
3502 dp->db_id = DATA_ID;
3503 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3504 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3505 dp->db_line_count = 0;
3506
3507 return hp;
3508}
3509
3510/*
3511 * create a new, empty, pointer block
3512 */
3513 static bhdr_T *
3514ml_new_ptr(mfp)
3515 memfile_T *mfp;
3516{
3517 bhdr_T *hp;
3518 PTR_BL *pp;
3519
3520 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3521 return NULL;
3522
3523 pp = (PTR_BL *)(hp->bh_data);
3524 pp->pb_id = PTR_ID;
3525 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003526 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3527 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003528
3529 return hp;
3530}
3531
3532/*
3533 * lookup line 'lnum' in a memline
3534 *
3535 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3536 * if ML_FLUSH only flush a locked block
3537 * if ML_FIND just find the line
3538 *
3539 * If the block was found it is locked and put in ml_locked.
3540 * The stack is updated to lead to the locked block. The ip_high field in
3541 * the stack is updated to reflect the last line in the block AFTER the
3542 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003543 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 *
3545 * return: NULL for failure, pointer to block header otherwise
3546 */
3547 static bhdr_T *
3548ml_find_line(buf, lnum, action)
3549 buf_T *buf;
3550 linenr_T lnum;
3551 int action;
3552{
3553 DATA_BL *dp;
3554 PTR_BL *pp;
3555 infoptr_T *ip;
3556 bhdr_T *hp;
3557 memfile_T *mfp;
3558 linenr_T t;
3559 blocknr_T bnum, bnum2;
3560 int dirty;
3561 linenr_T low, high;
3562 int top;
3563 int page_count;
3564 int idx;
3565
3566 mfp = buf->b_ml.ml_mfp;
3567
3568 /*
3569 * If there is a locked block check if the wanted line is in it.
3570 * If not, flush and release the locked block.
3571 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3572 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003573 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 */
3575 if (buf->b_ml.ml_locked)
3576 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003577 if (ML_SIMPLE(action)
3578 && buf->b_ml.ml_locked_low <= lnum
3579 && buf->b_ml.ml_locked_high >= lnum
3580 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003582 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 if (action == ML_INSERT)
3584 {
3585 ++(buf->b_ml.ml_locked_lineadd);
3586 ++(buf->b_ml.ml_locked_high);
3587 }
3588 else if (action == ML_DELETE)
3589 {
3590 --(buf->b_ml.ml_locked_lineadd);
3591 --(buf->b_ml.ml_locked_high);
3592 }
3593 return (buf->b_ml.ml_locked);
3594 }
3595
3596 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3597 buf->b_ml.ml_flags & ML_LOCKED_POS);
3598 buf->b_ml.ml_locked = NULL;
3599
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003600 /*
3601 * If lines have been added or deleted in the locked block, need to
3602 * update the line count in pointer blocks.
3603 */
3604 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3606 }
3607
3608 if (action == ML_FLUSH) /* nothing else to do */
3609 return NULL;
3610
3611 bnum = 1; /* start at the root of the tree */
3612 page_count = 1;
3613 low = 1;
3614 high = buf->b_ml.ml_line_count;
3615
3616 if (action == ML_FIND) /* first try stack entries */
3617 {
3618 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3619 {
3620 ip = &(buf->b_ml.ml_stack[top]);
3621 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3622 {
3623 bnum = ip->ip_bnum;
3624 low = ip->ip_low;
3625 high = ip->ip_high;
3626 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3627 break;
3628 }
3629 }
3630 if (top < 0)
3631 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3632 }
3633 else /* ML_DELETE or ML_INSERT */
3634 buf->b_ml.ml_stack_top = 0; /* start at the root */
3635
3636/*
3637 * search downwards in the tree until a data block is found
3638 */
3639 for (;;)
3640 {
3641 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3642 goto error_noblock;
3643
3644 /*
3645 * update high for insert/delete
3646 */
3647 if (action == ML_INSERT)
3648 ++high;
3649 else if (action == ML_DELETE)
3650 --high;
3651
3652 dp = (DATA_BL *)(hp->bh_data);
3653 if (dp->db_id == DATA_ID) /* data block */
3654 {
3655 buf->b_ml.ml_locked = hp;
3656 buf->b_ml.ml_locked_low = low;
3657 buf->b_ml.ml_locked_high = high;
3658 buf->b_ml.ml_locked_lineadd = 0;
3659 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3660 return hp;
3661 }
3662
3663 pp = (PTR_BL *)(dp); /* must be pointer block */
3664 if (pp->pb_id != PTR_ID)
3665 {
3666 EMSG(_("E317: pointer block id wrong"));
3667 goto error_block;
3668 }
3669
3670 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3671 goto error_block;
3672 ip = &(buf->b_ml.ml_stack[top]);
3673 ip->ip_bnum = bnum;
3674 ip->ip_low = low;
3675 ip->ip_high = high;
3676 ip->ip_index = -1; /* index not known yet */
3677
3678 dirty = FALSE;
3679 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3680 {
3681 t = pp->pb_pointer[idx].pe_line_count;
3682 CHECK(t == 0, _("pe_line_count is zero"));
3683 if ((low += t) > lnum)
3684 {
3685 ip->ip_index = idx;
3686 bnum = pp->pb_pointer[idx].pe_bnum;
3687 page_count = pp->pb_pointer[idx].pe_page_count;
3688 high = low - 1;
3689 low -= t;
3690
3691 /*
3692 * a negative block number may have been changed
3693 */
3694 if (bnum < 0)
3695 {
3696 bnum2 = mf_trans_del(mfp, bnum);
3697 if (bnum != bnum2)
3698 {
3699 bnum = bnum2;
3700 pp->pb_pointer[idx].pe_bnum = bnum;
3701 dirty = TRUE;
3702 }
3703 }
3704
3705 break;
3706 }
3707 }
3708 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3709 {
3710 if (lnum > buf->b_ml.ml_line_count)
3711 EMSGN(_("E322: line number out of range: %ld past the end"),
3712 lnum - buf->b_ml.ml_line_count);
3713
3714 else
3715 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3716 goto error_block;
3717 }
3718 if (action == ML_DELETE)
3719 {
3720 pp->pb_pointer[idx].pe_line_count--;
3721 dirty = TRUE;
3722 }
3723 else if (action == ML_INSERT)
3724 {
3725 pp->pb_pointer[idx].pe_line_count++;
3726 dirty = TRUE;
3727 }
3728 mf_put(mfp, hp, dirty, FALSE);
3729 }
3730
3731error_block:
3732 mf_put(mfp, hp, FALSE, FALSE);
3733error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003734 /*
3735 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3736 * the incremented/decremented line counts, because there won't be a line
3737 * inserted/deleted after all.
3738 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 if (action == ML_DELETE)
3740 ml_lineadd(buf, 1);
3741 else if (action == ML_INSERT)
3742 ml_lineadd(buf, -1);
3743 buf->b_ml.ml_stack_top = 0;
3744 return NULL;
3745}
3746
3747/*
3748 * add an entry to the info pointer stack
3749 *
3750 * return -1 for failure, number of the new entry otherwise
3751 */
3752 static int
3753ml_add_stack(buf)
3754 buf_T *buf;
3755{
3756 int top;
3757 infoptr_T *newstack;
3758
3759 top = buf->b_ml.ml_stack_top;
3760
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003761 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 if (top == buf->b_ml.ml_stack_size)
3763 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003764 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765
3766 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3767 (buf->b_ml.ml_stack_size + STACK_INCR));
3768 if (newstack == NULL)
3769 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003770 mch_memmove(newstack, buf->b_ml.ml_stack,
3771 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 vim_free(buf->b_ml.ml_stack);
3773 buf->b_ml.ml_stack = newstack;
3774 buf->b_ml.ml_stack_size += STACK_INCR;
3775 }
3776
3777 buf->b_ml.ml_stack_top++;
3778 return top;
3779}
3780
3781/*
3782 * Update the pointer blocks on the stack for inserted/deleted lines.
3783 * The stack itself is also updated.
3784 *
3785 * When a insert/delete line action fails, the line is not inserted/deleted,
3786 * but the pointer blocks have already been updated. That is fixed here by
3787 * walking through the stack.
3788 *
3789 * Count is the number of lines added, negative if lines have been deleted.
3790 */
3791 static void
3792ml_lineadd(buf, count)
3793 buf_T *buf;
3794 int count;
3795{
3796 int idx;
3797 infoptr_T *ip;
3798 PTR_BL *pp;
3799 memfile_T *mfp = buf->b_ml.ml_mfp;
3800 bhdr_T *hp;
3801
3802 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3803 {
3804 ip = &(buf->b_ml.ml_stack[idx]);
3805 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3806 break;
3807 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3808 if (pp->pb_id != PTR_ID)
3809 {
3810 mf_put(mfp, hp, FALSE, FALSE);
3811 EMSG(_("E317: pointer block id wrong 2"));
3812 break;
3813 }
3814 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3815 ip->ip_high += count;
3816 mf_put(mfp, hp, TRUE, FALSE);
3817 }
3818}
3819
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003820#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003821/*
3822 * Resolve a symlink in the last component of a file name.
3823 * Note that f_resolve() does it for every part of the path, we don't do that
3824 * here.
3825 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3826 * Otherwise returns FAIL.
3827 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003828 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003829resolve_symlink(fname, buf)
3830 char_u *fname;
3831 char_u *buf;
3832{
3833 char_u tmp[MAXPATHL];
3834 int ret;
3835 int depth = 0;
3836
3837 if (fname == NULL)
3838 return FAIL;
3839
3840 /* Put the result so far in tmp[], starting with the original name. */
3841 vim_strncpy(tmp, fname, MAXPATHL - 1);
3842
3843 for (;;)
3844 {
3845 /* Limit symlink depth to 100, catch recursive loops. */
3846 if (++depth == 100)
3847 {
3848 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3849 return FAIL;
3850 }
3851
3852 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3853 if (ret <= 0)
3854 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003855 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003856 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003857 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003858 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003859 * call to vim_FullName(). */
3860 if (depth == 1)
3861 return FAIL;
3862
3863 /* Use the resolved name in tmp[]. */
3864 break;
3865 }
3866
3867 /* There must be some error reading links, use original name. */
3868 return FAIL;
3869 }
3870 buf[ret] = NUL;
3871
3872 /*
3873 * Check whether the symlink is relative or absolute.
3874 * If it's relative, build a new path based on the directory
3875 * portion of the filename (if any) and the path the symlink
3876 * points to.
3877 */
3878 if (mch_isFullName(buf))
3879 STRCPY(tmp, buf);
3880 else
3881 {
3882 char_u *tail;
3883
3884 tail = gettail(tmp);
3885 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3886 return FAIL;
3887 STRCPY(tail, buf);
3888 }
3889 }
3890
3891 /*
3892 * Try to resolve the full name of the file so that the swapfile name will
3893 * be consistent even when opening a relative symlink from different
3894 * working directories.
3895 */
3896 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3897}
3898#endif
3899
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003901 * Make swap file name out of the file name and a directory name.
3902 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003904 char_u *
3905makeswapname(fname, ffname, buf, dir_name)
3906 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003907 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908 buf_T *buf;
3909 char_u *dir_name;
3910{
3911 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003912 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003913#ifdef HAVE_READLINK
3914 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003915#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916
3917#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3918 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003919 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920 { /* Ends with '//', Use Full path */
3921 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003922 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923 {
3924 r = modname(s, (char_u *)".swp", FALSE);
3925 vim_free(s);
3926 }
3927 return r;
3928 }
3929#endif
3930
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003931#ifdef HAVE_READLINK
3932 /* Expand symlink in the file name, so that we put the swap file with the
3933 * actual file instead of with the symlink. */
3934 if (resolve_symlink(fname, fname_buf) == OK)
3935 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003936#endif
3937
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 r = buf_modname(
3939#ifdef SHORT_FNAME
3940 TRUE,
3941#else
3942 (buf->b_p_sn || buf->b_shortname),
3943#endif
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003944 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003945 (char_u *)
Bram Moolenaare60acc12011-05-10 16:41:25 +02003946#if defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 "_swp",
3948#else
3949 ".swp",
3950#endif
3951#ifdef SHORT_FNAME /* always 8.3 file name */
3952 FALSE
3953#else
3954 /* Prepend a '.' to the swap file name for the current directory. */
3955 dir_name[0] == '.' && dir_name[1] == NUL
3956#endif
3957 );
3958 if (r == NULL) /* out of memory */
3959 return NULL;
3960
3961 s = get_file_in_dir(r, dir_name);
3962 vim_free(r);
3963 return s;
3964}
3965
3966/*
3967 * Get file name to use for swap file or backup file.
3968 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3969 * option "dname".
3970 * - If "dname" is ".", return "fname" (swap file in dir of file).
3971 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3972 * relative to dir of file).
3973 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
3974 * dir).
3975 *
3976 * The return value is an allocated string and can be NULL.
3977 */
3978 char_u *
3979get_file_in_dir(fname, dname)
3980 char_u *fname;
3981 char_u *dname; /* don't use "dirname", it is a global for Alpha */
3982{
3983 char_u *t;
3984 char_u *tail;
3985 char_u *retval;
3986 int save_char;
3987
3988 tail = gettail(fname);
3989
3990 if (dname[0] == '.' && dname[1] == NUL)
3991 retval = vim_strsave(fname);
3992 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
3993 {
3994 if (tail == fname) /* no path before file name */
3995 retval = concat_fnames(dname + 2, tail, TRUE);
3996 else
3997 {
3998 save_char = *tail;
3999 *tail = NUL;
4000 t = concat_fnames(fname, dname + 2, TRUE);
4001 *tail = save_char;
4002 if (t == NULL) /* out of memory */
4003 retval = NULL;
4004 else
4005 {
4006 retval = concat_fnames(t, tail, TRUE);
4007 vim_free(t);
4008 }
4009 }
4010 }
4011 else
4012 retval = concat_fnames(dname, tail, TRUE);
4013
4014 return retval;
4015}
4016
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004017static void attention_message __ARGS((buf_T *buf, char_u *fname));
4018
4019/*
4020 * Print the ATTENTION message: info about an existing swap file.
4021 */
4022 static void
4023attention_message(buf, fname)
4024 buf_T *buf; /* buffer being edited */
4025 char_u *fname; /* swap file name */
4026{
4027 struct stat st;
4028 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004029 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004030
4031 ++no_wait_return;
4032 (void)EMSG(_("E325: ATTENTION"));
4033 MSG_PUTS(_("\nFound a swap file by the name \""));
4034 msg_home_replace(fname);
4035 MSG_PUTS("\"\n");
4036 sx = swapfile_info(fname);
4037 MSG_PUTS(_("While opening file \""));
4038 msg_outtrans(buf->b_fname);
4039 MSG_PUTS("\"\n");
4040 if (mch_stat((char *)buf->b_fname, &st) != -1)
4041 {
4042 MSG_PUTS(_(" dated: "));
4043 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004044 p = ctime(&x); /* includes '\n' */
4045 if (p == NULL)
4046 MSG_PUTS("(invalid)\n");
4047 else
4048 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004049 if (sx != 0 && x > sx)
4050 MSG_PUTS(_(" NEWER than swap file!\n"));
4051 }
4052 /* Some of these messages are long to allow translation to
4053 * other languages. */
Bram Moolenaarc41fc712011-02-15 11:57:04 +01004054 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."));
4055 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4056 MSG_PUTS(_("(2) An edit session for this file crashed.\n"));
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004057 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4058 msg_outtrans(buf->b_fname);
4059 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4060 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4061 msg_outtrans(fname);
4062 MSG_PUTS(_("\"\n to avoid this message.\n"));
4063 cmdline_row = msg_row;
4064 --no_wait_return;
4065}
4066
4067#ifdef FEAT_AUTOCMD
4068static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4069
4070/*
4071 * Trigger the SwapExists autocommands.
4072 * Returns a value for equivalent to do_dialog() (see below):
4073 * 0: still need to ask for a choice
4074 * 1: open read-only
4075 * 2: edit anyway
4076 * 3: recover
4077 * 4: delete it
4078 * 5: quit
4079 * 6: abort
4080 */
4081 static int
4082do_swapexists(buf, fname)
4083 buf_T *buf;
4084 char_u *fname;
4085{
4086 set_vim_var_string(VV_SWAPNAME, fname, -1);
4087 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4088
4089 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004090 * edited. Disallow changing directory here. */
4091 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004092 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004093 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004094
4095 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4096
4097 switch (*get_vim_var_str(VV_SWAPCHOICE))
4098 {
4099 case 'o': return 1;
4100 case 'e': return 2;
4101 case 'r': return 3;
4102 case 'd': return 4;
4103 case 'q': return 5;
4104 case 'a': return 6;
4105 }
4106
4107 return 0;
4108}
4109#endif
4110
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111/*
4112 * Find out what name to use for the swap file for buffer 'buf'.
4113 *
4114 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004115 * Returns the name in allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 *
4117 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004118 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004119 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 */
4121 static char_u *
4122findswapname(buf, dirp, old_fname)
4123 buf_T *buf;
4124 char_u **dirp; /* pointer to list of directories */
4125 char_u *old_fname; /* don't give warning for this file name */
4126{
4127 char_u *fname;
4128 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 char_u *dir_name;
4130#ifdef AMIGA
4131 BPTR fh;
4132#endif
4133#ifndef SHORT_FNAME
4134 int r;
4135#endif
4136
4137#if !defined(SHORT_FNAME) \
4138 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
4139# define CREATE_DUMMY_FILE
4140 FILE *dummyfd = NULL;
4141
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004142 /*
4143 * If we start editing a new file, e.g. "test.doc", which resides on an
4144 * MSDOS compatible filesystem, it is possible that the file
4145 * "test.doc.swp" which we create will be exactly the same file. To avoid
4146 * this problem we temporarily create "test.doc". Don't do this when the
4147 * check below for a 8.3 file name is used.
4148 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
4150 && mch_getperm(buf->b_fname) < 0)
4151 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4152#endif
4153
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004154 /*
4155 * Isolate a directory name from *dirp and put it in dir_name.
4156 * First allocate some memory to put the directory name in.
4157 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
4159 if (dir_name != NULL)
4160 (void)copy_option_part(dirp, dir_name, 31000, ",");
4161
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004162 /*
4163 * we try different names until we find one that does not exist yet
4164 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165 if (dir_name == NULL) /* out of memory */
4166 fname = NULL;
4167 else
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004168 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169
4170 for (;;)
4171 {
4172 if (fname == NULL) /* must be out of memory */
4173 break;
4174 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4175 {
4176 vim_free(fname);
4177 fname = NULL;
4178 break;
4179 }
4180#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4181/*
4182 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4183 * file names. If this is the first try and the swap file name does not fit in
4184 * 8.3, detect if this is the case, set shortname and try again.
4185 */
4186 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4187 && !(buf->b_p_sn || buf->b_shortname))
4188 {
4189 char_u *tail;
4190 char_u *fname2;
4191 struct stat s1, s2;
4192 int f1, f2;
4193 int created1 = FALSE, created2 = FALSE;
4194 int same = FALSE;
4195
4196 /*
4197 * Check if swapfile name does not fit in 8.3:
4198 * It either contains two dots, is longer than 8 chars, or starts
4199 * with a dot.
4200 */
4201 tail = gettail(buf->b_fname);
4202 if ( vim_strchr(tail, '.') != NULL
4203 || STRLEN(tail) > (size_t)8
4204 || *gettail(fname) == '.')
4205 {
4206 fname2 = alloc(n + 2);
4207 if (fname2 != NULL)
4208 {
4209 STRCPY(fname2, fname);
4210 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4211 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4212 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4213 */
4214 if (vim_strchr(tail, '.') != NULL)
4215 fname2[n - 1] = 'x';
4216 else if (*gettail(fname) == '.')
4217 {
4218 fname2[n] = 'x';
4219 fname2[n + 1] = NUL;
4220 }
4221 else
4222 fname2[n - 5] += 1;
4223 /*
4224 * may need to create the files to be able to use mch_stat()
4225 */
4226 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4227 if (f1 < 0)
4228 {
4229 f1 = mch_open_rw((char *)fname,
4230 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4231#if defined(OS2)
4232 if (f1 < 0 && errno == ENOENT)
4233 same = TRUE;
4234#endif
4235 created1 = TRUE;
4236 }
4237 if (f1 >= 0)
4238 {
4239 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4240 if (f2 < 0)
4241 {
4242 f2 = mch_open_rw((char *)fname2,
4243 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4244 created2 = TRUE;
4245 }
4246 if (f2 >= 0)
4247 {
4248 /*
4249 * Both files exist now. If mch_stat() returns the
4250 * same device and inode they are the same file.
4251 */
4252 if (mch_fstat(f1, &s1) != -1
4253 && mch_fstat(f2, &s2) != -1
4254 && s1.st_dev == s2.st_dev
4255 && s1.st_ino == s2.st_ino)
4256 same = TRUE;
4257 close(f2);
4258 if (created2)
4259 mch_remove(fname2);
4260 }
4261 close(f1);
4262 if (created1)
4263 mch_remove(fname);
4264 }
4265 vim_free(fname2);
4266 if (same)
4267 {
4268 buf->b_shortname = TRUE;
4269 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004270 fname = makeswapname(buf->b_fname, buf->b_ffname,
4271 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 continue; /* try again with b_shortname set */
4273 }
4274 }
4275 }
4276 }
4277#endif
4278 /*
4279 * check if the swapfile already exists
4280 */
4281 if (mch_getperm(fname) < 0) /* it does not exist */
4282 {
4283#ifdef HAVE_LSTAT
4284 struct stat sb;
4285
4286 /*
4287 * Extra security check: When a swap file is a symbolic link, this
4288 * is most likely a symlink attack.
4289 */
4290 if (mch_lstat((char *)fname, &sb) < 0)
4291#else
4292# ifdef AMIGA
4293 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4294 /*
4295 * on the Amiga mch_getperm() will return -1 when the file exists
4296 * but is being used by another program. This happens if you edit
4297 * a file twice.
4298 */
4299 if (fh != (BPTR)NULL) /* can open file, OK */
4300 {
4301 Close(fh);
4302 mch_remove(fname);
4303 break;
4304 }
4305 if (IoErr() != ERROR_OBJECT_IN_USE
4306 && IoErr() != ERROR_OBJECT_EXISTS)
4307# endif
4308#endif
4309 break;
4310 }
4311
4312 /*
4313 * A file name equal to old_fname is OK to use.
4314 */
4315 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4316 break;
4317
4318 /*
4319 * get here when file already exists
4320 */
4321 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4322 {
4323#ifndef SHORT_FNAME
4324 /*
4325 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4326 * and file.doc are the same file. To guess if this problem is
4327 * present try if file.doc.swx exists. If it does, we set
4328 * buf->b_shortname and try file_doc.swp (dots replaced by
4329 * underscores for this file), and try again. If it doesn't we
4330 * assume that "file.doc.swp" already exists.
4331 */
4332 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4333 {
4334 fname[n - 1] = 'x';
4335 r = mch_getperm(fname); /* try "file.swx" */
4336 fname[n - 1] = 'p';
4337 if (r >= 0) /* "file.swx" seems to exist */
4338 {
4339 buf->b_shortname = TRUE;
4340 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004341 fname = makeswapname(buf->b_fname, buf->b_ffname,
4342 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 continue; /* try again with '.' replaced with '_' */
4344 }
4345 }
4346#endif
4347 /*
4348 * If we get here the ".swp" file really exists.
4349 * Give an error message, unless recovering, no file name, we are
4350 * viewing a help file or when the path of the file is different
4351 * (happens when all .swp files are in one directory).
4352 */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004353 if (!recoverymode && buf->b_fname != NULL
4354 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 {
4356 int fd;
4357 struct block0 b0;
4358 int differ = FALSE;
4359
4360 /*
4361 * Try to read block 0 from the swap file to get the original
4362 * file name (and inode number).
4363 */
4364 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4365 if (fd >= 0)
4366 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004367 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 {
4369 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004370 * If the swapfile has the same directory as the
4371 * buffer don't compare the directory names, they can
4372 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004373 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004374 if (b0.b0_flags & B0_SAME_DIR)
4375 {
4376 if (fnamecmp(gettail(buf->b_ffname),
4377 gettail(b0.b0_fname)) != 0
4378 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004379 {
4380#ifdef CHECK_INODE
4381 /* Symlinks may point to the same file even
4382 * when the name differs, need to check the
4383 * inode too. */
4384 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4385 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4386 char_to_long(b0.b0_ino)))
4387#endif
4388 differ = TRUE;
4389 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004390 }
4391 else
4392 {
4393 /*
4394 * The name in the swap file may be
4395 * "~user/path/file". Expand it first.
4396 */
4397 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004399 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004400 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004401 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004402#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004403 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4404 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004406 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004407 }
4408 close(fd);
4409 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410
4411 /* give the ATTENTION message when there is an old swap file
4412 * for the current file, and the buffer was not recovered. */
4413 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4414 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4415 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004416#if defined(HAS_SWAP_EXISTS_ACTION)
4417 int choice = 0;
4418#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004419#ifdef CREATE_DUMMY_FILE
4420 int did_use_dummy = FALSE;
4421
4422 /* Avoid getting a warning for the file being created
4423 * outside of Vim, it was created at the start of this
4424 * function. Delete the file now, because Vim might exit
4425 * here if the window is closed. */
4426 if (dummyfd != NULL)
4427 {
4428 fclose(dummyfd);
4429 dummyfd = NULL;
4430 mch_remove(buf->b_fname);
4431 did_use_dummy = TRUE;
4432 }
4433#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434
4435#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4436 process_still_running = FALSE;
4437#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004438#ifdef FEAT_AUTOCMD
4439 /*
4440 * If there is an SwapExists autocommand and we can handle
4441 * the response, trigger it. It may return 0 to ask the
4442 * user anyway.
4443 */
4444 if (swap_exists_action != SEA_NONE
4445 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4446 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004448 if (choice == 0)
4449#endif
4450 {
4451#ifdef FEAT_GUI
4452 /* If we are supposed to start the GUI but it wasn't
4453 * completely started yet, start it now. This makes
4454 * the messages displayed in the Vim window when
4455 * loading a session from the .gvimrc file. */
4456 if (gui.starting && !gui.in_use)
4457 gui_start();
4458#endif
4459 /* Show info about the existing swap file. */
4460 attention_message(buf, fname);
4461
4462 /* We don't want a 'q' typed at the more-prompt
4463 * interrupt loading a file. */
4464 got_int = FALSE;
4465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466
4467#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004468 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469 {
4470 char_u *name;
4471
4472 name = alloc((unsigned)(STRLEN(fname)
4473 + STRLEN(_("Swap file \""))
4474 + STRLEN(_("\" already exists!")) + 5));
4475 if (name != NULL)
4476 {
4477 STRCPY(name, _("Swap file \""));
4478 home_replace(NULL, fname, name + STRLEN(name),
4479 1000, TRUE);
4480 STRCAT(name, _("\" already exists!"));
4481 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004482 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483 (char_u *)_("VIM - ATTENTION"),
4484 name == NULL
4485 ? (char_u *)_("Swap file already exists!")
4486 : name,
4487# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4488 process_still_running
4489 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4490# endif
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004491 (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 +00004492
4493# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4494 if (process_still_running && choice >= 4)
4495 choice++; /* Skip missing "Delete it" button */
4496# endif
4497 vim_free(name);
4498
4499 /* pretend screen didn't scroll, need redraw anyway */
4500 msg_scrolled = 0;
4501 redraw_all_later(NOT_VALID);
4502 }
4503#endif
4504
4505#if defined(HAS_SWAP_EXISTS_ACTION)
4506 if (choice > 0)
4507 {
4508 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509 {
4510 case 1:
4511 buf->b_p_ro = TRUE;
4512 break;
4513 case 2:
4514 break;
4515 case 3:
4516 swap_exists_action = SEA_RECOVER;
4517 break;
4518 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004519 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 break;
4521 case 5:
4522 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 break;
4524 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004525 swap_exists_action = SEA_QUIT;
4526 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 break;
4528 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529
4530 /* If the file was deleted this fname can be used. */
4531 if (mch_getperm(fname) < 0)
4532 break;
4533 }
4534 else
4535#endif
4536 {
4537 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004538 if (msg_silent == 0)
4539 /* call wait_return() later */
4540 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 }
4542
4543#ifdef CREATE_DUMMY_FILE
4544 /* Going to try another name, need the dummy file again. */
4545 if (did_use_dummy)
4546 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4547#endif
4548 }
4549 }
4550 }
4551
4552 /*
4553 * Change the ".swp" extension to find another file that can be used.
4554 * First decrement the last char: ".swo", ".swn", etc.
4555 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004556 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 */
4558 if (fname[n - 1] == 'a') /* ".s?a" */
4559 {
4560 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4561 {
4562 EMSG(_("E326: Too many swap files found"));
4563 vim_free(fname);
4564 fname = NULL;
4565 break;
4566 }
4567 --fname[n - 2]; /* ".svz", ".suz", etc. */
4568 fname[n - 1] = 'z' + 1;
4569 }
4570 --fname[n - 1]; /* ".swo", ".swn", etc. */
4571 }
4572
4573 vim_free(dir_name);
4574#ifdef CREATE_DUMMY_FILE
4575 if (dummyfd != NULL) /* file has been created temporarily */
4576 {
4577 fclose(dummyfd);
4578 mch_remove(buf->b_fname);
4579 }
4580#endif
4581 return fname;
4582}
4583
4584 static int
4585b0_magic_wrong(b0p)
4586 ZERO_BL *b0p;
4587{
4588 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4589 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4590 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4591 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4592}
4593
4594#ifdef CHECK_INODE
4595/*
4596 * Compare current file name with file name from swap file.
4597 * Try to use inode numbers when possible.
4598 * Return non-zero when files are different.
4599 *
4600 * When comparing file names a few things have to be taken into consideration:
4601 * - When working over a network the full path of a file depends on the host.
4602 * We check the inode number if possible. It is not 100% reliable though,
4603 * because the device number cannot be used over a network.
4604 * - When a file does not exist yet (editing a new file) there is no inode
4605 * number.
4606 * - The file name in a swap file may not be valid on the current host. The
4607 * "~user" form is used whenever possible to avoid this.
4608 *
4609 * This is getting complicated, let's make a table:
4610 *
4611 * ino_c ino_s fname_c fname_s differ =
4612 *
4613 * both files exist -> compare inode numbers:
4614 * != 0 != 0 X X ino_c != ino_s
4615 *
4616 * inode number(s) unknown, file names available -> compare file names
4617 * == 0 X OK OK fname_c != fname_s
4618 * X == 0 OK OK fname_c != fname_s
4619 *
4620 * current file doesn't exist, file for swap file exist, file name(s) not
4621 * available -> probably different
4622 * == 0 != 0 FAIL X TRUE
4623 * == 0 != 0 X FAIL TRUE
4624 *
4625 * current file exists, inode for swap unknown, file name(s) not
4626 * available -> probably different
4627 * != 0 == 0 FAIL X TRUE
4628 * != 0 == 0 X FAIL TRUE
4629 *
4630 * current file doesn't exist, inode for swap unknown, one file name not
4631 * available -> probably different
4632 * == 0 == 0 FAIL OK TRUE
4633 * == 0 == 0 OK FAIL TRUE
4634 *
4635 * current file doesn't exist, inode for swap unknown, both file names not
4636 * available -> probably same file
4637 * == 0 == 0 FAIL FAIL FALSE
4638 *
4639 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4640 * can't be changed without making the block 0 incompatible with 32 bit
4641 * versions.
4642 */
4643
4644 static int
4645fnamecmp_ino(fname_c, fname_s, ino_block0)
4646 char_u *fname_c; /* current file name */
4647 char_u *fname_s; /* file name from swap file */
4648 long ino_block0;
4649{
4650 struct stat st;
4651 ino_t ino_c = 0; /* ino of current file */
4652 ino_t ino_s; /* ino of file from swap file */
4653 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4654 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4655 int retval_c; /* flag: buf_c valid */
4656 int retval_s; /* flag: buf_s valid */
4657
4658 if (mch_stat((char *)fname_c, &st) == 0)
4659 ino_c = (ino_t)st.st_ino;
4660
4661 /*
4662 * First we try to get the inode from the file name, because the inode in
4663 * the swap file may be outdated. If that fails (e.g. this path is not
4664 * valid on this machine), use the inode from block 0.
4665 */
4666 if (mch_stat((char *)fname_s, &st) == 0)
4667 ino_s = (ino_t)st.st_ino;
4668 else
4669 ino_s = (ino_t)ino_block0;
4670
4671 if (ino_c && ino_s)
4672 return (ino_c != ino_s);
4673
4674 /*
4675 * One of the inode numbers is unknown, try a forced vim_FullName() and
4676 * compare the file names.
4677 */
4678 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4679 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4680 if (retval_c == OK && retval_s == OK)
4681 return (STRCMP(buf_c, buf_s) != 0);
4682
4683 /*
4684 * Can't compare inodes or file names, guess that the files are different,
4685 * unless both appear not to exist at all.
4686 */
4687 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4688 return FALSE;
4689 return TRUE;
4690}
4691#endif /* CHECK_INODE */
4692
4693/*
4694 * Move a long integer into a four byte character array.
4695 * Used for machine independency in block zero.
4696 */
4697 static void
4698long_to_char(n, s)
4699 long n;
4700 char_u *s;
4701{
4702 s[0] = (char_u)(n & 0xff);
4703 n = (unsigned)n >> 8;
4704 s[1] = (char_u)(n & 0xff);
4705 n = (unsigned)n >> 8;
4706 s[2] = (char_u)(n & 0xff);
4707 n = (unsigned)n >> 8;
4708 s[3] = (char_u)(n & 0xff);
4709}
4710
4711 static long
4712char_to_long(s)
4713 char_u *s;
4714{
4715 long retval;
4716
4717 retval = s[3];
4718 retval <<= 8;
4719 retval |= s[2];
4720 retval <<= 8;
4721 retval |= s[1];
4722 retval <<= 8;
4723 retval |= s[0];
4724
4725 return retval;
4726}
4727
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004728/*
4729 * Set the flags in the first block of the swap file:
4730 * - file is modified or not: buf->b_changed
4731 * - 'fileformat'
4732 * - 'fileencoding'
4733 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004735ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004736 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737{
4738 bhdr_T *hp;
4739 ZERO_BL *b0p;
4740
4741 if (!buf->b_ml.ml_mfp)
4742 return;
4743 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4744 {
4745 if (hp->bh_bnum == 0)
4746 {
4747 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004748 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4749 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4750 | (get_fileformat(buf) + 1);
4751#ifdef FEAT_MBYTE
4752 add_b0_fenc(b0p, buf);
4753#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 hp->bh_flags |= BH_DIRTY;
4755 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4756 break;
4757 }
4758 }
4759}
4760
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004761#if defined(FEAT_CRYPT) || defined(PROTO)
4762/*
4763 * If "data" points to a data block encrypt the text in it and return a copy
4764 * in allocated memory. Return NULL when out of memory.
4765 * Otherwise return "data".
4766 */
4767 char_u *
4768ml_encrypt_data(mfp, data, offset, size)
4769 memfile_T *mfp;
4770 char_u *data;
4771 off_t offset;
4772 unsigned size;
4773{
4774 DATA_BL *dp = (DATA_BL *)data;
4775 char_u *head_end;
4776 char_u *text_start;
4777 char_u *new_data;
4778 int text_len;
4779
4780 if (dp->db_id != DATA_ID)
4781 return data;
4782
4783 new_data = (char_u *)alloc(size);
4784 if (new_data == NULL)
4785 return NULL;
4786 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4787 text_start = (char_u *)dp + dp->db_txt_start;
4788 text_len = size - dp->db_txt_start;
4789
4790 /* Copy the header and the text. */
4791 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4792
4793 /* Encrypt the text. */
4794 crypt_push_state();
4795 ml_crypt_prepare(mfp, offset, FALSE);
4796 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4797 crypt_pop_state();
4798
4799 /* Clear the gap. */
4800 if (head_end < text_start)
4801 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4802
4803 return new_data;
4804}
4805
4806/*
4807 * Decrypt the text in "data" if it points to a data block.
4808 */
4809 void
4810ml_decrypt_data(mfp, data, offset, size)
4811 memfile_T *mfp;
4812 char_u *data;
4813 off_t offset;
4814 unsigned size;
4815{
4816 DATA_BL *dp = (DATA_BL *)data;
4817 char_u *head_end;
4818 char_u *text_start;
4819 int text_len;
4820
4821 if (dp->db_id == DATA_ID)
4822 {
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 = dp->db_txt_end - dp->db_txt_start;
4826
4827 if (head_end > text_start || dp->db_txt_start > size
4828 || dp->db_txt_end > size)
4829 return; /* data was messed up */
4830
4831 /* Decrypt the text in place. */
4832 crypt_push_state();
4833 ml_crypt_prepare(mfp, offset, TRUE);
4834 crypt_decode(text_start, text_len);
4835 crypt_pop_state();
4836 }
4837}
4838
4839/*
4840 * Prepare for encryption/decryption, using the key, seed and offset.
4841 */
4842 static void
4843ml_crypt_prepare(mfp, offset, reading)
4844 memfile_T *mfp;
4845 off_t offset;
4846 int reading;
4847{
4848 buf_T *buf = mfp->mf_buffer;
4849 char_u salt[50];
4850 int method;
4851 char_u *key;
4852 char_u *seed;
4853
4854 if (reading && mfp->mf_old_key != NULL)
4855 {
4856 /* Reading back blocks with the previous key/method/seed. */
4857 method = mfp->mf_old_cm;
4858 key = mfp->mf_old_key;
4859 seed = mfp->mf_old_seed;
4860 }
4861 else
4862 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02004863 method = get_crypt_method(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004864 key = buf->b_p_key;
4865 seed = mfp->mf_seed;
4866 }
4867
4868 use_crypt_method = method; /* select pkzip or blowfish */
4869 if (method == 0)
4870 {
4871 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4872 crypt_init_keys(salt);
4873 }
4874 else
4875 {
4876 /* Using blowfish, add salt and seed. We use the byte offset of the
4877 * block for the salt. */
4878 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004879 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004880 bf_ofb_init(seed, MF_SEED_LEN);
4881 }
4882}
4883
4884#endif
4885
4886
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887#if defined(FEAT_BYTEOFF) || defined(PROTO)
4888
4889#define MLCS_MAXL 800 /* max no of lines in chunk */
4890#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4891
4892/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004893 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4895 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4896 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4897 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4898 */
4899 static void
4900ml_updatechunk(buf, line, len, updtype)
4901 buf_T *buf;
4902 linenr_T line;
4903 long len;
4904 int updtype;
4905{
4906 static buf_T *ml_upd_lastbuf = NULL;
4907 static linenr_T ml_upd_lastline;
4908 static linenr_T ml_upd_lastcurline;
4909 static int ml_upd_lastcurix;
4910
4911 linenr_T curline = ml_upd_lastcurline;
4912 int curix = ml_upd_lastcurix;
4913 long size;
4914 chunksize_T *curchnk;
4915 int rest;
4916 bhdr_T *hp;
4917 DATA_BL *dp;
4918
4919 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4920 return;
4921 if (buf->b_ml.ml_chunksize == NULL)
4922 {
4923 buf->b_ml.ml_chunksize = (chunksize_T *)
4924 alloc((unsigned)sizeof(chunksize_T) * 100);
4925 if (buf->b_ml.ml_chunksize == NULL)
4926 {
4927 buf->b_ml.ml_usedchunks = -1;
4928 return;
4929 }
4930 buf->b_ml.ml_numchunks = 100;
4931 buf->b_ml.ml_usedchunks = 1;
4932 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4933 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4934 }
4935
4936 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4937 {
4938 /*
4939 * First line in empty buffer from ml_flush_line() -- reset
4940 */
4941 buf->b_ml.ml_usedchunks = 1;
4942 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4943 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4944 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4945 return;
4946 }
4947
4948 /*
4949 * Find chunk that our line belongs to, curline will be at start of the
4950 * chunk.
4951 */
4952 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4953 || updtype != ML_CHNK_ADDLINE)
4954 {
4955 for (curline = 1, curix = 0;
4956 curix < buf->b_ml.ml_usedchunks - 1
4957 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4958 curix++)
4959 {
4960 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4961 }
4962 }
4963 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
4964 && curix < buf->b_ml.ml_usedchunks - 1)
4965 {
4966 /* Adjust cached curix & curline */
4967 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4968 curix++;
4969 }
4970 curchnk = buf->b_ml.ml_chunksize + curix;
4971
4972 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00004973 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 curchnk->mlcs_totalsize += len;
4975 if (updtype == ML_CHNK_ADDLINE)
4976 {
4977 curchnk->mlcs_numlines++;
4978
4979 /* May resize here so we don't have to do it in both cases below */
4980 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
4981 {
4982 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
4983 buf->b_ml.ml_chunksize = (chunksize_T *)
4984 vim_realloc(buf->b_ml.ml_chunksize,
4985 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
4986 if (buf->b_ml.ml_chunksize == NULL)
4987 {
4988 /* Hmmmm, Give up on offset for this buffer */
4989 buf->b_ml.ml_usedchunks = -1;
4990 return;
4991 }
4992 }
4993
4994 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
4995 {
4996 int count; /* number of entries in block */
4997 int idx;
4998 int text_end;
4999 int linecnt;
5000
5001 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5002 buf->b_ml.ml_chunksize + curix,
5003 (buf->b_ml.ml_usedchunks - curix) *
5004 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005005 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 size = 0;
5007 linecnt = 0;
5008 while (curline < buf->b_ml.ml_line_count
5009 && linecnt < MLCS_MINL)
5010 {
5011 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5012 {
5013 buf->b_ml.ml_usedchunks = -1;
5014 return;
5015 }
5016 dp = (DATA_BL *)(hp->bh_data);
5017 count = (long)(buf->b_ml.ml_locked_high) -
5018 (long)(buf->b_ml.ml_locked_low) + 1;
5019 idx = curline - buf->b_ml.ml_locked_low;
5020 curline = buf->b_ml.ml_locked_high + 1;
5021 if (idx == 0)/* first line in block, text at the end */
5022 text_end = dp->db_txt_end;
5023 else
5024 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5025 /* Compute index of last line to use in this MEMLINE */
5026 rest = count - idx;
5027 if (linecnt + rest > MLCS_MINL)
5028 {
5029 idx += MLCS_MINL - linecnt - 1;
5030 linecnt = MLCS_MINL;
5031 }
5032 else
5033 {
5034 idx = count - 1;
5035 linecnt += rest;
5036 }
5037 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5038 }
5039 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5040 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5041 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5042 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5043 buf->b_ml.ml_usedchunks++;
5044 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5045 return;
5046 }
5047 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5048 && curix == buf->b_ml.ml_usedchunks - 1
5049 && buf->b_ml.ml_line_count - line <= 1)
5050 {
5051 /*
5052 * We are in the last chunk and it is cheap to crate a new one
5053 * after this. Do it now to avoid the loop above later on
5054 */
5055 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5056 buf->b_ml.ml_usedchunks++;
5057 if (line == buf->b_ml.ml_line_count)
5058 {
5059 curchnk->mlcs_numlines = 0;
5060 curchnk->mlcs_totalsize = 0;
5061 }
5062 else
5063 {
5064 /*
5065 * Line is just prior to last, move count for last
5066 * This is the common case when loading a new file
5067 */
5068 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5069 if (hp == NULL)
5070 {
5071 buf->b_ml.ml_usedchunks = -1;
5072 return;
5073 }
5074 dp = (DATA_BL *)(hp->bh_data);
5075 if (dp->db_line_count == 1)
5076 rest = dp->db_txt_end - dp->db_txt_start;
5077 else
5078 rest =
5079 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5080 - dp->db_txt_start;
5081 curchnk->mlcs_totalsize = rest;
5082 curchnk->mlcs_numlines = 1;
5083 curchnk[-1].mlcs_totalsize -= rest;
5084 curchnk[-1].mlcs_numlines -= 1;
5085 }
5086 }
5087 }
5088 else if (updtype == ML_CHNK_DELLINE)
5089 {
5090 curchnk->mlcs_numlines--;
5091 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5092 if (curix < (buf->b_ml.ml_usedchunks - 1)
5093 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5094 <= MLCS_MINL)
5095 {
5096 curix++;
5097 curchnk = buf->b_ml.ml_chunksize + curix;
5098 }
5099 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5100 {
5101 buf->b_ml.ml_usedchunks--;
5102 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5103 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5104 return;
5105 }
5106 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5107 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5108 > MLCS_MINL))
5109 {
5110 return;
5111 }
5112
5113 /* Collapse chunks */
5114 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5115 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5116 buf->b_ml.ml_usedchunks--;
5117 if (curix < buf->b_ml.ml_usedchunks)
5118 {
5119 mch_memmove(buf->b_ml.ml_chunksize + curix,
5120 buf->b_ml.ml_chunksize + curix + 1,
5121 (buf->b_ml.ml_usedchunks - curix) *
5122 sizeof(chunksize_T));
5123 }
5124 return;
5125 }
5126 ml_upd_lastbuf = buf;
5127 ml_upd_lastline = line;
5128 ml_upd_lastcurline = curline;
5129 ml_upd_lastcurix = curix;
5130}
5131
5132/*
5133 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005134 * Find line with offset if "lnum" is 0; return remaining offset in offp
5135 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136 * return -1 if information is not available
5137 */
5138 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005139ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005141 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005142 long *offp;
5143{
5144 linenr_T curline;
5145 int curix;
5146 long size;
5147 bhdr_T *hp;
5148 DATA_BL *dp;
5149 int count; /* number of entries in block */
5150 int idx;
5151 int start_idx;
5152 int text_end;
5153 long offset;
5154 int len;
5155 int ffdos = (get_fileformat(buf) == EOL_DOS);
5156 int extra = 0;
5157
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005158 /* take care of cached line first */
5159 ml_flush_line(curbuf);
5160
Bram Moolenaar071d4272004-06-13 20:20:40 +00005161 if (buf->b_ml.ml_usedchunks == -1
5162 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005163 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164 return -1;
5165
5166 if (offp == NULL)
5167 offset = 0;
5168 else
5169 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005170 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5172 /*
5173 * Find the last chunk before the one containing our line. Last chunk is
5174 * special because it will never qualify
5175 */
5176 curline = 1;
5177 curix = size = 0;
5178 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005179 && ((lnum != 0
5180 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181 || (offset != 0
5182 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5183 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5184 {
5185 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5186 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5187 if (offset && ffdos)
5188 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5189 curix++;
5190 }
5191
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005192 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 {
5194 if (curline > buf->b_ml.ml_line_count
5195 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5196 return -1;
5197 dp = (DATA_BL *)(hp->bh_data);
5198 count = (long)(buf->b_ml.ml_locked_high) -
5199 (long)(buf->b_ml.ml_locked_low) + 1;
5200 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5201 if (idx == 0)/* first line in block, text at the end */
5202 text_end = dp->db_txt_end;
5203 else
5204 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5205 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005206 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005208 if (curline + (count - idx) >= lnum)
5209 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 else
5211 idx = count - 1;
5212 }
5213 else
5214 {
5215 extra = 0;
5216 while (offset >= size
5217 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5218 + ffdos)
5219 {
5220 if (ffdos)
5221 size++;
5222 if (idx == count - 1)
5223 {
5224 extra = 1;
5225 break;
5226 }
5227 idx++;
5228 }
5229 }
5230 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5231 size += len;
5232 if (offset != 0 && size >= offset)
5233 {
5234 if (size + ffdos == offset)
5235 *offp = 0;
5236 else if (idx == start_idx)
5237 *offp = offset - size + len;
5238 else
5239 *offp = offset - size + len
5240 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5241 curline += idx - start_idx + extra;
5242 if (curline > buf->b_ml.ml_line_count)
5243 return -1; /* exactly one byte beyond the end */
5244 return curline;
5245 }
5246 curline = buf->b_ml.ml_locked_high + 1;
5247 }
5248
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005249 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005250 {
5251 /* Count extra CR characters. */
5252 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005253 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005254
5255 /* Don't count the last line break if 'bin' and 'noeol'. */
5256 if (buf->b_p_bin && !buf->b_p_eol)
5257 size -= ffdos + 1;
5258 }
5259
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260 return size;
5261}
5262
5263/*
5264 * Goto byte in buffer with offset 'cnt'.
5265 */
5266 void
5267goto_byte(cnt)
5268 long cnt;
5269{
5270 long boff = cnt;
5271 linenr_T lnum;
5272
5273 ml_flush_line(curbuf); /* cached line may be dirty */
5274 setpcmark();
5275 if (boff)
5276 --boff;
5277 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5278 if (lnum < 1) /* past the end */
5279 {
5280 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5281 curwin->w_curswant = MAXCOL;
5282 coladvance((colnr_T)MAXCOL);
5283 }
5284 else
5285 {
5286 curwin->w_cursor.lnum = lnum;
5287 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005288# ifdef FEAT_VIRTUALEDIT
5289 curwin->w_cursor.coladd = 0;
5290# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 curwin->w_set_curswant = TRUE;
5292 }
5293 check_cursor();
5294
5295# ifdef FEAT_MBYTE
5296 /* Make sure the cursor is on the first byte of a multi-byte char. */
5297 if (has_mbyte)
5298 mb_adjust_cursor();
5299# endif
5300}
5301#endif