blob: e4e5bad35c60857422f398fc274a25af472503a3 [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 Moolenaarc236c162008-07-13 17:41:49 +000045#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
Bram Moolenaar8c8de832008-06-24 22:58:06 +000046# include "vimio.h" /* for mch_open(), must be before vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#endif
48
49#include "vim.h"
50
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#ifndef UNIX /* it's in os_unix.h for Unix */
52# include <time.h>
53#endif
54
Bram Moolenaar5a6404c2006-11-01 17:12:57 +000055#if defined(SASC) || defined(__amigaos4__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000056# include <proto/dos.h> /* for Open() and Close() */
57#endif
58
Bram Moolenaar5a6404c2006-11-01 17:12:57 +000059#ifdef HAVE_ERRNO_H
60# include <errno.h>
61#endif
62
Bram Moolenaar071d4272004-06-13 20:20:40 +000063typedef struct block0 ZERO_BL; /* contents of the first block */
64typedef struct pointer_block PTR_BL; /* contents of a pointer block */
65typedef struct data_block DATA_BL; /* contents of a data block */
66typedef struct pointer_entry PTR_EN; /* block/line-count pair */
67
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020068#define DATA_ID (('d' << 8) + 'a') /* data block id */
69#define PTR_ID (('p' << 8) + 't') /* pointer block id */
70#define BLOCK0_ID0 'b' /* block 0 id 0 */
71#define BLOCK0_ID1 '0' /* block 0 id 1 */
72#define BLOCK0_ID1_C0 'c' /* block 0 id 1 'cm' 0 */
73#define BLOCK0_ID1_C1 'C' /* block 0 id 1 'cm' 1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000074
75/*
76 * pointer to a block, used in a pointer block
77 */
78struct pointer_entry
79{
80 blocknr_T pe_bnum; /* block number */
81 linenr_T pe_line_count; /* number of lines in this branch */
82 linenr_T pe_old_lnum; /* lnum for this block (for recovery) */
83 int pe_page_count; /* number of pages in block pe_bnum */
84};
85
86/*
87 * A pointer block contains a list of branches in the tree.
88 */
89struct pointer_block
90{
91 short_u pb_id; /* ID for pointer block: PTR_ID */
Bram Moolenaar20a825a2010-05-31 21:27:30 +020092 short_u pb_count; /* number of pointers in this block */
Bram Moolenaar071d4272004-06-13 20:20:40 +000093 short_u pb_count_max; /* maximum value for pb_count */
94 PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer)
95 * followed by empty space until end of page */
96};
97
98/*
99 * A data block is a leaf in the tree.
100 *
101 * The text of the lines is at the end of the block. The text of the first line
102 * in the block is put at the end, the text of the second line in front of it,
103 * etc. Thus the order of the lines is the opposite of the line number.
104 */
105struct data_block
106{
107 short_u db_id; /* ID for data block: DATA_ID */
108 unsigned db_free; /* free space available */
109 unsigned db_txt_start; /* byte where text starts */
110 unsigned db_txt_end; /* byte just after data block */
111 linenr_T db_line_count; /* number of lines in this block */
112 unsigned db_index[1]; /* index for start of line (actually bigger)
113 * followed by empty space upto db_txt_start
114 * followed by the text in the lines until
115 * end of page */
116};
117
118/*
119 * The low bits of db_index hold the actual index. The topmost bit is
120 * used for the global command to be able to mark a line.
121 * This method is not clean, but otherwise there would be at least one extra
122 * byte used for each line.
123 * The mark has to be in this place to keep it with the correct line when other
124 * lines are inserted or deleted.
125 */
126#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
127#define DB_INDEX_MASK (~DB_MARKED)
128
129#define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */
130#define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */
131
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000132#define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200133#define B0_FNAME_SIZE_NOCRYPT 898 /* 2 bytes used for other things */
134#define B0_FNAME_SIZE_CRYPT 890 /* 10 bytes used for other things */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000135#define B0_UNAME_SIZE 40
136#define B0_HNAME_SIZE 40
Bram Moolenaar071d4272004-06-13 20:20:40 +0000137/*
138 * Restrict the numbers to 32 bits, otherwise most compilers will complain.
139 * This won't detect a 64 bit machine that only swaps a byte in the top 32
140 * bits, but that is crazy anyway.
141 */
142#define B0_MAGIC_LONG 0x30313233L
143#define B0_MAGIC_INT 0x20212223L
144#define B0_MAGIC_SHORT 0x10111213L
145#define B0_MAGIC_CHAR 0x55
146
147/*
148 * Block zero holds all info about the swap file.
149 *
150 * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
151 * swap files unusable!
152 *
153 * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
154 *
Bram Moolenaarbae0c162007-05-10 19:30:25 +0000155 * This block is built up of single bytes, to make it portable across
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156 * different machines. b0_magic_* is used to check the byte order and size of
157 * variables, because the rest of the swap file is not portable.
158 */
159struct block0
160{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200161 char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1,
162 * BLOCK0_ID1_C0, BLOCK0_ID1_C1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163 char_u b0_version[10]; /* Vim version string */
164 char_u b0_page_size[4];/* number of bytes per page */
165 char_u b0_mtime[4]; /* last modification time of file */
166 char_u b0_ino[4]; /* inode of b0_fname */
167 char_u b0_pid[4]; /* process id of creator (or 0) */
168 char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */
169 char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000170 char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171 long b0_magic_long; /* check for byte order of long */
172 int b0_magic_int; /* check for byte order of int */
173 short b0_magic_short; /* check for byte order of short */
174 char_u b0_magic_char; /* check for last char */
175};
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000176
177/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000178 * Note: b0_dirty and b0_flags are put at the end of the file name. For very
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000179 * long file names in older versions of Vim they are invalid.
180 * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
181 * when there is room, for very long file names it's omitted.
182 */
183#define B0_DIRTY 0x55
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200184#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000185
186/*
187 * The b0_flags field is new in Vim 7.0.
188 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200189#define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2]
190
191/*
192 * Crypt seed goes here, 8 bytes. New in Vim 7.3.
193 * Without encryption these bytes may be used for 'fenc'.
194 */
195#define b0_seed b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000196
197/* The lowest two bits contain the fileformat. Zero means it's not set
198 * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
199 * EOL_MAC + 1. */
200#define B0_FF_MASK 3
201
202/* Swap file is in directory of edited file. Used to find the file from
203 * different mount points. */
204#define B0_SAME_DIR 4
205
206/* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
207 * When empty there is only the NUL. */
208#define B0_HAS_FENC 8
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209
210#define STACK_INCR 5 /* nr of entries added to ml_stack at a time */
211
212/*
213 * The line number where the first mark may be is remembered.
214 * If it is 0 there are no marks at all.
215 * (always used for the current buffer only, no buffer change possible while
216 * executing a global command).
217 */
218static linenr_T lowest_marked = 0;
219
220/*
221 * arguments for ml_find_line()
222 */
223#define ML_DELETE 0x11 /* delete line */
224#define ML_INSERT 0x12 /* insert line */
225#define ML_FIND 0x13 /* just find the line */
226#define ML_FLUSH 0x02 /* flush locked block */
227#define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */
228
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200229/* argument for ml_upd_block0() */
230typedef enum {
231 UB_FNAME = 0 /* update timestamp and filename */
232 , UB_SAME_DIR /* update the B0_SAME_DIR flag */
233 , UB_CRYPT /* update crypt key */
234} upd_block0_T;
235
236#ifdef FEAT_CRYPT
237static void ml_set_b0_crypt __ARGS((buf_T *buf, ZERO_BL *b0p));
238#endif
239static int ml_check_b0_id __ARGS((ZERO_BL *b0p));
240static void ml_upd_block0 __ARGS((buf_T *buf, upd_block0_T what));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241static void set_b0_fname __ARGS((ZERO_BL *, buf_T *buf));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000242static void set_b0_dir_flag __ARGS((ZERO_BL *b0p, buf_T *buf));
243#ifdef FEAT_MBYTE
244static void add_b0_fenc __ARGS((ZERO_BL *b0p, buf_T *buf));
245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246static time_t swapfile_info __ARGS((char_u *));
247static int recov_file_names __ARGS((char_u **, char_u *, int prepend_dot));
248static int ml_append_int __ARGS((buf_T *, linenr_T, char_u *, colnr_T, int, int));
249static int ml_delete_int __ARGS((buf_T *, linenr_T, int));
250static char_u *findswapname __ARGS((buf_T *, char_u **, char_u *));
251static void ml_flush_line __ARGS((buf_T *));
252static bhdr_T *ml_new_data __ARGS((memfile_T *, int, int));
253static bhdr_T *ml_new_ptr __ARGS((memfile_T *));
254static bhdr_T *ml_find_line __ARGS((buf_T *, linenr_T, int));
255static int ml_add_stack __ARGS((buf_T *));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256static void ml_lineadd __ARGS((buf_T *, int));
257static int b0_magic_wrong __ARGS((ZERO_BL *));
258#ifdef CHECK_INODE
259static int fnamecmp_ino __ARGS((char_u *, char_u *, long));
260#endif
261static void long_to_char __ARGS((long, char_u *));
262static long char_to_long __ARGS((char_u *));
263#if defined(UNIX) || defined(WIN3264)
264static char_u *make_percent_swname __ARGS((char_u *dir, char_u *name));
265#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200266#ifdef FEAT_CRYPT
267static void ml_crypt_prepare __ARGS((memfile_T *mfp, off_t offset, int reading));
268#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000269#ifdef FEAT_BYTEOFF
270static void ml_updatechunk __ARGS((buf_T *buf, long line, long len, int updtype));
271#endif
272
273/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000274 * Open a new memline for "buf".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275 *
Bram Moolenaar4770d092006-01-12 23:22:24 +0000276 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277 */
278 int
Bram Moolenaar4770d092006-01-12 23:22:24 +0000279ml_open(buf)
280 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000281{
282 memfile_T *mfp;
283 bhdr_T *hp = NULL;
284 ZERO_BL *b0p;
285 PTR_BL *pp;
286 DATA_BL *dp;
287
Bram Moolenaar4770d092006-01-12 23:22:24 +0000288 /*
289 * init fields in memline struct
290 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200291 buf->b_ml.ml_stack_size = 0; /* no stack yet */
Bram Moolenaar4770d092006-01-12 23:22:24 +0000292 buf->b_ml.ml_stack = NULL; /* no stack yet */
293 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
294 buf->b_ml.ml_locked = NULL; /* no cached block */
295 buf->b_ml.ml_line_lnum = 0; /* no cached line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000296#ifdef FEAT_BYTEOFF
Bram Moolenaar4770d092006-01-12 23:22:24 +0000297 buf->b_ml.ml_chunksize = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298#endif
299
Bram Moolenaar4770d092006-01-12 23:22:24 +0000300 /*
301 * When 'updatecount' is non-zero swap file may be opened later.
302 */
303 if (p_uc && buf->b_p_swf)
304 buf->b_may_swap = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000305 else
Bram Moolenaar4770d092006-01-12 23:22:24 +0000306 buf->b_may_swap = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307
Bram Moolenaar4770d092006-01-12 23:22:24 +0000308 /*
309 * Open the memfile. No swap file is created yet.
310 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311 mfp = mf_open(NULL, 0);
312 if (mfp == NULL)
313 goto error;
314
Bram Moolenaar4770d092006-01-12 23:22:24 +0000315 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200316#ifdef FEAT_CRYPT
317 mfp->mf_buffer = buf;
318#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000319 buf->b_ml.ml_flags = ML_EMPTY;
320 buf->b_ml.ml_line_count = 1;
Bram Moolenaar592e0a22004-07-03 16:05:59 +0000321#ifdef FEAT_LINEBREAK
322 curwin->w_nrwidth_line_count = 0;
323#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324
325#if defined(MSDOS) && !defined(DJGPP)
326 /* for 16 bit MS-DOS create a swapfile now, because we run out of
327 * memory very quickly */
328 if (p_uc != 0)
Bram Moolenaar4770d092006-01-12 23:22:24 +0000329 ml_open_file(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000330#endif
331
332/*
333 * fill block0 struct and write page 0
334 */
335 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
336 goto error;
337 if (hp->bh_bnum != 0)
338 {
339 EMSG(_("E298: Didn't get block nr 0?"));
340 goto error;
341 }
342 b0p = (ZERO_BL *)(hp->bh_data);
343
344 b0p->b0_id[0] = BLOCK0_ID0;
345 b0p->b0_id[1] = BLOCK0_ID1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 b0p->b0_magic_long = (long)B0_MAGIC_LONG;
347 b0p->b0_magic_int = (int)B0_MAGIC_INT;
348 b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
349 b0p->b0_magic_char = B0_MAGIC_CHAR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 STRNCPY(b0p->b0_version, "VIM ", 4);
351 STRNCPY(b0p->b0_version + 4, Version, 6);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000352 long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000353
Bram Moolenaar76b92b22006-03-24 22:46:53 +0000354#ifdef FEAT_SPELL
355 if (!buf->b_spell)
356#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000357 {
358 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
359 b0p->b0_flags = get_fileformat(buf) + 1;
360 set_b0_fname(b0p, buf);
361 (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
362 b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
363 mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
364 b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
365 long_to_char(mch_get_pid(), b0p->b0_pid);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200366#ifdef FEAT_CRYPT
367 if (*buf->b_p_key != NUL)
368 ml_set_b0_crypt(buf, b0p);
369#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371
372 /*
373 * Always sync block number 0 to disk, so we can check the file name in
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200374 * the swap file in findswapname(). Don't do this for a help files or
375 * a spell buffer though.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 * Only works when there's a swapfile, otherwise it's done when the file
377 * is created.
378 */
379 mf_put(mfp, hp, TRUE, FALSE);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000380 if (!buf->b_help && !B_SPELL(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 (void)mf_sync(mfp, 0);
382
Bram Moolenaar4770d092006-01-12 23:22:24 +0000383 /*
384 * Fill in root pointer block and write page 1.
385 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386 if ((hp = ml_new_ptr(mfp)) == NULL)
387 goto error;
388 if (hp->bh_bnum != 1)
389 {
390 EMSG(_("E298: Didn't get block nr 1?"));
391 goto error;
392 }
393 pp = (PTR_BL *)(hp->bh_data);
394 pp->pb_count = 1;
395 pp->pb_pointer[0].pe_bnum = 2;
396 pp->pb_pointer[0].pe_page_count = 1;
397 pp->pb_pointer[0].pe_old_lnum = 1;
398 pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */
399 mf_put(mfp, hp, TRUE, FALSE);
400
Bram Moolenaar4770d092006-01-12 23:22:24 +0000401 /*
402 * Allocate first data block and create an empty line 1.
403 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
405 goto error;
406 if (hp->bh_bnum != 2)
407 {
408 EMSG(_("E298: Didn't get block nr 2?"));
409 goto error;
410 }
411
412 dp = (DATA_BL *)(hp->bh_data);
413 dp->db_index[0] = --dp->db_txt_start; /* at end of block */
414 dp->db_free -= 1 + INDEX_SIZE;
415 dp->db_line_count = 1;
Bram Moolenaarf05da212009-11-17 16:13:15 +0000416 *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417
418 return OK;
419
420error:
421 if (mfp != NULL)
422 {
423 if (hp)
424 mf_put(mfp, hp, FALSE, FALSE);
425 mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */
426 }
Bram Moolenaar4770d092006-01-12 23:22:24 +0000427 buf->b_ml.ml_mfp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 return FAIL;
429}
430
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200431#if defined(FEAT_CRYPT) || defined(PROTO)
432/*
433 * Prepare encryption for "buf" with block 0 "b0p".
434 */
435 static void
436ml_set_b0_crypt(buf, b0p)
437 buf_T *buf;
438 ZERO_BL *b0p;
439{
440 if (*buf->b_p_key == NUL)
441 b0p->b0_id[1] = BLOCK0_ID1;
442 else
443 {
Bram Moolenaar49771f42010-07-20 17:32:38 +0200444 if (get_crypt_method(buf) == 0)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200445 b0p->b0_id[1] = BLOCK0_ID1_C0;
446 else
447 {
448 b0p->b0_id[1] = BLOCK0_ID1_C1;
449 /* Generate a seed and store it in block 0 and in the memfile. */
450 sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0);
451 mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
452 }
453 }
454}
455
456/*
457 * Called after the crypt key or 'cryptmethod' was changed for "buf".
458 * Will apply this to the swapfile.
459 * "old_key" is the previous key. It is equal to buf->b_p_key when
460 * 'cryptmethod' is changed.
Bram Moolenaar49771f42010-07-20 17:32:38 +0200461 * "old_cm" is the previous 'cryptmethod'. It is equal to the current
462 * 'cryptmethod' when 'key' is changed.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200463 */
464 void
465ml_set_crypt_key(buf, old_key, old_cm)
466 buf_T *buf;
467 char_u *old_key;
468 int old_cm;
469{
470 memfile_T *mfp = buf->b_ml.ml_mfp;
471 bhdr_T *hp;
472 int page_count;
473 int idx;
474 long error;
475 infoptr_T *ip;
476 PTR_BL *pp;
477 DATA_BL *dp;
478 blocknr_T bnum;
479 int top;
480
Bram Moolenaar3832c462010-08-04 15:32:46 +0200481 if (mfp == NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200482 return; /* no memfile yet, nothing to do */
483
484 /* Set the key, method and seed to be used for reading, these must be the
485 * old values. */
486 mfp->mf_old_key = old_key;
487 mfp->mf_old_cm = old_cm;
488 if (old_cm > 0)
489 mch_memmove(mfp->mf_old_seed, mfp->mf_seed, MF_SEED_LEN);
490
491 /* Update block 0 with the crypt flag and may set a new seed. */
492 ml_upd_block0(buf, UB_CRYPT);
493
494 if (mfp->mf_infile_count > 2)
495 {
496 /*
497 * Need to read back all data blocks from disk, decrypt them with the
498 * old key/method and mark them to be written. The algorithm is
499 * similar to what happens in ml_recover(), but we skip negative block
500 * numbers.
501 */
502 ml_flush_line(buf); /* flush buffered line */
503 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
504
505 hp = NULL;
506 bnum = 1; /* start with block 1 */
507 page_count = 1; /* which is 1 page */
508 idx = 0; /* start with first index in block 1 */
509 error = 0;
510 buf->b_ml.ml_stack_top = 0;
Bram Moolenaare242b832010-06-24 05:39:03 +0200511 vim_free(buf->b_ml.ml_stack);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200512 buf->b_ml.ml_stack = NULL;
513 buf->b_ml.ml_stack_size = 0; /* no stack yet */
514
515 for ( ; !got_int; line_breakcheck())
516 {
517 if (hp != NULL)
518 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
519
520 /* get the block (pointer or data) */
521 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
522 {
523 if (bnum == 1)
524 break;
525 ++error;
526 }
527 else
528 {
529 pp = (PTR_BL *)(hp->bh_data);
530 if (pp->pb_id == PTR_ID) /* it is a pointer block */
531 {
532 if (pp->pb_count == 0)
533 {
534 /* empty block? */
535 ++error;
536 }
537 else if (idx < (int)pp->pb_count) /* go a block deeper */
538 {
539 if (pp->pb_pointer[idx].pe_bnum < 0)
540 {
541 /* Skip data block with negative block number. */
542 ++idx; /* get same block again for next index */
543 continue;
544 }
545
546 /* going one block deeper in the tree, new entry in
547 * stack */
548 if ((top = ml_add_stack(buf)) < 0)
549 {
550 ++error;
551 break; /* out of memory */
552 }
553 ip = &(buf->b_ml.ml_stack[top]);
554 ip->ip_bnum = bnum;
555 ip->ip_index = idx;
556
557 bnum = pp->pb_pointer[idx].pe_bnum;
558 page_count = pp->pb_pointer[idx].pe_page_count;
559 continue;
560 }
561 }
562 else /* not a pointer block */
563 {
564 dp = (DATA_BL *)(hp->bh_data);
565 if (dp->db_id != DATA_ID) /* block id wrong */
566 ++error;
567 else
568 {
569 /* It is a data block, need to write it back to disk. */
570 mf_put(mfp, hp, TRUE, FALSE);
571 hp = NULL;
572 }
573 }
574 }
575
576 if (buf->b_ml.ml_stack_top == 0) /* finished */
577 break;
578
579 /* go one block up in the tree */
580 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
581 bnum = ip->ip_bnum;
582 idx = ip->ip_index + 1; /* go to next index */
583 page_count = 1;
584 }
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +0100585
586 if (error > 0)
587 EMSG(_("E843: Error while updating swap file crypt"));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200588 }
589
590 mfp->mf_old_key = NULL;
591}
592#endif
593
Bram Moolenaar071d4272004-06-13 20:20:40 +0000594/*
595 * ml_setname() is called when the file name of "buf" has been changed.
596 * It may rename the swap file.
597 */
598 void
599ml_setname(buf)
600 buf_T *buf;
601{
602 int success = FALSE;
603 memfile_T *mfp;
604 char_u *fname;
605 char_u *dirp;
606#if defined(MSDOS) || defined(MSWIN)
607 char_u *p;
608#endif
609
610 mfp = buf->b_ml.ml_mfp;
611 if (mfp->mf_fd < 0) /* there is no swap file yet */
612 {
613 /*
614 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
615 * For help files we will make a swap file now.
616 */
617 if (p_uc != 0)
618 ml_open_file(buf); /* create a swap file */
619 return;
620 }
621
622 /*
623 * Try all directories in the 'directory' option.
624 */
625 dirp = p_dir;
626 for (;;)
627 {
628 if (*dirp == NUL) /* tried all directories, fail */
629 break;
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000630 fname = findswapname(buf, &dirp, mfp->mf_fname);
631 /* alloc's fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 if (fname == NULL) /* no file name found for this dir */
633 continue;
634
635#if defined(MSDOS) || defined(MSWIN)
636 /*
637 * Set full pathname for swap file now, because a ":!cd dir" may
638 * change directory without us knowing it.
639 */
640 p = FullName_save(fname, FALSE);
641 vim_free(fname);
642 fname = p;
643 if (fname == NULL)
644 continue;
645#endif
646 /* if the file name is the same we don't have to do anything */
647 if (fnamecmp(fname, mfp->mf_fname) == 0)
648 {
649 vim_free(fname);
650 success = TRUE;
651 break;
652 }
653 /* need to close the swap file before renaming */
654 if (mfp->mf_fd >= 0)
655 {
656 close(mfp->mf_fd);
657 mfp->mf_fd = -1;
658 }
659
660 /* try to rename the swap file */
661 if (vim_rename(mfp->mf_fname, fname) == 0)
662 {
663 success = TRUE;
664 vim_free(mfp->mf_fname);
665 mfp->mf_fname = fname;
666 vim_free(mfp->mf_ffname);
667#if defined(MSDOS) || defined(MSWIN)
668 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
669#else
670 mf_set_ffname(mfp);
671#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200672 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673 break;
674 }
675 vim_free(fname); /* this fname didn't work, try another */
676 }
677
678 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
679 {
680 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
681 if (mfp->mf_fd < 0)
682 {
683 /* could not (re)open the swap file, what can we do???? */
684 EMSG(_("E301: Oops, lost the swap file!!!"));
685 return;
686 }
Bram Moolenaarf05da212009-11-17 16:13:15 +0000687#ifdef HAVE_FD_CLOEXEC
688 {
689 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
690 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
691 fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
692 }
693#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 }
695 if (!success)
696 EMSG(_("E302: Could not rename swap file"));
697}
698
699/*
700 * Open a file for the memfile for all buffers that are not readonly or have
701 * been modified.
702 * Used when 'updatecount' changes from zero to non-zero.
703 */
704 void
705ml_open_files()
706{
707 buf_T *buf;
708
709 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
710 if (!buf->b_p_ro || buf->b_changed)
711 ml_open_file(buf);
712}
713
714/*
715 * Open a swap file for an existing memfile, if there is no swap file yet.
716 * If we are unable to find a file name, mf_fname will be NULL
717 * and the memfile will be in memory only (no recovery possible).
718 */
719 void
720ml_open_file(buf)
721 buf_T *buf;
722{
723 memfile_T *mfp;
724 char_u *fname;
725 char_u *dirp;
726
727 mfp = buf->b_ml.ml_mfp;
728 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf)
729 return; /* nothing to do */
730
Bram Moolenaara1956f62006-03-12 22:18:00 +0000731#ifdef FEAT_SPELL
Bram Moolenaar4770d092006-01-12 23:22:24 +0000732 /* For a spell buffer use a temp file name. */
733 if (buf->b_spell)
734 {
735 fname = vim_tempname('s');
736 if (fname != NULL)
737 (void)mf_open_file(mfp, fname); /* consumes fname! */
738 buf->b_may_swap = FALSE;
739 return;
740 }
741#endif
742
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 /*
744 * Try all directories in 'directory' option.
745 */
746 dirp = p_dir;
747 for (;;)
748 {
749 if (*dirp == NUL)
750 break;
Bram Moolenaare242b832010-06-24 05:39:03 +0200751 /* There is a small chance that between choosing the swap file name
752 * and creating it, another Vim creates the file. In that case the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753 * creation will fail and we will use another directory. */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000754 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 if (fname == NULL)
756 continue;
757 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
758 {
759#if defined(MSDOS) || defined(MSWIN) || defined(RISCOS)
760 /*
761 * set full pathname for swap file now, because a ":!cd dir" may
762 * change directory without us knowing it.
763 */
764 mf_fullname(mfp);
765#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200766 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000767
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768 /* Flush block zero, so others can read it */
769 if (mf_sync(mfp, MFS_ZERO) == OK)
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000770 {
771 /* Mark all blocks that should be in the swapfile as dirty.
772 * Needed for when the 'swapfile' option was reset, so that
773 * the swap file was deleted, and then on again. */
774 mf_set_dirty(mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 break;
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 /* Writing block 0 failed: close the file and try another dir */
778 mf_close_file(buf, FALSE);
779 }
780 }
781
782 if (mfp->mf_fname == NULL) /* Failed! */
783 {
784 need_wait_return = TRUE; /* call wait_return later */
785 ++no_wait_return;
786 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
787 buf_spname(buf) != NULL
788 ? (char_u *)buf_spname(buf)
789 : buf->b_fname);
790 --no_wait_return;
791 }
792
793 /* don't try to open a swap file again */
794 buf->b_may_swap = FALSE;
795}
796
797/*
798 * If still need to create a swap file, and starting to edit a not-readonly
799 * file, or reading into an existing buffer, create a swap file now.
800 */
801 void
802check_need_swap(newfile)
803 int newfile; /* reading file into new buffer */
804{
805 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
806 ml_open_file(curbuf);
807}
808
809/*
810 * Close memline for buffer 'buf'.
811 * If 'del_file' is TRUE, delete the swap file
812 */
813 void
814ml_close(buf, del_file)
815 buf_T *buf;
816 int del_file;
817{
818 if (buf->b_ml.ml_mfp == NULL) /* not open */
819 return;
820 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
821 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
822 vim_free(buf->b_ml.ml_line_ptr);
823 vim_free(buf->b_ml.ml_stack);
824#ifdef FEAT_BYTEOFF
825 vim_free(buf->b_ml.ml_chunksize);
826 buf->b_ml.ml_chunksize = NULL;
827#endif
828 buf->b_ml.ml_mfp = NULL;
829
830 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
831 * this buffer is loaded. */
832 buf->b_flags &= ~BF_RECOVERED;
833}
834
835/*
836 * Close all existing memlines and memfiles.
837 * Only used when exiting.
838 * When 'del_file' is TRUE, delete the memfiles.
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000839 * But don't delete files that were ":preserve"d when we are POSIX compatible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840 */
841 void
842ml_close_all(del_file)
843 int del_file;
844{
845 buf_T *buf;
846
847 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000848 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
849 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850#ifdef TEMPDIRNAMES
851 vim_deltempdir(); /* delete created temp directory */
852#endif
853}
854
855/*
856 * Close all memfiles for not modified buffers.
857 * Only use just before exiting!
858 */
859 void
860ml_close_notmod()
861{
862 buf_T *buf;
863
864 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
865 if (!bufIsChanged(buf))
866 ml_close(buf, TRUE); /* close all not-modified buffers */
867}
868
869/*
870 * Update the timestamp in the .swp file.
871 * Used when the file has been written.
872 */
873 void
874ml_timestamp(buf)
875 buf_T *buf;
876{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200877 ml_upd_block0(buf, UB_FNAME);
878}
879
880/*
881 * Return FAIL when the ID of "b0p" is wrong.
882 */
883 static int
884ml_check_b0_id(b0p)
885 ZERO_BL *b0p;
886{
887 if (b0p->b0_id[0] != BLOCK0_ID0
888 || (b0p->b0_id[1] != BLOCK0_ID1
889 && b0p->b0_id[1] != BLOCK0_ID1_C0
890 && b0p->b0_id[1] != BLOCK0_ID1_C1)
891 )
892 return FAIL;
893 return OK;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000894}
895
896/*
897 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
898 */
899 static void
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200900ml_upd_block0(buf, what)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000901 buf_T *buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200902 upd_block0_T what;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000903{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 memfile_T *mfp;
905 bhdr_T *hp;
906 ZERO_BL *b0p;
907
908 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
910 return;
911 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200912 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000913 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000915 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200916 if (what == UB_FNAME)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000917 set_b0_fname(b0p, buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200918#ifdef FEAT_CRYPT
919 else if (what == UB_CRYPT)
920 ml_set_b0_crypt(buf, b0p);
921#endif
922 else /* what == UB_SAME_DIR */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000923 set_b0_dir_flag(b0p, buf);
924 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925 mf_put(mfp, hp, TRUE, FALSE);
926}
927
928/*
929 * Write file name and timestamp into block 0 of a swap file.
930 * Also set buf->b_mtime.
931 * Don't use NameBuff[]!!!
932 */
933 static void
934set_b0_fname(b0p, buf)
935 ZERO_BL *b0p;
936 buf_T *buf;
937{
938 struct stat st;
939
940 if (buf->b_ffname == NULL)
941 b0p->b0_fname[0] = NUL;
942 else
943 {
944#if defined(MSDOS) || defined(MSWIN) || defined(AMIGA) || defined(RISCOS)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000945 /* Systems that cannot translate "~user" back into a path: copy the
946 * file name unmodified. Do use slashes instead of backslashes for
947 * portability. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200948 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000949# ifdef BACKSLASH_IN_FILENAME
950 forward_slash(b0p->b0_fname);
951# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000952#else
953 size_t flen, ulen;
954 char_u uname[B0_UNAME_SIZE];
955
956 /*
957 * For a file under the home directory of the current user, we try to
958 * replace the home directory path with "~user". This helps when
959 * editing the same file on different machines over a network.
960 * First replace home dir path with "~/" with home_replace().
961 * Then insert the user name to get "~user/".
962 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200963 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
964 B0_FNAME_SIZE_CRYPT, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965 if (b0p->b0_fname[0] == '~')
966 {
967 flen = STRLEN(b0p->b0_fname);
968 /* If there is no user name or it is too long, don't use "~/" */
969 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200970 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
971 vim_strncpy(b0p->b0_fname, buf->b_ffname,
972 B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973 else
974 {
975 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
976 mch_memmove(b0p->b0_fname + 1, uname, ulen);
977 }
978 }
979#endif
980 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
981 {
982 long_to_char((long)st.st_mtime, b0p->b0_mtime);
983#ifdef CHECK_INODE
984 long_to_char((long)st.st_ino, b0p->b0_ino);
985#endif
986 buf_store_time(buf, &st, buf->b_ffname);
987 buf->b_mtime_read = buf->b_mtime;
988 }
989 else
990 {
991 long_to_char(0L, b0p->b0_mtime);
992#ifdef CHECK_INODE
993 long_to_char(0L, b0p->b0_ino);
994#endif
995 buf->b_mtime = 0;
996 buf->b_mtime_read = 0;
997 buf->b_orig_size = 0;
998 buf->b_orig_mode = 0;
999 }
1000 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001001
1002#ifdef FEAT_MBYTE
1003 /* Also add the 'fileencoding' if there is room. */
1004 add_b0_fenc(b0p, curbuf);
1005#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006}
1007
1008/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001009 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1010 * swapfile for "buf" are in the same directory.
1011 * This is fail safe: if we are not sure the directories are equal the flag is
1012 * not set.
1013 */
1014 static void
1015set_b0_dir_flag(b0p, buf)
1016 ZERO_BL *b0p;
1017 buf_T *buf;
1018{
1019 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1020 b0p->b0_flags |= B0_SAME_DIR;
1021 else
1022 b0p->b0_flags &= ~B0_SAME_DIR;
1023}
1024
1025#ifdef FEAT_MBYTE
1026/*
1027 * When there is room, add the 'fileencoding' to block zero.
1028 */
1029 static void
1030add_b0_fenc(b0p, buf)
1031 ZERO_BL *b0p;
1032 buf_T *buf;
1033{
1034 int n;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001035 int size = B0_FNAME_SIZE_NOCRYPT;
1036
1037# ifdef FEAT_CRYPT
1038 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1039 * With encryption it's OK to move elsewhere, the swap file is not
1040 * compatible anyway. */
1041 if (*buf->b_p_key != NUL)
1042 size = B0_FNAME_SIZE_CRYPT;
1043# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001044
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001045 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001046 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001047 b0p->b0_flags &= ~B0_HAS_FENC;
1048 else
1049 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001050 mch_memmove((char *)b0p->b0_fname + size - n,
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001051 (char *)buf->b_p_fenc, (size_t)n);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001052 *(b0p->b0_fname + size - n - 1) = NUL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001053 b0p->b0_flags |= B0_HAS_FENC;
1054 }
1055}
1056#endif
1057
1058
1059/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001060 * Try to recover curbuf from the .swp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 */
1062 void
1063ml_recover()
1064{
1065 buf_T *buf = NULL;
1066 memfile_T *mfp = NULL;
1067 char_u *fname;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001068 char_u *fname_used = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069 bhdr_T *hp = NULL;
1070 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001071 int b0_ff;
1072 char_u *b0_fenc = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001073#ifdef FEAT_CRYPT
1074 int b0_cm = -1;
1075#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076 PTR_BL *pp;
1077 DATA_BL *dp;
1078 infoptr_T *ip;
1079 blocknr_T bnum;
1080 int page_count;
1081 struct stat org_stat, swp_stat;
1082 int len;
1083 int directly;
1084 linenr_T lnum;
1085 char_u *p;
1086 int i;
1087 long error;
1088 int cannot_open;
1089 linenr_T line_count;
1090 int has_error;
1091 int idx;
1092 int top;
1093 int txt_start;
1094 off_t size;
1095 int called_from_main;
1096 int serious_error = TRUE;
1097 long mtime;
1098 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001099 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100
1101 recoverymode = TRUE;
1102 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1103 attr = hl_attr(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001104
1105 /*
1106 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
1107 * Otherwise a search is done to find the swap file(s).
1108 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109 fname = curbuf->b_fname;
1110 if (fname == NULL) /* When there is no file name */
1111 fname = (char_u *)"";
1112 len = (int)STRLEN(fname);
1113 if (len >= 4 &&
1114#if defined(VMS) || defined(RISCOS)
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001115 STRNICMP(fname + len - 4, "_s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116#else
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001117 STRNICMP(fname + len - 4, ".s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118#endif
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001119 == 0
1120 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
1121 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 {
1123 directly = TRUE;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001124 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001125 }
1126 else
1127 {
1128 directly = FALSE;
1129
1130 /* count the number of matching swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001131 len = recover_names(fname, FALSE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132 if (len == 0) /* no swap files found */
1133 {
1134 EMSG2(_("E305: No swap file found for %s"), fname);
1135 goto theend;
1136 }
1137 if (len == 1) /* one swap file found, use it */
1138 i = 1;
1139 else /* several swap files found, choose */
1140 {
1141 /* list the names of the swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001142 (void)recover_names(fname, TRUE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 msg_putchar('\n');
1144 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001145 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 if (i < 1 || i > len)
1147 goto theend;
1148 }
1149 /* get the swap file name that will be used */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001150 (void)recover_names(fname, FALSE, i, &fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001152 if (fname_used == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153 goto theend; /* out of memory */
1154
1155 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +00001156 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 getout(1);
1158
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001159 /*
1160 * Allocate a buffer structure for the swap file that is used for recovery.
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001161 * Only the memline and crypt information in it are really used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001162 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1164 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001166
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001167 /*
1168 * init fields in memline struct
1169 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001170 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1171 buf->b_ml.ml_stack = NULL; /* no stack yet */
1172 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1173 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1174 buf->b_ml.ml_locked = NULL; /* no locked block */
1175 buf->b_ml.ml_flags = 0;
Bram Moolenaar0fe849a2010-07-25 15:11:11 +02001176#ifdef FEAT_CRYPT
1177 buf->b_p_key = empty_option;
1178 buf->b_p_cm = empty_option;
1179#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001181 /*
1182 * open the memfile from the old swap file
1183 */
1184 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1185 mf_open() will consume "fname_used"! */
1186 mfp = mf_open(fname_used, O_RDONLY);
1187 fname_used = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 if (mfp == NULL || mfp->mf_fd < 0)
1189 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001190 if (fname_used != NULL)
1191 EMSG2(_("E306: Cannot open %s"), fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 goto theend;
1193 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001195#ifdef FEAT_CRYPT
1196 mfp->mf_buffer = buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001197#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198
1199 /*
1200 * The page size set in mf_open() might be different from the page size
1201 * used in the swap file, we must get it from block 0. But to read block
1202 * 0 we need a page size. Use the minimal size for block 0 here, it will
1203 * be set to the real value below.
1204 */
1205 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1206
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001207 /*
1208 * try to read block 0
1209 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1211 {
1212 msg_start();
1213 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1214 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001215 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001216 attr | MSG_HIST);
1217 msg_end();
1218 goto theend;
1219 }
1220 b0p = (ZERO_BL *)(hp->bh_data);
1221 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1222 {
1223 msg_start();
1224 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1225 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1226 MSG_HIST);
1227 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1228 msg_end();
1229 goto theend;
1230 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001231 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 {
1233 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1234 goto theend;
1235 }
1236 if (b0_magic_wrong(b0p))
1237 {
1238 msg_start();
1239 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1240#if defined(MSDOS) || defined(MSWIN)
1241 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1242 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1243 attr | MSG_HIST);
1244 else
1245#endif
1246 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1247 attr | MSG_HIST);
1248 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001249 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250 b0p->b0_fname[0] = NUL;
1251 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1252 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1253 msg_end();
1254 goto theend;
1255 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001256
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001257#ifdef FEAT_CRYPT
1258 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
Bram Moolenaar49771f42010-07-20 17:32:38 +02001259 b0_cm = 0;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001260 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1261 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02001262 b0_cm = 1;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001263 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1264 }
Bram Moolenaar49771f42010-07-20 17:32:38 +02001265 set_crypt_method(buf, b0_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001266#else
1267 if (b0p->b0_id[1] != BLOCK0_ID1)
1268 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001269 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001270 goto theend;
1271 }
1272#endif
1273
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274 /*
1275 * If we guessed the wrong page size, we have to recalculate the
1276 * highest block number in the file.
1277 */
1278 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1279 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001280 unsigned previous_page_size = mfp->mf_page_size;
1281
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001283 if (mfp->mf_page_size < previous_page_size)
1284 {
1285 msg_start();
1286 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1287 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1288 attr | MSG_HIST);
1289 msg_end();
1290 goto theend;
1291 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1293 mfp->mf_blocknr_max = 0; /* no file or empty file */
1294 else
1295 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1296 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001297
1298 /* need to reallocate the memory used to store the data */
1299 p = alloc(mfp->mf_page_size);
1300 if (p == NULL)
1301 goto theend;
1302 mch_memmove(p, hp->bh_data, previous_page_size);
1303 vim_free(hp->bh_data);
1304 hp->bh_data = p;
1305 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306 }
1307
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001308 /*
1309 * If .swp file name given directly, use name from swap file for buffer.
1310 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001311 if (directly)
1312 {
1313 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1314 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1315 goto theend;
1316 }
1317
1318 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001319 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001320
1321 if (buf_spname(curbuf) != NULL)
1322 STRCPY(NameBuff, buf_spname(curbuf));
1323 else
1324 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001325 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326 msg_putchar('\n');
1327
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001328 /*
1329 * check date of swap file and original file
1330 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 mtime = char_to_long(b0p->b0_mtime);
1332 if (curbuf->b_ffname != NULL
1333 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1334 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1335 && org_stat.st_mtime > swp_stat.st_mtime)
1336 || org_stat.st_mtime != mtime))
1337 {
1338 EMSG(_("E308: Warning: Original file may have been changed"));
1339 }
1340 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001341
1342 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1343 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1344 if (b0p->b0_flags & B0_HAS_FENC)
1345 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001346 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001347
1348#ifdef FEAT_CRYPT
1349 /* Use the same size as in add_b0_fenc(). */
1350 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001351 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001352#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001353 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001354 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001355 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001356 }
1357
Bram Moolenaar071d4272004-06-13 20:20:40 +00001358 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1359 hp = NULL;
1360
1361 /*
1362 * Now that we are sure that the file is going to be recovered, clear the
1363 * contents of the current buffer.
1364 */
1365 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1366 ml_delete((linenr_T)1, FALSE);
1367
1368 /*
1369 * Try reading the original file to obtain the values of 'fileformat',
1370 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001371 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 */
1373 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001374 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001377#ifdef FEAT_CRYPT
1378 if (b0_cm >= 0)
1379 {
1380 /* Need to ask the user for the crypt key. If this fails we continue
1381 * without a key, will probably get garbage text. */
1382 if (*curbuf->b_p_key != NUL)
1383 {
1384 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1385 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1386 MSG_PUTS(_("\nenter the new crypt key."));
1387 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1388 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1389 }
1390 else
1391 smsg((char_u *)_(need_key_msg), fname_used);
1392 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1393 if (buf->b_p_key == NULL)
1394 buf->b_p_key = curbuf->b_p_key;
1395 else if (*buf->b_p_key == NUL)
1396 {
1397 vim_free(buf->b_p_key);
1398 buf->b_p_key = curbuf->b_p_key;
1399 }
1400 if (buf->b_p_key == NULL)
1401 buf->b_p_key = empty_option;
1402 }
1403#endif
1404
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001405 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1406 if (b0_ff != 0)
1407 set_fileformat(b0_ff - 1, OPT_LOCAL);
1408 if (b0_fenc != NULL)
1409 {
1410 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1411 vim_free(b0_fenc);
1412 }
1413 unchanged(curbuf, TRUE);
1414
Bram Moolenaar071d4272004-06-13 20:20:40 +00001415 bnum = 1; /* start with block 1 */
1416 page_count = 1; /* which is 1 page */
1417 lnum = 0; /* append after line 0 in curbuf */
1418 line_count = 0;
1419 idx = 0; /* start with first index in block 1 */
1420 error = 0;
1421 buf->b_ml.ml_stack_top = 0;
1422 buf->b_ml.ml_stack = NULL;
1423 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1424
1425 if (curbuf->b_ffname == NULL)
1426 cannot_open = TRUE;
1427 else
1428 cannot_open = FALSE;
1429
1430 serious_error = FALSE;
1431 for ( ; !got_int; line_breakcheck())
1432 {
1433 if (hp != NULL)
1434 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1435
1436 /*
1437 * get block
1438 */
1439 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1440 {
1441 if (bnum == 1)
1442 {
1443 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1444 goto theend;
1445 }
1446 ++error;
1447 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1448 (colnr_T)0, TRUE);
1449 }
1450 else /* there is a block */
1451 {
1452 pp = (PTR_BL *)(hp->bh_data);
1453 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1454 {
1455 /* check line count when using pointer block first time */
1456 if (idx == 0 && line_count != 0)
1457 {
1458 for (i = 0; i < (int)pp->pb_count; ++i)
1459 line_count -= pp->pb_pointer[i].pe_line_count;
1460 if (line_count != 0)
1461 {
1462 ++error;
1463 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1464 (colnr_T)0, TRUE);
1465 }
1466 }
1467
1468 if (pp->pb_count == 0)
1469 {
1470 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1471 (colnr_T)0, TRUE);
1472 ++error;
1473 }
1474 else if (idx < (int)pp->pb_count) /* go a block deeper */
1475 {
1476 if (pp->pb_pointer[idx].pe_bnum < 0)
1477 {
1478 /*
1479 * Data block with negative block number.
1480 * Try to read lines from the original file.
1481 * This is slow, but it works.
1482 */
1483 if (!cannot_open)
1484 {
1485 line_count = pp->pb_pointer[idx].pe_line_count;
1486 if (readfile(curbuf->b_ffname, NULL, lnum,
1487 pp->pb_pointer[idx].pe_old_lnum - 1,
1488 line_count, NULL, 0) == FAIL)
1489 cannot_open = TRUE;
1490 else
1491 lnum += line_count;
1492 }
1493 if (cannot_open)
1494 {
1495 ++error;
1496 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1497 (colnr_T)0, TRUE);
1498 }
1499 ++idx; /* get same block again for next index */
1500 continue;
1501 }
1502
1503 /*
1504 * going one block deeper in the tree
1505 */
1506 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1507 {
1508 ++error;
1509 break; /* out of memory */
1510 }
1511 ip = &(buf->b_ml.ml_stack[top]);
1512 ip->ip_bnum = bnum;
1513 ip->ip_index = idx;
1514
1515 bnum = pp->pb_pointer[idx].pe_bnum;
1516 line_count = pp->pb_pointer[idx].pe_line_count;
1517 page_count = pp->pb_pointer[idx].pe_page_count;
1518 continue;
1519 }
1520 }
1521 else /* not a pointer block */
1522 {
1523 dp = (DATA_BL *)(hp->bh_data);
1524 if (dp->db_id != DATA_ID) /* block id wrong */
1525 {
1526 if (bnum == 1)
1527 {
1528 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1529 mfp->mf_fname);
1530 goto theend;
1531 }
1532 ++error;
1533 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1534 (colnr_T)0, TRUE);
1535 }
1536 else
1537 {
1538 /*
1539 * it is a data block
1540 * Append all the lines in this block
1541 */
1542 has_error = FALSE;
1543 /*
1544 * check length of block
1545 * if wrong, use length in pointer block
1546 */
1547 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1548 {
1549 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1550 (colnr_T)0, TRUE);
1551 ++error;
1552 has_error = TRUE;
1553 dp->db_txt_end = page_count * mfp->mf_page_size;
1554 }
1555
1556 /* make sure there is a NUL at the end of the block */
1557 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1558
1559 /*
1560 * check number of lines in block
1561 * if wrong, use count in data block
1562 */
1563 if (line_count != dp->db_line_count)
1564 {
1565 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1566 (colnr_T)0, TRUE);
1567 ++error;
1568 has_error = TRUE;
1569 }
1570
1571 for (i = 0; i < dp->db_line_count; ++i)
1572 {
1573 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001574 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575 || txt_start >= (int)dp->db_txt_end)
1576 {
1577 p = (char_u *)"???";
1578 ++error;
1579 }
1580 else
1581 p = (char_u *)dp + txt_start;
1582 ml_append(lnum++, p, (colnr_T)0, TRUE);
1583 }
1584 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001585 ml_append(lnum++, (char_u *)_("???END"),
1586 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 }
1588 }
1589 }
1590
1591 if (buf->b_ml.ml_stack_top == 0) /* finished */
1592 break;
1593
1594 /*
1595 * go one block up in the tree
1596 */
1597 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1598 bnum = ip->ip_bnum;
1599 idx = ip->ip_index + 1; /* go to next index */
1600 page_count = 1;
1601 }
1602
1603 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001604 * Compare the buffer contents with the original file. When they differ
1605 * set the 'modified' flag.
1606 * Lines 1 - lnum are the new contents.
1607 * Lines lnum + 1 to ml_line_count are the original contents.
1608 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001610 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1611 {
1612 /* Recovering an empty file results in two lines and the first line is
1613 * empty. Don't set the modified flag then. */
1614 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1615 {
1616 changed_int();
1617 ++curbuf->b_changedtick;
1618 }
1619 }
1620 else
1621 {
1622 for (idx = 1; idx <= lnum; ++idx)
1623 {
1624 /* Need to copy one line, fetching the other one may flush it. */
1625 p = vim_strsave(ml_get(idx));
1626 i = STRCMP(p, ml_get(idx + lnum));
1627 vim_free(p);
1628 if (i != 0)
1629 {
1630 changed_int();
1631 ++curbuf->b_changedtick;
1632 break;
1633 }
1634 }
1635 }
1636
1637 /*
1638 * Delete the lines from the original file and the dummy line from the
1639 * empty buffer. These will now be after the last line in the buffer.
1640 */
1641 while (curbuf->b_ml.ml_line_count > lnum
1642 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1643 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 curbuf->b_flags |= BF_RECOVERED;
1645
1646 recoverymode = FALSE;
1647 if (got_int)
1648 EMSG(_("E311: Recovery Interrupted"));
1649 else if (error)
1650 {
1651 ++no_wait_return;
1652 MSG(">>>>>>>>>>>>>");
1653 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1654 --no_wait_return;
1655 MSG(_("See \":help E312\" for more information."));
1656 MSG(">>>>>>>>>>>>>");
1657 }
1658 else
1659 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001660 if (curbuf->b_changed)
1661 {
1662 MSG(_("Recovery completed. You should check if everything is OK."));
1663 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1664 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1665 }
1666 else
1667 MSG(_("Recovery completed. Buffer contents equals file contents."));
1668 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 cmdline_row = msg_row;
1670 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001671#ifdef FEAT_CRYPT
1672 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1673 {
1674 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1675 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1676 }
1677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 redraw_curbuf_later(NOT_VALID);
1679
1680theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001681 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 recoverymode = FALSE;
1683 if (mfp != NULL)
1684 {
1685 if (hp != NULL)
1686 mf_put(mfp, hp, FALSE, FALSE);
1687 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1688 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001689 if (buf != NULL)
1690 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001691#ifdef FEAT_CRYPT
1692 if (buf->b_p_key != curbuf->b_p_key)
1693 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001694 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001695#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001696 vim_free(buf->b_ml.ml_stack);
1697 vim_free(buf);
1698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699 if (serious_error && called_from_main)
1700 ml_close(curbuf, TRUE);
1701#ifdef FEAT_AUTOCMD
1702 else
1703 {
1704 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1705 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1706 }
1707#endif
1708 return;
1709}
1710
1711/*
1712 * Find the names of swap files in current directory and the directory given
1713 * with the 'directory' option.
1714 *
1715 * Used to:
1716 * - list the swap files for "vim -r"
1717 * - count the number of swap files when recovering
1718 * - list the swap files when recovering
1719 * - find the name of the n'th swap file when recovering
1720 */
1721 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001722recover_names(fname, list, nr, fname_out)
1723 char_u *fname; /* base for swap file name */
1724 int list; /* when TRUE, list the swap file names */
1725 int nr; /* when non-zero, return nr'th swap file name */
1726 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727{
1728 int num_names;
1729 char_u *(names[6]);
1730 char_u *tail;
1731 char_u *p;
1732 int num_files;
1733 int file_count = 0;
1734 char_u **files;
1735 int i;
1736 char_u *dirp;
1737 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001738 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001739#ifdef HAVE_READLINK
1740 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001741#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001742
Bram Moolenaar64354da2010-05-25 21:37:17 +02001743 if (fname != NULL)
1744 {
1745#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001746 /* Expand symlink in the file name, because the swap file is created
1747 * with the actual file instead of with the symlink. */
1748 if (resolve_symlink(fname, fname_buf) == OK)
1749 fname_res = fname_buf;
1750 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001751#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001752 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001753 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754
1755 if (list)
1756 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001757 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001758 msg((char_u *)_("Swap files found:"));
1759 msg_putchar('\n');
1760 }
1761
1762 /*
1763 * Do the loop for every directory in 'directory'.
1764 * First allocate some memory to put the directory name in.
1765 */
1766 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1767 dirp = p_dir;
1768 while (dir_name != NULL && *dirp)
1769 {
1770 /*
1771 * Isolate a directory name from *dirp and put it in dir_name (we know
1772 * it is large enough, so use 31000 for length).
1773 * Advance dirp to next directory name.
1774 */
1775 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1776
1777 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1778 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001779 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780 {
1781#ifdef VMS
1782 names[0] = vim_strsave((char_u *)"*_sw%");
1783#else
1784# ifdef RISCOS
1785 names[0] = vim_strsave((char_u *)"*_sw#");
1786# else
1787 names[0] = vim_strsave((char_u *)"*.sw?");
1788# endif
1789#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001790#if defined(UNIX) || defined(WIN3264)
1791 /* For Unix names starting with a dot are special. MS-Windows
1792 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 names[1] = vim_strsave((char_u *)".*.sw?");
1794 names[2] = vim_strsave((char_u *)".sw?");
1795 num_names = 3;
1796#else
1797# ifdef VMS
1798 names[1] = vim_strsave((char_u *)".*_sw%");
1799 num_names = 2;
1800# else
1801 num_names = 1;
1802# endif
1803#endif
1804 }
1805 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001806 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 }
1808 else /* check directory dir_name */
1809 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001810 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 {
1812#ifdef VMS
1813 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1814#else
1815# ifdef RISCOS
1816 names[0] = concat_fnames(dir_name, (char_u *)"*_sw#", TRUE);
1817# else
1818 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
1819# endif
1820#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001821#if defined(UNIX) || defined(WIN3264)
1822 /* For Unix names starting with a dot are special. MS-Windows
1823 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1825 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1826 num_names = 3;
1827#else
1828# ifdef VMS
1829 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1830 num_names = 2;
1831# else
1832 num_names = 1;
1833# endif
1834#endif
1835 }
1836 else
1837 {
1838#if defined(UNIX) || defined(WIN3264)
1839 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001840 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 {
1842 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001843 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 }
1845 else
1846#endif
1847 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001848 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001849 tail = concat_fnames(dir_name, tail, TRUE);
1850 }
1851 if (tail == NULL)
1852 num_names = 0;
1853 else
1854 {
1855 num_names = recov_file_names(names, tail, FALSE);
1856 vim_free(tail);
1857 }
1858 }
1859 }
1860
1861 /* check for out-of-memory */
1862 for (i = 0; i < num_names; ++i)
1863 {
1864 if (names[i] == NULL)
1865 {
1866 for (i = 0; i < num_names; ++i)
1867 vim_free(names[i]);
1868 num_names = 0;
1869 }
1870 }
1871 if (num_names == 0)
1872 num_files = 0;
1873 else if (expand_wildcards(num_names, names, &num_files, &files,
1874 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1875 num_files = 0;
1876
1877 /*
1878 * When no swap file found, wildcard expansion might have failed (e.g.
1879 * not able to execute the shell).
1880 * Try finding a swap file by simply adding ".swp" to the file name.
1881 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001882 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 {
1884 struct stat st;
1885 char_u *swapname;
1886
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001887 swapname = modname(fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001888#if defined(VMS) || defined(RISCOS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001889 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001891 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001893 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001894 if (swapname != NULL)
1895 {
1896 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1897 {
1898 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1899 if (files != NULL)
1900 {
1901 files[0] = swapname;
1902 swapname = NULL;
1903 num_files = 1;
1904 }
1905 }
1906 vim_free(swapname);
1907 }
1908 }
1909
1910 /*
1911 * remove swapfile name of the current buffer, it must be ignored
1912 */
1913 if (curbuf->b_ml.ml_mfp != NULL
1914 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1915 {
1916 for (i = 0; i < num_files; ++i)
1917 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1918 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001919 /* Remove the name from files[i]. Move further entries
1920 * down. When the array becomes empty free it here, since
1921 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001923 if (--num_files == 0)
1924 vim_free(files);
1925 else
1926 for ( ; i < num_files; ++i)
1927 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 }
1929 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001930 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 {
1932 file_count += num_files;
1933 if (nr <= file_count)
1934 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001935 *fname_out = vim_strsave(
1936 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 dirp = (char_u *)""; /* stop searching */
1938 }
1939 }
1940 else if (list)
1941 {
1942 if (dir_name[0] == '.' && dir_name[1] == NUL)
1943 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001944 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 MSG_PUTS(_(" In current directory:\n"));
1946 else
1947 MSG_PUTS(_(" Using specified name:\n"));
1948 }
1949 else
1950 {
1951 MSG_PUTS(_(" In directory "));
1952 msg_home_replace(dir_name);
1953 MSG_PUTS(":\n");
1954 }
1955
1956 if (num_files)
1957 {
1958 for (i = 0; i < num_files; ++i)
1959 {
1960 /* print the swap file name */
1961 msg_outnum((long)++file_count);
1962 MSG_PUTS(". ");
1963 msg_puts(gettail(files[i]));
1964 msg_putchar('\n');
1965 (void)swapfile_info(files[i]);
1966 }
1967 }
1968 else
1969 MSG_PUTS(_(" -- none --\n"));
1970 out_flush();
1971 }
1972 else
1973 file_count += num_files;
1974
1975 for (i = 0; i < num_names; ++i)
1976 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001977 if (num_files > 0)
1978 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 }
1980 vim_free(dir_name);
1981 return file_count;
1982}
1983
1984#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1985/*
1986 * Append the full path to name with path separators made into percent
1987 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1988 */
1989 static char_u *
1990make_percent_swname(dir, name)
1991 char_u *dir;
1992 char_u *name;
1993{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001994 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995
1996 f = fix_fname(name != NULL ? name : (char_u *) "");
1997 d = NULL;
1998 if (f != NULL)
1999 {
2000 s = alloc((unsigned)(STRLEN(f) + 1));
2001 if (s != NULL)
2002 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002003 STRCPY(s, f);
2004 for (d = s; *d != NUL; mb_ptr_adv(d))
2005 if (vim_ispathsep(*d))
2006 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007 d = concat_fnames(dir, s, TRUE);
2008 vim_free(s);
2009 }
2010 vim_free(f);
2011 }
2012 return d;
2013}
2014#endif
2015
2016#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2017static int process_still_running;
2018#endif
2019
2020/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002021 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 * Returns timestamp (0 when unknown).
2023 */
2024 static time_t
2025swapfile_info(fname)
2026 char_u *fname;
2027{
2028 struct stat st;
2029 int fd;
2030 struct block0 b0;
2031 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002032 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033#ifdef UNIX
2034 char_u uname[B0_UNAME_SIZE];
2035#endif
2036
2037 /* print the swap file date */
2038 if (mch_stat((char *)fname, &st) != -1)
2039 {
2040#ifdef UNIX
2041 /* print name of owner of the file */
2042 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2043 {
2044 MSG_PUTS(_(" owned by: "));
2045 msg_outtrans(uname);
2046 MSG_PUTS(_(" dated: "));
2047 }
2048 else
2049#endif
2050 MSG_PUTS(_(" dated: "));
2051 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002052 p = ctime(&x); /* includes '\n' */
2053 if (p == NULL)
2054 MSG_PUTS("(invalid)\n");
2055 else
2056 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 }
2058
2059 /*
2060 * print the original file name
2061 */
2062 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2063 if (fd >= 0)
2064 {
2065 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
2066 {
2067 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2068 {
2069 MSG_PUTS(_(" [from Vim version 3.0]"));
2070 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002071 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 {
2073 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2074 }
2075 else
2076 {
2077 MSG_PUTS(_(" file name: "));
2078 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002079 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 else
2081 msg_outtrans(b0.b0_fname);
2082
2083 MSG_PUTS(_("\n modified: "));
2084 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2085
2086 if (*(b0.b0_uname) != NUL)
2087 {
2088 MSG_PUTS(_("\n user name: "));
2089 msg_outtrans(b0.b0_uname);
2090 }
2091
2092 if (*(b0.b0_hname) != NUL)
2093 {
2094 if (*(b0.b0_uname) != NUL)
2095 MSG_PUTS(_(" host name: "));
2096 else
2097 MSG_PUTS(_("\n host name: "));
2098 msg_outtrans(b0.b0_hname);
2099 }
2100
2101 if (char_to_long(b0.b0_pid) != 0L)
2102 {
2103 MSG_PUTS(_("\n process ID: "));
2104 msg_outnum(char_to_long(b0.b0_pid));
2105#if defined(UNIX) || defined(__EMX__)
2106 /* EMX kill() not working correctly, it seems */
2107 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2108 {
2109 MSG_PUTS(_(" (still running)"));
2110# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2111 process_still_running = TRUE;
2112# endif
2113 }
2114#endif
2115 }
2116
2117 if (b0_magic_wrong(&b0))
2118 {
2119#if defined(MSDOS) || defined(MSWIN)
2120 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2121 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2122 else
2123#endif
2124 MSG_PUTS(_("\n [not usable on this computer]"));
2125 }
2126 }
2127 }
2128 else
2129 MSG_PUTS(_(" [cannot be read]"));
2130 close(fd);
2131 }
2132 else
2133 MSG_PUTS(_(" [cannot be opened]"));
2134 msg_putchar('\n');
2135
2136 return x;
2137}
2138
2139 static int
2140recov_file_names(names, path, prepend_dot)
2141 char_u **names;
2142 char_u *path;
2143 int prepend_dot;
2144{
2145 int num_names;
2146
2147#ifdef SHORT_FNAME
2148 /*
2149 * (MS-DOS) always short names
2150 */
2151 names[0] = modname(path, (char_u *)".sw?", FALSE);
2152 num_names = 1;
2153#else /* !SHORT_FNAME */
2154 /*
2155 * (Win32 and Win64) never short names, but do prepend a dot.
2156 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2157 * Only use the short name if it is different.
2158 */
2159 char_u *p;
2160 int i;
2161# ifndef WIN3264
2162 int shortname = curbuf->b_shortname;
2163
2164 curbuf->b_shortname = FALSE;
2165# endif
2166
2167 num_names = 0;
2168
2169 /*
2170 * May also add the file name with a dot prepended, for swap file in same
2171 * dir as original file.
2172 */
2173 if (prepend_dot)
2174 {
2175 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2176 if (names[num_names] == NULL)
2177 goto end;
2178 ++num_names;
2179 }
2180
2181 /*
2182 * Form the normal swap file name pattern by appending ".sw?".
2183 */
2184#ifdef VMS
2185 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2186#else
2187# ifdef RISCOS
2188 names[num_names] = concat_fnames(path, (char_u *)"_sw#", FALSE);
2189# else
2190 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
2191# endif
2192#endif
2193 if (names[num_names] == NULL)
2194 goto end;
2195 if (num_names >= 1) /* check if we have the same name twice */
2196 {
2197 p = names[num_names - 1];
2198 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2199 if (i > 0)
2200 p += i; /* file name has been expanded to full path */
2201
2202 if (STRCMP(p, names[num_names]) != 0)
2203 ++num_names;
2204 else
2205 vim_free(names[num_names]);
2206 }
2207 else
2208 ++num_names;
2209
2210# ifndef WIN3264
2211 /*
2212 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2213 */
2214 curbuf->b_shortname = TRUE;
2215#ifdef VMS
2216 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2217#else
2218# ifdef RISCOS
2219 names[num_names] = modname(path, (char_u *)"_sw#", FALSE);
2220# else
2221 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
2222# endif
2223#endif
2224 if (names[num_names] == NULL)
2225 goto end;
2226
2227 /*
2228 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2229 */
2230 p = names[num_names];
2231 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2232 if (i > 0)
2233 p += i; /* file name has been expanded to full path */
2234 if (STRCMP(names[num_names - 1], p) == 0)
2235 vim_free(names[num_names]);
2236 else
2237 ++num_names;
2238# endif
2239
2240end:
2241# ifndef WIN3264
2242 curbuf->b_shortname = shortname;
2243# endif
2244
2245#endif /* !SHORT_FNAME */
2246
2247 return num_names;
2248}
2249
2250/*
2251 * sync all memlines
2252 *
2253 * If 'check_file' is TRUE, check if original file exists and was not changed.
2254 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2255 * always sync at least one block.
2256 */
2257 void
2258ml_sync_all(check_file, check_char)
2259 int check_file;
2260 int check_char;
2261{
2262 buf_T *buf;
2263 struct stat st;
2264
2265 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2266 {
2267 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2268 continue; /* no file */
2269
2270 ml_flush_line(buf); /* flush buffered line */
2271 /* flush locked block */
2272 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2273 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2274 && buf->b_ffname != NULL)
2275 {
2276 /*
2277 * If the original file does not exist anymore or has been changed
2278 * call ml_preserve() to get rid of all negative numbered blocks.
2279 */
2280 if (mch_stat((char *)buf->b_ffname, &st) == -1
2281 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002282 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 {
2284 ml_preserve(buf, FALSE);
2285 did_check_timestamps = FALSE;
2286 need_check_timestamps = TRUE; /* give message later */
2287 }
2288 }
2289 if (buf->b_ml.ml_mfp->mf_dirty)
2290 {
2291 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2292 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2293 if (check_char && ui_char_avail()) /* character available now */
2294 break;
2295 }
2296 }
2297}
2298
2299/*
2300 * sync one buffer, including negative blocks
2301 *
2302 * after this all the blocks are in the swap file
2303 *
2304 * Used for the :preserve command and when the original file has been
2305 * changed or deleted.
2306 *
2307 * when message is TRUE the success of preserving is reported
2308 */
2309 void
2310ml_preserve(buf, message)
2311 buf_T *buf;
2312 int message;
2313{
2314 bhdr_T *hp;
2315 linenr_T lnum;
2316 memfile_T *mfp = buf->b_ml.ml_mfp;
2317 int status;
2318 int got_int_save = got_int;
2319
2320 if (mfp == NULL || mfp->mf_fname == NULL)
2321 {
2322 if (message)
2323 EMSG(_("E313: Cannot preserve, there is no swap file"));
2324 return;
2325 }
2326
2327 /* We only want to stop when interrupted here, not when interrupted
2328 * before. */
2329 got_int = FALSE;
2330
2331 ml_flush_line(buf); /* flush buffered line */
2332 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2333 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2334
2335 /* stack is invalid after mf_sync(.., MFS_ALL) */
2336 buf->b_ml.ml_stack_top = 0;
2337
2338 /*
2339 * Some of the data blocks may have been changed from negative to
2340 * positive block number. In that case the pointer blocks need to be
2341 * updated.
2342 *
2343 * We don't know in which pointer block the references are, so we visit
2344 * all data blocks until there are no more translations to be done (or
2345 * we hit the end of the file, which can only happen in case a write fails,
2346 * e.g. when file system if full).
2347 * ml_find_line() does the work by translating the negative block numbers
2348 * when getting the first line of each data block.
2349 */
2350 if (mf_need_trans(mfp) && !got_int)
2351 {
2352 lnum = 1;
2353 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2354 {
2355 hp = ml_find_line(buf, lnum, ML_FIND);
2356 if (hp == NULL)
2357 {
2358 status = FAIL;
2359 goto theend;
2360 }
2361 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2362 lnum = buf->b_ml.ml_locked_high + 1;
2363 }
2364 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2365 /* sync the updated pointer blocks */
2366 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2367 status = FAIL;
2368 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2369 }
2370theend:
2371 got_int |= got_int_save;
2372
2373 if (message)
2374 {
2375 if (status == OK)
2376 MSG(_("File preserved"));
2377 else
2378 EMSG(_("E314: Preserve failed"));
2379 }
2380}
2381
2382/*
2383 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2384 * until the next call!
2385 * line1 = ml_get(1);
2386 * line2 = ml_get(2); // line1 is now invalid!
2387 * Make a copy of the line if necessary.
2388 */
2389/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002390 * Return a pointer to a (read-only copy of a) line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 *
2392 * On failure an error message is given and IObuff is returned (to avoid
2393 * having to check for error everywhere).
2394 */
2395 char_u *
2396ml_get(lnum)
2397 linenr_T lnum;
2398{
2399 return ml_get_buf(curbuf, lnum, FALSE);
2400}
2401
2402/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002403 * Return pointer to position "pos".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404 */
2405 char_u *
2406ml_get_pos(pos)
2407 pos_T *pos;
2408{
2409 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2410}
2411
2412/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002413 * Return pointer to cursor line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 */
2415 char_u *
2416ml_get_curline()
2417{
2418 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2419}
2420
2421/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002422 * Return pointer to cursor position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 */
2424 char_u *
2425ml_get_cursor()
2426{
2427 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2428 curwin->w_cursor.col);
2429}
2430
2431/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002432 * Return a pointer to a line in a specific buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 *
2434 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2435 * changed)
2436 */
2437 char_u *
2438ml_get_buf(buf, lnum, will_change)
2439 buf_T *buf;
2440 linenr_T lnum;
2441 int will_change; /* line will be changed */
2442{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002443 bhdr_T *hp;
2444 DATA_BL *dp;
2445 char_u *ptr;
2446 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447
2448 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2449 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002450 if (recursive == 0)
2451 {
2452 /* Avoid giving this message for a recursive call, may happen when
2453 * the GUI redraws part of the text. */
2454 ++recursive;
2455 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2456 --recursive;
2457 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458errorret:
2459 STRCPY(IObuff, "???");
2460 return IObuff;
2461 }
2462 if (lnum <= 0) /* pretend line 0 is line 1 */
2463 lnum = 1;
2464
2465 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2466 return (char_u *)"";
2467
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002468 /*
2469 * See if it is the same line as requested last time.
2470 * Otherwise may need to flush last used line.
2471 * Don't use the last used line when 'swapfile' is reset, need to load all
2472 * blocks.
2473 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002474 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 {
2476 ml_flush_line(buf);
2477
2478 /*
2479 * Find the data block containing the line.
2480 * This also fills the stack with the blocks from the root to the data
2481 * block and releases any locked block.
2482 */
2483 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2484 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002485 if (recursive == 0)
2486 {
2487 /* Avoid giving this message for a recursive call, may happen
2488 * when the GUI redraws part of the text. */
2489 ++recursive;
2490 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2491 --recursive;
2492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 goto errorret;
2494 }
2495
2496 dp = (DATA_BL *)(hp->bh_data);
2497
2498 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2499 buf->b_ml.ml_line_ptr = ptr;
2500 buf->b_ml.ml_line_lnum = lnum;
2501 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2502 }
2503 if (will_change)
2504 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2505
2506 return buf->b_ml.ml_line_ptr;
2507}
2508
2509/*
2510 * Check if a line that was just obtained by a call to ml_get
2511 * is in allocated memory.
2512 */
2513 int
2514ml_line_alloced()
2515{
2516 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2517}
2518
2519/*
2520 * Append a line after lnum (may be 0 to insert a line in front of the file).
2521 * "line" does not need to be allocated, but can't be another line in a
2522 * buffer, unlocking may make it invalid.
2523 *
2524 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2525 * will be set for recovery
2526 * Check: The caller of this function should probably also call
2527 * appended_lines().
2528 *
2529 * return FAIL for failure, OK otherwise
2530 */
2531 int
2532ml_append(lnum, line, len, newfile)
2533 linenr_T lnum; /* append after this line (can be 0) */
2534 char_u *line; /* text of the new line */
2535 colnr_T len; /* length of new line, including NUL, or 0 */
2536 int newfile; /* flag, see above */
2537{
2538 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002539 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 return FAIL;
2541
2542 if (curbuf->b_ml.ml_line_lnum != 0)
2543 ml_flush_line(curbuf);
2544 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2545}
2546
Bram Moolenaara1956f62006-03-12 22:18:00 +00002547#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002548/*
2549 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2550 * a memline.
2551 */
2552 int
2553ml_append_buf(buf, lnum, line, len, newfile)
2554 buf_T *buf;
2555 linenr_T lnum; /* append after this line (can be 0) */
2556 char_u *line; /* text of the new line */
2557 colnr_T len; /* length of new line, including NUL, or 0 */
2558 int newfile; /* flag, see above */
2559{
2560 if (buf->b_ml.ml_mfp == NULL)
2561 return FAIL;
2562
2563 if (buf->b_ml.ml_line_lnum != 0)
2564 ml_flush_line(buf);
2565 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2566}
2567#endif
2568
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569 static int
2570ml_append_int(buf, lnum, line, len, newfile, mark)
2571 buf_T *buf;
2572 linenr_T lnum; /* append after this line (can be 0) */
2573 char_u *line; /* text of the new line */
2574 colnr_T len; /* length of line, including NUL, or 0 */
2575 int newfile; /* flag, see above */
2576 int mark; /* mark the new line */
2577{
2578 int i;
2579 int line_count; /* number of indexes in current block */
2580 int offset;
2581 int from, to;
2582 int space_needed; /* space needed for new line */
2583 int page_size;
2584 int page_count;
2585 int db_idx; /* index for lnum in data block */
2586 bhdr_T *hp;
2587 memfile_T *mfp;
2588 DATA_BL *dp;
2589 PTR_BL *pp;
2590 infoptr_T *ip;
2591
2592 /* lnum out of range */
2593 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2594 return FAIL;
2595
2596 if (lowest_marked && lowest_marked > lnum)
2597 lowest_marked = lnum + 1;
2598
2599 if (len == 0)
2600 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2601 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2602
2603 mfp = buf->b_ml.ml_mfp;
2604 page_size = mfp->mf_page_size;
2605
2606/*
2607 * find the data block containing the previous line
2608 * This also fills the stack with the blocks from the root to the data block
2609 * This also releases any locked block.
2610 */
2611 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2612 ML_INSERT)) == NULL)
2613 return FAIL;
2614
2615 buf->b_ml.ml_flags &= ~ML_EMPTY;
2616
2617 if (lnum == 0) /* got line one instead, correct db_idx */
2618 db_idx = -1; /* careful, it is negative! */
2619 else
2620 db_idx = lnum - buf->b_ml.ml_locked_low;
2621 /* get line count before the insertion */
2622 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2623
2624 dp = (DATA_BL *)(hp->bh_data);
2625
2626/*
2627 * If
2628 * - there is not enough room in the current block
2629 * - appending to the last line in the block
2630 * - not appending to the last line in the file
2631 * insert in front of the next block.
2632 */
2633 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2634 && lnum < buf->b_ml.ml_line_count)
2635 {
2636 /*
2637 * Now that the line is not going to be inserted in the block that we
2638 * expected, the line count has to be adjusted in the pointer blocks
2639 * by using ml_locked_lineadd.
2640 */
2641 --(buf->b_ml.ml_locked_lineadd);
2642 --(buf->b_ml.ml_locked_high);
2643 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2644 return FAIL;
2645
2646 db_idx = -1; /* careful, it is negative! */
2647 /* get line count before the insertion */
2648 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2649 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2650
2651 dp = (DATA_BL *)(hp->bh_data);
2652 }
2653
2654 ++buf->b_ml.ml_line_count;
2655
2656 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2657 {
2658/*
2659 * Insert new line in existing data block, or in data block allocated above.
2660 */
2661 dp->db_txt_start -= len;
2662 dp->db_free -= space_needed;
2663 ++(dp->db_line_count);
2664
2665 /*
2666 * move the text of the lines that follow to the front
2667 * adjust the indexes of the lines that follow
2668 */
2669 if (line_count > db_idx + 1) /* if there are following lines */
2670 {
2671 /*
2672 * Offset is the start of the previous line.
2673 * This will become the character just after the new line.
2674 */
2675 if (db_idx < 0)
2676 offset = dp->db_txt_end;
2677 else
2678 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2679 mch_memmove((char *)dp + dp->db_txt_start,
2680 (char *)dp + dp->db_txt_start + len,
2681 (size_t)(offset - (dp->db_txt_start + len)));
2682 for (i = line_count - 1; i > db_idx; --i)
2683 dp->db_index[i + 1] = dp->db_index[i] - len;
2684 dp->db_index[db_idx + 1] = offset - len;
2685 }
2686 else /* add line at the end */
2687 dp->db_index[db_idx + 1] = dp->db_txt_start;
2688
2689 /*
2690 * copy the text into the block
2691 */
2692 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2693 if (mark)
2694 dp->db_index[db_idx + 1] |= DB_MARKED;
2695
2696 /*
2697 * Mark the block dirty.
2698 */
2699 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2700 if (!newfile)
2701 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2702 }
2703 else /* not enough space in data block */
2704 {
2705/*
2706 * If there is not enough room we have to create a new data block and copy some
2707 * lines into it.
2708 * Then we have to insert an entry in the pointer block.
2709 * If this pointer block also is full, we go up another block, and so on, up
2710 * to the root if necessary.
2711 * The line counts in the pointer blocks have already been adjusted by
2712 * ml_find_line().
2713 */
2714 long line_count_left, line_count_right;
2715 int page_count_left, page_count_right;
2716 bhdr_T *hp_left;
2717 bhdr_T *hp_right;
2718 bhdr_T *hp_new;
2719 int lines_moved;
2720 int data_moved = 0; /* init to shut up gcc */
2721 int total_moved = 0; /* init to shut up gcc */
2722 DATA_BL *dp_right, *dp_left;
2723 int stack_idx;
2724 int in_left;
2725 int lineadd;
2726 blocknr_T bnum_left, bnum_right;
2727 linenr_T lnum_left, lnum_right;
2728 int pb_idx;
2729 PTR_BL *pp_new;
2730
2731 /*
2732 * We are going to allocate a new data block. Depending on the
2733 * situation it will be put to the left or right of the existing
2734 * block. If possible we put the new line in the left block and move
2735 * the lines after it to the right block. Otherwise the new line is
2736 * also put in the right block. This method is more efficient when
2737 * inserting a lot of lines at one place.
2738 */
2739 if (db_idx < 0) /* left block is new, right block is existing */
2740 {
2741 lines_moved = 0;
2742 in_left = TRUE;
2743 /* space_needed does not change */
2744 }
2745 else /* left block is existing, right block is new */
2746 {
2747 lines_moved = line_count - db_idx - 1;
2748 if (lines_moved == 0)
2749 in_left = FALSE; /* put new line in right block */
2750 /* space_needed does not change */
2751 else
2752 {
2753 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2754 dp->db_txt_start;
2755 total_moved = data_moved + lines_moved * INDEX_SIZE;
2756 if ((int)dp->db_free + total_moved >= space_needed)
2757 {
2758 in_left = TRUE; /* put new line in left block */
2759 space_needed = total_moved;
2760 }
2761 else
2762 {
2763 in_left = FALSE; /* put new line in right block */
2764 space_needed += total_moved;
2765 }
2766 }
2767 }
2768
2769 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2770 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2771 {
2772 /* correct line counts in pointer blocks */
2773 --(buf->b_ml.ml_locked_lineadd);
2774 --(buf->b_ml.ml_locked_high);
2775 return FAIL;
2776 }
2777 if (db_idx < 0) /* left block is new */
2778 {
2779 hp_left = hp_new;
2780 hp_right = hp;
2781 line_count_left = 0;
2782 line_count_right = line_count;
2783 }
2784 else /* right block is new */
2785 {
2786 hp_left = hp;
2787 hp_right = hp_new;
2788 line_count_left = line_count;
2789 line_count_right = 0;
2790 }
2791 dp_right = (DATA_BL *)(hp_right->bh_data);
2792 dp_left = (DATA_BL *)(hp_left->bh_data);
2793 bnum_left = hp_left->bh_bnum;
2794 bnum_right = hp_right->bh_bnum;
2795 page_count_left = hp_left->bh_page_count;
2796 page_count_right = hp_right->bh_page_count;
2797
2798 /*
2799 * May move the new line into the right/new block.
2800 */
2801 if (!in_left)
2802 {
2803 dp_right->db_txt_start -= len;
2804 dp_right->db_free -= len + INDEX_SIZE;
2805 dp_right->db_index[0] = dp_right->db_txt_start;
2806 if (mark)
2807 dp_right->db_index[0] |= DB_MARKED;
2808
2809 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2810 line, (size_t)len);
2811 ++line_count_right;
2812 }
2813 /*
2814 * may move lines from the left/old block to the right/new one.
2815 */
2816 if (lines_moved)
2817 {
2818 /*
2819 */
2820 dp_right->db_txt_start -= data_moved;
2821 dp_right->db_free -= total_moved;
2822 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2823 (char *)dp_left + dp_left->db_txt_start,
2824 (size_t)data_moved);
2825 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2826 dp_left->db_txt_start += data_moved;
2827 dp_left->db_free += total_moved;
2828
2829 /*
2830 * update indexes in the new block
2831 */
2832 for (to = line_count_right, from = db_idx + 1;
2833 from < line_count_left; ++from, ++to)
2834 dp_right->db_index[to] = dp->db_index[from] + offset;
2835 line_count_right += lines_moved;
2836 line_count_left -= lines_moved;
2837 }
2838
2839 /*
2840 * May move the new line into the left (old or new) block.
2841 */
2842 if (in_left)
2843 {
2844 dp_left->db_txt_start -= len;
2845 dp_left->db_free -= len + INDEX_SIZE;
2846 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2847 if (mark)
2848 dp_left->db_index[line_count_left] |= DB_MARKED;
2849 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2850 line, (size_t)len);
2851 ++line_count_left;
2852 }
2853
2854 if (db_idx < 0) /* left block is new */
2855 {
2856 lnum_left = lnum + 1;
2857 lnum_right = 0;
2858 }
2859 else /* right block is new */
2860 {
2861 lnum_left = 0;
2862 if (in_left)
2863 lnum_right = lnum + 2;
2864 else
2865 lnum_right = lnum + 1;
2866 }
2867 dp_left->db_line_count = line_count_left;
2868 dp_right->db_line_count = line_count_right;
2869
2870 /*
2871 * release the two data blocks
2872 * The new one (hp_new) already has a correct blocknumber.
2873 * The old one (hp, in ml_locked) gets a positive blocknumber if
2874 * we changed it and we are not editing a new file.
2875 */
2876 if (lines_moved || in_left)
2877 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2878 if (!newfile && db_idx >= 0 && in_left)
2879 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2880 mf_put(mfp, hp_new, TRUE, FALSE);
2881
2882 /*
2883 * flush the old data block
2884 * set ml_locked_lineadd to 0, because the updating of the
2885 * pointer blocks is done below
2886 */
2887 lineadd = buf->b_ml.ml_locked_lineadd;
2888 buf->b_ml.ml_locked_lineadd = 0;
2889 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2890
2891 /*
2892 * update pointer blocks for the new data block
2893 */
2894 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2895 --stack_idx)
2896 {
2897 ip = &(buf->b_ml.ml_stack[stack_idx]);
2898 pb_idx = ip->ip_index;
2899 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2900 return FAIL;
2901 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2902 if (pp->pb_id != PTR_ID)
2903 {
2904 EMSG(_("E317: pointer block id wrong 3"));
2905 mf_put(mfp, hp, FALSE, FALSE);
2906 return FAIL;
2907 }
2908 /*
2909 * TODO: If the pointer block is full and we are adding at the end
2910 * try to insert in front of the next block
2911 */
2912 /* block not full, add one entry */
2913 if (pp->pb_count < pp->pb_count_max)
2914 {
2915 if (pb_idx + 1 < (int)pp->pb_count)
2916 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2917 &pp->pb_pointer[pb_idx + 1],
2918 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2919 ++pp->pb_count;
2920 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2921 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2922 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2923 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2924 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2925 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2926
2927 if (lnum_left != 0)
2928 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2929 if (lnum_right != 0)
2930 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2931
2932 mf_put(mfp, hp, TRUE, FALSE);
2933 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2934
2935 if (lineadd)
2936 {
2937 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002938 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 ml_lineadd(buf, lineadd);
2940 /* fix stack itself */
2941 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2942 lineadd;
2943 ++(buf->b_ml.ml_stack_top);
2944 }
2945
2946 /*
2947 * We are finished, break the loop here.
2948 */
2949 break;
2950 }
2951 else /* pointer block full */
2952 {
2953 /*
2954 * split the pointer block
2955 * allocate a new pointer block
2956 * move some of the pointer into the new block
2957 * prepare for updating the parent block
2958 */
2959 for (;;) /* do this twice when splitting block 1 */
2960 {
2961 hp_new = ml_new_ptr(mfp);
2962 if (hp_new == NULL) /* TODO: try to fix tree */
2963 return FAIL;
2964 pp_new = (PTR_BL *)(hp_new->bh_data);
2965
2966 if (hp->bh_bnum != 1)
2967 break;
2968
2969 /*
2970 * if block 1 becomes full the tree is given an extra level
2971 * The pointers from block 1 are moved into the new block.
2972 * block 1 is updated to point to the new block
2973 * then continue to split the new block
2974 */
2975 mch_memmove(pp_new, pp, (size_t)page_size);
2976 pp->pb_count = 1;
2977 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2978 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2979 pp->pb_pointer[0].pe_old_lnum = 1;
2980 pp->pb_pointer[0].pe_page_count = 1;
2981 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2982 hp = hp_new; /* new block is to be split */
2983 pp = pp_new;
2984 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2985 ip->ip_index = 0;
2986 ++stack_idx; /* do block 1 again later */
2987 }
2988 /*
2989 * move the pointers after the current one to the new block
2990 * If there are none, the new entry will be in the new block.
2991 */
2992 total_moved = pp->pb_count - pb_idx - 1;
2993 if (total_moved)
2994 {
2995 mch_memmove(&pp_new->pb_pointer[0],
2996 &pp->pb_pointer[pb_idx + 1],
2997 (size_t)(total_moved) * sizeof(PTR_EN));
2998 pp_new->pb_count = total_moved;
2999 pp->pb_count -= total_moved - 1;
3000 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
3001 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
3002 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
3003 if (lnum_right)
3004 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
3005 }
3006 else
3007 {
3008 pp_new->pb_count = 1;
3009 pp_new->pb_pointer[0].pe_bnum = bnum_right;
3010 pp_new->pb_pointer[0].pe_line_count = line_count_right;
3011 pp_new->pb_pointer[0].pe_page_count = page_count_right;
3012 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
3013 }
3014 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3015 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3016 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3017 if (lnum_left)
3018 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3019 lnum_left = 0;
3020 lnum_right = 0;
3021
3022 /*
3023 * recompute line counts
3024 */
3025 line_count_right = 0;
3026 for (i = 0; i < (int)pp_new->pb_count; ++i)
3027 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3028 line_count_left = 0;
3029 for (i = 0; i < (int)pp->pb_count; ++i)
3030 line_count_left += pp->pb_pointer[i].pe_line_count;
3031
3032 bnum_left = hp->bh_bnum;
3033 bnum_right = hp_new->bh_bnum;
3034 page_count_left = 1;
3035 page_count_right = 1;
3036 mf_put(mfp, hp, TRUE, FALSE);
3037 mf_put(mfp, hp_new, TRUE, FALSE);
3038 }
3039 }
3040
3041 /*
3042 * Safety check: fallen out of for loop?
3043 */
3044 if (stack_idx < 0)
3045 {
3046 EMSG(_("E318: Updated too many blocks?"));
3047 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3048 }
3049 }
3050
3051#ifdef FEAT_BYTEOFF
3052 /* The line was inserted below 'lnum' */
3053 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3054#endif
3055#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003056 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 {
3058 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003059 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003060 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 (char_u *)"\n", 1);
3062 }
3063#endif
3064 return OK;
3065}
3066
3067/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003068 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003070 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071 * copied to allocated memory already.
3072 *
3073 * Check: The caller of this function should probably also call
3074 * changed_lines(), unless update_screen(NOT_VALID) is used.
3075 *
3076 * return FAIL for failure, OK otherwise
3077 */
3078 int
3079ml_replace(lnum, line, copy)
3080 linenr_T lnum;
3081 char_u *line;
3082 int copy;
3083{
3084 if (line == NULL) /* just checking... */
3085 return FAIL;
3086
3087 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003088 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 return FAIL;
3090
3091 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3092 return FAIL;
3093#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003094 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 {
3096 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003097 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 }
3099#endif
3100 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3101 ml_flush_line(curbuf); /* flush it */
3102 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3103 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3104 curbuf->b_ml.ml_line_ptr = line;
3105 curbuf->b_ml.ml_line_lnum = lnum;
3106 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3107
3108 return OK;
3109}
3110
3111/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003112 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 *
3114 * Check: The caller of this function should probably also call
3115 * deleted_lines() after this.
3116 *
3117 * return FAIL for failure, OK otherwise
3118 */
3119 int
3120ml_delete(lnum, message)
3121 linenr_T lnum;
3122 int message;
3123{
3124 ml_flush_line(curbuf);
3125 return ml_delete_int(curbuf, lnum, message);
3126}
3127
3128 static int
3129ml_delete_int(buf, lnum, message)
3130 buf_T *buf;
3131 linenr_T lnum;
3132 int message;
3133{
3134 bhdr_T *hp;
3135 memfile_T *mfp;
3136 DATA_BL *dp;
3137 PTR_BL *pp;
3138 infoptr_T *ip;
3139 int count; /* number of entries in block */
3140 int idx;
3141 int stack_idx;
3142 int text_start;
3143 int line_start;
3144 long line_size;
3145 int i;
3146
3147 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3148 return FAIL;
3149
3150 if (lowest_marked && lowest_marked > lnum)
3151 lowest_marked--;
3152
3153/*
3154 * If the file becomes empty the last line is replaced by an empty line.
3155 */
3156 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3157 {
3158 if (message
3159#ifdef FEAT_NETBEANS_INTG
3160 && !netbeansSuppressNoLines
3161#endif
3162 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003163 set_keep_msg((char_u *)_(no_lines_msg), 0);
3164
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
3166 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3167 buf->b_ml.ml_flags |= ML_EMPTY;
3168
3169 return i;
3170 }
3171
3172/*
3173 * find the data block containing the line
3174 * This also fills the stack with the blocks from the root to the data block
3175 * This also releases any locked block.
3176 */
3177 mfp = buf->b_ml.ml_mfp;
3178 if (mfp == NULL)
3179 return FAIL;
3180
3181 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3182 return FAIL;
3183
3184 dp = (DATA_BL *)(hp->bh_data);
3185 /* compute line count before the delete */
3186 count = (long)(buf->b_ml.ml_locked_high)
3187 - (long)(buf->b_ml.ml_locked_low) + 2;
3188 idx = lnum - buf->b_ml.ml_locked_low;
3189
3190 --buf->b_ml.ml_line_count;
3191
3192 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3193 if (idx == 0) /* first line in block, text at the end */
3194 line_size = dp->db_txt_end - line_start;
3195 else
3196 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3197
3198#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003199 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003200 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201#endif
3202
3203/*
3204 * special case: If there is only one line in the data block it becomes empty.
3205 * Then we have to remove the entry, pointing to this data block, from the
3206 * pointer block. If this pointer block also becomes empty, we go up another
3207 * block, and so on, up to the root if necessary.
3208 * The line counts in the pointer blocks have already been adjusted by
3209 * ml_find_line().
3210 */
3211 if (count == 1)
3212 {
3213 mf_free(mfp, hp); /* free the data block */
3214 buf->b_ml.ml_locked = NULL;
3215
3216 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx)
3217 {
3218 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3219 ip = &(buf->b_ml.ml_stack[stack_idx]);
3220 idx = ip->ip_index;
3221 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3222 return FAIL;
3223 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3224 if (pp->pb_id != PTR_ID)
3225 {
3226 EMSG(_("E317: pointer block id wrong 4"));
3227 mf_put(mfp, hp, FALSE, FALSE);
3228 return FAIL;
3229 }
3230 count = --(pp->pb_count);
3231 if (count == 0) /* the pointer block becomes empty! */
3232 mf_free(mfp, hp);
3233 else
3234 {
3235 if (count != idx) /* move entries after the deleted one */
3236 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3237 (size_t)(count - idx) * sizeof(PTR_EN));
3238 mf_put(mfp, hp, TRUE, FALSE);
3239
3240 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003241 /* fix line count for rest of blocks in the stack */
3242 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 {
3244 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3245 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003246 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 }
3248 ++(buf->b_ml.ml_stack_top);
3249
3250 break;
3251 }
3252 }
3253 CHECK(stack_idx < 0, _("deleted block 1?"));
3254 }
3255 else
3256 {
3257 /*
3258 * delete the text by moving the next lines forwards
3259 */
3260 text_start = dp->db_txt_start;
3261 mch_memmove((char *)dp + text_start + line_size,
3262 (char *)dp + text_start, (size_t)(line_start - text_start));
3263
3264 /*
3265 * delete the index by moving the next indexes backwards
3266 * Adjust the indexes for the text movement.
3267 */
3268 for (i = idx; i < count - 1; ++i)
3269 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3270
3271 dp->db_free += line_size + INDEX_SIZE;
3272 dp->db_txt_start += line_size;
3273 --(dp->db_line_count);
3274
3275 /*
3276 * mark the block dirty and make sure it is in the file (for recovery)
3277 */
3278 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3279 }
3280
3281#ifdef FEAT_BYTEOFF
3282 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3283#endif
3284 return OK;
3285}
3286
3287/*
3288 * set the B_MARKED flag for line 'lnum'
3289 */
3290 void
3291ml_setmarked(lnum)
3292 linenr_T lnum;
3293{
3294 bhdr_T *hp;
3295 DATA_BL *dp;
3296 /* invalid line number */
3297 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3298 || curbuf->b_ml.ml_mfp == NULL)
3299 return; /* give error message? */
3300
3301 if (lowest_marked == 0 || lowest_marked > lnum)
3302 lowest_marked = lnum;
3303
3304 /*
3305 * find the data block containing the line
3306 * This also fills the stack with the blocks from the root to the data block
3307 * This also releases any locked block.
3308 */
3309 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3310 return; /* give error message? */
3311
3312 dp = (DATA_BL *)(hp->bh_data);
3313 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3314 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3315}
3316
3317/*
3318 * find the first line with its B_MARKED flag set
3319 */
3320 linenr_T
3321ml_firstmarked()
3322{
3323 bhdr_T *hp;
3324 DATA_BL *dp;
3325 linenr_T lnum;
3326 int i;
3327
3328 if (curbuf->b_ml.ml_mfp == NULL)
3329 return (linenr_T) 0;
3330
3331 /*
3332 * The search starts with lowest_marked line. This is the last line where
3333 * a mark was found, adjusted by inserting/deleting lines.
3334 */
3335 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3336 {
3337 /*
3338 * Find the data block containing the line.
3339 * This also fills the stack with the blocks from the root to the data
3340 * block This also releases any locked block.
3341 */
3342 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3343 return (linenr_T)0; /* give error message? */
3344
3345 dp = (DATA_BL *)(hp->bh_data);
3346
3347 for (i = lnum - curbuf->b_ml.ml_locked_low;
3348 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3349 if ((dp->db_index[i]) & DB_MARKED)
3350 {
3351 (dp->db_index[i]) &= DB_INDEX_MASK;
3352 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3353 lowest_marked = lnum + 1;
3354 return lnum;
3355 }
3356 }
3357
3358 return (linenr_T) 0;
3359}
3360
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361/*
3362 * clear all DB_MARKED flags
3363 */
3364 void
3365ml_clearmarked()
3366{
3367 bhdr_T *hp;
3368 DATA_BL *dp;
3369 linenr_T lnum;
3370 int i;
3371
3372 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3373 return;
3374
3375 /*
3376 * The search starts with line lowest_marked.
3377 */
3378 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3379 {
3380 /*
3381 * Find the data block containing the line.
3382 * This also fills the stack with the blocks from the root to the data
3383 * block and releases any locked block.
3384 */
3385 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3386 return; /* give error message? */
3387
3388 dp = (DATA_BL *)(hp->bh_data);
3389
3390 for (i = lnum - curbuf->b_ml.ml_locked_low;
3391 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3392 if ((dp->db_index[i]) & DB_MARKED)
3393 {
3394 (dp->db_index[i]) &= DB_INDEX_MASK;
3395 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3396 }
3397 }
3398
3399 lowest_marked = 0;
3400 return;
3401}
3402
3403/*
3404 * flush ml_line if necessary
3405 */
3406 static void
3407ml_flush_line(buf)
3408 buf_T *buf;
3409{
3410 bhdr_T *hp;
3411 DATA_BL *dp;
3412 linenr_T lnum;
3413 char_u *new_line;
3414 char_u *old_line;
3415 colnr_T new_len;
3416 int old_len;
3417 int extra;
3418 int idx;
3419 int start;
3420 int count;
3421 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003422 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423
3424 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3425 return; /* nothing to do */
3426
3427 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3428 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003429 /* This code doesn't work recursively, but Netbeans may call back here
3430 * when obtaining the cursor position. */
3431 if (entered)
3432 return;
3433 entered = TRUE;
3434
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435 lnum = buf->b_ml.ml_line_lnum;
3436 new_line = buf->b_ml.ml_line_ptr;
3437
3438 hp = ml_find_line(buf, lnum, ML_FIND);
3439 if (hp == NULL)
3440 EMSGN(_("E320: Cannot find line %ld"), lnum);
3441 else
3442 {
3443 dp = (DATA_BL *)(hp->bh_data);
3444 idx = lnum - buf->b_ml.ml_locked_low;
3445 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3446 old_line = (char_u *)dp + start;
3447 if (idx == 0) /* line is last in block */
3448 old_len = dp->db_txt_end - start;
3449 else /* text of previous line follows */
3450 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3451 new_len = (colnr_T)STRLEN(new_line) + 1;
3452 extra = new_len - old_len; /* negative if lines gets smaller */
3453
3454 /*
3455 * if new line fits in data block, replace directly
3456 */
3457 if ((int)dp->db_free >= extra)
3458 {
3459 /* if the length changes and there are following lines */
3460 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3461 if (extra != 0 && idx < count - 1)
3462 {
3463 /* move text of following lines */
3464 mch_memmove((char *)dp + dp->db_txt_start - extra,
3465 (char *)dp + dp->db_txt_start,
3466 (size_t)(start - dp->db_txt_start));
3467
3468 /* adjust pointers of this and following lines */
3469 for (i = idx + 1; i < count; ++i)
3470 dp->db_index[i] -= extra;
3471 }
3472 dp->db_index[idx] -= extra;
3473
3474 /* adjust free space */
3475 dp->db_free -= extra;
3476 dp->db_txt_start -= extra;
3477
3478 /* copy new line into the data block */
3479 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3480 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3481#ifdef FEAT_BYTEOFF
3482 /* The else case is already covered by the insert and delete */
3483 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3484#endif
3485 }
3486 else
3487 {
3488 /*
3489 * Cannot do it in one data block: Delete and append.
3490 * Append first, because ml_delete_int() cannot delete the
3491 * last line in a buffer, which causes trouble for a buffer
3492 * that has only one line.
3493 * Don't forget to copy the mark!
3494 */
3495 /* How about handling errors??? */
3496 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3497 (dp->db_index[idx] & DB_MARKED));
3498 (void)ml_delete_int(buf, lnum, FALSE);
3499 }
3500 }
3501 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003502
3503 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003504 }
3505
3506 buf->b_ml.ml_line_lnum = 0;
3507}
3508
3509/*
3510 * create a new, empty, data block
3511 */
3512 static bhdr_T *
3513ml_new_data(mfp, negative, page_count)
3514 memfile_T *mfp;
3515 int negative;
3516 int page_count;
3517{
3518 bhdr_T *hp;
3519 DATA_BL *dp;
3520
3521 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3522 return NULL;
3523
3524 dp = (DATA_BL *)(hp->bh_data);
3525 dp->db_id = DATA_ID;
3526 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3527 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3528 dp->db_line_count = 0;
3529
3530 return hp;
3531}
3532
3533/*
3534 * create a new, empty, pointer block
3535 */
3536 static bhdr_T *
3537ml_new_ptr(mfp)
3538 memfile_T *mfp;
3539{
3540 bhdr_T *hp;
3541 PTR_BL *pp;
3542
3543 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3544 return NULL;
3545
3546 pp = (PTR_BL *)(hp->bh_data);
3547 pp->pb_id = PTR_ID;
3548 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003549 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3550 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551
3552 return hp;
3553}
3554
3555/*
3556 * lookup line 'lnum' in a memline
3557 *
3558 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3559 * if ML_FLUSH only flush a locked block
3560 * if ML_FIND just find the line
3561 *
3562 * If the block was found it is locked and put in ml_locked.
3563 * The stack is updated to lead to the locked block. The ip_high field in
3564 * the stack is updated to reflect the last line in the block AFTER the
3565 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003566 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567 *
3568 * return: NULL for failure, pointer to block header otherwise
3569 */
3570 static bhdr_T *
3571ml_find_line(buf, lnum, action)
3572 buf_T *buf;
3573 linenr_T lnum;
3574 int action;
3575{
3576 DATA_BL *dp;
3577 PTR_BL *pp;
3578 infoptr_T *ip;
3579 bhdr_T *hp;
3580 memfile_T *mfp;
3581 linenr_T t;
3582 blocknr_T bnum, bnum2;
3583 int dirty;
3584 linenr_T low, high;
3585 int top;
3586 int page_count;
3587 int idx;
3588
3589 mfp = buf->b_ml.ml_mfp;
3590
3591 /*
3592 * If there is a locked block check if the wanted line is in it.
3593 * If not, flush and release the locked block.
3594 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3595 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003596 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597 */
3598 if (buf->b_ml.ml_locked)
3599 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003600 if (ML_SIMPLE(action)
3601 && buf->b_ml.ml_locked_low <= lnum
3602 && buf->b_ml.ml_locked_high >= lnum
3603 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003605 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 if (action == ML_INSERT)
3607 {
3608 ++(buf->b_ml.ml_locked_lineadd);
3609 ++(buf->b_ml.ml_locked_high);
3610 }
3611 else if (action == ML_DELETE)
3612 {
3613 --(buf->b_ml.ml_locked_lineadd);
3614 --(buf->b_ml.ml_locked_high);
3615 }
3616 return (buf->b_ml.ml_locked);
3617 }
3618
3619 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3620 buf->b_ml.ml_flags & ML_LOCKED_POS);
3621 buf->b_ml.ml_locked = NULL;
3622
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003623 /*
3624 * If lines have been added or deleted in the locked block, need to
3625 * update the line count in pointer blocks.
3626 */
3627 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3629 }
3630
3631 if (action == ML_FLUSH) /* nothing else to do */
3632 return NULL;
3633
3634 bnum = 1; /* start at the root of the tree */
3635 page_count = 1;
3636 low = 1;
3637 high = buf->b_ml.ml_line_count;
3638
3639 if (action == ML_FIND) /* first try stack entries */
3640 {
3641 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3642 {
3643 ip = &(buf->b_ml.ml_stack[top]);
3644 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3645 {
3646 bnum = ip->ip_bnum;
3647 low = ip->ip_low;
3648 high = ip->ip_high;
3649 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3650 break;
3651 }
3652 }
3653 if (top < 0)
3654 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3655 }
3656 else /* ML_DELETE or ML_INSERT */
3657 buf->b_ml.ml_stack_top = 0; /* start at the root */
3658
3659/*
3660 * search downwards in the tree until a data block is found
3661 */
3662 for (;;)
3663 {
3664 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3665 goto error_noblock;
3666
3667 /*
3668 * update high for insert/delete
3669 */
3670 if (action == ML_INSERT)
3671 ++high;
3672 else if (action == ML_DELETE)
3673 --high;
3674
3675 dp = (DATA_BL *)(hp->bh_data);
3676 if (dp->db_id == DATA_ID) /* data block */
3677 {
3678 buf->b_ml.ml_locked = hp;
3679 buf->b_ml.ml_locked_low = low;
3680 buf->b_ml.ml_locked_high = high;
3681 buf->b_ml.ml_locked_lineadd = 0;
3682 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3683 return hp;
3684 }
3685
3686 pp = (PTR_BL *)(dp); /* must be pointer block */
3687 if (pp->pb_id != PTR_ID)
3688 {
3689 EMSG(_("E317: pointer block id wrong"));
3690 goto error_block;
3691 }
3692
3693 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3694 goto error_block;
3695 ip = &(buf->b_ml.ml_stack[top]);
3696 ip->ip_bnum = bnum;
3697 ip->ip_low = low;
3698 ip->ip_high = high;
3699 ip->ip_index = -1; /* index not known yet */
3700
3701 dirty = FALSE;
3702 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3703 {
3704 t = pp->pb_pointer[idx].pe_line_count;
3705 CHECK(t == 0, _("pe_line_count is zero"));
3706 if ((low += t) > lnum)
3707 {
3708 ip->ip_index = idx;
3709 bnum = pp->pb_pointer[idx].pe_bnum;
3710 page_count = pp->pb_pointer[idx].pe_page_count;
3711 high = low - 1;
3712 low -= t;
3713
3714 /*
3715 * a negative block number may have been changed
3716 */
3717 if (bnum < 0)
3718 {
3719 bnum2 = mf_trans_del(mfp, bnum);
3720 if (bnum != bnum2)
3721 {
3722 bnum = bnum2;
3723 pp->pb_pointer[idx].pe_bnum = bnum;
3724 dirty = TRUE;
3725 }
3726 }
3727
3728 break;
3729 }
3730 }
3731 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3732 {
3733 if (lnum > buf->b_ml.ml_line_count)
3734 EMSGN(_("E322: line number out of range: %ld past the end"),
3735 lnum - buf->b_ml.ml_line_count);
3736
3737 else
3738 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3739 goto error_block;
3740 }
3741 if (action == ML_DELETE)
3742 {
3743 pp->pb_pointer[idx].pe_line_count--;
3744 dirty = TRUE;
3745 }
3746 else if (action == ML_INSERT)
3747 {
3748 pp->pb_pointer[idx].pe_line_count++;
3749 dirty = TRUE;
3750 }
3751 mf_put(mfp, hp, dirty, FALSE);
3752 }
3753
3754error_block:
3755 mf_put(mfp, hp, FALSE, FALSE);
3756error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003757 /*
3758 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3759 * the incremented/decremented line counts, because there won't be a line
3760 * inserted/deleted after all.
3761 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 if (action == ML_DELETE)
3763 ml_lineadd(buf, 1);
3764 else if (action == ML_INSERT)
3765 ml_lineadd(buf, -1);
3766 buf->b_ml.ml_stack_top = 0;
3767 return NULL;
3768}
3769
3770/*
3771 * add an entry to the info pointer stack
3772 *
3773 * return -1 for failure, number of the new entry otherwise
3774 */
3775 static int
3776ml_add_stack(buf)
3777 buf_T *buf;
3778{
3779 int top;
3780 infoptr_T *newstack;
3781
3782 top = buf->b_ml.ml_stack_top;
3783
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003784 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 if (top == buf->b_ml.ml_stack_size)
3786 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003787 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788
3789 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3790 (buf->b_ml.ml_stack_size + STACK_INCR));
3791 if (newstack == NULL)
3792 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003793 mch_memmove(newstack, buf->b_ml.ml_stack,
3794 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 vim_free(buf->b_ml.ml_stack);
3796 buf->b_ml.ml_stack = newstack;
3797 buf->b_ml.ml_stack_size += STACK_INCR;
3798 }
3799
3800 buf->b_ml.ml_stack_top++;
3801 return top;
3802}
3803
3804/*
3805 * Update the pointer blocks on the stack for inserted/deleted lines.
3806 * The stack itself is also updated.
3807 *
3808 * When a insert/delete line action fails, the line is not inserted/deleted,
3809 * but the pointer blocks have already been updated. That is fixed here by
3810 * walking through the stack.
3811 *
3812 * Count is the number of lines added, negative if lines have been deleted.
3813 */
3814 static void
3815ml_lineadd(buf, count)
3816 buf_T *buf;
3817 int count;
3818{
3819 int idx;
3820 infoptr_T *ip;
3821 PTR_BL *pp;
3822 memfile_T *mfp = buf->b_ml.ml_mfp;
3823 bhdr_T *hp;
3824
3825 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3826 {
3827 ip = &(buf->b_ml.ml_stack[idx]);
3828 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3829 break;
3830 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3831 if (pp->pb_id != PTR_ID)
3832 {
3833 mf_put(mfp, hp, FALSE, FALSE);
3834 EMSG(_("E317: pointer block id wrong 2"));
3835 break;
3836 }
3837 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3838 ip->ip_high += count;
3839 mf_put(mfp, hp, TRUE, FALSE);
3840 }
3841}
3842
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003843#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003844/*
3845 * Resolve a symlink in the last component of a file name.
3846 * Note that f_resolve() does it for every part of the path, we don't do that
3847 * here.
3848 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3849 * Otherwise returns FAIL.
3850 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003851 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003852resolve_symlink(fname, buf)
3853 char_u *fname;
3854 char_u *buf;
3855{
3856 char_u tmp[MAXPATHL];
3857 int ret;
3858 int depth = 0;
3859
3860 if (fname == NULL)
3861 return FAIL;
3862
3863 /* Put the result so far in tmp[], starting with the original name. */
3864 vim_strncpy(tmp, fname, MAXPATHL - 1);
3865
3866 for (;;)
3867 {
3868 /* Limit symlink depth to 100, catch recursive loops. */
3869 if (++depth == 100)
3870 {
3871 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3872 return FAIL;
3873 }
3874
3875 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3876 if (ret <= 0)
3877 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003878 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003879 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003880 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003881 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003882 * call to vim_FullName(). */
3883 if (depth == 1)
3884 return FAIL;
3885
3886 /* Use the resolved name in tmp[]. */
3887 break;
3888 }
3889
3890 /* There must be some error reading links, use original name. */
3891 return FAIL;
3892 }
3893 buf[ret] = NUL;
3894
3895 /*
3896 * Check whether the symlink is relative or absolute.
3897 * If it's relative, build a new path based on the directory
3898 * portion of the filename (if any) and the path the symlink
3899 * points to.
3900 */
3901 if (mch_isFullName(buf))
3902 STRCPY(tmp, buf);
3903 else
3904 {
3905 char_u *tail;
3906
3907 tail = gettail(tmp);
3908 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3909 return FAIL;
3910 STRCPY(tail, buf);
3911 }
3912 }
3913
3914 /*
3915 * Try to resolve the full name of the file so that the swapfile name will
3916 * be consistent even when opening a relative symlink from different
3917 * working directories.
3918 */
3919 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3920}
3921#endif
3922
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003924 * Make swap file name out of the file name and a directory name.
3925 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003927 char_u *
3928makeswapname(fname, ffname, buf, dir_name)
3929 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003930 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931 buf_T *buf;
3932 char_u *dir_name;
3933{
3934 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003935 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003936#ifdef HAVE_READLINK
3937 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003938#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939
3940#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3941 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003942 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 { /* Ends with '//', Use Full path */
3944 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003945 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 {
3947 r = modname(s, (char_u *)".swp", FALSE);
3948 vim_free(s);
3949 }
3950 return r;
3951 }
3952#endif
3953
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003954#ifdef HAVE_READLINK
3955 /* Expand symlink in the file name, so that we put the swap file with the
3956 * actual file instead of with the symlink. */
3957 if (resolve_symlink(fname, fname_buf) == OK)
3958 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003959#endif
3960
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 r = buf_modname(
3962#ifdef SHORT_FNAME
3963 TRUE,
3964#else
3965 (buf->b_p_sn || buf->b_shortname),
3966#endif
Bram Moolenaar38323e42007-03-06 19:22:53 +00003967#ifdef RISCOS
3968 /* Avoid problems if fname has special chars, eg <Wimp$Scrap> */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003969 ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003970#else
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003971 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972#endif
3973 (char_u *)
3974#if defined(VMS) || defined(RISCOS)
3975 "_swp",
3976#else
3977 ".swp",
3978#endif
3979#ifdef SHORT_FNAME /* always 8.3 file name */
3980 FALSE
3981#else
3982 /* Prepend a '.' to the swap file name for the current directory. */
3983 dir_name[0] == '.' && dir_name[1] == NUL
3984#endif
3985 );
3986 if (r == NULL) /* out of memory */
3987 return NULL;
3988
3989 s = get_file_in_dir(r, dir_name);
3990 vim_free(r);
3991 return s;
3992}
3993
3994/*
3995 * Get file name to use for swap file or backup file.
3996 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3997 * option "dname".
3998 * - If "dname" is ".", return "fname" (swap file in dir of file).
3999 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
4000 * relative to dir of file).
4001 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
4002 * dir).
4003 *
4004 * The return value is an allocated string and can be NULL.
4005 */
4006 char_u *
4007get_file_in_dir(fname, dname)
4008 char_u *fname;
4009 char_u *dname; /* don't use "dirname", it is a global for Alpha */
4010{
4011 char_u *t;
4012 char_u *tail;
4013 char_u *retval;
4014 int save_char;
4015
4016 tail = gettail(fname);
4017
4018 if (dname[0] == '.' && dname[1] == NUL)
4019 retval = vim_strsave(fname);
4020 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
4021 {
4022 if (tail == fname) /* no path before file name */
4023 retval = concat_fnames(dname + 2, tail, TRUE);
4024 else
4025 {
4026 save_char = *tail;
4027 *tail = NUL;
4028 t = concat_fnames(fname, dname + 2, TRUE);
4029 *tail = save_char;
4030 if (t == NULL) /* out of memory */
4031 retval = NULL;
4032 else
4033 {
4034 retval = concat_fnames(t, tail, TRUE);
4035 vim_free(t);
4036 }
4037 }
4038 }
4039 else
4040 retval = concat_fnames(dname, tail, TRUE);
4041
4042 return retval;
4043}
4044
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004045static void attention_message __ARGS((buf_T *buf, char_u *fname));
4046
4047/*
4048 * Print the ATTENTION message: info about an existing swap file.
4049 */
4050 static void
4051attention_message(buf, fname)
4052 buf_T *buf; /* buffer being edited */
4053 char_u *fname; /* swap file name */
4054{
4055 struct stat st;
4056 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004057 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004058
4059 ++no_wait_return;
4060 (void)EMSG(_("E325: ATTENTION"));
4061 MSG_PUTS(_("\nFound a swap file by the name \""));
4062 msg_home_replace(fname);
4063 MSG_PUTS("\"\n");
4064 sx = swapfile_info(fname);
4065 MSG_PUTS(_("While opening file \""));
4066 msg_outtrans(buf->b_fname);
4067 MSG_PUTS("\"\n");
4068 if (mch_stat((char *)buf->b_fname, &st) != -1)
4069 {
4070 MSG_PUTS(_(" dated: "));
4071 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004072 p = ctime(&x); /* includes '\n' */
4073 if (p == NULL)
4074 MSG_PUTS("(invalid)\n");
4075 else
4076 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004077 if (sx != 0 && x > sx)
4078 MSG_PUTS(_(" NEWER than swap file!\n"));
4079 }
4080 /* Some of these messages are long to allow translation to
4081 * other languages. */
4082 MSG_PUTS(_("\n(1) Another program may be editing the same file.\n If this is the case, be careful not to end up with two\n different instances of the same file when making changes.\n"));
4083 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4084 MSG_PUTS(_("\n(2) An edit session for this file crashed.\n"));
4085 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4086 msg_outtrans(buf->b_fname);
4087 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4088 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4089 msg_outtrans(fname);
4090 MSG_PUTS(_("\"\n to avoid this message.\n"));
4091 cmdline_row = msg_row;
4092 --no_wait_return;
4093}
4094
4095#ifdef FEAT_AUTOCMD
4096static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4097
4098/*
4099 * Trigger the SwapExists autocommands.
4100 * Returns a value for equivalent to do_dialog() (see below):
4101 * 0: still need to ask for a choice
4102 * 1: open read-only
4103 * 2: edit anyway
4104 * 3: recover
4105 * 4: delete it
4106 * 5: quit
4107 * 6: abort
4108 */
4109 static int
4110do_swapexists(buf, fname)
4111 buf_T *buf;
4112 char_u *fname;
4113{
4114 set_vim_var_string(VV_SWAPNAME, fname, -1);
4115 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4116
4117 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004118 * edited. Disallow changing directory here. */
4119 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004120 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004121 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004122
4123 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4124
4125 switch (*get_vim_var_str(VV_SWAPCHOICE))
4126 {
4127 case 'o': return 1;
4128 case 'e': return 2;
4129 case 'r': return 3;
4130 case 'd': return 4;
4131 case 'q': return 5;
4132 case 'a': return 6;
4133 }
4134
4135 return 0;
4136}
4137#endif
4138
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139/*
4140 * Find out what name to use for the swap file for buffer 'buf'.
4141 *
4142 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004143 * Returns the name in allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 *
4145 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004146 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004147 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 */
4149 static char_u *
4150findswapname(buf, dirp, old_fname)
4151 buf_T *buf;
4152 char_u **dirp; /* pointer to list of directories */
4153 char_u *old_fname; /* don't give warning for this file name */
4154{
4155 char_u *fname;
4156 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 char_u *dir_name;
4158#ifdef AMIGA
4159 BPTR fh;
4160#endif
4161#ifndef SHORT_FNAME
4162 int r;
4163#endif
4164
4165#if !defined(SHORT_FNAME) \
4166 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
4167# define CREATE_DUMMY_FILE
4168 FILE *dummyfd = NULL;
4169
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004170 /*
4171 * If we start editing a new file, e.g. "test.doc", which resides on an
4172 * MSDOS compatible filesystem, it is possible that the file
4173 * "test.doc.swp" which we create will be exactly the same file. To avoid
4174 * this problem we temporarily create "test.doc". Don't do this when the
4175 * check below for a 8.3 file name is used.
4176 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
4178 && mch_getperm(buf->b_fname) < 0)
4179 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4180#endif
4181
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004182 /*
4183 * Isolate a directory name from *dirp and put it in dir_name.
4184 * First allocate some memory to put the directory name in.
4185 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
4187 if (dir_name != NULL)
4188 (void)copy_option_part(dirp, dir_name, 31000, ",");
4189
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004190 /*
4191 * we try different names until we find one that does not exist yet
4192 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 if (dir_name == NULL) /* out of memory */
4194 fname = NULL;
4195 else
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004196 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197
4198 for (;;)
4199 {
4200 if (fname == NULL) /* must be out of memory */
4201 break;
4202 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4203 {
4204 vim_free(fname);
4205 fname = NULL;
4206 break;
4207 }
4208#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4209/*
4210 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4211 * file names. If this is the first try and the swap file name does not fit in
4212 * 8.3, detect if this is the case, set shortname and try again.
4213 */
4214 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4215 && !(buf->b_p_sn || buf->b_shortname))
4216 {
4217 char_u *tail;
4218 char_u *fname2;
4219 struct stat s1, s2;
4220 int f1, f2;
4221 int created1 = FALSE, created2 = FALSE;
4222 int same = FALSE;
4223
4224 /*
4225 * Check if swapfile name does not fit in 8.3:
4226 * It either contains two dots, is longer than 8 chars, or starts
4227 * with a dot.
4228 */
4229 tail = gettail(buf->b_fname);
4230 if ( vim_strchr(tail, '.') != NULL
4231 || STRLEN(tail) > (size_t)8
4232 || *gettail(fname) == '.')
4233 {
4234 fname2 = alloc(n + 2);
4235 if (fname2 != NULL)
4236 {
4237 STRCPY(fname2, fname);
4238 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4239 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4240 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4241 */
4242 if (vim_strchr(tail, '.') != NULL)
4243 fname2[n - 1] = 'x';
4244 else if (*gettail(fname) == '.')
4245 {
4246 fname2[n] = 'x';
4247 fname2[n + 1] = NUL;
4248 }
4249 else
4250 fname2[n - 5] += 1;
4251 /*
4252 * may need to create the files to be able to use mch_stat()
4253 */
4254 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4255 if (f1 < 0)
4256 {
4257 f1 = mch_open_rw((char *)fname,
4258 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4259#if defined(OS2)
4260 if (f1 < 0 && errno == ENOENT)
4261 same = TRUE;
4262#endif
4263 created1 = TRUE;
4264 }
4265 if (f1 >= 0)
4266 {
4267 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4268 if (f2 < 0)
4269 {
4270 f2 = mch_open_rw((char *)fname2,
4271 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4272 created2 = TRUE;
4273 }
4274 if (f2 >= 0)
4275 {
4276 /*
4277 * Both files exist now. If mch_stat() returns the
4278 * same device and inode they are the same file.
4279 */
4280 if (mch_fstat(f1, &s1) != -1
4281 && mch_fstat(f2, &s2) != -1
4282 && s1.st_dev == s2.st_dev
4283 && s1.st_ino == s2.st_ino)
4284 same = TRUE;
4285 close(f2);
4286 if (created2)
4287 mch_remove(fname2);
4288 }
4289 close(f1);
4290 if (created1)
4291 mch_remove(fname);
4292 }
4293 vim_free(fname2);
4294 if (same)
4295 {
4296 buf->b_shortname = TRUE;
4297 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004298 fname = makeswapname(buf->b_fname, buf->b_ffname,
4299 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 continue; /* try again with b_shortname set */
4301 }
4302 }
4303 }
4304 }
4305#endif
4306 /*
4307 * check if the swapfile already exists
4308 */
4309 if (mch_getperm(fname) < 0) /* it does not exist */
4310 {
4311#ifdef HAVE_LSTAT
4312 struct stat sb;
4313
4314 /*
4315 * Extra security check: When a swap file is a symbolic link, this
4316 * is most likely a symlink attack.
4317 */
4318 if (mch_lstat((char *)fname, &sb) < 0)
4319#else
4320# ifdef AMIGA
4321 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4322 /*
4323 * on the Amiga mch_getperm() will return -1 when the file exists
4324 * but is being used by another program. This happens if you edit
4325 * a file twice.
4326 */
4327 if (fh != (BPTR)NULL) /* can open file, OK */
4328 {
4329 Close(fh);
4330 mch_remove(fname);
4331 break;
4332 }
4333 if (IoErr() != ERROR_OBJECT_IN_USE
4334 && IoErr() != ERROR_OBJECT_EXISTS)
4335# endif
4336#endif
4337 break;
4338 }
4339
4340 /*
4341 * A file name equal to old_fname is OK to use.
4342 */
4343 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4344 break;
4345
4346 /*
4347 * get here when file already exists
4348 */
4349 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4350 {
4351#ifndef SHORT_FNAME
4352 /*
4353 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4354 * and file.doc are the same file. To guess if this problem is
4355 * present try if file.doc.swx exists. If it does, we set
4356 * buf->b_shortname and try file_doc.swp (dots replaced by
4357 * underscores for this file), and try again. If it doesn't we
4358 * assume that "file.doc.swp" already exists.
4359 */
4360 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4361 {
4362 fname[n - 1] = 'x';
4363 r = mch_getperm(fname); /* try "file.swx" */
4364 fname[n - 1] = 'p';
4365 if (r >= 0) /* "file.swx" seems to exist */
4366 {
4367 buf->b_shortname = TRUE;
4368 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004369 fname = makeswapname(buf->b_fname, buf->b_ffname,
4370 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004371 continue; /* try again with '.' replaced with '_' */
4372 }
4373 }
4374#endif
4375 /*
4376 * If we get here the ".swp" file really exists.
4377 * Give an error message, unless recovering, no file name, we are
4378 * viewing a help file or when the path of the file is different
4379 * (happens when all .swp files are in one directory).
4380 */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004381 if (!recoverymode && buf->b_fname != NULL
4382 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 {
4384 int fd;
4385 struct block0 b0;
4386 int differ = FALSE;
4387
4388 /*
4389 * Try to read block 0 from the swap file to get the original
4390 * file name (and inode number).
4391 */
4392 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4393 if (fd >= 0)
4394 {
4395 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
4396 {
4397 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004398 * If the swapfile has the same directory as the
4399 * buffer don't compare the directory names, they can
4400 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004401 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004402 if (b0.b0_flags & B0_SAME_DIR)
4403 {
4404 if (fnamecmp(gettail(buf->b_ffname),
4405 gettail(b0.b0_fname)) != 0
4406 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004407 {
4408#ifdef CHECK_INODE
4409 /* Symlinks may point to the same file even
4410 * when the name differs, need to check the
4411 * inode too. */
4412 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4413 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4414 char_to_long(b0.b0_ino)))
4415#endif
4416 differ = TRUE;
4417 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004418 }
4419 else
4420 {
4421 /*
4422 * The name in the swap file may be
4423 * "~user/path/file". Expand it first.
4424 */
4425 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004426#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004427 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004428 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004429 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004431 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4432 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 }
4436 close(fd);
4437 }
4438#ifdef RISCOS
4439 else
4440 /* Can't open swap file, though it does exist.
4441 * Assume that the user is editing two files with
4442 * the same name in different directories. No error.
4443 */
4444 differ = TRUE;
4445#endif
4446
4447 /* give the ATTENTION message when there is an old swap file
4448 * for the current file, and the buffer was not recovered. */
4449 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4450 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4451 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004452#if defined(HAS_SWAP_EXISTS_ACTION)
4453 int choice = 0;
4454#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455#ifdef CREATE_DUMMY_FILE
4456 int did_use_dummy = FALSE;
4457
4458 /* Avoid getting a warning for the file being created
4459 * outside of Vim, it was created at the start of this
4460 * function. Delete the file now, because Vim might exit
4461 * here if the window is closed. */
4462 if (dummyfd != NULL)
4463 {
4464 fclose(dummyfd);
4465 dummyfd = NULL;
4466 mch_remove(buf->b_fname);
4467 did_use_dummy = TRUE;
4468 }
4469#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470
4471#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4472 process_still_running = FALSE;
4473#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004474#ifdef FEAT_AUTOCMD
4475 /*
4476 * If there is an SwapExists autocommand and we can handle
4477 * the response, trigger it. It may return 0 to ask the
4478 * user anyway.
4479 */
4480 if (swap_exists_action != SEA_NONE
4481 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4482 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004484 if (choice == 0)
4485#endif
4486 {
4487#ifdef FEAT_GUI
4488 /* If we are supposed to start the GUI but it wasn't
4489 * completely started yet, start it now. This makes
4490 * the messages displayed in the Vim window when
4491 * loading a session from the .gvimrc file. */
4492 if (gui.starting && !gui.in_use)
4493 gui_start();
4494#endif
4495 /* Show info about the existing swap file. */
4496 attention_message(buf, fname);
4497
4498 /* We don't want a 'q' typed at the more-prompt
4499 * interrupt loading a file. */
4500 got_int = FALSE;
4501 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502
4503#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004504 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 {
4506 char_u *name;
4507
4508 name = alloc((unsigned)(STRLEN(fname)
4509 + STRLEN(_("Swap file \""))
4510 + STRLEN(_("\" already exists!")) + 5));
4511 if (name != NULL)
4512 {
4513 STRCPY(name, _("Swap file \""));
4514 home_replace(NULL, fname, name + STRLEN(name),
4515 1000, TRUE);
4516 STRCAT(name, _("\" already exists!"));
4517 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004518 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519 (char_u *)_("VIM - ATTENTION"),
4520 name == NULL
4521 ? (char_u *)_("Swap file already exists!")
4522 : name,
4523# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4524 process_still_running
4525 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4526# endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004527 (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL);
4528
4529# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4530 if (process_still_running && choice >= 4)
4531 choice++; /* Skip missing "Delete it" button */
4532# endif
4533 vim_free(name);
4534
4535 /* pretend screen didn't scroll, need redraw anyway */
4536 msg_scrolled = 0;
4537 redraw_all_later(NOT_VALID);
4538 }
4539#endif
4540
4541#if defined(HAS_SWAP_EXISTS_ACTION)
4542 if (choice > 0)
4543 {
4544 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 {
4546 case 1:
4547 buf->b_p_ro = TRUE;
4548 break;
4549 case 2:
4550 break;
4551 case 3:
4552 swap_exists_action = SEA_RECOVER;
4553 break;
4554 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004555 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 break;
4557 case 5:
4558 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004559 break;
4560 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004561 swap_exists_action = SEA_QUIT;
4562 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 break;
4564 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565
4566 /* If the file was deleted this fname can be used. */
4567 if (mch_getperm(fname) < 0)
4568 break;
4569 }
4570 else
4571#endif
4572 {
4573 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004574 if (msg_silent == 0)
4575 /* call wait_return() later */
4576 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 }
4578
4579#ifdef CREATE_DUMMY_FILE
4580 /* Going to try another name, need the dummy file again. */
4581 if (did_use_dummy)
4582 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4583#endif
4584 }
4585 }
4586 }
4587
4588 /*
4589 * Change the ".swp" extension to find another file that can be used.
4590 * First decrement the last char: ".swo", ".swn", etc.
4591 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004592 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004593 */
4594 if (fname[n - 1] == 'a') /* ".s?a" */
4595 {
4596 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4597 {
4598 EMSG(_("E326: Too many swap files found"));
4599 vim_free(fname);
4600 fname = NULL;
4601 break;
4602 }
4603 --fname[n - 2]; /* ".svz", ".suz", etc. */
4604 fname[n - 1] = 'z' + 1;
4605 }
4606 --fname[n - 1]; /* ".swo", ".swn", etc. */
4607 }
4608
4609 vim_free(dir_name);
4610#ifdef CREATE_DUMMY_FILE
4611 if (dummyfd != NULL) /* file has been created temporarily */
4612 {
4613 fclose(dummyfd);
4614 mch_remove(buf->b_fname);
4615 }
4616#endif
4617 return fname;
4618}
4619
4620 static int
4621b0_magic_wrong(b0p)
4622 ZERO_BL *b0p;
4623{
4624 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4625 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4626 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4627 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4628}
4629
4630#ifdef CHECK_INODE
4631/*
4632 * Compare current file name with file name from swap file.
4633 * Try to use inode numbers when possible.
4634 * Return non-zero when files are different.
4635 *
4636 * When comparing file names a few things have to be taken into consideration:
4637 * - When working over a network the full path of a file depends on the host.
4638 * We check the inode number if possible. It is not 100% reliable though,
4639 * because the device number cannot be used over a network.
4640 * - When a file does not exist yet (editing a new file) there is no inode
4641 * number.
4642 * - The file name in a swap file may not be valid on the current host. The
4643 * "~user" form is used whenever possible to avoid this.
4644 *
4645 * This is getting complicated, let's make a table:
4646 *
4647 * ino_c ino_s fname_c fname_s differ =
4648 *
4649 * both files exist -> compare inode numbers:
4650 * != 0 != 0 X X ino_c != ino_s
4651 *
4652 * inode number(s) unknown, file names available -> compare file names
4653 * == 0 X OK OK fname_c != fname_s
4654 * X == 0 OK OK fname_c != fname_s
4655 *
4656 * current file doesn't exist, file for swap file exist, file name(s) not
4657 * available -> probably different
4658 * == 0 != 0 FAIL X TRUE
4659 * == 0 != 0 X FAIL TRUE
4660 *
4661 * current file exists, inode for swap unknown, file name(s) not
4662 * available -> probably different
4663 * != 0 == 0 FAIL X TRUE
4664 * != 0 == 0 X FAIL TRUE
4665 *
4666 * current file doesn't exist, inode for swap unknown, one file name not
4667 * available -> probably different
4668 * == 0 == 0 FAIL OK TRUE
4669 * == 0 == 0 OK FAIL TRUE
4670 *
4671 * current file doesn't exist, inode for swap unknown, both file names not
4672 * available -> probably same file
4673 * == 0 == 0 FAIL FAIL FALSE
4674 *
4675 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4676 * can't be changed without making the block 0 incompatible with 32 bit
4677 * versions.
4678 */
4679
4680 static int
4681fnamecmp_ino(fname_c, fname_s, ino_block0)
4682 char_u *fname_c; /* current file name */
4683 char_u *fname_s; /* file name from swap file */
4684 long ino_block0;
4685{
4686 struct stat st;
4687 ino_t ino_c = 0; /* ino of current file */
4688 ino_t ino_s; /* ino of file from swap file */
4689 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4690 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4691 int retval_c; /* flag: buf_c valid */
4692 int retval_s; /* flag: buf_s valid */
4693
4694 if (mch_stat((char *)fname_c, &st) == 0)
4695 ino_c = (ino_t)st.st_ino;
4696
4697 /*
4698 * First we try to get the inode from the file name, because the inode in
4699 * the swap file may be outdated. If that fails (e.g. this path is not
4700 * valid on this machine), use the inode from block 0.
4701 */
4702 if (mch_stat((char *)fname_s, &st) == 0)
4703 ino_s = (ino_t)st.st_ino;
4704 else
4705 ino_s = (ino_t)ino_block0;
4706
4707 if (ino_c && ino_s)
4708 return (ino_c != ino_s);
4709
4710 /*
4711 * One of the inode numbers is unknown, try a forced vim_FullName() and
4712 * compare the file names.
4713 */
4714 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4715 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4716 if (retval_c == OK && retval_s == OK)
4717 return (STRCMP(buf_c, buf_s) != 0);
4718
4719 /*
4720 * Can't compare inodes or file names, guess that the files are different,
4721 * unless both appear not to exist at all.
4722 */
4723 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4724 return FALSE;
4725 return TRUE;
4726}
4727#endif /* CHECK_INODE */
4728
4729/*
4730 * Move a long integer into a four byte character array.
4731 * Used for machine independency in block zero.
4732 */
4733 static void
4734long_to_char(n, s)
4735 long n;
4736 char_u *s;
4737{
4738 s[0] = (char_u)(n & 0xff);
4739 n = (unsigned)n >> 8;
4740 s[1] = (char_u)(n & 0xff);
4741 n = (unsigned)n >> 8;
4742 s[2] = (char_u)(n & 0xff);
4743 n = (unsigned)n >> 8;
4744 s[3] = (char_u)(n & 0xff);
4745}
4746
4747 static long
4748char_to_long(s)
4749 char_u *s;
4750{
4751 long retval;
4752
4753 retval = s[3];
4754 retval <<= 8;
4755 retval |= s[2];
4756 retval <<= 8;
4757 retval |= s[1];
4758 retval <<= 8;
4759 retval |= s[0];
4760
4761 return retval;
4762}
4763
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004764/*
4765 * Set the flags in the first block of the swap file:
4766 * - file is modified or not: buf->b_changed
4767 * - 'fileformat'
4768 * - 'fileencoding'
4769 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004771ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773{
4774 bhdr_T *hp;
4775 ZERO_BL *b0p;
4776
4777 if (!buf->b_ml.ml_mfp)
4778 return;
4779 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4780 {
4781 if (hp->bh_bnum == 0)
4782 {
4783 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004784 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4785 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4786 | (get_fileformat(buf) + 1);
4787#ifdef FEAT_MBYTE
4788 add_b0_fenc(b0p, buf);
4789#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 hp->bh_flags |= BH_DIRTY;
4791 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4792 break;
4793 }
4794 }
4795}
4796
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004797#if defined(FEAT_CRYPT) || defined(PROTO)
4798/*
4799 * If "data" points to a data block encrypt the text in it and return a copy
4800 * in allocated memory. Return NULL when out of memory.
4801 * Otherwise return "data".
4802 */
4803 char_u *
4804ml_encrypt_data(mfp, data, offset, size)
4805 memfile_T *mfp;
4806 char_u *data;
4807 off_t offset;
4808 unsigned size;
4809{
4810 DATA_BL *dp = (DATA_BL *)data;
4811 char_u *head_end;
4812 char_u *text_start;
4813 char_u *new_data;
4814 int text_len;
4815
4816 if (dp->db_id != DATA_ID)
4817 return data;
4818
4819 new_data = (char_u *)alloc(size);
4820 if (new_data == NULL)
4821 return NULL;
4822 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4823 text_start = (char_u *)dp + dp->db_txt_start;
4824 text_len = size - dp->db_txt_start;
4825
4826 /* Copy the header and the text. */
4827 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4828
4829 /* Encrypt the text. */
4830 crypt_push_state();
4831 ml_crypt_prepare(mfp, offset, FALSE);
4832 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4833 crypt_pop_state();
4834
4835 /* Clear the gap. */
4836 if (head_end < text_start)
4837 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4838
4839 return new_data;
4840}
4841
4842/*
4843 * Decrypt the text in "data" if it points to a data block.
4844 */
4845 void
4846ml_decrypt_data(mfp, data, offset, size)
4847 memfile_T *mfp;
4848 char_u *data;
4849 off_t offset;
4850 unsigned size;
4851{
4852 DATA_BL *dp = (DATA_BL *)data;
4853 char_u *head_end;
4854 char_u *text_start;
4855 int text_len;
4856
4857 if (dp->db_id == DATA_ID)
4858 {
4859 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4860 text_start = (char_u *)dp + dp->db_txt_start;
4861 text_len = dp->db_txt_end - dp->db_txt_start;
4862
4863 if (head_end > text_start || dp->db_txt_start > size
4864 || dp->db_txt_end > size)
4865 return; /* data was messed up */
4866
4867 /* Decrypt the text in place. */
4868 crypt_push_state();
4869 ml_crypt_prepare(mfp, offset, TRUE);
4870 crypt_decode(text_start, text_len);
4871 crypt_pop_state();
4872 }
4873}
4874
4875/*
4876 * Prepare for encryption/decryption, using the key, seed and offset.
4877 */
4878 static void
4879ml_crypt_prepare(mfp, offset, reading)
4880 memfile_T *mfp;
4881 off_t offset;
4882 int reading;
4883{
4884 buf_T *buf = mfp->mf_buffer;
4885 char_u salt[50];
4886 int method;
4887 char_u *key;
4888 char_u *seed;
4889
4890 if (reading && mfp->mf_old_key != NULL)
4891 {
4892 /* Reading back blocks with the previous key/method/seed. */
4893 method = mfp->mf_old_cm;
4894 key = mfp->mf_old_key;
4895 seed = mfp->mf_old_seed;
4896 }
4897 else
4898 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02004899 method = get_crypt_method(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004900 key = buf->b_p_key;
4901 seed = mfp->mf_seed;
4902 }
4903
4904 use_crypt_method = method; /* select pkzip or blowfish */
4905 if (method == 0)
4906 {
4907 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4908 crypt_init_keys(salt);
4909 }
4910 else
4911 {
4912 /* Using blowfish, add salt and seed. We use the byte offset of the
4913 * block for the salt. */
4914 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004915 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004916 bf_ofb_init(seed, MF_SEED_LEN);
4917 }
4918}
4919
4920#endif
4921
4922
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923#if defined(FEAT_BYTEOFF) || defined(PROTO)
4924
4925#define MLCS_MAXL 800 /* max no of lines in chunk */
4926#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4927
4928/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004929 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4931 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4932 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4933 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4934 */
4935 static void
4936ml_updatechunk(buf, line, len, updtype)
4937 buf_T *buf;
4938 linenr_T line;
4939 long len;
4940 int updtype;
4941{
4942 static buf_T *ml_upd_lastbuf = NULL;
4943 static linenr_T ml_upd_lastline;
4944 static linenr_T ml_upd_lastcurline;
4945 static int ml_upd_lastcurix;
4946
4947 linenr_T curline = ml_upd_lastcurline;
4948 int curix = ml_upd_lastcurix;
4949 long size;
4950 chunksize_T *curchnk;
4951 int rest;
4952 bhdr_T *hp;
4953 DATA_BL *dp;
4954
4955 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4956 return;
4957 if (buf->b_ml.ml_chunksize == NULL)
4958 {
4959 buf->b_ml.ml_chunksize = (chunksize_T *)
4960 alloc((unsigned)sizeof(chunksize_T) * 100);
4961 if (buf->b_ml.ml_chunksize == NULL)
4962 {
4963 buf->b_ml.ml_usedchunks = -1;
4964 return;
4965 }
4966 buf->b_ml.ml_numchunks = 100;
4967 buf->b_ml.ml_usedchunks = 1;
4968 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4969 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4970 }
4971
4972 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4973 {
4974 /*
4975 * First line in empty buffer from ml_flush_line() -- reset
4976 */
4977 buf->b_ml.ml_usedchunks = 1;
4978 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4979 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4980 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4981 return;
4982 }
4983
4984 /*
4985 * Find chunk that our line belongs to, curline will be at start of the
4986 * chunk.
4987 */
4988 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4989 || updtype != ML_CHNK_ADDLINE)
4990 {
4991 for (curline = 1, curix = 0;
4992 curix < buf->b_ml.ml_usedchunks - 1
4993 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4994 curix++)
4995 {
4996 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4997 }
4998 }
4999 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
5000 && curix < buf->b_ml.ml_usedchunks - 1)
5001 {
5002 /* Adjust cached curix & curline */
5003 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5004 curix++;
5005 }
5006 curchnk = buf->b_ml.ml_chunksize + curix;
5007
5008 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00005009 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005010 curchnk->mlcs_totalsize += len;
5011 if (updtype == ML_CHNK_ADDLINE)
5012 {
5013 curchnk->mlcs_numlines++;
5014
5015 /* May resize here so we don't have to do it in both cases below */
5016 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5017 {
5018 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5019 buf->b_ml.ml_chunksize = (chunksize_T *)
5020 vim_realloc(buf->b_ml.ml_chunksize,
5021 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5022 if (buf->b_ml.ml_chunksize == NULL)
5023 {
5024 /* Hmmmm, Give up on offset for this buffer */
5025 buf->b_ml.ml_usedchunks = -1;
5026 return;
5027 }
5028 }
5029
5030 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5031 {
5032 int count; /* number of entries in block */
5033 int idx;
5034 int text_end;
5035 int linecnt;
5036
5037 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5038 buf->b_ml.ml_chunksize + curix,
5039 (buf->b_ml.ml_usedchunks - curix) *
5040 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005041 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005042 size = 0;
5043 linecnt = 0;
5044 while (curline < buf->b_ml.ml_line_count
5045 && linecnt < MLCS_MINL)
5046 {
5047 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5048 {
5049 buf->b_ml.ml_usedchunks = -1;
5050 return;
5051 }
5052 dp = (DATA_BL *)(hp->bh_data);
5053 count = (long)(buf->b_ml.ml_locked_high) -
5054 (long)(buf->b_ml.ml_locked_low) + 1;
5055 idx = curline - buf->b_ml.ml_locked_low;
5056 curline = buf->b_ml.ml_locked_high + 1;
5057 if (idx == 0)/* first line in block, text at the end */
5058 text_end = dp->db_txt_end;
5059 else
5060 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5061 /* Compute index of last line to use in this MEMLINE */
5062 rest = count - idx;
5063 if (linecnt + rest > MLCS_MINL)
5064 {
5065 idx += MLCS_MINL - linecnt - 1;
5066 linecnt = MLCS_MINL;
5067 }
5068 else
5069 {
5070 idx = count - 1;
5071 linecnt += rest;
5072 }
5073 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5074 }
5075 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5076 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5077 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5078 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5079 buf->b_ml.ml_usedchunks++;
5080 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5081 return;
5082 }
5083 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5084 && curix == buf->b_ml.ml_usedchunks - 1
5085 && buf->b_ml.ml_line_count - line <= 1)
5086 {
5087 /*
5088 * We are in the last chunk and it is cheap to crate a new one
5089 * after this. Do it now to avoid the loop above later on
5090 */
5091 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5092 buf->b_ml.ml_usedchunks++;
5093 if (line == buf->b_ml.ml_line_count)
5094 {
5095 curchnk->mlcs_numlines = 0;
5096 curchnk->mlcs_totalsize = 0;
5097 }
5098 else
5099 {
5100 /*
5101 * Line is just prior to last, move count for last
5102 * This is the common case when loading a new file
5103 */
5104 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5105 if (hp == NULL)
5106 {
5107 buf->b_ml.ml_usedchunks = -1;
5108 return;
5109 }
5110 dp = (DATA_BL *)(hp->bh_data);
5111 if (dp->db_line_count == 1)
5112 rest = dp->db_txt_end - dp->db_txt_start;
5113 else
5114 rest =
5115 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5116 - dp->db_txt_start;
5117 curchnk->mlcs_totalsize = rest;
5118 curchnk->mlcs_numlines = 1;
5119 curchnk[-1].mlcs_totalsize -= rest;
5120 curchnk[-1].mlcs_numlines -= 1;
5121 }
5122 }
5123 }
5124 else if (updtype == ML_CHNK_DELLINE)
5125 {
5126 curchnk->mlcs_numlines--;
5127 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5128 if (curix < (buf->b_ml.ml_usedchunks - 1)
5129 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5130 <= MLCS_MINL)
5131 {
5132 curix++;
5133 curchnk = buf->b_ml.ml_chunksize + curix;
5134 }
5135 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5136 {
5137 buf->b_ml.ml_usedchunks--;
5138 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5139 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5140 return;
5141 }
5142 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5143 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5144 > MLCS_MINL))
5145 {
5146 return;
5147 }
5148
5149 /* Collapse chunks */
5150 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5151 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5152 buf->b_ml.ml_usedchunks--;
5153 if (curix < buf->b_ml.ml_usedchunks)
5154 {
5155 mch_memmove(buf->b_ml.ml_chunksize + curix,
5156 buf->b_ml.ml_chunksize + curix + 1,
5157 (buf->b_ml.ml_usedchunks - curix) *
5158 sizeof(chunksize_T));
5159 }
5160 return;
5161 }
5162 ml_upd_lastbuf = buf;
5163 ml_upd_lastline = line;
5164 ml_upd_lastcurline = curline;
5165 ml_upd_lastcurix = curix;
5166}
5167
5168/*
5169 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005170 * Find line with offset if "lnum" is 0; return remaining offset in offp
5171 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172 * return -1 if information is not available
5173 */
5174 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005175ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005177 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005178 long *offp;
5179{
5180 linenr_T curline;
5181 int curix;
5182 long size;
5183 bhdr_T *hp;
5184 DATA_BL *dp;
5185 int count; /* number of entries in block */
5186 int idx;
5187 int start_idx;
5188 int text_end;
5189 long offset;
5190 int len;
5191 int ffdos = (get_fileformat(buf) == EOL_DOS);
5192 int extra = 0;
5193
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005194 /* take care of cached line first */
5195 ml_flush_line(curbuf);
5196
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 if (buf->b_ml.ml_usedchunks == -1
5198 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005199 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200 return -1;
5201
5202 if (offp == NULL)
5203 offset = 0;
5204 else
5205 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005206 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5208 /*
5209 * Find the last chunk before the one containing our line. Last chunk is
5210 * special because it will never qualify
5211 */
5212 curline = 1;
5213 curix = size = 0;
5214 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005215 && ((lnum != 0
5216 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217 || (offset != 0
5218 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5219 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5220 {
5221 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5222 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5223 if (offset && ffdos)
5224 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5225 curix++;
5226 }
5227
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005228 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229 {
5230 if (curline > buf->b_ml.ml_line_count
5231 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5232 return -1;
5233 dp = (DATA_BL *)(hp->bh_data);
5234 count = (long)(buf->b_ml.ml_locked_high) -
5235 (long)(buf->b_ml.ml_locked_low) + 1;
5236 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5237 if (idx == 0)/* first line in block, text at the end */
5238 text_end = dp->db_txt_end;
5239 else
5240 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5241 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005242 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005243 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005244 if (curline + (count - idx) >= lnum)
5245 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 else
5247 idx = count - 1;
5248 }
5249 else
5250 {
5251 extra = 0;
5252 while (offset >= size
5253 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5254 + ffdos)
5255 {
5256 if (ffdos)
5257 size++;
5258 if (idx == count - 1)
5259 {
5260 extra = 1;
5261 break;
5262 }
5263 idx++;
5264 }
5265 }
5266 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5267 size += len;
5268 if (offset != 0 && size >= offset)
5269 {
5270 if (size + ffdos == offset)
5271 *offp = 0;
5272 else if (idx == start_idx)
5273 *offp = offset - size + len;
5274 else
5275 *offp = offset - size + len
5276 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5277 curline += idx - start_idx + extra;
5278 if (curline > buf->b_ml.ml_line_count)
5279 return -1; /* exactly one byte beyond the end */
5280 return curline;
5281 }
5282 curline = buf->b_ml.ml_locked_high + 1;
5283 }
5284
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005285 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005286 {
5287 /* Count extra CR characters. */
5288 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005289 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005290
5291 /* Don't count the last line break if 'bin' and 'noeol'. */
5292 if (buf->b_p_bin && !buf->b_p_eol)
5293 size -= ffdos + 1;
5294 }
5295
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296 return size;
5297}
5298
5299/*
5300 * Goto byte in buffer with offset 'cnt'.
5301 */
5302 void
5303goto_byte(cnt)
5304 long cnt;
5305{
5306 long boff = cnt;
5307 linenr_T lnum;
5308
5309 ml_flush_line(curbuf); /* cached line may be dirty */
5310 setpcmark();
5311 if (boff)
5312 --boff;
5313 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5314 if (lnum < 1) /* past the end */
5315 {
5316 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5317 curwin->w_curswant = MAXCOL;
5318 coladvance((colnr_T)MAXCOL);
5319 }
5320 else
5321 {
5322 curwin->w_cursor.lnum = lnum;
5323 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005324# ifdef FEAT_VIRTUALEDIT
5325 curwin->w_cursor.coladd = 0;
5326# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005327 curwin->w_set_curswant = TRUE;
5328 }
5329 check_cursor();
5330
5331# ifdef FEAT_MBYTE
5332 /* Make sure the cursor is on the first byte of a multi-byte char. */
5333 if (has_mbyte)
5334 mb_adjust_cursor();
5335# endif
5336}
5337#endif