blob: 8201a01206f4cc722472f57d589f5887d4a73e69 [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;
Bram Moolenaar986a0032011-06-13 01:07:27 +02001510 idx = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 continue;
1512 }
1513 }
1514 else /* not a pointer block */
1515 {
1516 dp = (DATA_BL *)(hp->bh_data);
1517 if (dp->db_id != DATA_ID) /* block id wrong */
1518 {
1519 if (bnum == 1)
1520 {
1521 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1522 mfp->mf_fname);
1523 goto theend;
1524 }
1525 ++error;
1526 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1527 (colnr_T)0, TRUE);
1528 }
1529 else
1530 {
1531 /*
1532 * it is a data block
1533 * Append all the lines in this block
1534 */
1535 has_error = FALSE;
1536 /*
1537 * check length of block
1538 * if wrong, use length in pointer block
1539 */
1540 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1541 {
1542 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1543 (colnr_T)0, TRUE);
1544 ++error;
1545 has_error = TRUE;
1546 dp->db_txt_end = page_count * mfp->mf_page_size;
1547 }
1548
1549 /* make sure there is a NUL at the end of the block */
1550 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1551
1552 /*
1553 * check number of lines in block
1554 * if wrong, use count in data block
1555 */
1556 if (line_count != dp->db_line_count)
1557 {
1558 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1559 (colnr_T)0, TRUE);
1560 ++error;
1561 has_error = TRUE;
1562 }
1563
1564 for (i = 0; i < dp->db_line_count; ++i)
1565 {
1566 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001567 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 || txt_start >= (int)dp->db_txt_end)
1569 {
1570 p = (char_u *)"???";
1571 ++error;
1572 }
1573 else
1574 p = (char_u *)dp + txt_start;
1575 ml_append(lnum++, p, (colnr_T)0, TRUE);
1576 }
1577 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001578 ml_append(lnum++, (char_u *)_("???END"),
1579 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 }
1581 }
1582 }
1583
1584 if (buf->b_ml.ml_stack_top == 0) /* finished */
1585 break;
1586
1587 /*
1588 * go one block up in the tree
1589 */
1590 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1591 bnum = ip->ip_bnum;
1592 idx = ip->ip_index + 1; /* go to next index */
1593 page_count = 1;
1594 }
1595
1596 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001597 * Compare the buffer contents with the original file. When they differ
1598 * set the 'modified' flag.
1599 * Lines 1 - lnum are the new contents.
1600 * Lines lnum + 1 to ml_line_count are the original contents.
1601 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001603 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1604 {
1605 /* Recovering an empty file results in two lines and the first line is
1606 * empty. Don't set the modified flag then. */
1607 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1608 {
1609 changed_int();
1610 ++curbuf->b_changedtick;
1611 }
1612 }
1613 else
1614 {
1615 for (idx = 1; idx <= lnum; ++idx)
1616 {
1617 /* Need to copy one line, fetching the other one may flush it. */
1618 p = vim_strsave(ml_get(idx));
1619 i = STRCMP(p, ml_get(idx + lnum));
1620 vim_free(p);
1621 if (i != 0)
1622 {
1623 changed_int();
1624 ++curbuf->b_changedtick;
1625 break;
1626 }
1627 }
1628 }
1629
1630 /*
1631 * Delete the lines from the original file and the dummy line from the
1632 * empty buffer. These will now be after the last line in the buffer.
1633 */
1634 while (curbuf->b_ml.ml_line_count > lnum
1635 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1636 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 curbuf->b_flags |= BF_RECOVERED;
1638
1639 recoverymode = FALSE;
1640 if (got_int)
1641 EMSG(_("E311: Recovery Interrupted"));
1642 else if (error)
1643 {
1644 ++no_wait_return;
1645 MSG(">>>>>>>>>>>>>");
1646 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1647 --no_wait_return;
1648 MSG(_("See \":help E312\" for more information."));
1649 MSG(">>>>>>>>>>>>>");
1650 }
1651 else
1652 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001653 if (curbuf->b_changed)
1654 {
1655 MSG(_("Recovery completed. You should check if everything is OK."));
1656 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1657 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1658 }
1659 else
1660 MSG(_("Recovery completed. Buffer contents equals file contents."));
1661 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662 cmdline_row = msg_row;
1663 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001664#ifdef FEAT_CRYPT
1665 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1666 {
1667 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1668 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1669 }
1670#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 redraw_curbuf_later(NOT_VALID);
1672
1673theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001674 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 recoverymode = FALSE;
1676 if (mfp != NULL)
1677 {
1678 if (hp != NULL)
1679 mf_put(mfp, hp, FALSE, FALSE);
1680 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1681 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001682 if (buf != NULL)
1683 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001684#ifdef FEAT_CRYPT
1685 if (buf->b_p_key != curbuf->b_p_key)
1686 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001687 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001688#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001689 vim_free(buf->b_ml.ml_stack);
1690 vim_free(buf);
1691 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692 if (serious_error && called_from_main)
1693 ml_close(curbuf, TRUE);
1694#ifdef FEAT_AUTOCMD
1695 else
1696 {
1697 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1698 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1699 }
1700#endif
1701 return;
1702}
1703
1704/*
1705 * Find the names of swap files in current directory and the directory given
1706 * with the 'directory' option.
1707 *
1708 * Used to:
1709 * - list the swap files for "vim -r"
1710 * - count the number of swap files when recovering
1711 * - list the swap files when recovering
1712 * - find the name of the n'th swap file when recovering
1713 */
1714 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001715recover_names(fname, list, nr, fname_out)
1716 char_u *fname; /* base for swap file name */
1717 int list; /* when TRUE, list the swap file names */
1718 int nr; /* when non-zero, return nr'th swap file name */
1719 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720{
1721 int num_names;
1722 char_u *(names[6]);
1723 char_u *tail;
1724 char_u *p;
1725 int num_files;
1726 int file_count = 0;
1727 char_u **files;
1728 int i;
1729 char_u *dirp;
1730 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001731 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001732#ifdef HAVE_READLINK
1733 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001734#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001735
Bram Moolenaar64354da2010-05-25 21:37:17 +02001736 if (fname != NULL)
1737 {
1738#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001739 /* Expand symlink in the file name, because the swap file is created
1740 * with the actual file instead of with the symlink. */
1741 if (resolve_symlink(fname, fname_buf) == OK)
1742 fname_res = fname_buf;
1743 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001744#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001745 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001746 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747
1748 if (list)
1749 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001750 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751 msg((char_u *)_("Swap files found:"));
1752 msg_putchar('\n');
1753 }
1754
1755 /*
1756 * Do the loop for every directory in 'directory'.
1757 * First allocate some memory to put the directory name in.
1758 */
1759 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1760 dirp = p_dir;
1761 while (dir_name != NULL && *dirp)
1762 {
1763 /*
1764 * Isolate a directory name from *dirp and put it in dir_name (we know
1765 * it is large enough, so use 31000 for length).
1766 * Advance dirp to next directory name.
1767 */
1768 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1769
1770 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1771 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001772 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 {
1774#ifdef VMS
1775 names[0] = vim_strsave((char_u *)"*_sw%");
1776#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 names[0] = vim_strsave((char_u *)"*.sw?");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001779#if defined(UNIX) || defined(WIN3264)
1780 /* For Unix names starting with a dot are special. MS-Windows
1781 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 names[1] = vim_strsave((char_u *)".*.sw?");
1783 names[2] = vim_strsave((char_u *)".sw?");
1784 num_names = 3;
1785#else
1786# ifdef VMS
1787 names[1] = vim_strsave((char_u *)".*_sw%");
1788 num_names = 2;
1789# else
1790 num_names = 1;
1791# endif
1792#endif
1793 }
1794 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001795 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 }
1797 else /* check directory dir_name */
1798 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001799 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 {
1801#ifdef VMS
1802 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1803#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001805#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001806#if defined(UNIX) || defined(WIN3264)
1807 /* For Unix names starting with a dot are special. MS-Windows
1808 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1810 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1811 num_names = 3;
1812#else
1813# ifdef VMS
1814 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1815 num_names = 2;
1816# else
1817 num_names = 1;
1818# endif
1819#endif
1820 }
1821 else
1822 {
1823#if defined(UNIX) || defined(WIN3264)
1824 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001825 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 {
1827 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001828 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 }
1830 else
1831#endif
1832 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001833 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834 tail = concat_fnames(dir_name, tail, TRUE);
1835 }
1836 if (tail == NULL)
1837 num_names = 0;
1838 else
1839 {
1840 num_names = recov_file_names(names, tail, FALSE);
1841 vim_free(tail);
1842 }
1843 }
1844 }
1845
1846 /* check for out-of-memory */
1847 for (i = 0; i < num_names; ++i)
1848 {
1849 if (names[i] == NULL)
1850 {
1851 for (i = 0; i < num_names; ++i)
1852 vim_free(names[i]);
1853 num_names = 0;
1854 }
1855 }
1856 if (num_names == 0)
1857 num_files = 0;
1858 else if (expand_wildcards(num_names, names, &num_files, &files,
1859 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1860 num_files = 0;
1861
1862 /*
1863 * When no swap file found, wildcard expansion might have failed (e.g.
1864 * not able to execute the shell).
1865 * Try finding a swap file by simply adding ".swp" to the file name.
1866 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001867 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868 {
1869 struct stat st;
1870 char_u *swapname;
1871
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001872 swapname = modname(fname_res,
Bram Moolenaare60acc12011-05-10 16:41:25 +02001873#if defined(VMS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001874 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001876 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001878 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 if (swapname != NULL)
1880 {
1881 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1882 {
1883 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1884 if (files != NULL)
1885 {
1886 files[0] = swapname;
1887 swapname = NULL;
1888 num_files = 1;
1889 }
1890 }
1891 vim_free(swapname);
1892 }
1893 }
1894
1895 /*
1896 * remove swapfile name of the current buffer, it must be ignored
1897 */
1898 if (curbuf->b_ml.ml_mfp != NULL
1899 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1900 {
1901 for (i = 0; i < num_files; ++i)
1902 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1903 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001904 /* Remove the name from files[i]. Move further entries
1905 * down. When the array becomes empty free it here, since
1906 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001907 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001908 if (--num_files == 0)
1909 vim_free(files);
1910 else
1911 for ( ; i < num_files; ++i)
1912 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 }
1914 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001915 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 file_count += num_files;
1918 if (nr <= file_count)
1919 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001920 *fname_out = vim_strsave(
1921 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 dirp = (char_u *)""; /* stop searching */
1923 }
1924 }
1925 else if (list)
1926 {
1927 if (dir_name[0] == '.' && dir_name[1] == NUL)
1928 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001929 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930 MSG_PUTS(_(" In current directory:\n"));
1931 else
1932 MSG_PUTS(_(" Using specified name:\n"));
1933 }
1934 else
1935 {
1936 MSG_PUTS(_(" In directory "));
1937 msg_home_replace(dir_name);
1938 MSG_PUTS(":\n");
1939 }
1940
1941 if (num_files)
1942 {
1943 for (i = 0; i < num_files; ++i)
1944 {
1945 /* print the swap file name */
1946 msg_outnum((long)++file_count);
1947 MSG_PUTS(". ");
1948 msg_puts(gettail(files[i]));
1949 msg_putchar('\n');
1950 (void)swapfile_info(files[i]);
1951 }
1952 }
1953 else
1954 MSG_PUTS(_(" -- none --\n"));
1955 out_flush();
1956 }
1957 else
1958 file_count += num_files;
1959
1960 for (i = 0; i < num_names; ++i)
1961 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001962 if (num_files > 0)
1963 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
1965 vim_free(dir_name);
1966 return file_count;
1967}
1968
1969#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1970/*
1971 * Append the full path to name with path separators made into percent
1972 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1973 */
1974 static char_u *
1975make_percent_swname(dir, name)
1976 char_u *dir;
1977 char_u *name;
1978{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001979 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980
1981 f = fix_fname(name != NULL ? name : (char_u *) "");
1982 d = NULL;
1983 if (f != NULL)
1984 {
1985 s = alloc((unsigned)(STRLEN(f) + 1));
1986 if (s != NULL)
1987 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001988 STRCPY(s, f);
1989 for (d = s; *d != NUL; mb_ptr_adv(d))
1990 if (vim_ispathsep(*d))
1991 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 d = concat_fnames(dir, s, TRUE);
1993 vim_free(s);
1994 }
1995 vim_free(f);
1996 }
1997 return d;
1998}
1999#endif
2000
2001#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2002static int process_still_running;
2003#endif
2004
2005/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002006 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007 * Returns timestamp (0 when unknown).
2008 */
2009 static time_t
2010swapfile_info(fname)
2011 char_u *fname;
2012{
2013 struct stat st;
2014 int fd;
2015 struct block0 b0;
2016 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002017 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018#ifdef UNIX
2019 char_u uname[B0_UNAME_SIZE];
2020#endif
2021
2022 /* print the swap file date */
2023 if (mch_stat((char *)fname, &st) != -1)
2024 {
2025#ifdef UNIX
2026 /* print name of owner of the file */
2027 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2028 {
2029 MSG_PUTS(_(" owned by: "));
2030 msg_outtrans(uname);
2031 MSG_PUTS(_(" dated: "));
2032 }
2033 else
2034#endif
2035 MSG_PUTS(_(" dated: "));
2036 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002037 p = ctime(&x); /* includes '\n' */
2038 if (p == NULL)
2039 MSG_PUTS("(invalid)\n");
2040 else
2041 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 }
2043
2044 /*
2045 * print the original file name
2046 */
2047 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2048 if (fd >= 0)
2049 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01002050 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 {
2052 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2053 {
2054 MSG_PUTS(_(" [from Vim version 3.0]"));
2055 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002056 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 {
2058 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2059 }
2060 else
2061 {
2062 MSG_PUTS(_(" file name: "));
2063 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002064 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 else
2066 msg_outtrans(b0.b0_fname);
2067
2068 MSG_PUTS(_("\n modified: "));
2069 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2070
2071 if (*(b0.b0_uname) != NUL)
2072 {
2073 MSG_PUTS(_("\n user name: "));
2074 msg_outtrans(b0.b0_uname);
2075 }
2076
2077 if (*(b0.b0_hname) != NUL)
2078 {
2079 if (*(b0.b0_uname) != NUL)
2080 MSG_PUTS(_(" host name: "));
2081 else
2082 MSG_PUTS(_("\n host name: "));
2083 msg_outtrans(b0.b0_hname);
2084 }
2085
2086 if (char_to_long(b0.b0_pid) != 0L)
2087 {
2088 MSG_PUTS(_("\n process ID: "));
2089 msg_outnum(char_to_long(b0.b0_pid));
2090#if defined(UNIX) || defined(__EMX__)
2091 /* EMX kill() not working correctly, it seems */
2092 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2093 {
2094 MSG_PUTS(_(" (still running)"));
2095# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2096 process_still_running = TRUE;
2097# endif
2098 }
2099#endif
2100 }
2101
2102 if (b0_magic_wrong(&b0))
2103 {
2104#if defined(MSDOS) || defined(MSWIN)
2105 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2106 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2107 else
2108#endif
2109 MSG_PUTS(_("\n [not usable on this computer]"));
2110 }
2111 }
2112 }
2113 else
2114 MSG_PUTS(_(" [cannot be read]"));
2115 close(fd);
2116 }
2117 else
2118 MSG_PUTS(_(" [cannot be opened]"));
2119 msg_putchar('\n');
2120
2121 return x;
2122}
2123
2124 static int
2125recov_file_names(names, path, prepend_dot)
2126 char_u **names;
2127 char_u *path;
2128 int prepend_dot;
2129{
2130 int num_names;
2131
2132#ifdef SHORT_FNAME
2133 /*
2134 * (MS-DOS) always short names
2135 */
2136 names[0] = modname(path, (char_u *)".sw?", FALSE);
2137 num_names = 1;
2138#else /* !SHORT_FNAME */
2139 /*
2140 * (Win32 and Win64) never short names, but do prepend a dot.
2141 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2142 * Only use the short name if it is different.
2143 */
2144 char_u *p;
2145 int i;
2146# ifndef WIN3264
2147 int shortname = curbuf->b_shortname;
2148
2149 curbuf->b_shortname = FALSE;
2150# endif
2151
2152 num_names = 0;
2153
2154 /*
2155 * May also add the file name with a dot prepended, for swap file in same
2156 * dir as original file.
2157 */
2158 if (prepend_dot)
2159 {
2160 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2161 if (names[num_names] == NULL)
2162 goto end;
2163 ++num_names;
2164 }
2165
2166 /*
2167 * Form the normal swap file name pattern by appending ".sw?".
2168 */
2169#ifdef VMS
2170 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2171#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173#endif
2174 if (names[num_names] == NULL)
2175 goto end;
2176 if (num_names >= 1) /* check if we have the same name twice */
2177 {
2178 p = names[num_names - 1];
2179 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2180 if (i > 0)
2181 p += i; /* file name has been expanded to full path */
2182
2183 if (STRCMP(p, names[num_names]) != 0)
2184 ++num_names;
2185 else
2186 vim_free(names[num_names]);
2187 }
2188 else
2189 ++num_names;
2190
2191# ifndef WIN3264
2192 /*
2193 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2194 */
2195 curbuf->b_shortname = TRUE;
2196#ifdef VMS
2197 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2198#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200#endif
2201 if (names[num_names] == NULL)
2202 goto end;
2203
2204 /*
2205 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2206 */
2207 p = names[num_names];
2208 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2209 if (i > 0)
2210 p += i; /* file name has been expanded to full path */
2211 if (STRCMP(names[num_names - 1], p) == 0)
2212 vim_free(names[num_names]);
2213 else
2214 ++num_names;
2215# endif
2216
2217end:
2218# ifndef WIN3264
2219 curbuf->b_shortname = shortname;
2220# endif
2221
2222#endif /* !SHORT_FNAME */
2223
2224 return num_names;
2225}
2226
2227/*
2228 * sync all memlines
2229 *
2230 * If 'check_file' is TRUE, check if original file exists and was not changed.
2231 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2232 * always sync at least one block.
2233 */
2234 void
2235ml_sync_all(check_file, check_char)
2236 int check_file;
2237 int check_char;
2238{
2239 buf_T *buf;
2240 struct stat st;
2241
2242 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2243 {
2244 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2245 continue; /* no file */
2246
2247 ml_flush_line(buf); /* flush buffered line */
2248 /* flush locked block */
2249 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2250 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2251 && buf->b_ffname != NULL)
2252 {
2253 /*
2254 * If the original file does not exist anymore or has been changed
2255 * call ml_preserve() to get rid of all negative numbered blocks.
2256 */
2257 if (mch_stat((char *)buf->b_ffname, &st) == -1
2258 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002259 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260 {
2261 ml_preserve(buf, FALSE);
2262 did_check_timestamps = FALSE;
2263 need_check_timestamps = TRUE; /* give message later */
2264 }
2265 }
2266 if (buf->b_ml.ml_mfp->mf_dirty)
2267 {
2268 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2269 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2270 if (check_char && ui_char_avail()) /* character available now */
2271 break;
2272 }
2273 }
2274}
2275
2276/*
2277 * sync one buffer, including negative blocks
2278 *
2279 * after this all the blocks are in the swap file
2280 *
2281 * Used for the :preserve command and when the original file has been
2282 * changed or deleted.
2283 *
2284 * when message is TRUE the success of preserving is reported
2285 */
2286 void
2287ml_preserve(buf, message)
2288 buf_T *buf;
2289 int message;
2290{
2291 bhdr_T *hp;
2292 linenr_T lnum;
2293 memfile_T *mfp = buf->b_ml.ml_mfp;
2294 int status;
2295 int got_int_save = got_int;
2296
2297 if (mfp == NULL || mfp->mf_fname == NULL)
2298 {
2299 if (message)
2300 EMSG(_("E313: Cannot preserve, there is no swap file"));
2301 return;
2302 }
2303
2304 /* We only want to stop when interrupted here, not when interrupted
2305 * before. */
2306 got_int = FALSE;
2307
2308 ml_flush_line(buf); /* flush buffered line */
2309 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2310 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2311
2312 /* stack is invalid after mf_sync(.., MFS_ALL) */
2313 buf->b_ml.ml_stack_top = 0;
2314
2315 /*
2316 * Some of the data blocks may have been changed from negative to
2317 * positive block number. In that case the pointer blocks need to be
2318 * updated.
2319 *
2320 * We don't know in which pointer block the references are, so we visit
2321 * all data blocks until there are no more translations to be done (or
2322 * we hit the end of the file, which can only happen in case a write fails,
2323 * e.g. when file system if full).
2324 * ml_find_line() does the work by translating the negative block numbers
2325 * when getting the first line of each data block.
2326 */
2327 if (mf_need_trans(mfp) && !got_int)
2328 {
2329 lnum = 1;
2330 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2331 {
2332 hp = ml_find_line(buf, lnum, ML_FIND);
2333 if (hp == NULL)
2334 {
2335 status = FAIL;
2336 goto theend;
2337 }
2338 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2339 lnum = buf->b_ml.ml_locked_high + 1;
2340 }
2341 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2342 /* sync the updated pointer blocks */
2343 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2344 status = FAIL;
2345 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2346 }
2347theend:
2348 got_int |= got_int_save;
2349
2350 if (message)
2351 {
2352 if (status == OK)
2353 MSG(_("File preserved"));
2354 else
2355 EMSG(_("E314: Preserve failed"));
2356 }
2357}
2358
2359/*
2360 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2361 * until the next call!
2362 * line1 = ml_get(1);
2363 * line2 = ml_get(2); // line1 is now invalid!
2364 * Make a copy of the line if necessary.
2365 */
2366/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002367 * Return a pointer to a (read-only copy of a) line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 *
2369 * On failure an error message is given and IObuff is returned (to avoid
2370 * having to check for error everywhere).
2371 */
2372 char_u *
2373ml_get(lnum)
2374 linenr_T lnum;
2375{
2376 return ml_get_buf(curbuf, lnum, FALSE);
2377}
2378
2379/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002380 * Return pointer to position "pos".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 */
2382 char_u *
2383ml_get_pos(pos)
2384 pos_T *pos;
2385{
2386 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2387}
2388
2389/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002390 * Return pointer to cursor line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 */
2392 char_u *
2393ml_get_curline()
2394{
2395 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2396}
2397
2398/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002399 * Return pointer to cursor position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 */
2401 char_u *
2402ml_get_cursor()
2403{
2404 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2405 curwin->w_cursor.col);
2406}
2407
2408/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002409 * Return a pointer to a line in a specific buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410 *
2411 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2412 * changed)
2413 */
2414 char_u *
2415ml_get_buf(buf, lnum, will_change)
2416 buf_T *buf;
2417 linenr_T lnum;
2418 int will_change; /* line will be changed */
2419{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002420 bhdr_T *hp;
2421 DATA_BL *dp;
2422 char_u *ptr;
2423 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424
2425 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2426 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002427 if (recursive == 0)
2428 {
2429 /* Avoid giving this message for a recursive call, may happen when
2430 * the GUI redraws part of the text. */
2431 ++recursive;
2432 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2433 --recursive;
2434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435errorret:
2436 STRCPY(IObuff, "???");
2437 return IObuff;
2438 }
2439 if (lnum <= 0) /* pretend line 0 is line 1 */
2440 lnum = 1;
2441
2442 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2443 return (char_u *)"";
2444
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002445 /*
2446 * See if it is the same line as requested last time.
2447 * Otherwise may need to flush last used line.
2448 * Don't use the last used line when 'swapfile' is reset, need to load all
2449 * blocks.
2450 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002451 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 {
2453 ml_flush_line(buf);
2454
2455 /*
2456 * Find the data block containing the line.
2457 * This also fills the stack with the blocks from the root to the data
2458 * block and releases any locked block.
2459 */
2460 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2461 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002462 if (recursive == 0)
2463 {
2464 /* Avoid giving this message for a recursive call, may happen
2465 * when the GUI redraws part of the text. */
2466 ++recursive;
2467 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2468 --recursive;
2469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 goto errorret;
2471 }
2472
2473 dp = (DATA_BL *)(hp->bh_data);
2474
2475 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2476 buf->b_ml.ml_line_ptr = ptr;
2477 buf->b_ml.ml_line_lnum = lnum;
2478 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2479 }
2480 if (will_change)
2481 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2482
2483 return buf->b_ml.ml_line_ptr;
2484}
2485
2486/*
2487 * Check if a line that was just obtained by a call to ml_get
2488 * is in allocated memory.
2489 */
2490 int
2491ml_line_alloced()
2492{
2493 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2494}
2495
2496/*
2497 * Append a line after lnum (may be 0 to insert a line in front of the file).
2498 * "line" does not need to be allocated, but can't be another line in a
2499 * buffer, unlocking may make it invalid.
2500 *
2501 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2502 * will be set for recovery
2503 * Check: The caller of this function should probably also call
2504 * appended_lines().
2505 *
2506 * return FAIL for failure, OK otherwise
2507 */
2508 int
2509ml_append(lnum, line, len, newfile)
2510 linenr_T lnum; /* append after this line (can be 0) */
2511 char_u *line; /* text of the new line */
2512 colnr_T len; /* length of new line, including NUL, or 0 */
2513 int newfile; /* flag, see above */
2514{
2515 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002516 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 return FAIL;
2518
2519 if (curbuf->b_ml.ml_line_lnum != 0)
2520 ml_flush_line(curbuf);
2521 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2522}
2523
Bram Moolenaara1956f62006-03-12 22:18:00 +00002524#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002525/*
2526 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2527 * a memline.
2528 */
2529 int
2530ml_append_buf(buf, lnum, line, len, newfile)
2531 buf_T *buf;
2532 linenr_T lnum; /* append after this line (can be 0) */
2533 char_u *line; /* text of the new line */
2534 colnr_T len; /* length of new line, including NUL, or 0 */
2535 int newfile; /* flag, see above */
2536{
2537 if (buf->b_ml.ml_mfp == NULL)
2538 return FAIL;
2539
2540 if (buf->b_ml.ml_line_lnum != 0)
2541 ml_flush_line(buf);
2542 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2543}
2544#endif
2545
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 static int
2547ml_append_int(buf, lnum, line, len, newfile, mark)
2548 buf_T *buf;
2549 linenr_T lnum; /* append after this line (can be 0) */
2550 char_u *line; /* text of the new line */
2551 colnr_T len; /* length of line, including NUL, or 0 */
2552 int newfile; /* flag, see above */
2553 int mark; /* mark the new line */
2554{
2555 int i;
2556 int line_count; /* number of indexes in current block */
2557 int offset;
2558 int from, to;
2559 int space_needed; /* space needed for new line */
2560 int page_size;
2561 int page_count;
2562 int db_idx; /* index for lnum in data block */
2563 bhdr_T *hp;
2564 memfile_T *mfp;
2565 DATA_BL *dp;
2566 PTR_BL *pp;
2567 infoptr_T *ip;
2568
2569 /* lnum out of range */
2570 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2571 return FAIL;
2572
2573 if (lowest_marked && lowest_marked > lnum)
2574 lowest_marked = lnum + 1;
2575
2576 if (len == 0)
2577 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2578 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2579
2580 mfp = buf->b_ml.ml_mfp;
2581 page_size = mfp->mf_page_size;
2582
2583/*
2584 * find the data block containing the previous line
2585 * This also fills the stack with the blocks from the root to the data block
2586 * This also releases any locked block.
2587 */
2588 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2589 ML_INSERT)) == NULL)
2590 return FAIL;
2591
2592 buf->b_ml.ml_flags &= ~ML_EMPTY;
2593
2594 if (lnum == 0) /* got line one instead, correct db_idx */
2595 db_idx = -1; /* careful, it is negative! */
2596 else
2597 db_idx = lnum - buf->b_ml.ml_locked_low;
2598 /* get line count before the insertion */
2599 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2600
2601 dp = (DATA_BL *)(hp->bh_data);
2602
2603/*
2604 * If
2605 * - there is not enough room in the current block
2606 * - appending to the last line in the block
2607 * - not appending to the last line in the file
2608 * insert in front of the next block.
2609 */
2610 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2611 && lnum < buf->b_ml.ml_line_count)
2612 {
2613 /*
2614 * Now that the line is not going to be inserted in the block that we
2615 * expected, the line count has to be adjusted in the pointer blocks
2616 * by using ml_locked_lineadd.
2617 */
2618 --(buf->b_ml.ml_locked_lineadd);
2619 --(buf->b_ml.ml_locked_high);
2620 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2621 return FAIL;
2622
2623 db_idx = -1; /* careful, it is negative! */
2624 /* get line count before the insertion */
2625 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2626 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2627
2628 dp = (DATA_BL *)(hp->bh_data);
2629 }
2630
2631 ++buf->b_ml.ml_line_count;
2632
2633 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2634 {
2635/*
2636 * Insert new line in existing data block, or in data block allocated above.
2637 */
2638 dp->db_txt_start -= len;
2639 dp->db_free -= space_needed;
2640 ++(dp->db_line_count);
2641
2642 /*
2643 * move the text of the lines that follow to the front
2644 * adjust the indexes of the lines that follow
2645 */
2646 if (line_count > db_idx + 1) /* if there are following lines */
2647 {
2648 /*
2649 * Offset is the start of the previous line.
2650 * This will become the character just after the new line.
2651 */
2652 if (db_idx < 0)
2653 offset = dp->db_txt_end;
2654 else
2655 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2656 mch_memmove((char *)dp + dp->db_txt_start,
2657 (char *)dp + dp->db_txt_start + len,
2658 (size_t)(offset - (dp->db_txt_start + len)));
2659 for (i = line_count - 1; i > db_idx; --i)
2660 dp->db_index[i + 1] = dp->db_index[i] - len;
2661 dp->db_index[db_idx + 1] = offset - len;
2662 }
2663 else /* add line at the end */
2664 dp->db_index[db_idx + 1] = dp->db_txt_start;
2665
2666 /*
2667 * copy the text into the block
2668 */
2669 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2670 if (mark)
2671 dp->db_index[db_idx + 1] |= DB_MARKED;
2672
2673 /*
2674 * Mark the block dirty.
2675 */
2676 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2677 if (!newfile)
2678 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2679 }
2680 else /* not enough space in data block */
2681 {
2682/*
2683 * If there is not enough room we have to create a new data block and copy some
2684 * lines into it.
2685 * Then we have to insert an entry in the pointer block.
2686 * If this pointer block also is full, we go up another block, and so on, up
2687 * to the root if necessary.
2688 * The line counts in the pointer blocks have already been adjusted by
2689 * ml_find_line().
2690 */
2691 long line_count_left, line_count_right;
2692 int page_count_left, page_count_right;
2693 bhdr_T *hp_left;
2694 bhdr_T *hp_right;
2695 bhdr_T *hp_new;
2696 int lines_moved;
2697 int data_moved = 0; /* init to shut up gcc */
2698 int total_moved = 0; /* init to shut up gcc */
2699 DATA_BL *dp_right, *dp_left;
2700 int stack_idx;
2701 int in_left;
2702 int lineadd;
2703 blocknr_T bnum_left, bnum_right;
2704 linenr_T lnum_left, lnum_right;
2705 int pb_idx;
2706 PTR_BL *pp_new;
2707
2708 /*
2709 * We are going to allocate a new data block. Depending on the
2710 * situation it will be put to the left or right of the existing
2711 * block. If possible we put the new line in the left block and move
2712 * the lines after it to the right block. Otherwise the new line is
2713 * also put in the right block. This method is more efficient when
2714 * inserting a lot of lines at one place.
2715 */
2716 if (db_idx < 0) /* left block is new, right block is existing */
2717 {
2718 lines_moved = 0;
2719 in_left = TRUE;
2720 /* space_needed does not change */
2721 }
2722 else /* left block is existing, right block is new */
2723 {
2724 lines_moved = line_count - db_idx - 1;
2725 if (lines_moved == 0)
2726 in_left = FALSE; /* put new line in right block */
2727 /* space_needed does not change */
2728 else
2729 {
2730 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2731 dp->db_txt_start;
2732 total_moved = data_moved + lines_moved * INDEX_SIZE;
2733 if ((int)dp->db_free + total_moved >= space_needed)
2734 {
2735 in_left = TRUE; /* put new line in left block */
2736 space_needed = total_moved;
2737 }
2738 else
2739 {
2740 in_left = FALSE; /* put new line in right block */
2741 space_needed += total_moved;
2742 }
2743 }
2744 }
2745
2746 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2747 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2748 {
2749 /* correct line counts in pointer blocks */
2750 --(buf->b_ml.ml_locked_lineadd);
2751 --(buf->b_ml.ml_locked_high);
2752 return FAIL;
2753 }
2754 if (db_idx < 0) /* left block is new */
2755 {
2756 hp_left = hp_new;
2757 hp_right = hp;
2758 line_count_left = 0;
2759 line_count_right = line_count;
2760 }
2761 else /* right block is new */
2762 {
2763 hp_left = hp;
2764 hp_right = hp_new;
2765 line_count_left = line_count;
2766 line_count_right = 0;
2767 }
2768 dp_right = (DATA_BL *)(hp_right->bh_data);
2769 dp_left = (DATA_BL *)(hp_left->bh_data);
2770 bnum_left = hp_left->bh_bnum;
2771 bnum_right = hp_right->bh_bnum;
2772 page_count_left = hp_left->bh_page_count;
2773 page_count_right = hp_right->bh_page_count;
2774
2775 /*
2776 * May move the new line into the right/new block.
2777 */
2778 if (!in_left)
2779 {
2780 dp_right->db_txt_start -= len;
2781 dp_right->db_free -= len + INDEX_SIZE;
2782 dp_right->db_index[0] = dp_right->db_txt_start;
2783 if (mark)
2784 dp_right->db_index[0] |= DB_MARKED;
2785
2786 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2787 line, (size_t)len);
2788 ++line_count_right;
2789 }
2790 /*
2791 * may move lines from the left/old block to the right/new one.
2792 */
2793 if (lines_moved)
2794 {
2795 /*
2796 */
2797 dp_right->db_txt_start -= data_moved;
2798 dp_right->db_free -= total_moved;
2799 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2800 (char *)dp_left + dp_left->db_txt_start,
2801 (size_t)data_moved);
2802 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2803 dp_left->db_txt_start += data_moved;
2804 dp_left->db_free += total_moved;
2805
2806 /*
2807 * update indexes in the new block
2808 */
2809 for (to = line_count_right, from = db_idx + 1;
2810 from < line_count_left; ++from, ++to)
2811 dp_right->db_index[to] = dp->db_index[from] + offset;
2812 line_count_right += lines_moved;
2813 line_count_left -= lines_moved;
2814 }
2815
2816 /*
2817 * May move the new line into the left (old or new) block.
2818 */
2819 if (in_left)
2820 {
2821 dp_left->db_txt_start -= len;
2822 dp_left->db_free -= len + INDEX_SIZE;
2823 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2824 if (mark)
2825 dp_left->db_index[line_count_left] |= DB_MARKED;
2826 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2827 line, (size_t)len);
2828 ++line_count_left;
2829 }
2830
2831 if (db_idx < 0) /* left block is new */
2832 {
2833 lnum_left = lnum + 1;
2834 lnum_right = 0;
2835 }
2836 else /* right block is new */
2837 {
2838 lnum_left = 0;
2839 if (in_left)
2840 lnum_right = lnum + 2;
2841 else
2842 lnum_right = lnum + 1;
2843 }
2844 dp_left->db_line_count = line_count_left;
2845 dp_right->db_line_count = line_count_right;
2846
2847 /*
2848 * release the two data blocks
2849 * The new one (hp_new) already has a correct blocknumber.
2850 * The old one (hp, in ml_locked) gets a positive blocknumber if
2851 * we changed it and we are not editing a new file.
2852 */
2853 if (lines_moved || in_left)
2854 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2855 if (!newfile && db_idx >= 0 && in_left)
2856 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2857 mf_put(mfp, hp_new, TRUE, FALSE);
2858
2859 /*
2860 * flush the old data block
2861 * set ml_locked_lineadd to 0, because the updating of the
2862 * pointer blocks is done below
2863 */
2864 lineadd = buf->b_ml.ml_locked_lineadd;
2865 buf->b_ml.ml_locked_lineadd = 0;
2866 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2867
2868 /*
2869 * update pointer blocks for the new data block
2870 */
2871 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2872 --stack_idx)
2873 {
2874 ip = &(buf->b_ml.ml_stack[stack_idx]);
2875 pb_idx = ip->ip_index;
2876 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2877 return FAIL;
2878 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2879 if (pp->pb_id != PTR_ID)
2880 {
2881 EMSG(_("E317: pointer block id wrong 3"));
2882 mf_put(mfp, hp, FALSE, FALSE);
2883 return FAIL;
2884 }
2885 /*
2886 * TODO: If the pointer block is full and we are adding at the end
2887 * try to insert in front of the next block
2888 */
2889 /* block not full, add one entry */
2890 if (pp->pb_count < pp->pb_count_max)
2891 {
2892 if (pb_idx + 1 < (int)pp->pb_count)
2893 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2894 &pp->pb_pointer[pb_idx + 1],
2895 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2896 ++pp->pb_count;
2897 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2898 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2899 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2900 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2901 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2902 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2903
2904 if (lnum_left != 0)
2905 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2906 if (lnum_right != 0)
2907 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2908
2909 mf_put(mfp, hp, TRUE, FALSE);
2910 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2911
2912 if (lineadd)
2913 {
2914 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002915 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 ml_lineadd(buf, lineadd);
2917 /* fix stack itself */
2918 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2919 lineadd;
2920 ++(buf->b_ml.ml_stack_top);
2921 }
2922
2923 /*
2924 * We are finished, break the loop here.
2925 */
2926 break;
2927 }
2928 else /* pointer block full */
2929 {
2930 /*
2931 * split the pointer block
2932 * allocate a new pointer block
2933 * move some of the pointer into the new block
2934 * prepare for updating the parent block
2935 */
2936 for (;;) /* do this twice when splitting block 1 */
2937 {
2938 hp_new = ml_new_ptr(mfp);
2939 if (hp_new == NULL) /* TODO: try to fix tree */
2940 return FAIL;
2941 pp_new = (PTR_BL *)(hp_new->bh_data);
2942
2943 if (hp->bh_bnum != 1)
2944 break;
2945
2946 /*
2947 * if block 1 becomes full the tree is given an extra level
2948 * The pointers from block 1 are moved into the new block.
2949 * block 1 is updated to point to the new block
2950 * then continue to split the new block
2951 */
2952 mch_memmove(pp_new, pp, (size_t)page_size);
2953 pp->pb_count = 1;
2954 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2955 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2956 pp->pb_pointer[0].pe_old_lnum = 1;
2957 pp->pb_pointer[0].pe_page_count = 1;
2958 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2959 hp = hp_new; /* new block is to be split */
2960 pp = pp_new;
2961 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2962 ip->ip_index = 0;
2963 ++stack_idx; /* do block 1 again later */
2964 }
2965 /*
2966 * move the pointers after the current one to the new block
2967 * If there are none, the new entry will be in the new block.
2968 */
2969 total_moved = pp->pb_count - pb_idx - 1;
2970 if (total_moved)
2971 {
2972 mch_memmove(&pp_new->pb_pointer[0],
2973 &pp->pb_pointer[pb_idx + 1],
2974 (size_t)(total_moved) * sizeof(PTR_EN));
2975 pp_new->pb_count = total_moved;
2976 pp->pb_count -= total_moved - 1;
2977 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2978 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2979 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2980 if (lnum_right)
2981 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2982 }
2983 else
2984 {
2985 pp_new->pb_count = 1;
2986 pp_new->pb_pointer[0].pe_bnum = bnum_right;
2987 pp_new->pb_pointer[0].pe_line_count = line_count_right;
2988 pp_new->pb_pointer[0].pe_page_count = page_count_right;
2989 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
2990 }
2991 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2992 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2993 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2994 if (lnum_left)
2995 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2996 lnum_left = 0;
2997 lnum_right = 0;
2998
2999 /*
3000 * recompute line counts
3001 */
3002 line_count_right = 0;
3003 for (i = 0; i < (int)pp_new->pb_count; ++i)
3004 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3005 line_count_left = 0;
3006 for (i = 0; i < (int)pp->pb_count; ++i)
3007 line_count_left += pp->pb_pointer[i].pe_line_count;
3008
3009 bnum_left = hp->bh_bnum;
3010 bnum_right = hp_new->bh_bnum;
3011 page_count_left = 1;
3012 page_count_right = 1;
3013 mf_put(mfp, hp, TRUE, FALSE);
3014 mf_put(mfp, hp_new, TRUE, FALSE);
3015 }
3016 }
3017
3018 /*
3019 * Safety check: fallen out of for loop?
3020 */
3021 if (stack_idx < 0)
3022 {
3023 EMSG(_("E318: Updated too many blocks?"));
3024 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3025 }
3026 }
3027
3028#ifdef FEAT_BYTEOFF
3029 /* The line was inserted below 'lnum' */
3030 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3031#endif
3032#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003033 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 {
3035 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003036 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003037 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 (char_u *)"\n", 1);
3039 }
3040#endif
3041 return OK;
3042}
3043
3044/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003045 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003047 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 * copied to allocated memory already.
3049 *
3050 * Check: The caller of this function should probably also call
3051 * changed_lines(), unless update_screen(NOT_VALID) is used.
3052 *
3053 * return FAIL for failure, OK otherwise
3054 */
3055 int
3056ml_replace(lnum, line, copy)
3057 linenr_T lnum;
3058 char_u *line;
3059 int copy;
3060{
3061 if (line == NULL) /* just checking... */
3062 return FAIL;
3063
3064 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003065 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 return FAIL;
3067
3068 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3069 return FAIL;
3070#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003071 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003072 {
3073 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003074 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003075 }
3076#endif
3077 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3078 ml_flush_line(curbuf); /* flush it */
3079 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3080 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3081 curbuf->b_ml.ml_line_ptr = line;
3082 curbuf->b_ml.ml_line_lnum = lnum;
3083 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3084
3085 return OK;
3086}
3087
3088/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003089 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 *
3091 * Check: The caller of this function should probably also call
3092 * deleted_lines() after this.
3093 *
3094 * return FAIL for failure, OK otherwise
3095 */
3096 int
3097ml_delete(lnum, message)
3098 linenr_T lnum;
3099 int message;
3100{
3101 ml_flush_line(curbuf);
3102 return ml_delete_int(curbuf, lnum, message);
3103}
3104
3105 static int
3106ml_delete_int(buf, lnum, message)
3107 buf_T *buf;
3108 linenr_T lnum;
3109 int message;
3110{
3111 bhdr_T *hp;
3112 memfile_T *mfp;
3113 DATA_BL *dp;
3114 PTR_BL *pp;
3115 infoptr_T *ip;
3116 int count; /* number of entries in block */
3117 int idx;
3118 int stack_idx;
3119 int text_start;
3120 int line_start;
3121 long line_size;
3122 int i;
3123
3124 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3125 return FAIL;
3126
3127 if (lowest_marked && lowest_marked > lnum)
3128 lowest_marked--;
3129
3130/*
3131 * If the file becomes empty the last line is replaced by an empty line.
3132 */
3133 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3134 {
3135 if (message
3136#ifdef FEAT_NETBEANS_INTG
3137 && !netbeansSuppressNoLines
3138#endif
3139 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003140 set_keep_msg((char_u *)_(no_lines_msg), 0);
3141
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
3143 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3144 buf->b_ml.ml_flags |= ML_EMPTY;
3145
3146 return i;
3147 }
3148
3149/*
3150 * find the data block containing the line
3151 * This also fills the stack with the blocks from the root to the data block
3152 * This also releases any locked block.
3153 */
3154 mfp = buf->b_ml.ml_mfp;
3155 if (mfp == NULL)
3156 return FAIL;
3157
3158 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3159 return FAIL;
3160
3161 dp = (DATA_BL *)(hp->bh_data);
3162 /* compute line count before the delete */
3163 count = (long)(buf->b_ml.ml_locked_high)
3164 - (long)(buf->b_ml.ml_locked_low) + 2;
3165 idx = lnum - buf->b_ml.ml_locked_low;
3166
3167 --buf->b_ml.ml_line_count;
3168
3169 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3170 if (idx == 0) /* first line in block, text at the end */
3171 line_size = dp->db_txt_end - line_start;
3172 else
3173 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3174
3175#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003176 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003177 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178#endif
3179
3180/*
3181 * special case: If there is only one line in the data block it becomes empty.
3182 * Then we have to remove the entry, pointing to this data block, from the
3183 * pointer block. If this pointer block also becomes empty, we go up another
3184 * block, and so on, up to the root if necessary.
3185 * The line counts in the pointer blocks have already been adjusted by
3186 * ml_find_line().
3187 */
3188 if (count == 1)
3189 {
3190 mf_free(mfp, hp); /* free the data block */
3191 buf->b_ml.ml_locked = NULL;
3192
Bram Moolenaare60acc12011-05-10 16:41:25 +02003193 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3194 --stack_idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 {
3196 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3197 ip = &(buf->b_ml.ml_stack[stack_idx]);
3198 idx = ip->ip_index;
3199 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3200 return FAIL;
3201 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3202 if (pp->pb_id != PTR_ID)
3203 {
3204 EMSG(_("E317: pointer block id wrong 4"));
3205 mf_put(mfp, hp, FALSE, FALSE);
3206 return FAIL;
3207 }
3208 count = --(pp->pb_count);
3209 if (count == 0) /* the pointer block becomes empty! */
3210 mf_free(mfp, hp);
3211 else
3212 {
3213 if (count != idx) /* move entries after the deleted one */
3214 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3215 (size_t)(count - idx) * sizeof(PTR_EN));
3216 mf_put(mfp, hp, TRUE, FALSE);
3217
3218 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003219 /* fix line count for rest of blocks in the stack */
3220 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 {
3222 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3223 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003224 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225 }
3226 ++(buf->b_ml.ml_stack_top);
3227
3228 break;
3229 }
3230 }
3231 CHECK(stack_idx < 0, _("deleted block 1?"));
3232 }
3233 else
3234 {
3235 /*
3236 * delete the text by moving the next lines forwards
3237 */
3238 text_start = dp->db_txt_start;
3239 mch_memmove((char *)dp + text_start + line_size,
3240 (char *)dp + text_start, (size_t)(line_start - text_start));
3241
3242 /*
3243 * delete the index by moving the next indexes backwards
3244 * Adjust the indexes for the text movement.
3245 */
3246 for (i = idx; i < count - 1; ++i)
3247 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3248
3249 dp->db_free += line_size + INDEX_SIZE;
3250 dp->db_txt_start += line_size;
3251 --(dp->db_line_count);
3252
3253 /*
3254 * mark the block dirty and make sure it is in the file (for recovery)
3255 */
3256 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3257 }
3258
3259#ifdef FEAT_BYTEOFF
3260 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3261#endif
3262 return OK;
3263}
3264
3265/*
3266 * set the B_MARKED flag for line 'lnum'
3267 */
3268 void
3269ml_setmarked(lnum)
3270 linenr_T lnum;
3271{
3272 bhdr_T *hp;
3273 DATA_BL *dp;
3274 /* invalid line number */
3275 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3276 || curbuf->b_ml.ml_mfp == NULL)
3277 return; /* give error message? */
3278
3279 if (lowest_marked == 0 || lowest_marked > lnum)
3280 lowest_marked = lnum;
3281
3282 /*
3283 * find the data block containing the line
3284 * This also fills the stack with the blocks from the root to the data block
3285 * This also releases any locked block.
3286 */
3287 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3288 return; /* give error message? */
3289
3290 dp = (DATA_BL *)(hp->bh_data);
3291 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3292 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3293}
3294
3295/*
3296 * find the first line with its B_MARKED flag set
3297 */
3298 linenr_T
3299ml_firstmarked()
3300{
3301 bhdr_T *hp;
3302 DATA_BL *dp;
3303 linenr_T lnum;
3304 int i;
3305
3306 if (curbuf->b_ml.ml_mfp == NULL)
3307 return (linenr_T) 0;
3308
3309 /*
3310 * The search starts with lowest_marked line. This is the last line where
3311 * a mark was found, adjusted by inserting/deleting lines.
3312 */
3313 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3314 {
3315 /*
3316 * Find the data block containing the line.
3317 * This also fills the stack with the blocks from the root to the data
3318 * block This also releases any locked block.
3319 */
3320 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3321 return (linenr_T)0; /* give error message? */
3322
3323 dp = (DATA_BL *)(hp->bh_data);
3324
3325 for (i = lnum - curbuf->b_ml.ml_locked_low;
3326 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3327 if ((dp->db_index[i]) & DB_MARKED)
3328 {
3329 (dp->db_index[i]) &= DB_INDEX_MASK;
3330 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3331 lowest_marked = lnum + 1;
3332 return lnum;
3333 }
3334 }
3335
3336 return (linenr_T) 0;
3337}
3338
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339/*
3340 * clear all DB_MARKED flags
3341 */
3342 void
3343ml_clearmarked()
3344{
3345 bhdr_T *hp;
3346 DATA_BL *dp;
3347 linenr_T lnum;
3348 int i;
3349
3350 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3351 return;
3352
3353 /*
3354 * The search starts with line lowest_marked.
3355 */
3356 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3357 {
3358 /*
3359 * Find the data block containing the line.
3360 * This also fills the stack with the blocks from the root to the data
3361 * block and releases any locked block.
3362 */
3363 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3364 return; /* give error message? */
3365
3366 dp = (DATA_BL *)(hp->bh_data);
3367
3368 for (i = lnum - curbuf->b_ml.ml_locked_low;
3369 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3370 if ((dp->db_index[i]) & DB_MARKED)
3371 {
3372 (dp->db_index[i]) &= DB_INDEX_MASK;
3373 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3374 }
3375 }
3376
3377 lowest_marked = 0;
3378 return;
3379}
3380
3381/*
3382 * flush ml_line if necessary
3383 */
3384 static void
3385ml_flush_line(buf)
3386 buf_T *buf;
3387{
3388 bhdr_T *hp;
3389 DATA_BL *dp;
3390 linenr_T lnum;
3391 char_u *new_line;
3392 char_u *old_line;
3393 colnr_T new_len;
3394 int old_len;
3395 int extra;
3396 int idx;
3397 int start;
3398 int count;
3399 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003400 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401
3402 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3403 return; /* nothing to do */
3404
3405 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3406 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003407 /* This code doesn't work recursively, but Netbeans may call back here
3408 * when obtaining the cursor position. */
3409 if (entered)
3410 return;
3411 entered = TRUE;
3412
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 lnum = buf->b_ml.ml_line_lnum;
3414 new_line = buf->b_ml.ml_line_ptr;
3415
3416 hp = ml_find_line(buf, lnum, ML_FIND);
3417 if (hp == NULL)
3418 EMSGN(_("E320: Cannot find line %ld"), lnum);
3419 else
3420 {
3421 dp = (DATA_BL *)(hp->bh_data);
3422 idx = lnum - buf->b_ml.ml_locked_low;
3423 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3424 old_line = (char_u *)dp + start;
3425 if (idx == 0) /* line is last in block */
3426 old_len = dp->db_txt_end - start;
3427 else /* text of previous line follows */
3428 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3429 new_len = (colnr_T)STRLEN(new_line) + 1;
3430 extra = new_len - old_len; /* negative if lines gets smaller */
3431
3432 /*
3433 * if new line fits in data block, replace directly
3434 */
3435 if ((int)dp->db_free >= extra)
3436 {
3437 /* if the length changes and there are following lines */
3438 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3439 if (extra != 0 && idx < count - 1)
3440 {
3441 /* move text of following lines */
3442 mch_memmove((char *)dp + dp->db_txt_start - extra,
3443 (char *)dp + dp->db_txt_start,
3444 (size_t)(start - dp->db_txt_start));
3445
3446 /* adjust pointers of this and following lines */
3447 for (i = idx + 1; i < count; ++i)
3448 dp->db_index[i] -= extra;
3449 }
3450 dp->db_index[idx] -= extra;
3451
3452 /* adjust free space */
3453 dp->db_free -= extra;
3454 dp->db_txt_start -= extra;
3455
3456 /* copy new line into the data block */
3457 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3458 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3459#ifdef FEAT_BYTEOFF
3460 /* The else case is already covered by the insert and delete */
3461 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3462#endif
3463 }
3464 else
3465 {
3466 /*
3467 * Cannot do it in one data block: Delete and append.
3468 * Append first, because ml_delete_int() cannot delete the
3469 * last line in a buffer, which causes trouble for a buffer
3470 * that has only one line.
3471 * Don't forget to copy the mark!
3472 */
3473 /* How about handling errors??? */
3474 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3475 (dp->db_index[idx] & DB_MARKED));
3476 (void)ml_delete_int(buf, lnum, FALSE);
3477 }
3478 }
3479 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003480
3481 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482 }
3483
3484 buf->b_ml.ml_line_lnum = 0;
3485}
3486
3487/*
3488 * create a new, empty, data block
3489 */
3490 static bhdr_T *
3491ml_new_data(mfp, negative, page_count)
3492 memfile_T *mfp;
3493 int negative;
3494 int page_count;
3495{
3496 bhdr_T *hp;
3497 DATA_BL *dp;
3498
3499 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3500 return NULL;
3501
3502 dp = (DATA_BL *)(hp->bh_data);
3503 dp->db_id = DATA_ID;
3504 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3505 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3506 dp->db_line_count = 0;
3507
3508 return hp;
3509}
3510
3511/*
3512 * create a new, empty, pointer block
3513 */
3514 static bhdr_T *
3515ml_new_ptr(mfp)
3516 memfile_T *mfp;
3517{
3518 bhdr_T *hp;
3519 PTR_BL *pp;
3520
3521 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3522 return NULL;
3523
3524 pp = (PTR_BL *)(hp->bh_data);
3525 pp->pb_id = PTR_ID;
3526 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003527 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3528 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529
3530 return hp;
3531}
3532
3533/*
3534 * lookup line 'lnum' in a memline
3535 *
3536 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3537 * if ML_FLUSH only flush a locked block
3538 * if ML_FIND just find the line
3539 *
3540 * If the block was found it is locked and put in ml_locked.
3541 * The stack is updated to lead to the locked block. The ip_high field in
3542 * the stack is updated to reflect the last line in the block AFTER the
3543 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003544 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 *
3546 * return: NULL for failure, pointer to block header otherwise
3547 */
3548 static bhdr_T *
3549ml_find_line(buf, lnum, action)
3550 buf_T *buf;
3551 linenr_T lnum;
3552 int action;
3553{
3554 DATA_BL *dp;
3555 PTR_BL *pp;
3556 infoptr_T *ip;
3557 bhdr_T *hp;
3558 memfile_T *mfp;
3559 linenr_T t;
3560 blocknr_T bnum, bnum2;
3561 int dirty;
3562 linenr_T low, high;
3563 int top;
3564 int page_count;
3565 int idx;
3566
3567 mfp = buf->b_ml.ml_mfp;
3568
3569 /*
3570 * If there is a locked block check if the wanted line is in it.
3571 * If not, flush and release the locked block.
3572 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3573 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003574 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 */
3576 if (buf->b_ml.ml_locked)
3577 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003578 if (ML_SIMPLE(action)
3579 && buf->b_ml.ml_locked_low <= lnum
3580 && buf->b_ml.ml_locked_high >= lnum
3581 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003583 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 if (action == ML_INSERT)
3585 {
3586 ++(buf->b_ml.ml_locked_lineadd);
3587 ++(buf->b_ml.ml_locked_high);
3588 }
3589 else if (action == ML_DELETE)
3590 {
3591 --(buf->b_ml.ml_locked_lineadd);
3592 --(buf->b_ml.ml_locked_high);
3593 }
3594 return (buf->b_ml.ml_locked);
3595 }
3596
3597 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3598 buf->b_ml.ml_flags & ML_LOCKED_POS);
3599 buf->b_ml.ml_locked = NULL;
3600
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003601 /*
3602 * If lines have been added or deleted in the locked block, need to
3603 * update the line count in pointer blocks.
3604 */
3605 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3607 }
3608
3609 if (action == ML_FLUSH) /* nothing else to do */
3610 return NULL;
3611
3612 bnum = 1; /* start at the root of the tree */
3613 page_count = 1;
3614 low = 1;
3615 high = buf->b_ml.ml_line_count;
3616
3617 if (action == ML_FIND) /* first try stack entries */
3618 {
3619 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3620 {
3621 ip = &(buf->b_ml.ml_stack[top]);
3622 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3623 {
3624 bnum = ip->ip_bnum;
3625 low = ip->ip_low;
3626 high = ip->ip_high;
3627 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3628 break;
3629 }
3630 }
3631 if (top < 0)
3632 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3633 }
3634 else /* ML_DELETE or ML_INSERT */
3635 buf->b_ml.ml_stack_top = 0; /* start at the root */
3636
3637/*
3638 * search downwards in the tree until a data block is found
3639 */
3640 for (;;)
3641 {
3642 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3643 goto error_noblock;
3644
3645 /*
3646 * update high for insert/delete
3647 */
3648 if (action == ML_INSERT)
3649 ++high;
3650 else if (action == ML_DELETE)
3651 --high;
3652
3653 dp = (DATA_BL *)(hp->bh_data);
3654 if (dp->db_id == DATA_ID) /* data block */
3655 {
3656 buf->b_ml.ml_locked = hp;
3657 buf->b_ml.ml_locked_low = low;
3658 buf->b_ml.ml_locked_high = high;
3659 buf->b_ml.ml_locked_lineadd = 0;
3660 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3661 return hp;
3662 }
3663
3664 pp = (PTR_BL *)(dp); /* must be pointer block */
3665 if (pp->pb_id != PTR_ID)
3666 {
3667 EMSG(_("E317: pointer block id wrong"));
3668 goto error_block;
3669 }
3670
3671 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3672 goto error_block;
3673 ip = &(buf->b_ml.ml_stack[top]);
3674 ip->ip_bnum = bnum;
3675 ip->ip_low = low;
3676 ip->ip_high = high;
3677 ip->ip_index = -1; /* index not known yet */
3678
3679 dirty = FALSE;
3680 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3681 {
3682 t = pp->pb_pointer[idx].pe_line_count;
3683 CHECK(t == 0, _("pe_line_count is zero"));
3684 if ((low += t) > lnum)
3685 {
3686 ip->ip_index = idx;
3687 bnum = pp->pb_pointer[idx].pe_bnum;
3688 page_count = pp->pb_pointer[idx].pe_page_count;
3689 high = low - 1;
3690 low -= t;
3691
3692 /*
3693 * a negative block number may have been changed
3694 */
3695 if (bnum < 0)
3696 {
3697 bnum2 = mf_trans_del(mfp, bnum);
3698 if (bnum != bnum2)
3699 {
3700 bnum = bnum2;
3701 pp->pb_pointer[idx].pe_bnum = bnum;
3702 dirty = TRUE;
3703 }
3704 }
3705
3706 break;
3707 }
3708 }
3709 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3710 {
3711 if (lnum > buf->b_ml.ml_line_count)
3712 EMSGN(_("E322: line number out of range: %ld past the end"),
3713 lnum - buf->b_ml.ml_line_count);
3714
3715 else
3716 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3717 goto error_block;
3718 }
3719 if (action == ML_DELETE)
3720 {
3721 pp->pb_pointer[idx].pe_line_count--;
3722 dirty = TRUE;
3723 }
3724 else if (action == ML_INSERT)
3725 {
3726 pp->pb_pointer[idx].pe_line_count++;
3727 dirty = TRUE;
3728 }
3729 mf_put(mfp, hp, dirty, FALSE);
3730 }
3731
3732error_block:
3733 mf_put(mfp, hp, FALSE, FALSE);
3734error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003735 /*
3736 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3737 * the incremented/decremented line counts, because there won't be a line
3738 * inserted/deleted after all.
3739 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 if (action == ML_DELETE)
3741 ml_lineadd(buf, 1);
3742 else if (action == ML_INSERT)
3743 ml_lineadd(buf, -1);
3744 buf->b_ml.ml_stack_top = 0;
3745 return NULL;
3746}
3747
3748/*
3749 * add an entry to the info pointer stack
3750 *
3751 * return -1 for failure, number of the new entry otherwise
3752 */
3753 static int
3754ml_add_stack(buf)
3755 buf_T *buf;
3756{
3757 int top;
3758 infoptr_T *newstack;
3759
3760 top = buf->b_ml.ml_stack_top;
3761
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003762 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763 if (top == buf->b_ml.ml_stack_size)
3764 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003765 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003766
3767 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3768 (buf->b_ml.ml_stack_size + STACK_INCR));
3769 if (newstack == NULL)
3770 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003771 mch_memmove(newstack, buf->b_ml.ml_stack,
3772 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 vim_free(buf->b_ml.ml_stack);
3774 buf->b_ml.ml_stack = newstack;
3775 buf->b_ml.ml_stack_size += STACK_INCR;
3776 }
3777
3778 buf->b_ml.ml_stack_top++;
3779 return top;
3780}
3781
3782/*
3783 * Update the pointer blocks on the stack for inserted/deleted lines.
3784 * The stack itself is also updated.
3785 *
3786 * When a insert/delete line action fails, the line is not inserted/deleted,
3787 * but the pointer blocks have already been updated. That is fixed here by
3788 * walking through the stack.
3789 *
3790 * Count is the number of lines added, negative if lines have been deleted.
3791 */
3792 static void
3793ml_lineadd(buf, count)
3794 buf_T *buf;
3795 int count;
3796{
3797 int idx;
3798 infoptr_T *ip;
3799 PTR_BL *pp;
3800 memfile_T *mfp = buf->b_ml.ml_mfp;
3801 bhdr_T *hp;
3802
3803 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3804 {
3805 ip = &(buf->b_ml.ml_stack[idx]);
3806 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3807 break;
3808 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3809 if (pp->pb_id != PTR_ID)
3810 {
3811 mf_put(mfp, hp, FALSE, FALSE);
3812 EMSG(_("E317: pointer block id wrong 2"));
3813 break;
3814 }
3815 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3816 ip->ip_high += count;
3817 mf_put(mfp, hp, TRUE, FALSE);
3818 }
3819}
3820
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003821#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003822/*
3823 * Resolve a symlink in the last component of a file name.
3824 * Note that f_resolve() does it for every part of the path, we don't do that
3825 * here.
3826 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3827 * Otherwise returns FAIL.
3828 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003829 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003830resolve_symlink(fname, buf)
3831 char_u *fname;
3832 char_u *buf;
3833{
3834 char_u tmp[MAXPATHL];
3835 int ret;
3836 int depth = 0;
3837
3838 if (fname == NULL)
3839 return FAIL;
3840
3841 /* Put the result so far in tmp[], starting with the original name. */
3842 vim_strncpy(tmp, fname, MAXPATHL - 1);
3843
3844 for (;;)
3845 {
3846 /* Limit symlink depth to 100, catch recursive loops. */
3847 if (++depth == 100)
3848 {
3849 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3850 return FAIL;
3851 }
3852
3853 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3854 if (ret <= 0)
3855 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003856 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003857 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003858 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003859 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003860 * call to vim_FullName(). */
3861 if (depth == 1)
3862 return FAIL;
3863
3864 /* Use the resolved name in tmp[]. */
3865 break;
3866 }
3867
3868 /* There must be some error reading links, use original name. */
3869 return FAIL;
3870 }
3871 buf[ret] = NUL;
3872
3873 /*
3874 * Check whether the symlink is relative or absolute.
3875 * If it's relative, build a new path based on the directory
3876 * portion of the filename (if any) and the path the symlink
3877 * points to.
3878 */
3879 if (mch_isFullName(buf))
3880 STRCPY(tmp, buf);
3881 else
3882 {
3883 char_u *tail;
3884
3885 tail = gettail(tmp);
3886 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3887 return FAIL;
3888 STRCPY(tail, buf);
3889 }
3890 }
3891
3892 /*
3893 * Try to resolve the full name of the file so that the swapfile name will
3894 * be consistent even when opening a relative symlink from different
3895 * working directories.
3896 */
3897 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3898}
3899#endif
3900
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003902 * Make swap file name out of the file name and a directory name.
3903 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003905 char_u *
3906makeswapname(fname, ffname, buf, dir_name)
3907 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003908 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 buf_T *buf;
3910 char_u *dir_name;
3911{
3912 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003913 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003914#ifdef HAVE_READLINK
3915 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003916#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917
3918#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3919 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003920 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 { /* Ends with '//', Use Full path */
3922 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003923 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 {
3925 r = modname(s, (char_u *)".swp", FALSE);
3926 vim_free(s);
3927 }
3928 return r;
3929 }
3930#endif
3931
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003932#ifdef HAVE_READLINK
3933 /* Expand symlink in the file name, so that we put the swap file with the
3934 * actual file instead of with the symlink. */
3935 if (resolve_symlink(fname, fname_buf) == OK)
3936 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003937#endif
3938
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 r = buf_modname(
3940#ifdef SHORT_FNAME
3941 TRUE,
3942#else
3943 (buf->b_p_sn || buf->b_shortname),
3944#endif
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003945 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 (char_u *)
Bram Moolenaare60acc12011-05-10 16:41:25 +02003947#if defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 "_swp",
3949#else
3950 ".swp",
3951#endif
3952#ifdef SHORT_FNAME /* always 8.3 file name */
3953 FALSE
3954#else
3955 /* Prepend a '.' to the swap file name for the current directory. */
3956 dir_name[0] == '.' && dir_name[1] == NUL
3957#endif
3958 );
3959 if (r == NULL) /* out of memory */
3960 return NULL;
3961
3962 s = get_file_in_dir(r, dir_name);
3963 vim_free(r);
3964 return s;
3965}
3966
3967/*
3968 * Get file name to use for swap file or backup file.
3969 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3970 * option "dname".
3971 * - If "dname" is ".", return "fname" (swap file in dir of file).
3972 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3973 * relative to dir of file).
3974 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
3975 * dir).
3976 *
3977 * The return value is an allocated string and can be NULL.
3978 */
3979 char_u *
3980get_file_in_dir(fname, dname)
3981 char_u *fname;
3982 char_u *dname; /* don't use "dirname", it is a global for Alpha */
3983{
3984 char_u *t;
3985 char_u *tail;
3986 char_u *retval;
3987 int save_char;
3988
3989 tail = gettail(fname);
3990
3991 if (dname[0] == '.' && dname[1] == NUL)
3992 retval = vim_strsave(fname);
3993 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
3994 {
3995 if (tail == fname) /* no path before file name */
3996 retval = concat_fnames(dname + 2, tail, TRUE);
3997 else
3998 {
3999 save_char = *tail;
4000 *tail = NUL;
4001 t = concat_fnames(fname, dname + 2, TRUE);
4002 *tail = save_char;
4003 if (t == NULL) /* out of memory */
4004 retval = NULL;
4005 else
4006 {
4007 retval = concat_fnames(t, tail, TRUE);
4008 vim_free(t);
4009 }
4010 }
4011 }
4012 else
4013 retval = concat_fnames(dname, tail, TRUE);
4014
4015 return retval;
4016}
4017
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004018static void attention_message __ARGS((buf_T *buf, char_u *fname));
4019
4020/*
4021 * Print the ATTENTION message: info about an existing swap file.
4022 */
4023 static void
4024attention_message(buf, fname)
4025 buf_T *buf; /* buffer being edited */
4026 char_u *fname; /* swap file name */
4027{
4028 struct stat st;
4029 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004030 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004031
4032 ++no_wait_return;
4033 (void)EMSG(_("E325: ATTENTION"));
4034 MSG_PUTS(_("\nFound a swap file by the name \""));
4035 msg_home_replace(fname);
4036 MSG_PUTS("\"\n");
4037 sx = swapfile_info(fname);
4038 MSG_PUTS(_("While opening file \""));
4039 msg_outtrans(buf->b_fname);
4040 MSG_PUTS("\"\n");
4041 if (mch_stat((char *)buf->b_fname, &st) != -1)
4042 {
4043 MSG_PUTS(_(" dated: "));
4044 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004045 p = ctime(&x); /* includes '\n' */
4046 if (p == NULL)
4047 MSG_PUTS("(invalid)\n");
4048 else
4049 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004050 if (sx != 0 && x > sx)
4051 MSG_PUTS(_(" NEWER than swap file!\n"));
4052 }
4053 /* Some of these messages are long to allow translation to
4054 * other languages. */
Bram Moolenaarc41fc712011-02-15 11:57:04 +01004055 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."));
4056 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4057 MSG_PUTS(_("(2) An edit session for this file crashed.\n"));
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004058 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4059 msg_outtrans(buf->b_fname);
4060 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4061 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4062 msg_outtrans(fname);
4063 MSG_PUTS(_("\"\n to avoid this message.\n"));
4064 cmdline_row = msg_row;
4065 --no_wait_return;
4066}
4067
4068#ifdef FEAT_AUTOCMD
4069static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4070
4071/*
4072 * Trigger the SwapExists autocommands.
4073 * Returns a value for equivalent to do_dialog() (see below):
4074 * 0: still need to ask for a choice
4075 * 1: open read-only
4076 * 2: edit anyway
4077 * 3: recover
4078 * 4: delete it
4079 * 5: quit
4080 * 6: abort
4081 */
4082 static int
4083do_swapexists(buf, fname)
4084 buf_T *buf;
4085 char_u *fname;
4086{
4087 set_vim_var_string(VV_SWAPNAME, fname, -1);
4088 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4089
4090 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004091 * edited. Disallow changing directory here. */
4092 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004093 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004094 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004095
4096 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4097
4098 switch (*get_vim_var_str(VV_SWAPCHOICE))
4099 {
4100 case 'o': return 1;
4101 case 'e': return 2;
4102 case 'r': return 3;
4103 case 'd': return 4;
4104 case 'q': return 5;
4105 case 'a': return 6;
4106 }
4107
4108 return 0;
4109}
4110#endif
4111
Bram Moolenaar071d4272004-06-13 20:20:40 +00004112/*
4113 * Find out what name to use for the swap file for buffer 'buf'.
4114 *
4115 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004116 * Returns the name in allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 *
4118 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004119 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004120 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 */
4122 static char_u *
4123findswapname(buf, dirp, old_fname)
4124 buf_T *buf;
4125 char_u **dirp; /* pointer to list of directories */
4126 char_u *old_fname; /* don't give warning for this file name */
4127{
4128 char_u *fname;
4129 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 char_u *dir_name;
4131#ifdef AMIGA
4132 BPTR fh;
4133#endif
4134#ifndef SHORT_FNAME
4135 int r;
4136#endif
4137
4138#if !defined(SHORT_FNAME) \
4139 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
4140# define CREATE_DUMMY_FILE
4141 FILE *dummyfd = NULL;
4142
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004143 /*
4144 * If we start editing a new file, e.g. "test.doc", which resides on an
4145 * MSDOS compatible filesystem, it is possible that the file
4146 * "test.doc.swp" which we create will be exactly the same file. To avoid
4147 * this problem we temporarily create "test.doc". Don't do this when the
4148 * check below for a 8.3 file name is used.
4149 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
4151 && mch_getperm(buf->b_fname) < 0)
4152 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4153#endif
4154
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004155 /*
4156 * Isolate a directory name from *dirp and put it in dir_name.
4157 * First allocate some memory to put the directory name in.
4158 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
4160 if (dir_name != NULL)
4161 (void)copy_option_part(dirp, dir_name, 31000, ",");
4162
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004163 /*
4164 * we try different names until we find one that does not exist yet
4165 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166 if (dir_name == NULL) /* out of memory */
4167 fname = NULL;
4168 else
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004169 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170
4171 for (;;)
4172 {
4173 if (fname == NULL) /* must be out of memory */
4174 break;
4175 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4176 {
4177 vim_free(fname);
4178 fname = NULL;
4179 break;
4180 }
4181#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4182/*
4183 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4184 * file names. If this is the first try and the swap file name does not fit in
4185 * 8.3, detect if this is the case, set shortname and try again.
4186 */
4187 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4188 && !(buf->b_p_sn || buf->b_shortname))
4189 {
4190 char_u *tail;
4191 char_u *fname2;
4192 struct stat s1, s2;
4193 int f1, f2;
4194 int created1 = FALSE, created2 = FALSE;
4195 int same = FALSE;
4196
4197 /*
4198 * Check if swapfile name does not fit in 8.3:
4199 * It either contains two dots, is longer than 8 chars, or starts
4200 * with a dot.
4201 */
4202 tail = gettail(buf->b_fname);
4203 if ( vim_strchr(tail, '.') != NULL
4204 || STRLEN(tail) > (size_t)8
4205 || *gettail(fname) == '.')
4206 {
4207 fname2 = alloc(n + 2);
4208 if (fname2 != NULL)
4209 {
4210 STRCPY(fname2, fname);
4211 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4212 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4213 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4214 */
4215 if (vim_strchr(tail, '.') != NULL)
4216 fname2[n - 1] = 'x';
4217 else if (*gettail(fname) == '.')
4218 {
4219 fname2[n] = 'x';
4220 fname2[n + 1] = NUL;
4221 }
4222 else
4223 fname2[n - 5] += 1;
4224 /*
4225 * may need to create the files to be able to use mch_stat()
4226 */
4227 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4228 if (f1 < 0)
4229 {
4230 f1 = mch_open_rw((char *)fname,
4231 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4232#if defined(OS2)
4233 if (f1 < 0 && errno == ENOENT)
4234 same = TRUE;
4235#endif
4236 created1 = TRUE;
4237 }
4238 if (f1 >= 0)
4239 {
4240 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4241 if (f2 < 0)
4242 {
4243 f2 = mch_open_rw((char *)fname2,
4244 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4245 created2 = TRUE;
4246 }
4247 if (f2 >= 0)
4248 {
4249 /*
4250 * Both files exist now. If mch_stat() returns the
4251 * same device and inode they are the same file.
4252 */
4253 if (mch_fstat(f1, &s1) != -1
4254 && mch_fstat(f2, &s2) != -1
4255 && s1.st_dev == s2.st_dev
4256 && s1.st_ino == s2.st_ino)
4257 same = TRUE;
4258 close(f2);
4259 if (created2)
4260 mch_remove(fname2);
4261 }
4262 close(f1);
4263 if (created1)
4264 mch_remove(fname);
4265 }
4266 vim_free(fname2);
4267 if (same)
4268 {
4269 buf->b_shortname = TRUE;
4270 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004271 fname = makeswapname(buf->b_fname, buf->b_ffname,
4272 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 continue; /* try again with b_shortname set */
4274 }
4275 }
4276 }
4277 }
4278#endif
4279 /*
4280 * check if the swapfile already exists
4281 */
4282 if (mch_getperm(fname) < 0) /* it does not exist */
4283 {
4284#ifdef HAVE_LSTAT
4285 struct stat sb;
4286
4287 /*
4288 * Extra security check: When a swap file is a symbolic link, this
4289 * is most likely a symlink attack.
4290 */
4291 if (mch_lstat((char *)fname, &sb) < 0)
4292#else
4293# ifdef AMIGA
4294 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4295 /*
4296 * on the Amiga mch_getperm() will return -1 when the file exists
4297 * but is being used by another program. This happens if you edit
4298 * a file twice.
4299 */
4300 if (fh != (BPTR)NULL) /* can open file, OK */
4301 {
4302 Close(fh);
4303 mch_remove(fname);
4304 break;
4305 }
4306 if (IoErr() != ERROR_OBJECT_IN_USE
4307 && IoErr() != ERROR_OBJECT_EXISTS)
4308# endif
4309#endif
4310 break;
4311 }
4312
4313 /*
4314 * A file name equal to old_fname is OK to use.
4315 */
4316 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4317 break;
4318
4319 /*
4320 * get here when file already exists
4321 */
4322 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4323 {
4324#ifndef SHORT_FNAME
4325 /*
4326 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4327 * and file.doc are the same file. To guess if this problem is
4328 * present try if file.doc.swx exists. If it does, we set
4329 * buf->b_shortname and try file_doc.swp (dots replaced by
4330 * underscores for this file), and try again. If it doesn't we
4331 * assume that "file.doc.swp" already exists.
4332 */
4333 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4334 {
4335 fname[n - 1] = 'x';
4336 r = mch_getperm(fname); /* try "file.swx" */
4337 fname[n - 1] = 'p';
4338 if (r >= 0) /* "file.swx" seems to exist */
4339 {
4340 buf->b_shortname = TRUE;
4341 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004342 fname = makeswapname(buf->b_fname, buf->b_ffname,
4343 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 continue; /* try again with '.' replaced with '_' */
4345 }
4346 }
4347#endif
4348 /*
4349 * If we get here the ".swp" file really exists.
4350 * Give an error message, unless recovering, no file name, we are
4351 * viewing a help file or when the path of the file is different
4352 * (happens when all .swp files are in one directory).
4353 */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004354 if (!recoverymode && buf->b_fname != NULL
4355 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356 {
4357 int fd;
4358 struct block0 b0;
4359 int differ = FALSE;
4360
4361 /*
4362 * Try to read block 0 from the swap file to get the original
4363 * file name (and inode number).
4364 */
4365 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4366 if (fd >= 0)
4367 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004368 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 {
4370 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004371 * If the swapfile has the same directory as the
4372 * buffer don't compare the directory names, they can
4373 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004375 if (b0.b0_flags & B0_SAME_DIR)
4376 {
4377 if (fnamecmp(gettail(buf->b_ffname),
4378 gettail(b0.b0_fname)) != 0
4379 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004380 {
4381#ifdef CHECK_INODE
4382 /* Symlinks may point to the same file even
4383 * when the name differs, need to check the
4384 * inode too. */
4385 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4386 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4387 char_to_long(b0.b0_ino)))
4388#endif
4389 differ = TRUE;
4390 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004391 }
4392 else
4393 {
4394 /*
4395 * The name in the swap file may be
4396 * "~user/path/file". Expand it first.
4397 */
4398 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004400 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004401 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004402 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004404 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4405 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004408 }
4409 close(fd);
4410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411
4412 /* give the ATTENTION message when there is an old swap file
4413 * for the current file, and the buffer was not recovered. */
4414 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4415 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4416 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004417#if defined(HAS_SWAP_EXISTS_ACTION)
4418 int choice = 0;
4419#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420#ifdef CREATE_DUMMY_FILE
4421 int did_use_dummy = FALSE;
4422
4423 /* Avoid getting a warning for the file being created
4424 * outside of Vim, it was created at the start of this
4425 * function. Delete the file now, because Vim might exit
4426 * here if the window is closed. */
4427 if (dummyfd != NULL)
4428 {
4429 fclose(dummyfd);
4430 dummyfd = NULL;
4431 mch_remove(buf->b_fname);
4432 did_use_dummy = TRUE;
4433 }
4434#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435
4436#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4437 process_still_running = FALSE;
4438#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004439#ifdef FEAT_AUTOCMD
4440 /*
4441 * If there is an SwapExists autocommand and we can handle
4442 * the response, trigger it. It may return 0 to ask the
4443 * user anyway.
4444 */
4445 if (swap_exists_action != SEA_NONE
4446 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4447 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004449 if (choice == 0)
4450#endif
4451 {
4452#ifdef FEAT_GUI
4453 /* If we are supposed to start the GUI but it wasn't
4454 * completely started yet, start it now. This makes
4455 * the messages displayed in the Vim window when
4456 * loading a session from the .gvimrc file. */
4457 if (gui.starting && !gui.in_use)
4458 gui_start();
4459#endif
4460 /* Show info about the existing swap file. */
4461 attention_message(buf, fname);
4462
4463 /* We don't want a 'q' typed at the more-prompt
4464 * interrupt loading a file. */
4465 got_int = FALSE;
4466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467
4468#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004469 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 {
4471 char_u *name;
4472
4473 name = alloc((unsigned)(STRLEN(fname)
4474 + STRLEN(_("Swap file \""))
4475 + STRLEN(_("\" already exists!")) + 5));
4476 if (name != NULL)
4477 {
4478 STRCPY(name, _("Swap file \""));
4479 home_replace(NULL, fname, name + STRLEN(name),
4480 1000, TRUE);
4481 STRCAT(name, _("\" already exists!"));
4482 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004483 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 (char_u *)_("VIM - ATTENTION"),
4485 name == NULL
4486 ? (char_u *)_("Swap file already exists!")
4487 : name,
4488# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4489 process_still_running
4490 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4491# endif
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004492 (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 +00004493
4494# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4495 if (process_still_running && choice >= 4)
4496 choice++; /* Skip missing "Delete it" button */
4497# endif
4498 vim_free(name);
4499
4500 /* pretend screen didn't scroll, need redraw anyway */
4501 msg_scrolled = 0;
4502 redraw_all_later(NOT_VALID);
4503 }
4504#endif
4505
4506#if defined(HAS_SWAP_EXISTS_ACTION)
4507 if (choice > 0)
4508 {
4509 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004510 {
4511 case 1:
4512 buf->b_p_ro = TRUE;
4513 break;
4514 case 2:
4515 break;
4516 case 3:
4517 swap_exists_action = SEA_RECOVER;
4518 break;
4519 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004520 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 break;
4522 case 5:
4523 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524 break;
4525 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004526 swap_exists_action = SEA_QUIT;
4527 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528 break;
4529 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530
4531 /* If the file was deleted this fname can be used. */
4532 if (mch_getperm(fname) < 0)
4533 break;
4534 }
4535 else
4536#endif
4537 {
4538 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004539 if (msg_silent == 0)
4540 /* call wait_return() later */
4541 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 }
4543
4544#ifdef CREATE_DUMMY_FILE
4545 /* Going to try another name, need the dummy file again. */
4546 if (did_use_dummy)
4547 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4548#endif
4549 }
4550 }
4551 }
4552
4553 /*
4554 * Change the ".swp" extension to find another file that can be used.
4555 * First decrement the last char: ".swo", ".swn", etc.
4556 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004557 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 */
4559 if (fname[n - 1] == 'a') /* ".s?a" */
4560 {
4561 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4562 {
4563 EMSG(_("E326: Too many swap files found"));
4564 vim_free(fname);
4565 fname = NULL;
4566 break;
4567 }
4568 --fname[n - 2]; /* ".svz", ".suz", etc. */
4569 fname[n - 1] = 'z' + 1;
4570 }
4571 --fname[n - 1]; /* ".swo", ".swn", etc. */
4572 }
4573
4574 vim_free(dir_name);
4575#ifdef CREATE_DUMMY_FILE
4576 if (dummyfd != NULL) /* file has been created temporarily */
4577 {
4578 fclose(dummyfd);
4579 mch_remove(buf->b_fname);
4580 }
4581#endif
4582 return fname;
4583}
4584
4585 static int
4586b0_magic_wrong(b0p)
4587 ZERO_BL *b0p;
4588{
4589 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4590 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4591 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4592 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4593}
4594
4595#ifdef CHECK_INODE
4596/*
4597 * Compare current file name with file name from swap file.
4598 * Try to use inode numbers when possible.
4599 * Return non-zero when files are different.
4600 *
4601 * When comparing file names a few things have to be taken into consideration:
4602 * - When working over a network the full path of a file depends on the host.
4603 * We check the inode number if possible. It is not 100% reliable though,
4604 * because the device number cannot be used over a network.
4605 * - When a file does not exist yet (editing a new file) there is no inode
4606 * number.
4607 * - The file name in a swap file may not be valid on the current host. The
4608 * "~user" form is used whenever possible to avoid this.
4609 *
4610 * This is getting complicated, let's make a table:
4611 *
4612 * ino_c ino_s fname_c fname_s differ =
4613 *
4614 * both files exist -> compare inode numbers:
4615 * != 0 != 0 X X ino_c != ino_s
4616 *
4617 * inode number(s) unknown, file names available -> compare file names
4618 * == 0 X OK OK fname_c != fname_s
4619 * X == 0 OK OK fname_c != fname_s
4620 *
4621 * current file doesn't exist, file for swap file exist, file name(s) not
4622 * available -> probably different
4623 * == 0 != 0 FAIL X TRUE
4624 * == 0 != 0 X FAIL TRUE
4625 *
4626 * current file exists, inode for swap unknown, file name(s) not
4627 * available -> probably different
4628 * != 0 == 0 FAIL X TRUE
4629 * != 0 == 0 X FAIL TRUE
4630 *
4631 * current file doesn't exist, inode for swap unknown, one file name not
4632 * available -> probably different
4633 * == 0 == 0 FAIL OK TRUE
4634 * == 0 == 0 OK FAIL TRUE
4635 *
4636 * current file doesn't exist, inode for swap unknown, both file names not
4637 * available -> probably same file
4638 * == 0 == 0 FAIL FAIL FALSE
4639 *
4640 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4641 * can't be changed without making the block 0 incompatible with 32 bit
4642 * versions.
4643 */
4644
4645 static int
4646fnamecmp_ino(fname_c, fname_s, ino_block0)
4647 char_u *fname_c; /* current file name */
4648 char_u *fname_s; /* file name from swap file */
4649 long ino_block0;
4650{
4651 struct stat st;
4652 ino_t ino_c = 0; /* ino of current file */
4653 ino_t ino_s; /* ino of file from swap file */
4654 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4655 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4656 int retval_c; /* flag: buf_c valid */
4657 int retval_s; /* flag: buf_s valid */
4658
4659 if (mch_stat((char *)fname_c, &st) == 0)
4660 ino_c = (ino_t)st.st_ino;
4661
4662 /*
4663 * First we try to get the inode from the file name, because the inode in
4664 * the swap file may be outdated. If that fails (e.g. this path is not
4665 * valid on this machine), use the inode from block 0.
4666 */
4667 if (mch_stat((char *)fname_s, &st) == 0)
4668 ino_s = (ino_t)st.st_ino;
4669 else
4670 ino_s = (ino_t)ino_block0;
4671
4672 if (ino_c && ino_s)
4673 return (ino_c != ino_s);
4674
4675 /*
4676 * One of the inode numbers is unknown, try a forced vim_FullName() and
4677 * compare the file names.
4678 */
4679 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4680 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4681 if (retval_c == OK && retval_s == OK)
4682 return (STRCMP(buf_c, buf_s) != 0);
4683
4684 /*
4685 * Can't compare inodes or file names, guess that the files are different,
4686 * unless both appear not to exist at all.
4687 */
4688 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4689 return FALSE;
4690 return TRUE;
4691}
4692#endif /* CHECK_INODE */
4693
4694/*
4695 * Move a long integer into a four byte character array.
4696 * Used for machine independency in block zero.
4697 */
4698 static void
4699long_to_char(n, s)
4700 long n;
4701 char_u *s;
4702{
4703 s[0] = (char_u)(n & 0xff);
4704 n = (unsigned)n >> 8;
4705 s[1] = (char_u)(n & 0xff);
4706 n = (unsigned)n >> 8;
4707 s[2] = (char_u)(n & 0xff);
4708 n = (unsigned)n >> 8;
4709 s[3] = (char_u)(n & 0xff);
4710}
4711
4712 static long
4713char_to_long(s)
4714 char_u *s;
4715{
4716 long retval;
4717
4718 retval = s[3];
4719 retval <<= 8;
4720 retval |= s[2];
4721 retval <<= 8;
4722 retval |= s[1];
4723 retval <<= 8;
4724 retval |= s[0];
4725
4726 return retval;
4727}
4728
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004729/*
4730 * Set the flags in the first block of the swap file:
4731 * - file is modified or not: buf->b_changed
4732 * - 'fileformat'
4733 * - 'fileencoding'
4734 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004736ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738{
4739 bhdr_T *hp;
4740 ZERO_BL *b0p;
4741
4742 if (!buf->b_ml.ml_mfp)
4743 return;
4744 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4745 {
4746 if (hp->bh_bnum == 0)
4747 {
4748 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004749 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4750 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4751 | (get_fileformat(buf) + 1);
4752#ifdef FEAT_MBYTE
4753 add_b0_fenc(b0p, buf);
4754#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 hp->bh_flags |= BH_DIRTY;
4756 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4757 break;
4758 }
4759 }
4760}
4761
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004762#if defined(FEAT_CRYPT) || defined(PROTO)
4763/*
4764 * If "data" points to a data block encrypt the text in it and return a copy
4765 * in allocated memory. Return NULL when out of memory.
4766 * Otherwise return "data".
4767 */
4768 char_u *
4769ml_encrypt_data(mfp, data, offset, size)
4770 memfile_T *mfp;
4771 char_u *data;
4772 off_t offset;
4773 unsigned size;
4774{
4775 DATA_BL *dp = (DATA_BL *)data;
4776 char_u *head_end;
4777 char_u *text_start;
4778 char_u *new_data;
4779 int text_len;
4780
4781 if (dp->db_id != DATA_ID)
4782 return data;
4783
4784 new_data = (char_u *)alloc(size);
4785 if (new_data == NULL)
4786 return NULL;
4787 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4788 text_start = (char_u *)dp + dp->db_txt_start;
4789 text_len = size - dp->db_txt_start;
4790
4791 /* Copy the header and the text. */
4792 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4793
4794 /* Encrypt the text. */
4795 crypt_push_state();
4796 ml_crypt_prepare(mfp, offset, FALSE);
4797 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4798 crypt_pop_state();
4799
4800 /* Clear the gap. */
4801 if (head_end < text_start)
4802 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4803
4804 return new_data;
4805}
4806
4807/*
4808 * Decrypt the text in "data" if it points to a data block.
4809 */
4810 void
4811ml_decrypt_data(mfp, data, offset, size)
4812 memfile_T *mfp;
4813 char_u *data;
4814 off_t offset;
4815 unsigned size;
4816{
4817 DATA_BL *dp = (DATA_BL *)data;
4818 char_u *head_end;
4819 char_u *text_start;
4820 int text_len;
4821
4822 if (dp->db_id == DATA_ID)
4823 {
4824 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4825 text_start = (char_u *)dp + dp->db_txt_start;
4826 text_len = dp->db_txt_end - dp->db_txt_start;
4827
4828 if (head_end > text_start || dp->db_txt_start > size
4829 || dp->db_txt_end > size)
4830 return; /* data was messed up */
4831
4832 /* Decrypt the text in place. */
4833 crypt_push_state();
4834 ml_crypt_prepare(mfp, offset, TRUE);
4835 crypt_decode(text_start, text_len);
4836 crypt_pop_state();
4837 }
4838}
4839
4840/*
4841 * Prepare for encryption/decryption, using the key, seed and offset.
4842 */
4843 static void
4844ml_crypt_prepare(mfp, offset, reading)
4845 memfile_T *mfp;
4846 off_t offset;
4847 int reading;
4848{
4849 buf_T *buf = mfp->mf_buffer;
4850 char_u salt[50];
4851 int method;
4852 char_u *key;
4853 char_u *seed;
4854
4855 if (reading && mfp->mf_old_key != NULL)
4856 {
4857 /* Reading back blocks with the previous key/method/seed. */
4858 method = mfp->mf_old_cm;
4859 key = mfp->mf_old_key;
4860 seed = mfp->mf_old_seed;
4861 }
4862 else
4863 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02004864 method = get_crypt_method(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004865 key = buf->b_p_key;
4866 seed = mfp->mf_seed;
4867 }
4868
4869 use_crypt_method = method; /* select pkzip or blowfish */
4870 if (method == 0)
4871 {
4872 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4873 crypt_init_keys(salt);
4874 }
4875 else
4876 {
4877 /* Using blowfish, add salt and seed. We use the byte offset of the
4878 * block for the salt. */
4879 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004880 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004881 bf_ofb_init(seed, MF_SEED_LEN);
4882 }
4883}
4884
4885#endif
4886
4887
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888#if defined(FEAT_BYTEOFF) || defined(PROTO)
4889
4890#define MLCS_MAXL 800 /* max no of lines in chunk */
4891#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4892
4893/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004894 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4896 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4897 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4898 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4899 */
4900 static void
4901ml_updatechunk(buf, line, len, updtype)
4902 buf_T *buf;
4903 linenr_T line;
4904 long len;
4905 int updtype;
4906{
4907 static buf_T *ml_upd_lastbuf = NULL;
4908 static linenr_T ml_upd_lastline;
4909 static linenr_T ml_upd_lastcurline;
4910 static int ml_upd_lastcurix;
4911
4912 linenr_T curline = ml_upd_lastcurline;
4913 int curix = ml_upd_lastcurix;
4914 long size;
4915 chunksize_T *curchnk;
4916 int rest;
4917 bhdr_T *hp;
4918 DATA_BL *dp;
4919
4920 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4921 return;
4922 if (buf->b_ml.ml_chunksize == NULL)
4923 {
4924 buf->b_ml.ml_chunksize = (chunksize_T *)
4925 alloc((unsigned)sizeof(chunksize_T) * 100);
4926 if (buf->b_ml.ml_chunksize == NULL)
4927 {
4928 buf->b_ml.ml_usedchunks = -1;
4929 return;
4930 }
4931 buf->b_ml.ml_numchunks = 100;
4932 buf->b_ml.ml_usedchunks = 1;
4933 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4934 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4935 }
4936
4937 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4938 {
4939 /*
4940 * First line in empty buffer from ml_flush_line() -- reset
4941 */
4942 buf->b_ml.ml_usedchunks = 1;
4943 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4944 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4945 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4946 return;
4947 }
4948
4949 /*
4950 * Find chunk that our line belongs to, curline will be at start of the
4951 * chunk.
4952 */
4953 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4954 || updtype != ML_CHNK_ADDLINE)
4955 {
4956 for (curline = 1, curix = 0;
4957 curix < buf->b_ml.ml_usedchunks - 1
4958 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4959 curix++)
4960 {
4961 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4962 }
4963 }
4964 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
4965 && curix < buf->b_ml.ml_usedchunks - 1)
4966 {
4967 /* Adjust cached curix & curline */
4968 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4969 curix++;
4970 }
4971 curchnk = buf->b_ml.ml_chunksize + curix;
4972
4973 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00004974 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 curchnk->mlcs_totalsize += len;
4976 if (updtype == ML_CHNK_ADDLINE)
4977 {
4978 curchnk->mlcs_numlines++;
4979
4980 /* May resize here so we don't have to do it in both cases below */
4981 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
4982 {
4983 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
4984 buf->b_ml.ml_chunksize = (chunksize_T *)
4985 vim_realloc(buf->b_ml.ml_chunksize,
4986 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
4987 if (buf->b_ml.ml_chunksize == NULL)
4988 {
4989 /* Hmmmm, Give up on offset for this buffer */
4990 buf->b_ml.ml_usedchunks = -1;
4991 return;
4992 }
4993 }
4994
4995 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
4996 {
4997 int count; /* number of entries in block */
4998 int idx;
4999 int text_end;
5000 int linecnt;
5001
5002 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5003 buf->b_ml.ml_chunksize + curix,
5004 (buf->b_ml.ml_usedchunks - curix) *
5005 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005006 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007 size = 0;
5008 linecnt = 0;
5009 while (curline < buf->b_ml.ml_line_count
5010 && linecnt < MLCS_MINL)
5011 {
5012 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5013 {
5014 buf->b_ml.ml_usedchunks = -1;
5015 return;
5016 }
5017 dp = (DATA_BL *)(hp->bh_data);
5018 count = (long)(buf->b_ml.ml_locked_high) -
5019 (long)(buf->b_ml.ml_locked_low) + 1;
5020 idx = curline - buf->b_ml.ml_locked_low;
5021 curline = buf->b_ml.ml_locked_high + 1;
5022 if (idx == 0)/* first line in block, text at the end */
5023 text_end = dp->db_txt_end;
5024 else
5025 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5026 /* Compute index of last line to use in this MEMLINE */
5027 rest = count - idx;
5028 if (linecnt + rest > MLCS_MINL)
5029 {
5030 idx += MLCS_MINL - linecnt - 1;
5031 linecnt = MLCS_MINL;
5032 }
5033 else
5034 {
5035 idx = count - 1;
5036 linecnt += rest;
5037 }
5038 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5039 }
5040 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5041 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5042 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5043 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5044 buf->b_ml.ml_usedchunks++;
5045 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5046 return;
5047 }
5048 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5049 && curix == buf->b_ml.ml_usedchunks - 1
5050 && buf->b_ml.ml_line_count - line <= 1)
5051 {
5052 /*
5053 * We are in the last chunk and it is cheap to crate a new one
5054 * after this. Do it now to avoid the loop above later on
5055 */
5056 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5057 buf->b_ml.ml_usedchunks++;
5058 if (line == buf->b_ml.ml_line_count)
5059 {
5060 curchnk->mlcs_numlines = 0;
5061 curchnk->mlcs_totalsize = 0;
5062 }
5063 else
5064 {
5065 /*
5066 * Line is just prior to last, move count for last
5067 * This is the common case when loading a new file
5068 */
5069 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5070 if (hp == NULL)
5071 {
5072 buf->b_ml.ml_usedchunks = -1;
5073 return;
5074 }
5075 dp = (DATA_BL *)(hp->bh_data);
5076 if (dp->db_line_count == 1)
5077 rest = dp->db_txt_end - dp->db_txt_start;
5078 else
5079 rest =
5080 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5081 - dp->db_txt_start;
5082 curchnk->mlcs_totalsize = rest;
5083 curchnk->mlcs_numlines = 1;
5084 curchnk[-1].mlcs_totalsize -= rest;
5085 curchnk[-1].mlcs_numlines -= 1;
5086 }
5087 }
5088 }
5089 else if (updtype == ML_CHNK_DELLINE)
5090 {
5091 curchnk->mlcs_numlines--;
5092 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5093 if (curix < (buf->b_ml.ml_usedchunks - 1)
5094 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5095 <= MLCS_MINL)
5096 {
5097 curix++;
5098 curchnk = buf->b_ml.ml_chunksize + curix;
5099 }
5100 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5101 {
5102 buf->b_ml.ml_usedchunks--;
5103 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5104 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5105 return;
5106 }
5107 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5108 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5109 > MLCS_MINL))
5110 {
5111 return;
5112 }
5113
5114 /* Collapse chunks */
5115 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5116 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5117 buf->b_ml.ml_usedchunks--;
5118 if (curix < buf->b_ml.ml_usedchunks)
5119 {
5120 mch_memmove(buf->b_ml.ml_chunksize + curix,
5121 buf->b_ml.ml_chunksize + curix + 1,
5122 (buf->b_ml.ml_usedchunks - curix) *
5123 sizeof(chunksize_T));
5124 }
5125 return;
5126 }
5127 ml_upd_lastbuf = buf;
5128 ml_upd_lastline = line;
5129 ml_upd_lastcurline = curline;
5130 ml_upd_lastcurix = curix;
5131}
5132
5133/*
5134 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005135 * Find line with offset if "lnum" is 0; return remaining offset in offp
5136 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005137 * return -1 if information is not available
5138 */
5139 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005140ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005142 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005143 long *offp;
5144{
5145 linenr_T curline;
5146 int curix;
5147 long size;
5148 bhdr_T *hp;
5149 DATA_BL *dp;
5150 int count; /* number of entries in block */
5151 int idx;
5152 int start_idx;
5153 int text_end;
5154 long offset;
5155 int len;
5156 int ffdos = (get_fileformat(buf) == EOL_DOS);
5157 int extra = 0;
5158
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005159 /* take care of cached line first */
5160 ml_flush_line(curbuf);
5161
Bram Moolenaar071d4272004-06-13 20:20:40 +00005162 if (buf->b_ml.ml_usedchunks == -1
5163 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005164 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165 return -1;
5166
5167 if (offp == NULL)
5168 offset = 0;
5169 else
5170 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005171 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5173 /*
5174 * Find the last chunk before the one containing our line. Last chunk is
5175 * special because it will never qualify
5176 */
5177 curline = 1;
5178 curix = size = 0;
5179 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005180 && ((lnum != 0
5181 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 || (offset != 0
5183 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5184 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5185 {
5186 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5187 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5188 if (offset && ffdos)
5189 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5190 curix++;
5191 }
5192
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005193 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194 {
5195 if (curline > buf->b_ml.ml_line_count
5196 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5197 return -1;
5198 dp = (DATA_BL *)(hp->bh_data);
5199 count = (long)(buf->b_ml.ml_locked_high) -
5200 (long)(buf->b_ml.ml_locked_low) + 1;
5201 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5202 if (idx == 0)/* first line in block, text at the end */
5203 text_end = dp->db_txt_end;
5204 else
5205 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5206 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005207 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005209 if (curline + (count - idx) >= lnum)
5210 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211 else
5212 idx = count - 1;
5213 }
5214 else
5215 {
5216 extra = 0;
5217 while (offset >= size
5218 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5219 + ffdos)
5220 {
5221 if (ffdos)
5222 size++;
5223 if (idx == count - 1)
5224 {
5225 extra = 1;
5226 break;
5227 }
5228 idx++;
5229 }
5230 }
5231 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5232 size += len;
5233 if (offset != 0 && size >= offset)
5234 {
5235 if (size + ffdos == offset)
5236 *offp = 0;
5237 else if (idx == start_idx)
5238 *offp = offset - size + len;
5239 else
5240 *offp = offset - size + len
5241 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5242 curline += idx - start_idx + extra;
5243 if (curline > buf->b_ml.ml_line_count)
5244 return -1; /* exactly one byte beyond the end */
5245 return curline;
5246 }
5247 curline = buf->b_ml.ml_locked_high + 1;
5248 }
5249
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005250 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005251 {
5252 /* Count extra CR characters. */
5253 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005254 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005255
5256 /* Don't count the last line break if 'bin' and 'noeol'. */
5257 if (buf->b_p_bin && !buf->b_p_eol)
5258 size -= ffdos + 1;
5259 }
5260
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 return size;
5262}
5263
5264/*
5265 * Goto byte in buffer with offset 'cnt'.
5266 */
5267 void
5268goto_byte(cnt)
5269 long cnt;
5270{
5271 long boff = cnt;
5272 linenr_T lnum;
5273
5274 ml_flush_line(curbuf); /* cached line may be dirty */
5275 setpcmark();
5276 if (boff)
5277 --boff;
5278 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5279 if (lnum < 1) /* past the end */
5280 {
5281 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5282 curwin->w_curswant = MAXCOL;
5283 coladvance((colnr_T)MAXCOL);
5284 }
5285 else
5286 {
5287 curwin->w_cursor.lnum = lnum;
5288 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005289# ifdef FEAT_VIRTUALEDIT
5290 curwin->w_cursor.coladd = 0;
5291# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005292 curwin->w_set_curswant = TRUE;
5293 }
5294 check_cursor();
5295
5296# ifdef FEAT_MBYTE
5297 /* Make sure the cursor is on the first byte of a multi-byte char. */
5298 if (has_mbyte)
5299 mb_adjust_cursor();
5300# endif
5301}
5302#endif