blob: 0268087ab1d108cdf73e1dd4296a8ac7c41d7a5f [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 {
444 if (buf->b_p_cm == 0)
445 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.
461 * "old_cm" is the previous 'cryptmethod'. It is equal to buf->b_p_cm when
462 * 'key' is changed.
463 */
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
481 if (mfp == NULL || mfp->mf_fd < 0)
482 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 }
585 }
586
587 mfp->mf_old_key = NULL;
588}
589#endif
590
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591/*
592 * ml_setname() is called when the file name of "buf" has been changed.
593 * It may rename the swap file.
594 */
595 void
596ml_setname(buf)
597 buf_T *buf;
598{
599 int success = FALSE;
600 memfile_T *mfp;
601 char_u *fname;
602 char_u *dirp;
603#if defined(MSDOS) || defined(MSWIN)
604 char_u *p;
605#endif
606
607 mfp = buf->b_ml.ml_mfp;
608 if (mfp->mf_fd < 0) /* there is no swap file yet */
609 {
610 /*
611 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
612 * For help files we will make a swap file now.
613 */
614 if (p_uc != 0)
615 ml_open_file(buf); /* create a swap file */
616 return;
617 }
618
619 /*
620 * Try all directories in the 'directory' option.
621 */
622 dirp = p_dir;
623 for (;;)
624 {
625 if (*dirp == NUL) /* tried all directories, fail */
626 break;
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000627 fname = findswapname(buf, &dirp, mfp->mf_fname);
628 /* alloc's fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629 if (fname == NULL) /* no file name found for this dir */
630 continue;
631
632#if defined(MSDOS) || defined(MSWIN)
633 /*
634 * Set full pathname for swap file now, because a ":!cd dir" may
635 * change directory without us knowing it.
636 */
637 p = FullName_save(fname, FALSE);
638 vim_free(fname);
639 fname = p;
640 if (fname == NULL)
641 continue;
642#endif
643 /* if the file name is the same we don't have to do anything */
644 if (fnamecmp(fname, mfp->mf_fname) == 0)
645 {
646 vim_free(fname);
647 success = TRUE;
648 break;
649 }
650 /* need to close the swap file before renaming */
651 if (mfp->mf_fd >= 0)
652 {
653 close(mfp->mf_fd);
654 mfp->mf_fd = -1;
655 }
656
657 /* try to rename the swap file */
658 if (vim_rename(mfp->mf_fname, fname) == 0)
659 {
660 success = TRUE;
661 vim_free(mfp->mf_fname);
662 mfp->mf_fname = fname;
663 vim_free(mfp->mf_ffname);
664#if defined(MSDOS) || defined(MSWIN)
665 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
666#else
667 mf_set_ffname(mfp);
668#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200669 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670 break;
671 }
672 vim_free(fname); /* this fname didn't work, try another */
673 }
674
675 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
676 {
677 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
678 if (mfp->mf_fd < 0)
679 {
680 /* could not (re)open the swap file, what can we do???? */
681 EMSG(_("E301: Oops, lost the swap file!!!"));
682 return;
683 }
Bram Moolenaarf05da212009-11-17 16:13:15 +0000684#ifdef HAVE_FD_CLOEXEC
685 {
686 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
687 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
688 fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
689 }
690#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000691 }
692 if (!success)
693 EMSG(_("E302: Could not rename swap file"));
694}
695
696/*
697 * Open a file for the memfile for all buffers that are not readonly or have
698 * been modified.
699 * Used when 'updatecount' changes from zero to non-zero.
700 */
701 void
702ml_open_files()
703{
704 buf_T *buf;
705
706 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
707 if (!buf->b_p_ro || buf->b_changed)
708 ml_open_file(buf);
709}
710
711/*
712 * Open a swap file for an existing memfile, if there is no swap file yet.
713 * If we are unable to find a file name, mf_fname will be NULL
714 * and the memfile will be in memory only (no recovery possible).
715 */
716 void
717ml_open_file(buf)
718 buf_T *buf;
719{
720 memfile_T *mfp;
721 char_u *fname;
722 char_u *dirp;
723
724 mfp = buf->b_ml.ml_mfp;
725 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf)
726 return; /* nothing to do */
727
Bram Moolenaara1956f62006-03-12 22:18:00 +0000728#ifdef FEAT_SPELL
Bram Moolenaar4770d092006-01-12 23:22:24 +0000729 /* For a spell buffer use a temp file name. */
730 if (buf->b_spell)
731 {
732 fname = vim_tempname('s');
733 if (fname != NULL)
734 (void)mf_open_file(mfp, fname); /* consumes fname! */
735 buf->b_may_swap = FALSE;
736 return;
737 }
738#endif
739
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 /*
741 * Try all directories in 'directory' option.
742 */
743 dirp = p_dir;
744 for (;;)
745 {
746 if (*dirp == NUL)
747 break;
Bram Moolenaare242b832010-06-24 05:39:03 +0200748 /* There is a small chance that between choosing the swap file name
749 * and creating it, another Vim creates the file. In that case the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 * creation will fail and we will use another directory. */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000751 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752 if (fname == NULL)
753 continue;
754 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
755 {
756#if defined(MSDOS) || defined(MSWIN) || defined(RISCOS)
757 /*
758 * set full pathname for swap file now, because a ":!cd dir" may
759 * change directory without us knowing it.
760 */
761 mf_fullname(mfp);
762#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200763 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000764
Bram Moolenaar071d4272004-06-13 20:20:40 +0000765 /* Flush block zero, so others can read it */
766 if (mf_sync(mfp, MFS_ZERO) == OK)
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000767 {
768 /* Mark all blocks that should be in the swapfile as dirty.
769 * Needed for when the 'swapfile' option was reset, so that
770 * the swap file was deleted, and then on again. */
771 mf_set_dirty(mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772 break;
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000773 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774 /* Writing block 0 failed: close the file and try another dir */
775 mf_close_file(buf, FALSE);
776 }
777 }
778
779 if (mfp->mf_fname == NULL) /* Failed! */
780 {
781 need_wait_return = TRUE; /* call wait_return later */
782 ++no_wait_return;
783 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
784 buf_spname(buf) != NULL
785 ? (char_u *)buf_spname(buf)
786 : buf->b_fname);
787 --no_wait_return;
788 }
789
790 /* don't try to open a swap file again */
791 buf->b_may_swap = FALSE;
792}
793
794/*
795 * If still need to create a swap file, and starting to edit a not-readonly
796 * file, or reading into an existing buffer, create a swap file now.
797 */
798 void
799check_need_swap(newfile)
800 int newfile; /* reading file into new buffer */
801{
802 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
803 ml_open_file(curbuf);
804}
805
806/*
807 * Close memline for buffer 'buf'.
808 * If 'del_file' is TRUE, delete the swap file
809 */
810 void
811ml_close(buf, del_file)
812 buf_T *buf;
813 int del_file;
814{
815 if (buf->b_ml.ml_mfp == NULL) /* not open */
816 return;
817 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
818 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
819 vim_free(buf->b_ml.ml_line_ptr);
820 vim_free(buf->b_ml.ml_stack);
821#ifdef FEAT_BYTEOFF
822 vim_free(buf->b_ml.ml_chunksize);
823 buf->b_ml.ml_chunksize = NULL;
824#endif
825 buf->b_ml.ml_mfp = NULL;
826
827 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
828 * this buffer is loaded. */
829 buf->b_flags &= ~BF_RECOVERED;
830}
831
832/*
833 * Close all existing memlines and memfiles.
834 * Only used when exiting.
835 * When 'del_file' is TRUE, delete the memfiles.
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000836 * But don't delete files that were ":preserve"d when we are POSIX compatible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837 */
838 void
839ml_close_all(del_file)
840 int del_file;
841{
842 buf_T *buf;
843
844 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000845 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
846 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847#ifdef TEMPDIRNAMES
848 vim_deltempdir(); /* delete created temp directory */
849#endif
850}
851
852/*
853 * Close all memfiles for not modified buffers.
854 * Only use just before exiting!
855 */
856 void
857ml_close_notmod()
858{
859 buf_T *buf;
860
861 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
862 if (!bufIsChanged(buf))
863 ml_close(buf, TRUE); /* close all not-modified buffers */
864}
865
866/*
867 * Update the timestamp in the .swp file.
868 * Used when the file has been written.
869 */
870 void
871ml_timestamp(buf)
872 buf_T *buf;
873{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200874 ml_upd_block0(buf, UB_FNAME);
875}
876
877/*
878 * Return FAIL when the ID of "b0p" is wrong.
879 */
880 static int
881ml_check_b0_id(b0p)
882 ZERO_BL *b0p;
883{
884 if (b0p->b0_id[0] != BLOCK0_ID0
885 || (b0p->b0_id[1] != BLOCK0_ID1
886 && b0p->b0_id[1] != BLOCK0_ID1_C0
887 && b0p->b0_id[1] != BLOCK0_ID1_C1)
888 )
889 return FAIL;
890 return OK;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000891}
892
893/*
894 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
895 */
896 static void
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200897ml_upd_block0(buf, what)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000898 buf_T *buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200899 upd_block0_T what;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000900{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 memfile_T *mfp;
902 bhdr_T *hp;
903 ZERO_BL *b0p;
904
905 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
907 return;
908 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200909 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000910 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000912 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200913 if (what == UB_FNAME)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000914 set_b0_fname(b0p, buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200915#ifdef FEAT_CRYPT
916 else if (what == UB_CRYPT)
917 ml_set_b0_crypt(buf, b0p);
918#endif
919 else /* what == UB_SAME_DIR */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000920 set_b0_dir_flag(b0p, buf);
921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 mf_put(mfp, hp, TRUE, FALSE);
923}
924
925/*
926 * Write file name and timestamp into block 0 of a swap file.
927 * Also set buf->b_mtime.
928 * Don't use NameBuff[]!!!
929 */
930 static void
931set_b0_fname(b0p, buf)
932 ZERO_BL *b0p;
933 buf_T *buf;
934{
935 struct stat st;
936
937 if (buf->b_ffname == NULL)
938 b0p->b0_fname[0] = NUL;
939 else
940 {
941#if defined(MSDOS) || defined(MSWIN) || defined(AMIGA) || defined(RISCOS)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000942 /* Systems that cannot translate "~user" back into a path: copy the
943 * file name unmodified. Do use slashes instead of backslashes for
944 * portability. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200945 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000946# ifdef BACKSLASH_IN_FILENAME
947 forward_slash(b0p->b0_fname);
948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949#else
950 size_t flen, ulen;
951 char_u uname[B0_UNAME_SIZE];
952
953 /*
954 * For a file under the home directory of the current user, we try to
955 * replace the home directory path with "~user". This helps when
956 * editing the same file on different machines over a network.
957 * First replace home dir path with "~/" with home_replace().
958 * Then insert the user name to get "~user/".
959 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200960 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
961 B0_FNAME_SIZE_CRYPT, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962 if (b0p->b0_fname[0] == '~')
963 {
964 flen = STRLEN(b0p->b0_fname);
965 /* If there is no user name or it is too long, don't use "~/" */
966 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200967 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
968 vim_strncpy(b0p->b0_fname, buf->b_ffname,
969 B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970 else
971 {
972 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
973 mch_memmove(b0p->b0_fname + 1, uname, ulen);
974 }
975 }
976#endif
977 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
978 {
979 long_to_char((long)st.st_mtime, b0p->b0_mtime);
980#ifdef CHECK_INODE
981 long_to_char((long)st.st_ino, b0p->b0_ino);
982#endif
983 buf_store_time(buf, &st, buf->b_ffname);
984 buf->b_mtime_read = buf->b_mtime;
985 }
986 else
987 {
988 long_to_char(0L, b0p->b0_mtime);
989#ifdef CHECK_INODE
990 long_to_char(0L, b0p->b0_ino);
991#endif
992 buf->b_mtime = 0;
993 buf->b_mtime_read = 0;
994 buf->b_orig_size = 0;
995 buf->b_orig_mode = 0;
996 }
997 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000998
999#ifdef FEAT_MBYTE
1000 /* Also add the 'fileencoding' if there is room. */
1001 add_b0_fenc(b0p, curbuf);
1002#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003}
1004
1005/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001006 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1007 * swapfile for "buf" are in the same directory.
1008 * This is fail safe: if we are not sure the directories are equal the flag is
1009 * not set.
1010 */
1011 static void
1012set_b0_dir_flag(b0p, buf)
1013 ZERO_BL *b0p;
1014 buf_T *buf;
1015{
1016 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1017 b0p->b0_flags |= B0_SAME_DIR;
1018 else
1019 b0p->b0_flags &= ~B0_SAME_DIR;
1020}
1021
1022#ifdef FEAT_MBYTE
1023/*
1024 * When there is room, add the 'fileencoding' to block zero.
1025 */
1026 static void
1027add_b0_fenc(b0p, buf)
1028 ZERO_BL *b0p;
1029 buf_T *buf;
1030{
1031 int n;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001032 int size = B0_FNAME_SIZE_NOCRYPT;
1033
1034# ifdef FEAT_CRYPT
1035 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1036 * With encryption it's OK to move elsewhere, the swap file is not
1037 * compatible anyway. */
1038 if (*buf->b_p_key != NUL)
1039 size = B0_FNAME_SIZE_CRYPT;
1040# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001041
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001042 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001043 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001044 b0p->b0_flags &= ~B0_HAS_FENC;
1045 else
1046 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001047 mch_memmove((char *)b0p->b0_fname + size - n,
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001048 (char *)buf->b_p_fenc, (size_t)n);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001049 *(b0p->b0_fname + size - n - 1) = NUL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001050 b0p->b0_flags |= B0_HAS_FENC;
1051 }
1052}
1053#endif
1054
1055
1056/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001057 * Try to recover curbuf from the .swp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 */
1059 void
1060ml_recover()
1061{
1062 buf_T *buf = NULL;
1063 memfile_T *mfp = NULL;
1064 char_u *fname;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001065 char_u *fname_used = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066 bhdr_T *hp = NULL;
1067 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001068 int b0_ff;
1069 char_u *b0_fenc = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001070#ifdef FEAT_CRYPT
1071 int b0_cm = -1;
1072#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 PTR_BL *pp;
1074 DATA_BL *dp;
1075 infoptr_T *ip;
1076 blocknr_T bnum;
1077 int page_count;
1078 struct stat org_stat, swp_stat;
1079 int len;
1080 int directly;
1081 linenr_T lnum;
1082 char_u *p;
1083 int i;
1084 long error;
1085 int cannot_open;
1086 linenr_T line_count;
1087 int has_error;
1088 int idx;
1089 int top;
1090 int txt_start;
1091 off_t size;
1092 int called_from_main;
1093 int serious_error = TRUE;
1094 long mtime;
1095 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001096 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097
1098 recoverymode = TRUE;
1099 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1100 attr = hl_attr(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001101
1102 /*
1103 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
1104 * Otherwise a search is done to find the swap file(s).
1105 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 fname = curbuf->b_fname;
1107 if (fname == NULL) /* When there is no file name */
1108 fname = (char_u *)"";
1109 len = (int)STRLEN(fname);
1110 if (len >= 4 &&
1111#if defined(VMS) || defined(RISCOS)
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001112 STRNICMP(fname + len - 4, "_s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113#else
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001114 STRNICMP(fname + len - 4, ".s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115#endif
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001116 == 0
1117 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
1118 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 {
1120 directly = TRUE;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001121 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122 }
1123 else
1124 {
1125 directly = FALSE;
1126
1127 /* count the number of matching swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001128 len = recover_names(fname, FALSE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 if (len == 0) /* no swap files found */
1130 {
1131 EMSG2(_("E305: No swap file found for %s"), fname);
1132 goto theend;
1133 }
1134 if (len == 1) /* one swap file found, use it */
1135 i = 1;
1136 else /* several swap files found, choose */
1137 {
1138 /* list the names of the swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001139 (void)recover_names(fname, TRUE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 msg_putchar('\n');
1141 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001142 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 if (i < 1 || i > len)
1144 goto theend;
1145 }
1146 /* get the swap file name that will be used */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001147 (void)recover_names(fname, FALSE, i, &fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001149 if (fname_used == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001150 goto theend; /* out of memory */
1151
1152 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +00001153 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 getout(1);
1155
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001156 /*
1157 * Allocate a buffer structure for the swap file that is used for recovery.
1158 * Only the memline in it is really used.
1159 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1161 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001164 /*
1165 * init fields in memline struct
1166 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1168 buf->b_ml.ml_stack = NULL; /* no stack yet */
1169 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1170 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1171 buf->b_ml.ml_locked = NULL; /* no locked block */
1172 buf->b_ml.ml_flags = 0;
1173
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001174 /*
1175 * open the memfile from the old swap file
1176 */
1177 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1178 mf_open() will consume "fname_used"! */
1179 mfp = mf_open(fname_used, O_RDONLY);
1180 fname_used = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181 if (mfp == NULL || mfp->mf_fd < 0)
1182 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001183 if (fname_used != NULL)
1184 EMSG2(_("E306: Cannot open %s"), fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 goto theend;
1186 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001188#ifdef FEAT_CRYPT
1189 mfp->mf_buffer = buf;
1190 buf->b_p_key = empty_option;
1191#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192
1193 /*
1194 * The page size set in mf_open() might be different from the page size
1195 * used in the swap file, we must get it from block 0. But to read block
1196 * 0 we need a page size. Use the minimal size for block 0 here, it will
1197 * be set to the real value below.
1198 */
1199 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1200
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001201 /*
1202 * try to read block 0
1203 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1205 {
1206 msg_start();
1207 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1208 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001209 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001210 attr | MSG_HIST);
1211 msg_end();
1212 goto theend;
1213 }
1214 b0p = (ZERO_BL *)(hp->bh_data);
1215 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1216 {
1217 msg_start();
1218 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1219 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1220 MSG_HIST);
1221 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1222 msg_end();
1223 goto theend;
1224 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001225 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 {
1227 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1228 goto theend;
1229 }
1230 if (b0_magic_wrong(b0p))
1231 {
1232 msg_start();
1233 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1234#if defined(MSDOS) || defined(MSWIN)
1235 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1236 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1237 attr | MSG_HIST);
1238 else
1239#endif
1240 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1241 attr | MSG_HIST);
1242 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001243 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244 b0p->b0_fname[0] = NUL;
1245 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1246 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1247 msg_end();
1248 goto theend;
1249 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001250
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001251#ifdef FEAT_CRYPT
1252 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
1253 buf->b_p_cm = b0_cm = 0;
1254 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1255 {
1256 buf->b_p_cm = b0_cm = 1;
1257 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1258 }
1259#else
1260 if (b0p->b0_id[1] != BLOCK0_ID1)
1261 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001262 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001263 goto theend;
1264 }
1265#endif
1266
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267 /*
1268 * If we guessed the wrong page size, we have to recalculate the
1269 * highest block number in the file.
1270 */
1271 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1272 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001273 unsigned previous_page_size = mfp->mf_page_size;
1274
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001276 if (mfp->mf_page_size < previous_page_size)
1277 {
1278 msg_start();
1279 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1280 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1281 attr | MSG_HIST);
1282 msg_end();
1283 goto theend;
1284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1286 mfp->mf_blocknr_max = 0; /* no file or empty file */
1287 else
1288 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1289 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001290
1291 /* need to reallocate the memory used to store the data */
1292 p = alloc(mfp->mf_page_size);
1293 if (p == NULL)
1294 goto theend;
1295 mch_memmove(p, hp->bh_data, previous_page_size);
1296 vim_free(hp->bh_data);
1297 hp->bh_data = p;
1298 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299 }
1300
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001301 /*
1302 * If .swp file name given directly, use name from swap file for buffer.
1303 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 if (directly)
1305 {
1306 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1307 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1308 goto theend;
1309 }
1310
1311 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001312 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313
1314 if (buf_spname(curbuf) != NULL)
1315 STRCPY(NameBuff, buf_spname(curbuf));
1316 else
1317 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001318 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319 msg_putchar('\n');
1320
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001321 /*
1322 * check date of swap file and original file
1323 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324 mtime = char_to_long(b0p->b0_mtime);
1325 if (curbuf->b_ffname != NULL
1326 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1327 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1328 && org_stat.st_mtime > swp_stat.st_mtime)
1329 || org_stat.st_mtime != mtime))
1330 {
1331 EMSG(_("E308: Warning: Original file may have been changed"));
1332 }
1333 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001334
1335 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1336 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1337 if (b0p->b0_flags & B0_HAS_FENC)
1338 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001339 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001340
1341#ifdef FEAT_CRYPT
1342 /* Use the same size as in add_b0_fenc(). */
1343 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001344 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001345#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001346 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001347 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001348 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001349 }
1350
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1352 hp = NULL;
1353
1354 /*
1355 * Now that we are sure that the file is going to be recovered, clear the
1356 * contents of the current buffer.
1357 */
1358 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1359 ml_delete((linenr_T)1, FALSE);
1360
1361 /*
1362 * Try reading the original file to obtain the values of 'fileformat',
1363 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001364 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365 */
1366 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001367 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001370#ifdef FEAT_CRYPT
1371 if (b0_cm >= 0)
1372 {
1373 /* Need to ask the user for the crypt key. If this fails we continue
1374 * without a key, will probably get garbage text. */
1375 if (*curbuf->b_p_key != NUL)
1376 {
1377 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1378 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1379 MSG_PUTS(_("\nenter the new crypt key."));
1380 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1381 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1382 }
1383 else
1384 smsg((char_u *)_(need_key_msg), fname_used);
1385 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1386 if (buf->b_p_key == NULL)
1387 buf->b_p_key = curbuf->b_p_key;
1388 else if (*buf->b_p_key == NUL)
1389 {
1390 vim_free(buf->b_p_key);
1391 buf->b_p_key = curbuf->b_p_key;
1392 }
1393 if (buf->b_p_key == NULL)
1394 buf->b_p_key = empty_option;
1395 }
1396#endif
1397
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001398 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1399 if (b0_ff != 0)
1400 set_fileformat(b0_ff - 1, OPT_LOCAL);
1401 if (b0_fenc != NULL)
1402 {
1403 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1404 vim_free(b0_fenc);
1405 }
1406 unchanged(curbuf, TRUE);
1407
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 bnum = 1; /* start with block 1 */
1409 page_count = 1; /* which is 1 page */
1410 lnum = 0; /* append after line 0 in curbuf */
1411 line_count = 0;
1412 idx = 0; /* start with first index in block 1 */
1413 error = 0;
1414 buf->b_ml.ml_stack_top = 0;
1415 buf->b_ml.ml_stack = NULL;
1416 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1417
1418 if (curbuf->b_ffname == NULL)
1419 cannot_open = TRUE;
1420 else
1421 cannot_open = FALSE;
1422
1423 serious_error = FALSE;
1424 for ( ; !got_int; line_breakcheck())
1425 {
1426 if (hp != NULL)
1427 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1428
1429 /*
1430 * get block
1431 */
1432 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1433 {
1434 if (bnum == 1)
1435 {
1436 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1437 goto theend;
1438 }
1439 ++error;
1440 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1441 (colnr_T)0, TRUE);
1442 }
1443 else /* there is a block */
1444 {
1445 pp = (PTR_BL *)(hp->bh_data);
1446 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1447 {
1448 /* check line count when using pointer block first time */
1449 if (idx == 0 && line_count != 0)
1450 {
1451 for (i = 0; i < (int)pp->pb_count; ++i)
1452 line_count -= pp->pb_pointer[i].pe_line_count;
1453 if (line_count != 0)
1454 {
1455 ++error;
1456 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1457 (colnr_T)0, TRUE);
1458 }
1459 }
1460
1461 if (pp->pb_count == 0)
1462 {
1463 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1464 (colnr_T)0, TRUE);
1465 ++error;
1466 }
1467 else if (idx < (int)pp->pb_count) /* go a block deeper */
1468 {
1469 if (pp->pb_pointer[idx].pe_bnum < 0)
1470 {
1471 /*
1472 * Data block with negative block number.
1473 * Try to read lines from the original file.
1474 * This is slow, but it works.
1475 */
1476 if (!cannot_open)
1477 {
1478 line_count = pp->pb_pointer[idx].pe_line_count;
1479 if (readfile(curbuf->b_ffname, NULL, lnum,
1480 pp->pb_pointer[idx].pe_old_lnum - 1,
1481 line_count, NULL, 0) == FAIL)
1482 cannot_open = TRUE;
1483 else
1484 lnum += line_count;
1485 }
1486 if (cannot_open)
1487 {
1488 ++error;
1489 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1490 (colnr_T)0, TRUE);
1491 }
1492 ++idx; /* get same block again for next index */
1493 continue;
1494 }
1495
1496 /*
1497 * going one block deeper in the tree
1498 */
1499 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1500 {
1501 ++error;
1502 break; /* out of memory */
1503 }
1504 ip = &(buf->b_ml.ml_stack[top]);
1505 ip->ip_bnum = bnum;
1506 ip->ip_index = idx;
1507
1508 bnum = pp->pb_pointer[idx].pe_bnum;
1509 line_count = pp->pb_pointer[idx].pe_line_count;
1510 page_count = pp->pb_pointer[idx].pe_page_count;
1511 continue;
1512 }
1513 }
1514 else /* not a pointer block */
1515 {
1516 dp = (DATA_BL *)(hp->bh_data);
1517 if (dp->db_id != DATA_ID) /* block id wrong */
1518 {
1519 if (bnum == 1)
1520 {
1521 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1522 mfp->mf_fname);
1523 goto theend;
1524 }
1525 ++error;
1526 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1527 (colnr_T)0, TRUE);
1528 }
1529 else
1530 {
1531 /*
1532 * it is a data block
1533 * Append all the lines in this block
1534 */
1535 has_error = FALSE;
1536 /*
1537 * check length of block
1538 * if wrong, use length in pointer block
1539 */
1540 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1541 {
1542 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1543 (colnr_T)0, TRUE);
1544 ++error;
1545 has_error = TRUE;
1546 dp->db_txt_end = page_count * mfp->mf_page_size;
1547 }
1548
1549 /* make sure there is a NUL at the end of the block */
1550 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1551
1552 /*
1553 * check number of lines in block
1554 * if wrong, use count in data block
1555 */
1556 if (line_count != dp->db_line_count)
1557 {
1558 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1559 (colnr_T)0, TRUE);
1560 ++error;
1561 has_error = TRUE;
1562 }
1563
1564 for (i = 0; i < dp->db_line_count; ++i)
1565 {
1566 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001567 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 || txt_start >= (int)dp->db_txt_end)
1569 {
1570 p = (char_u *)"???";
1571 ++error;
1572 }
1573 else
1574 p = (char_u *)dp + txt_start;
1575 ml_append(lnum++, p, (colnr_T)0, TRUE);
1576 }
1577 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001578 ml_append(lnum++, (char_u *)_("???END"),
1579 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 }
1581 }
1582 }
1583
1584 if (buf->b_ml.ml_stack_top == 0) /* finished */
1585 break;
1586
1587 /*
1588 * go one block up in the tree
1589 */
1590 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1591 bnum = ip->ip_bnum;
1592 idx = ip->ip_index + 1; /* go to next index */
1593 page_count = 1;
1594 }
1595
1596 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001597 * Compare the buffer contents with the original file. When they differ
1598 * set the 'modified' flag.
1599 * Lines 1 - lnum are the new contents.
1600 * Lines lnum + 1 to ml_line_count are the original contents.
1601 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001603 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1604 {
1605 /* Recovering an empty file results in two lines and the first line is
1606 * empty. Don't set the modified flag then. */
1607 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1608 {
1609 changed_int();
1610 ++curbuf->b_changedtick;
1611 }
1612 }
1613 else
1614 {
1615 for (idx = 1; idx <= lnum; ++idx)
1616 {
1617 /* Need to copy one line, fetching the other one may flush it. */
1618 p = vim_strsave(ml_get(idx));
1619 i = STRCMP(p, ml_get(idx + lnum));
1620 vim_free(p);
1621 if (i != 0)
1622 {
1623 changed_int();
1624 ++curbuf->b_changedtick;
1625 break;
1626 }
1627 }
1628 }
1629
1630 /*
1631 * Delete the lines from the original file and the dummy line from the
1632 * empty buffer. These will now be after the last line in the buffer.
1633 */
1634 while (curbuf->b_ml.ml_line_count > lnum
1635 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1636 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 curbuf->b_flags |= BF_RECOVERED;
1638
1639 recoverymode = FALSE;
1640 if (got_int)
1641 EMSG(_("E311: Recovery Interrupted"));
1642 else if (error)
1643 {
1644 ++no_wait_return;
1645 MSG(">>>>>>>>>>>>>");
1646 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1647 --no_wait_return;
1648 MSG(_("See \":help E312\" for more information."));
1649 MSG(">>>>>>>>>>>>>");
1650 }
1651 else
1652 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001653 if (curbuf->b_changed)
1654 {
1655 MSG(_("Recovery completed. You should check if everything is OK."));
1656 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1657 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1658 }
1659 else
1660 MSG(_("Recovery completed. Buffer contents equals file contents."));
1661 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662 cmdline_row = msg_row;
1663 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001664#ifdef FEAT_CRYPT
1665 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1666 {
1667 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1668 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1669 }
1670#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001671 redraw_curbuf_later(NOT_VALID);
1672
1673theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001674 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 recoverymode = FALSE;
1676 if (mfp != NULL)
1677 {
1678 if (hp != NULL)
1679 mf_put(mfp, hp, FALSE, FALSE);
1680 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1681 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001682 if (buf != NULL)
1683 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001684#ifdef FEAT_CRYPT
1685 if (buf->b_p_key != curbuf->b_p_key)
1686 free_string_option(buf->b_p_key);
1687#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001688 vim_free(buf->b_ml.ml_stack);
1689 vim_free(buf);
1690 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 if (serious_error && called_from_main)
1692 ml_close(curbuf, TRUE);
1693#ifdef FEAT_AUTOCMD
1694 else
1695 {
1696 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1697 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1698 }
1699#endif
1700 return;
1701}
1702
1703/*
1704 * Find the names of swap files in current directory and the directory given
1705 * with the 'directory' option.
1706 *
1707 * Used to:
1708 * - list the swap files for "vim -r"
1709 * - count the number of swap files when recovering
1710 * - list the swap files when recovering
1711 * - find the name of the n'th swap file when recovering
1712 */
1713 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001714recover_names(fname, list, nr, fname_out)
1715 char_u *fname; /* base for swap file name */
1716 int list; /* when TRUE, list the swap file names */
1717 int nr; /* when non-zero, return nr'th swap file name */
1718 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719{
1720 int num_names;
1721 char_u *(names[6]);
1722 char_u *tail;
1723 char_u *p;
1724 int num_files;
1725 int file_count = 0;
1726 char_u **files;
1727 int i;
1728 char_u *dirp;
1729 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001730 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001731#ifdef HAVE_READLINK
1732 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001733#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001734
Bram Moolenaar64354da2010-05-25 21:37:17 +02001735 if (fname != NULL)
1736 {
1737#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001738 /* Expand symlink in the file name, because the swap file is created
1739 * with the actual file instead of with the symlink. */
1740 if (resolve_symlink(fname, fname_buf) == OK)
1741 fname_res = fname_buf;
1742 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001743#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001744 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746
1747 if (list)
1748 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001749 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750 msg((char_u *)_("Swap files found:"));
1751 msg_putchar('\n');
1752 }
1753
1754 /*
1755 * Do the loop for every directory in 'directory'.
1756 * First allocate some memory to put the directory name in.
1757 */
1758 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1759 dirp = p_dir;
1760 while (dir_name != NULL && *dirp)
1761 {
1762 /*
1763 * Isolate a directory name from *dirp and put it in dir_name (we know
1764 * it is large enough, so use 31000 for length).
1765 * Advance dirp to next directory name.
1766 */
1767 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1768
1769 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1770 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001771 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772 {
1773#ifdef VMS
1774 names[0] = vim_strsave((char_u *)"*_sw%");
1775#else
1776# ifdef RISCOS
1777 names[0] = vim_strsave((char_u *)"*_sw#");
1778# else
1779 names[0] = vim_strsave((char_u *)"*.sw?");
1780# endif
1781#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001782#if defined(UNIX) || defined(WIN3264)
1783 /* For Unix names starting with a dot are special. MS-Windows
1784 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785 names[1] = vim_strsave((char_u *)".*.sw?");
1786 names[2] = vim_strsave((char_u *)".sw?");
1787 num_names = 3;
1788#else
1789# ifdef VMS
1790 names[1] = vim_strsave((char_u *)".*_sw%");
1791 num_names = 2;
1792# else
1793 num_names = 1;
1794# endif
1795#endif
1796 }
1797 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001798 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 }
1800 else /* check directory dir_name */
1801 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001802 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 {
1804#ifdef VMS
1805 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1806#else
1807# ifdef RISCOS
1808 names[0] = concat_fnames(dir_name, (char_u *)"*_sw#", TRUE);
1809# else
1810 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
1811# endif
1812#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001813#if defined(UNIX) || defined(WIN3264)
1814 /* For Unix names starting with a dot are special. MS-Windows
1815 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1817 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1818 num_names = 3;
1819#else
1820# ifdef VMS
1821 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1822 num_names = 2;
1823# else
1824 num_names = 1;
1825# endif
1826#endif
1827 }
1828 else
1829 {
1830#if defined(UNIX) || defined(WIN3264)
1831 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001832 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 {
1834 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001835 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 }
1837 else
1838#endif
1839 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001840 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 tail = concat_fnames(dir_name, tail, TRUE);
1842 }
1843 if (tail == NULL)
1844 num_names = 0;
1845 else
1846 {
1847 num_names = recov_file_names(names, tail, FALSE);
1848 vim_free(tail);
1849 }
1850 }
1851 }
1852
1853 /* check for out-of-memory */
1854 for (i = 0; i < num_names; ++i)
1855 {
1856 if (names[i] == NULL)
1857 {
1858 for (i = 0; i < num_names; ++i)
1859 vim_free(names[i]);
1860 num_names = 0;
1861 }
1862 }
1863 if (num_names == 0)
1864 num_files = 0;
1865 else if (expand_wildcards(num_names, names, &num_files, &files,
1866 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1867 num_files = 0;
1868
1869 /*
1870 * When no swap file found, wildcard expansion might have failed (e.g.
1871 * not able to execute the shell).
1872 * Try finding a swap file by simply adding ".swp" to the file name.
1873 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001874 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 {
1876 struct stat st;
1877 char_u *swapname;
1878
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001879 swapname = modname(fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001880#if defined(VMS) || defined(RISCOS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001881 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001883 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001885 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 if (swapname != NULL)
1887 {
1888 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1889 {
1890 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1891 if (files != NULL)
1892 {
1893 files[0] = swapname;
1894 swapname = NULL;
1895 num_files = 1;
1896 }
1897 }
1898 vim_free(swapname);
1899 }
1900 }
1901
1902 /*
1903 * remove swapfile name of the current buffer, it must be ignored
1904 */
1905 if (curbuf->b_ml.ml_mfp != NULL
1906 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1907 {
1908 for (i = 0; i < num_files; ++i)
1909 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1910 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001911 /* Remove the name from files[i]. Move further entries
1912 * down. When the array becomes empty free it here, since
1913 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001915 if (--num_files == 0)
1916 vim_free(files);
1917 else
1918 for ( ; i < num_files; ++i)
1919 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 }
1921 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001922 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 {
1924 file_count += num_files;
1925 if (nr <= file_count)
1926 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001927 *fname_out = vim_strsave(
1928 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 dirp = (char_u *)""; /* stop searching */
1930 }
1931 }
1932 else if (list)
1933 {
1934 if (dir_name[0] == '.' && dir_name[1] == NUL)
1935 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001936 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 MSG_PUTS(_(" In current directory:\n"));
1938 else
1939 MSG_PUTS(_(" Using specified name:\n"));
1940 }
1941 else
1942 {
1943 MSG_PUTS(_(" In directory "));
1944 msg_home_replace(dir_name);
1945 MSG_PUTS(":\n");
1946 }
1947
1948 if (num_files)
1949 {
1950 for (i = 0; i < num_files; ++i)
1951 {
1952 /* print the swap file name */
1953 msg_outnum((long)++file_count);
1954 MSG_PUTS(". ");
1955 msg_puts(gettail(files[i]));
1956 msg_putchar('\n');
1957 (void)swapfile_info(files[i]);
1958 }
1959 }
1960 else
1961 MSG_PUTS(_(" -- none --\n"));
1962 out_flush();
1963 }
1964 else
1965 file_count += num_files;
1966
1967 for (i = 0; i < num_names; ++i)
1968 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001969 if (num_files > 0)
1970 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 }
1972 vim_free(dir_name);
1973 return file_count;
1974}
1975
1976#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1977/*
1978 * Append the full path to name with path separators made into percent
1979 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1980 */
1981 static char_u *
1982make_percent_swname(dir, name)
1983 char_u *dir;
1984 char_u *name;
1985{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001986 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001987
1988 f = fix_fname(name != NULL ? name : (char_u *) "");
1989 d = NULL;
1990 if (f != NULL)
1991 {
1992 s = alloc((unsigned)(STRLEN(f) + 1));
1993 if (s != NULL)
1994 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001995 STRCPY(s, f);
1996 for (d = s; *d != NUL; mb_ptr_adv(d))
1997 if (vim_ispathsep(*d))
1998 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00001999 d = concat_fnames(dir, s, TRUE);
2000 vim_free(s);
2001 }
2002 vim_free(f);
2003 }
2004 return d;
2005}
2006#endif
2007
2008#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2009static int process_still_running;
2010#endif
2011
2012/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002013 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014 * Returns timestamp (0 when unknown).
2015 */
2016 static time_t
2017swapfile_info(fname)
2018 char_u *fname;
2019{
2020 struct stat st;
2021 int fd;
2022 struct block0 b0;
2023 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002024 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025#ifdef UNIX
2026 char_u uname[B0_UNAME_SIZE];
2027#endif
2028
2029 /* print the swap file date */
2030 if (mch_stat((char *)fname, &st) != -1)
2031 {
2032#ifdef UNIX
2033 /* print name of owner of the file */
2034 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2035 {
2036 MSG_PUTS(_(" owned by: "));
2037 msg_outtrans(uname);
2038 MSG_PUTS(_(" dated: "));
2039 }
2040 else
2041#endif
2042 MSG_PUTS(_(" dated: "));
2043 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002044 p = ctime(&x); /* includes '\n' */
2045 if (p == NULL)
2046 MSG_PUTS("(invalid)\n");
2047 else
2048 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 }
2050
2051 /*
2052 * print the original file name
2053 */
2054 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2055 if (fd >= 0)
2056 {
2057 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
2058 {
2059 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2060 {
2061 MSG_PUTS(_(" [from Vim version 3.0]"));
2062 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002063 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064 {
2065 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2066 }
2067 else
2068 {
2069 MSG_PUTS(_(" file name: "));
2070 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002071 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 else
2073 msg_outtrans(b0.b0_fname);
2074
2075 MSG_PUTS(_("\n modified: "));
2076 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2077
2078 if (*(b0.b0_uname) != NUL)
2079 {
2080 MSG_PUTS(_("\n user name: "));
2081 msg_outtrans(b0.b0_uname);
2082 }
2083
2084 if (*(b0.b0_hname) != NUL)
2085 {
2086 if (*(b0.b0_uname) != NUL)
2087 MSG_PUTS(_(" host name: "));
2088 else
2089 MSG_PUTS(_("\n host name: "));
2090 msg_outtrans(b0.b0_hname);
2091 }
2092
2093 if (char_to_long(b0.b0_pid) != 0L)
2094 {
2095 MSG_PUTS(_("\n process ID: "));
2096 msg_outnum(char_to_long(b0.b0_pid));
2097#if defined(UNIX) || defined(__EMX__)
2098 /* EMX kill() not working correctly, it seems */
2099 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2100 {
2101 MSG_PUTS(_(" (still running)"));
2102# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2103 process_still_running = TRUE;
2104# endif
2105 }
2106#endif
2107 }
2108
2109 if (b0_magic_wrong(&b0))
2110 {
2111#if defined(MSDOS) || defined(MSWIN)
2112 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2113 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2114 else
2115#endif
2116 MSG_PUTS(_("\n [not usable on this computer]"));
2117 }
2118 }
2119 }
2120 else
2121 MSG_PUTS(_(" [cannot be read]"));
2122 close(fd);
2123 }
2124 else
2125 MSG_PUTS(_(" [cannot be opened]"));
2126 msg_putchar('\n');
2127
2128 return x;
2129}
2130
2131 static int
2132recov_file_names(names, path, prepend_dot)
2133 char_u **names;
2134 char_u *path;
2135 int prepend_dot;
2136{
2137 int num_names;
2138
2139#ifdef SHORT_FNAME
2140 /*
2141 * (MS-DOS) always short names
2142 */
2143 names[0] = modname(path, (char_u *)".sw?", FALSE);
2144 num_names = 1;
2145#else /* !SHORT_FNAME */
2146 /*
2147 * (Win32 and Win64) never short names, but do prepend a dot.
2148 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2149 * Only use the short name if it is different.
2150 */
2151 char_u *p;
2152 int i;
2153# ifndef WIN3264
2154 int shortname = curbuf->b_shortname;
2155
2156 curbuf->b_shortname = FALSE;
2157# endif
2158
2159 num_names = 0;
2160
2161 /*
2162 * May also add the file name with a dot prepended, for swap file in same
2163 * dir as original file.
2164 */
2165 if (prepend_dot)
2166 {
2167 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2168 if (names[num_names] == NULL)
2169 goto end;
2170 ++num_names;
2171 }
2172
2173 /*
2174 * Form the normal swap file name pattern by appending ".sw?".
2175 */
2176#ifdef VMS
2177 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2178#else
2179# ifdef RISCOS
2180 names[num_names] = concat_fnames(path, (char_u *)"_sw#", FALSE);
2181# else
2182 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
2183# endif
2184#endif
2185 if (names[num_names] == NULL)
2186 goto end;
2187 if (num_names >= 1) /* check if we have the same name twice */
2188 {
2189 p = names[num_names - 1];
2190 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2191 if (i > 0)
2192 p += i; /* file name has been expanded to full path */
2193
2194 if (STRCMP(p, names[num_names]) != 0)
2195 ++num_names;
2196 else
2197 vim_free(names[num_names]);
2198 }
2199 else
2200 ++num_names;
2201
2202# ifndef WIN3264
2203 /*
2204 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2205 */
2206 curbuf->b_shortname = TRUE;
2207#ifdef VMS
2208 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2209#else
2210# ifdef RISCOS
2211 names[num_names] = modname(path, (char_u *)"_sw#", FALSE);
2212# else
2213 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
2214# endif
2215#endif
2216 if (names[num_names] == NULL)
2217 goto end;
2218
2219 /*
2220 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2221 */
2222 p = names[num_names];
2223 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2224 if (i > 0)
2225 p += i; /* file name has been expanded to full path */
2226 if (STRCMP(names[num_names - 1], p) == 0)
2227 vim_free(names[num_names]);
2228 else
2229 ++num_names;
2230# endif
2231
2232end:
2233# ifndef WIN3264
2234 curbuf->b_shortname = shortname;
2235# endif
2236
2237#endif /* !SHORT_FNAME */
2238
2239 return num_names;
2240}
2241
2242/*
2243 * sync all memlines
2244 *
2245 * If 'check_file' is TRUE, check if original file exists and was not changed.
2246 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2247 * always sync at least one block.
2248 */
2249 void
2250ml_sync_all(check_file, check_char)
2251 int check_file;
2252 int check_char;
2253{
2254 buf_T *buf;
2255 struct stat st;
2256
2257 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2258 {
2259 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2260 continue; /* no file */
2261
2262 ml_flush_line(buf); /* flush buffered line */
2263 /* flush locked block */
2264 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2265 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2266 && buf->b_ffname != NULL)
2267 {
2268 /*
2269 * If the original file does not exist anymore or has been changed
2270 * call ml_preserve() to get rid of all negative numbered blocks.
2271 */
2272 if (mch_stat((char *)buf->b_ffname, &st) == -1
2273 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002274 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 {
2276 ml_preserve(buf, FALSE);
2277 did_check_timestamps = FALSE;
2278 need_check_timestamps = TRUE; /* give message later */
2279 }
2280 }
2281 if (buf->b_ml.ml_mfp->mf_dirty)
2282 {
2283 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2284 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2285 if (check_char && ui_char_avail()) /* character available now */
2286 break;
2287 }
2288 }
2289}
2290
2291/*
2292 * sync one buffer, including negative blocks
2293 *
2294 * after this all the blocks are in the swap file
2295 *
2296 * Used for the :preserve command and when the original file has been
2297 * changed or deleted.
2298 *
2299 * when message is TRUE the success of preserving is reported
2300 */
2301 void
2302ml_preserve(buf, message)
2303 buf_T *buf;
2304 int message;
2305{
2306 bhdr_T *hp;
2307 linenr_T lnum;
2308 memfile_T *mfp = buf->b_ml.ml_mfp;
2309 int status;
2310 int got_int_save = got_int;
2311
2312 if (mfp == NULL || mfp->mf_fname == NULL)
2313 {
2314 if (message)
2315 EMSG(_("E313: Cannot preserve, there is no swap file"));
2316 return;
2317 }
2318
2319 /* We only want to stop when interrupted here, not when interrupted
2320 * before. */
2321 got_int = FALSE;
2322
2323 ml_flush_line(buf); /* flush buffered line */
2324 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2325 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2326
2327 /* stack is invalid after mf_sync(.., MFS_ALL) */
2328 buf->b_ml.ml_stack_top = 0;
2329
2330 /*
2331 * Some of the data blocks may have been changed from negative to
2332 * positive block number. In that case the pointer blocks need to be
2333 * updated.
2334 *
2335 * We don't know in which pointer block the references are, so we visit
2336 * all data blocks until there are no more translations to be done (or
2337 * we hit the end of the file, which can only happen in case a write fails,
2338 * e.g. when file system if full).
2339 * ml_find_line() does the work by translating the negative block numbers
2340 * when getting the first line of each data block.
2341 */
2342 if (mf_need_trans(mfp) && !got_int)
2343 {
2344 lnum = 1;
2345 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2346 {
2347 hp = ml_find_line(buf, lnum, ML_FIND);
2348 if (hp == NULL)
2349 {
2350 status = FAIL;
2351 goto theend;
2352 }
2353 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2354 lnum = buf->b_ml.ml_locked_high + 1;
2355 }
2356 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2357 /* sync the updated pointer blocks */
2358 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2359 status = FAIL;
2360 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2361 }
2362theend:
2363 got_int |= got_int_save;
2364
2365 if (message)
2366 {
2367 if (status == OK)
2368 MSG(_("File preserved"));
2369 else
2370 EMSG(_("E314: Preserve failed"));
2371 }
2372}
2373
2374/*
2375 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2376 * until the next call!
2377 * line1 = ml_get(1);
2378 * line2 = ml_get(2); // line1 is now invalid!
2379 * Make a copy of the line if necessary.
2380 */
2381/*
2382 * get a pointer to a (read-only copy of a) line
2383 *
2384 * On failure an error message is given and IObuff is returned (to avoid
2385 * having to check for error everywhere).
2386 */
2387 char_u *
2388ml_get(lnum)
2389 linenr_T lnum;
2390{
2391 return ml_get_buf(curbuf, lnum, FALSE);
2392}
2393
2394/*
2395 * ml_get_pos: get pointer to position 'pos'
2396 */
2397 char_u *
2398ml_get_pos(pos)
2399 pos_T *pos;
2400{
2401 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2402}
2403
2404/*
2405 * ml_get_curline: get pointer to cursor line.
2406 */
2407 char_u *
2408ml_get_curline()
2409{
2410 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2411}
2412
2413/*
2414 * ml_get_cursor: get pointer to cursor position
2415 */
2416 char_u *
2417ml_get_cursor()
2418{
2419 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2420 curwin->w_cursor.col);
2421}
2422
2423/*
2424 * get a pointer to a line in a specific buffer
2425 *
2426 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2427 * changed)
2428 */
2429 char_u *
2430ml_get_buf(buf, lnum, will_change)
2431 buf_T *buf;
2432 linenr_T lnum;
2433 int will_change; /* line will be changed */
2434{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002435 bhdr_T *hp;
2436 DATA_BL *dp;
2437 char_u *ptr;
2438 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002439
2440 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2441 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002442 if (recursive == 0)
2443 {
2444 /* Avoid giving this message for a recursive call, may happen when
2445 * the GUI redraws part of the text. */
2446 ++recursive;
2447 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2448 --recursive;
2449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450errorret:
2451 STRCPY(IObuff, "???");
2452 return IObuff;
2453 }
2454 if (lnum <= 0) /* pretend line 0 is line 1 */
2455 lnum = 1;
2456
2457 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2458 return (char_u *)"";
2459
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002460 /*
2461 * See if it is the same line as requested last time.
2462 * Otherwise may need to flush last used line.
2463 * Don't use the last used line when 'swapfile' is reset, need to load all
2464 * blocks.
2465 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002466 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 {
2468 ml_flush_line(buf);
2469
2470 /*
2471 * Find the data block containing the line.
2472 * This also fills the stack with the blocks from the root to the data
2473 * block and releases any locked block.
2474 */
2475 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2476 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002477 if (recursive == 0)
2478 {
2479 /* Avoid giving this message for a recursive call, may happen
2480 * when the GUI redraws part of the text. */
2481 ++recursive;
2482 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2483 --recursive;
2484 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 goto errorret;
2486 }
2487
2488 dp = (DATA_BL *)(hp->bh_data);
2489
2490 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2491 buf->b_ml.ml_line_ptr = ptr;
2492 buf->b_ml.ml_line_lnum = lnum;
2493 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2494 }
2495 if (will_change)
2496 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2497
2498 return buf->b_ml.ml_line_ptr;
2499}
2500
2501/*
2502 * Check if a line that was just obtained by a call to ml_get
2503 * is in allocated memory.
2504 */
2505 int
2506ml_line_alloced()
2507{
2508 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2509}
2510
2511/*
2512 * Append a line after lnum (may be 0 to insert a line in front of the file).
2513 * "line" does not need to be allocated, but can't be another line in a
2514 * buffer, unlocking may make it invalid.
2515 *
2516 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2517 * will be set for recovery
2518 * Check: The caller of this function should probably also call
2519 * appended_lines().
2520 *
2521 * return FAIL for failure, OK otherwise
2522 */
2523 int
2524ml_append(lnum, line, len, newfile)
2525 linenr_T lnum; /* append after this line (can be 0) */
2526 char_u *line; /* text of the new line */
2527 colnr_T len; /* length of new line, including NUL, or 0 */
2528 int newfile; /* flag, see above */
2529{
2530 /* When starting up, we might still need to create the memfile */
2531 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL) == FAIL)
2532 return FAIL;
2533
2534 if (curbuf->b_ml.ml_line_lnum != 0)
2535 ml_flush_line(curbuf);
2536 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2537}
2538
Bram Moolenaara1956f62006-03-12 22:18:00 +00002539#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002540/*
2541 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2542 * a memline.
2543 */
2544 int
2545ml_append_buf(buf, lnum, line, len, newfile)
2546 buf_T *buf;
2547 linenr_T lnum; /* append after this line (can be 0) */
2548 char_u *line; /* text of the new line */
2549 colnr_T len; /* length of new line, including NUL, or 0 */
2550 int newfile; /* flag, see above */
2551{
2552 if (buf->b_ml.ml_mfp == NULL)
2553 return FAIL;
2554
2555 if (buf->b_ml.ml_line_lnum != 0)
2556 ml_flush_line(buf);
2557 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2558}
2559#endif
2560
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 static int
2562ml_append_int(buf, lnum, line, len, newfile, mark)
2563 buf_T *buf;
2564 linenr_T lnum; /* append after this line (can be 0) */
2565 char_u *line; /* text of the new line */
2566 colnr_T len; /* length of line, including NUL, or 0 */
2567 int newfile; /* flag, see above */
2568 int mark; /* mark the new line */
2569{
2570 int i;
2571 int line_count; /* number of indexes in current block */
2572 int offset;
2573 int from, to;
2574 int space_needed; /* space needed for new line */
2575 int page_size;
2576 int page_count;
2577 int db_idx; /* index for lnum in data block */
2578 bhdr_T *hp;
2579 memfile_T *mfp;
2580 DATA_BL *dp;
2581 PTR_BL *pp;
2582 infoptr_T *ip;
2583
2584 /* lnum out of range */
2585 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2586 return FAIL;
2587
2588 if (lowest_marked && lowest_marked > lnum)
2589 lowest_marked = lnum + 1;
2590
2591 if (len == 0)
2592 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2593 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2594
2595 mfp = buf->b_ml.ml_mfp;
2596 page_size = mfp->mf_page_size;
2597
2598/*
2599 * find the data block containing the previous line
2600 * This also fills the stack with the blocks from the root to the data block
2601 * This also releases any locked block.
2602 */
2603 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2604 ML_INSERT)) == NULL)
2605 return FAIL;
2606
2607 buf->b_ml.ml_flags &= ~ML_EMPTY;
2608
2609 if (lnum == 0) /* got line one instead, correct db_idx */
2610 db_idx = -1; /* careful, it is negative! */
2611 else
2612 db_idx = lnum - buf->b_ml.ml_locked_low;
2613 /* get line count before the insertion */
2614 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2615
2616 dp = (DATA_BL *)(hp->bh_data);
2617
2618/*
2619 * If
2620 * - there is not enough room in the current block
2621 * - appending to the last line in the block
2622 * - not appending to the last line in the file
2623 * insert in front of the next block.
2624 */
2625 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2626 && lnum < buf->b_ml.ml_line_count)
2627 {
2628 /*
2629 * Now that the line is not going to be inserted in the block that we
2630 * expected, the line count has to be adjusted in the pointer blocks
2631 * by using ml_locked_lineadd.
2632 */
2633 --(buf->b_ml.ml_locked_lineadd);
2634 --(buf->b_ml.ml_locked_high);
2635 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2636 return FAIL;
2637
2638 db_idx = -1; /* careful, it is negative! */
2639 /* get line count before the insertion */
2640 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2641 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2642
2643 dp = (DATA_BL *)(hp->bh_data);
2644 }
2645
2646 ++buf->b_ml.ml_line_count;
2647
2648 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2649 {
2650/*
2651 * Insert new line in existing data block, or in data block allocated above.
2652 */
2653 dp->db_txt_start -= len;
2654 dp->db_free -= space_needed;
2655 ++(dp->db_line_count);
2656
2657 /*
2658 * move the text of the lines that follow to the front
2659 * adjust the indexes of the lines that follow
2660 */
2661 if (line_count > db_idx + 1) /* if there are following lines */
2662 {
2663 /*
2664 * Offset is the start of the previous line.
2665 * This will become the character just after the new line.
2666 */
2667 if (db_idx < 0)
2668 offset = dp->db_txt_end;
2669 else
2670 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2671 mch_memmove((char *)dp + dp->db_txt_start,
2672 (char *)dp + dp->db_txt_start + len,
2673 (size_t)(offset - (dp->db_txt_start + len)));
2674 for (i = line_count - 1; i > db_idx; --i)
2675 dp->db_index[i + 1] = dp->db_index[i] - len;
2676 dp->db_index[db_idx + 1] = offset - len;
2677 }
2678 else /* add line at the end */
2679 dp->db_index[db_idx + 1] = dp->db_txt_start;
2680
2681 /*
2682 * copy the text into the block
2683 */
2684 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2685 if (mark)
2686 dp->db_index[db_idx + 1] |= DB_MARKED;
2687
2688 /*
2689 * Mark the block dirty.
2690 */
2691 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2692 if (!newfile)
2693 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2694 }
2695 else /* not enough space in data block */
2696 {
2697/*
2698 * If there is not enough room we have to create a new data block and copy some
2699 * lines into it.
2700 * Then we have to insert an entry in the pointer block.
2701 * If this pointer block also is full, we go up another block, and so on, up
2702 * to the root if necessary.
2703 * The line counts in the pointer blocks have already been adjusted by
2704 * ml_find_line().
2705 */
2706 long line_count_left, line_count_right;
2707 int page_count_left, page_count_right;
2708 bhdr_T *hp_left;
2709 bhdr_T *hp_right;
2710 bhdr_T *hp_new;
2711 int lines_moved;
2712 int data_moved = 0; /* init to shut up gcc */
2713 int total_moved = 0; /* init to shut up gcc */
2714 DATA_BL *dp_right, *dp_left;
2715 int stack_idx;
2716 int in_left;
2717 int lineadd;
2718 blocknr_T bnum_left, bnum_right;
2719 linenr_T lnum_left, lnum_right;
2720 int pb_idx;
2721 PTR_BL *pp_new;
2722
2723 /*
2724 * We are going to allocate a new data block. Depending on the
2725 * situation it will be put to the left or right of the existing
2726 * block. If possible we put the new line in the left block and move
2727 * the lines after it to the right block. Otherwise the new line is
2728 * also put in the right block. This method is more efficient when
2729 * inserting a lot of lines at one place.
2730 */
2731 if (db_idx < 0) /* left block is new, right block is existing */
2732 {
2733 lines_moved = 0;
2734 in_left = TRUE;
2735 /* space_needed does not change */
2736 }
2737 else /* left block is existing, right block is new */
2738 {
2739 lines_moved = line_count - db_idx - 1;
2740 if (lines_moved == 0)
2741 in_left = FALSE; /* put new line in right block */
2742 /* space_needed does not change */
2743 else
2744 {
2745 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2746 dp->db_txt_start;
2747 total_moved = data_moved + lines_moved * INDEX_SIZE;
2748 if ((int)dp->db_free + total_moved >= space_needed)
2749 {
2750 in_left = TRUE; /* put new line in left block */
2751 space_needed = total_moved;
2752 }
2753 else
2754 {
2755 in_left = FALSE; /* put new line in right block */
2756 space_needed += total_moved;
2757 }
2758 }
2759 }
2760
2761 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2762 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2763 {
2764 /* correct line counts in pointer blocks */
2765 --(buf->b_ml.ml_locked_lineadd);
2766 --(buf->b_ml.ml_locked_high);
2767 return FAIL;
2768 }
2769 if (db_idx < 0) /* left block is new */
2770 {
2771 hp_left = hp_new;
2772 hp_right = hp;
2773 line_count_left = 0;
2774 line_count_right = line_count;
2775 }
2776 else /* right block is new */
2777 {
2778 hp_left = hp;
2779 hp_right = hp_new;
2780 line_count_left = line_count;
2781 line_count_right = 0;
2782 }
2783 dp_right = (DATA_BL *)(hp_right->bh_data);
2784 dp_left = (DATA_BL *)(hp_left->bh_data);
2785 bnum_left = hp_left->bh_bnum;
2786 bnum_right = hp_right->bh_bnum;
2787 page_count_left = hp_left->bh_page_count;
2788 page_count_right = hp_right->bh_page_count;
2789
2790 /*
2791 * May move the new line into the right/new block.
2792 */
2793 if (!in_left)
2794 {
2795 dp_right->db_txt_start -= len;
2796 dp_right->db_free -= len + INDEX_SIZE;
2797 dp_right->db_index[0] = dp_right->db_txt_start;
2798 if (mark)
2799 dp_right->db_index[0] |= DB_MARKED;
2800
2801 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2802 line, (size_t)len);
2803 ++line_count_right;
2804 }
2805 /*
2806 * may move lines from the left/old block to the right/new one.
2807 */
2808 if (lines_moved)
2809 {
2810 /*
2811 */
2812 dp_right->db_txt_start -= data_moved;
2813 dp_right->db_free -= total_moved;
2814 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2815 (char *)dp_left + dp_left->db_txt_start,
2816 (size_t)data_moved);
2817 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2818 dp_left->db_txt_start += data_moved;
2819 dp_left->db_free += total_moved;
2820
2821 /*
2822 * update indexes in the new block
2823 */
2824 for (to = line_count_right, from = db_idx + 1;
2825 from < line_count_left; ++from, ++to)
2826 dp_right->db_index[to] = dp->db_index[from] + offset;
2827 line_count_right += lines_moved;
2828 line_count_left -= lines_moved;
2829 }
2830
2831 /*
2832 * May move the new line into the left (old or new) block.
2833 */
2834 if (in_left)
2835 {
2836 dp_left->db_txt_start -= len;
2837 dp_left->db_free -= len + INDEX_SIZE;
2838 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2839 if (mark)
2840 dp_left->db_index[line_count_left] |= DB_MARKED;
2841 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2842 line, (size_t)len);
2843 ++line_count_left;
2844 }
2845
2846 if (db_idx < 0) /* left block is new */
2847 {
2848 lnum_left = lnum + 1;
2849 lnum_right = 0;
2850 }
2851 else /* right block is new */
2852 {
2853 lnum_left = 0;
2854 if (in_left)
2855 lnum_right = lnum + 2;
2856 else
2857 lnum_right = lnum + 1;
2858 }
2859 dp_left->db_line_count = line_count_left;
2860 dp_right->db_line_count = line_count_right;
2861
2862 /*
2863 * release the two data blocks
2864 * The new one (hp_new) already has a correct blocknumber.
2865 * The old one (hp, in ml_locked) gets a positive blocknumber if
2866 * we changed it and we are not editing a new file.
2867 */
2868 if (lines_moved || in_left)
2869 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2870 if (!newfile && db_idx >= 0 && in_left)
2871 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2872 mf_put(mfp, hp_new, TRUE, FALSE);
2873
2874 /*
2875 * flush the old data block
2876 * set ml_locked_lineadd to 0, because the updating of the
2877 * pointer blocks is done below
2878 */
2879 lineadd = buf->b_ml.ml_locked_lineadd;
2880 buf->b_ml.ml_locked_lineadd = 0;
2881 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2882
2883 /*
2884 * update pointer blocks for the new data block
2885 */
2886 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2887 --stack_idx)
2888 {
2889 ip = &(buf->b_ml.ml_stack[stack_idx]);
2890 pb_idx = ip->ip_index;
2891 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2892 return FAIL;
2893 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2894 if (pp->pb_id != PTR_ID)
2895 {
2896 EMSG(_("E317: pointer block id wrong 3"));
2897 mf_put(mfp, hp, FALSE, FALSE);
2898 return FAIL;
2899 }
2900 /*
2901 * TODO: If the pointer block is full and we are adding at the end
2902 * try to insert in front of the next block
2903 */
2904 /* block not full, add one entry */
2905 if (pp->pb_count < pp->pb_count_max)
2906 {
2907 if (pb_idx + 1 < (int)pp->pb_count)
2908 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2909 &pp->pb_pointer[pb_idx + 1],
2910 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2911 ++pp->pb_count;
2912 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2913 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2914 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2915 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2916 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2917 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2918
2919 if (lnum_left != 0)
2920 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2921 if (lnum_right != 0)
2922 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2923
2924 mf_put(mfp, hp, TRUE, FALSE);
2925 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2926
2927 if (lineadd)
2928 {
2929 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002930 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 ml_lineadd(buf, lineadd);
2932 /* fix stack itself */
2933 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2934 lineadd;
2935 ++(buf->b_ml.ml_stack_top);
2936 }
2937
2938 /*
2939 * We are finished, break the loop here.
2940 */
2941 break;
2942 }
2943 else /* pointer block full */
2944 {
2945 /*
2946 * split the pointer block
2947 * allocate a new pointer block
2948 * move some of the pointer into the new block
2949 * prepare for updating the parent block
2950 */
2951 for (;;) /* do this twice when splitting block 1 */
2952 {
2953 hp_new = ml_new_ptr(mfp);
2954 if (hp_new == NULL) /* TODO: try to fix tree */
2955 return FAIL;
2956 pp_new = (PTR_BL *)(hp_new->bh_data);
2957
2958 if (hp->bh_bnum != 1)
2959 break;
2960
2961 /*
2962 * if block 1 becomes full the tree is given an extra level
2963 * The pointers from block 1 are moved into the new block.
2964 * block 1 is updated to point to the new block
2965 * then continue to split the new block
2966 */
2967 mch_memmove(pp_new, pp, (size_t)page_size);
2968 pp->pb_count = 1;
2969 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2970 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2971 pp->pb_pointer[0].pe_old_lnum = 1;
2972 pp->pb_pointer[0].pe_page_count = 1;
2973 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2974 hp = hp_new; /* new block is to be split */
2975 pp = pp_new;
2976 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2977 ip->ip_index = 0;
2978 ++stack_idx; /* do block 1 again later */
2979 }
2980 /*
2981 * move the pointers after the current one to the new block
2982 * If there are none, the new entry will be in the new block.
2983 */
2984 total_moved = pp->pb_count - pb_idx - 1;
2985 if (total_moved)
2986 {
2987 mch_memmove(&pp_new->pb_pointer[0],
2988 &pp->pb_pointer[pb_idx + 1],
2989 (size_t)(total_moved) * sizeof(PTR_EN));
2990 pp_new->pb_count = total_moved;
2991 pp->pb_count -= total_moved - 1;
2992 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2993 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2994 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2995 if (lnum_right)
2996 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2997 }
2998 else
2999 {
3000 pp_new->pb_count = 1;
3001 pp_new->pb_pointer[0].pe_bnum = bnum_right;
3002 pp_new->pb_pointer[0].pe_line_count = line_count_right;
3003 pp_new->pb_pointer[0].pe_page_count = page_count_right;
3004 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
3005 }
3006 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3007 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3008 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3009 if (lnum_left)
3010 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3011 lnum_left = 0;
3012 lnum_right = 0;
3013
3014 /*
3015 * recompute line counts
3016 */
3017 line_count_right = 0;
3018 for (i = 0; i < (int)pp_new->pb_count; ++i)
3019 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3020 line_count_left = 0;
3021 for (i = 0; i < (int)pp->pb_count; ++i)
3022 line_count_left += pp->pb_pointer[i].pe_line_count;
3023
3024 bnum_left = hp->bh_bnum;
3025 bnum_right = hp_new->bh_bnum;
3026 page_count_left = 1;
3027 page_count_right = 1;
3028 mf_put(mfp, hp, TRUE, FALSE);
3029 mf_put(mfp, hp_new, TRUE, FALSE);
3030 }
3031 }
3032
3033 /*
3034 * Safety check: fallen out of for loop?
3035 */
3036 if (stack_idx < 0)
3037 {
3038 EMSG(_("E318: Updated too many blocks?"));
3039 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3040 }
3041 }
3042
3043#ifdef FEAT_BYTEOFF
3044 /* The line was inserted below 'lnum' */
3045 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3046#endif
3047#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003048 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 {
3050 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003051 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003052 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053 (char_u *)"\n", 1);
3054 }
3055#endif
3056 return OK;
3057}
3058
3059/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003060 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003062 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 * copied to allocated memory already.
3064 *
3065 * Check: The caller of this function should probably also call
3066 * changed_lines(), unless update_screen(NOT_VALID) is used.
3067 *
3068 * return FAIL for failure, OK otherwise
3069 */
3070 int
3071ml_replace(lnum, line, copy)
3072 linenr_T lnum;
3073 char_u *line;
3074 int copy;
3075{
3076 if (line == NULL) /* just checking... */
3077 return FAIL;
3078
3079 /* When starting up, we might still need to create the memfile */
3080 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL) == FAIL)
3081 return FAIL;
3082
3083 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3084 return FAIL;
3085#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003086 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087 {
3088 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003089 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 }
3091#endif
3092 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3093 ml_flush_line(curbuf); /* flush it */
3094 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3095 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3096 curbuf->b_ml.ml_line_ptr = line;
3097 curbuf->b_ml.ml_line_lnum = lnum;
3098 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3099
3100 return OK;
3101}
3102
3103/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003104 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 *
3106 * Check: The caller of this function should probably also call
3107 * deleted_lines() after this.
3108 *
3109 * return FAIL for failure, OK otherwise
3110 */
3111 int
3112ml_delete(lnum, message)
3113 linenr_T lnum;
3114 int message;
3115{
3116 ml_flush_line(curbuf);
3117 return ml_delete_int(curbuf, lnum, message);
3118}
3119
3120 static int
3121ml_delete_int(buf, lnum, message)
3122 buf_T *buf;
3123 linenr_T lnum;
3124 int message;
3125{
3126 bhdr_T *hp;
3127 memfile_T *mfp;
3128 DATA_BL *dp;
3129 PTR_BL *pp;
3130 infoptr_T *ip;
3131 int count; /* number of entries in block */
3132 int idx;
3133 int stack_idx;
3134 int text_start;
3135 int line_start;
3136 long line_size;
3137 int i;
3138
3139 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3140 return FAIL;
3141
3142 if (lowest_marked && lowest_marked > lnum)
3143 lowest_marked--;
3144
3145/*
3146 * If the file becomes empty the last line is replaced by an empty line.
3147 */
3148 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3149 {
3150 if (message
3151#ifdef FEAT_NETBEANS_INTG
3152 && !netbeansSuppressNoLines
3153#endif
3154 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003155 set_keep_msg((char_u *)_(no_lines_msg), 0);
3156
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
3158 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3159 buf->b_ml.ml_flags |= ML_EMPTY;
3160
3161 return i;
3162 }
3163
3164/*
3165 * find the data block containing the line
3166 * This also fills the stack with the blocks from the root to the data block
3167 * This also releases any locked block.
3168 */
3169 mfp = buf->b_ml.ml_mfp;
3170 if (mfp == NULL)
3171 return FAIL;
3172
3173 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3174 return FAIL;
3175
3176 dp = (DATA_BL *)(hp->bh_data);
3177 /* compute line count before the delete */
3178 count = (long)(buf->b_ml.ml_locked_high)
3179 - (long)(buf->b_ml.ml_locked_low) + 2;
3180 idx = lnum - buf->b_ml.ml_locked_low;
3181
3182 --buf->b_ml.ml_line_count;
3183
3184 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3185 if (idx == 0) /* first line in block, text at the end */
3186 line_size = dp->db_txt_end - line_start;
3187 else
3188 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3189
3190#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003191 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003192 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193#endif
3194
3195/*
3196 * special case: If there is only one line in the data block it becomes empty.
3197 * Then we have to remove the entry, pointing to this data block, from the
3198 * pointer block. If this pointer block also becomes empty, we go up another
3199 * block, and so on, up to the root if necessary.
3200 * The line counts in the pointer blocks have already been adjusted by
3201 * ml_find_line().
3202 */
3203 if (count == 1)
3204 {
3205 mf_free(mfp, hp); /* free the data block */
3206 buf->b_ml.ml_locked = NULL;
3207
3208 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx)
3209 {
3210 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3211 ip = &(buf->b_ml.ml_stack[stack_idx]);
3212 idx = ip->ip_index;
3213 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3214 return FAIL;
3215 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3216 if (pp->pb_id != PTR_ID)
3217 {
3218 EMSG(_("E317: pointer block id wrong 4"));
3219 mf_put(mfp, hp, FALSE, FALSE);
3220 return FAIL;
3221 }
3222 count = --(pp->pb_count);
3223 if (count == 0) /* the pointer block becomes empty! */
3224 mf_free(mfp, hp);
3225 else
3226 {
3227 if (count != idx) /* move entries after the deleted one */
3228 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3229 (size_t)(count - idx) * sizeof(PTR_EN));
3230 mf_put(mfp, hp, TRUE, FALSE);
3231
3232 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003233 /* fix line count for rest of blocks in the stack */
3234 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 {
3236 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3237 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003238 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239 }
3240 ++(buf->b_ml.ml_stack_top);
3241
3242 break;
3243 }
3244 }
3245 CHECK(stack_idx < 0, _("deleted block 1?"));
3246 }
3247 else
3248 {
3249 /*
3250 * delete the text by moving the next lines forwards
3251 */
3252 text_start = dp->db_txt_start;
3253 mch_memmove((char *)dp + text_start + line_size,
3254 (char *)dp + text_start, (size_t)(line_start - text_start));
3255
3256 /*
3257 * delete the index by moving the next indexes backwards
3258 * Adjust the indexes for the text movement.
3259 */
3260 for (i = idx; i < count - 1; ++i)
3261 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3262
3263 dp->db_free += line_size + INDEX_SIZE;
3264 dp->db_txt_start += line_size;
3265 --(dp->db_line_count);
3266
3267 /*
3268 * mark the block dirty and make sure it is in the file (for recovery)
3269 */
3270 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3271 }
3272
3273#ifdef FEAT_BYTEOFF
3274 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3275#endif
3276 return OK;
3277}
3278
3279/*
3280 * set the B_MARKED flag for line 'lnum'
3281 */
3282 void
3283ml_setmarked(lnum)
3284 linenr_T lnum;
3285{
3286 bhdr_T *hp;
3287 DATA_BL *dp;
3288 /* invalid line number */
3289 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3290 || curbuf->b_ml.ml_mfp == NULL)
3291 return; /* give error message? */
3292
3293 if (lowest_marked == 0 || lowest_marked > lnum)
3294 lowest_marked = lnum;
3295
3296 /*
3297 * find the data block containing the line
3298 * This also fills the stack with the blocks from the root to the data block
3299 * This also releases any locked block.
3300 */
3301 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3302 return; /* give error message? */
3303
3304 dp = (DATA_BL *)(hp->bh_data);
3305 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3306 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3307}
3308
3309/*
3310 * find the first line with its B_MARKED flag set
3311 */
3312 linenr_T
3313ml_firstmarked()
3314{
3315 bhdr_T *hp;
3316 DATA_BL *dp;
3317 linenr_T lnum;
3318 int i;
3319
3320 if (curbuf->b_ml.ml_mfp == NULL)
3321 return (linenr_T) 0;
3322
3323 /*
3324 * The search starts with lowest_marked line. This is the last line where
3325 * a mark was found, adjusted by inserting/deleting lines.
3326 */
3327 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3328 {
3329 /*
3330 * Find the data block containing the line.
3331 * This also fills the stack with the blocks from the root to the data
3332 * block This also releases any locked block.
3333 */
3334 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3335 return (linenr_T)0; /* give error message? */
3336
3337 dp = (DATA_BL *)(hp->bh_data);
3338
3339 for (i = lnum - curbuf->b_ml.ml_locked_low;
3340 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3341 if ((dp->db_index[i]) & DB_MARKED)
3342 {
3343 (dp->db_index[i]) &= DB_INDEX_MASK;
3344 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3345 lowest_marked = lnum + 1;
3346 return lnum;
3347 }
3348 }
3349
3350 return (linenr_T) 0;
3351}
3352
3353#if 0 /* not used */
3354/*
3355 * return TRUE if line 'lnum' has a mark
3356 */
3357 int
3358ml_has_mark(lnum)
3359 linenr_T lnum;
3360{
3361 bhdr_T *hp;
3362 DATA_BL *dp;
3363
3364 if (curbuf->b_ml.ml_mfp == NULL
3365 || (hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3366 return FALSE;
3367
3368 dp = (DATA_BL *)(hp->bh_data);
3369 return (int)((dp->db_index[lnum - curbuf->b_ml.ml_locked_low]) & DB_MARKED);
3370}
3371#endif
3372
3373/*
3374 * clear all DB_MARKED flags
3375 */
3376 void
3377ml_clearmarked()
3378{
3379 bhdr_T *hp;
3380 DATA_BL *dp;
3381 linenr_T lnum;
3382 int i;
3383
3384 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3385 return;
3386
3387 /*
3388 * The search starts with line lowest_marked.
3389 */
3390 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3391 {
3392 /*
3393 * Find the data block containing the line.
3394 * This also fills the stack with the blocks from the root to the data
3395 * block and releases any locked block.
3396 */
3397 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3398 return; /* give error message? */
3399
3400 dp = (DATA_BL *)(hp->bh_data);
3401
3402 for (i = lnum - curbuf->b_ml.ml_locked_low;
3403 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3404 if ((dp->db_index[i]) & DB_MARKED)
3405 {
3406 (dp->db_index[i]) &= DB_INDEX_MASK;
3407 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3408 }
3409 }
3410
3411 lowest_marked = 0;
3412 return;
3413}
3414
3415/*
3416 * flush ml_line if necessary
3417 */
3418 static void
3419ml_flush_line(buf)
3420 buf_T *buf;
3421{
3422 bhdr_T *hp;
3423 DATA_BL *dp;
3424 linenr_T lnum;
3425 char_u *new_line;
3426 char_u *old_line;
3427 colnr_T new_len;
3428 int old_len;
3429 int extra;
3430 int idx;
3431 int start;
3432 int count;
3433 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003434 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435
3436 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3437 return; /* nothing to do */
3438
3439 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3440 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003441 /* This code doesn't work recursively, but Netbeans may call back here
3442 * when obtaining the cursor position. */
3443 if (entered)
3444 return;
3445 entered = TRUE;
3446
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 lnum = buf->b_ml.ml_line_lnum;
3448 new_line = buf->b_ml.ml_line_ptr;
3449
3450 hp = ml_find_line(buf, lnum, ML_FIND);
3451 if (hp == NULL)
3452 EMSGN(_("E320: Cannot find line %ld"), lnum);
3453 else
3454 {
3455 dp = (DATA_BL *)(hp->bh_data);
3456 idx = lnum - buf->b_ml.ml_locked_low;
3457 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3458 old_line = (char_u *)dp + start;
3459 if (idx == 0) /* line is last in block */
3460 old_len = dp->db_txt_end - start;
3461 else /* text of previous line follows */
3462 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3463 new_len = (colnr_T)STRLEN(new_line) + 1;
3464 extra = new_len - old_len; /* negative if lines gets smaller */
3465
3466 /*
3467 * if new line fits in data block, replace directly
3468 */
3469 if ((int)dp->db_free >= extra)
3470 {
3471 /* if the length changes and there are following lines */
3472 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3473 if (extra != 0 && idx < count - 1)
3474 {
3475 /* move text of following lines */
3476 mch_memmove((char *)dp + dp->db_txt_start - extra,
3477 (char *)dp + dp->db_txt_start,
3478 (size_t)(start - dp->db_txt_start));
3479
3480 /* adjust pointers of this and following lines */
3481 for (i = idx + 1; i < count; ++i)
3482 dp->db_index[i] -= extra;
3483 }
3484 dp->db_index[idx] -= extra;
3485
3486 /* adjust free space */
3487 dp->db_free -= extra;
3488 dp->db_txt_start -= extra;
3489
3490 /* copy new line into the data block */
3491 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3492 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3493#ifdef FEAT_BYTEOFF
3494 /* The else case is already covered by the insert and delete */
3495 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3496#endif
3497 }
3498 else
3499 {
3500 /*
3501 * Cannot do it in one data block: Delete and append.
3502 * Append first, because ml_delete_int() cannot delete the
3503 * last line in a buffer, which causes trouble for a buffer
3504 * that has only one line.
3505 * Don't forget to copy the mark!
3506 */
3507 /* How about handling errors??? */
3508 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3509 (dp->db_index[idx] & DB_MARKED));
3510 (void)ml_delete_int(buf, lnum, FALSE);
3511 }
3512 }
3513 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003514
3515 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516 }
3517
3518 buf->b_ml.ml_line_lnum = 0;
3519}
3520
3521/*
3522 * create a new, empty, data block
3523 */
3524 static bhdr_T *
3525ml_new_data(mfp, negative, page_count)
3526 memfile_T *mfp;
3527 int negative;
3528 int page_count;
3529{
3530 bhdr_T *hp;
3531 DATA_BL *dp;
3532
3533 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3534 return NULL;
3535
3536 dp = (DATA_BL *)(hp->bh_data);
3537 dp->db_id = DATA_ID;
3538 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3539 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3540 dp->db_line_count = 0;
3541
3542 return hp;
3543}
3544
3545/*
3546 * create a new, empty, pointer block
3547 */
3548 static bhdr_T *
3549ml_new_ptr(mfp)
3550 memfile_T *mfp;
3551{
3552 bhdr_T *hp;
3553 PTR_BL *pp;
3554
3555 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3556 return NULL;
3557
3558 pp = (PTR_BL *)(hp->bh_data);
3559 pp->pb_id = PTR_ID;
3560 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003561 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3562 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563
3564 return hp;
3565}
3566
3567/*
3568 * lookup line 'lnum' in a memline
3569 *
3570 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3571 * if ML_FLUSH only flush a locked block
3572 * if ML_FIND just find the line
3573 *
3574 * If the block was found it is locked and put in ml_locked.
3575 * The stack is updated to lead to the locked block. The ip_high field in
3576 * the stack is updated to reflect the last line in the block AFTER the
3577 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003578 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579 *
3580 * return: NULL for failure, pointer to block header otherwise
3581 */
3582 static bhdr_T *
3583ml_find_line(buf, lnum, action)
3584 buf_T *buf;
3585 linenr_T lnum;
3586 int action;
3587{
3588 DATA_BL *dp;
3589 PTR_BL *pp;
3590 infoptr_T *ip;
3591 bhdr_T *hp;
3592 memfile_T *mfp;
3593 linenr_T t;
3594 blocknr_T bnum, bnum2;
3595 int dirty;
3596 linenr_T low, high;
3597 int top;
3598 int page_count;
3599 int idx;
3600
3601 mfp = buf->b_ml.ml_mfp;
3602
3603 /*
3604 * If there is a locked block check if the wanted line is in it.
3605 * If not, flush and release the locked block.
3606 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3607 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003608 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609 */
3610 if (buf->b_ml.ml_locked)
3611 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003612 if (ML_SIMPLE(action)
3613 && buf->b_ml.ml_locked_low <= lnum
3614 && buf->b_ml.ml_locked_high >= lnum
3615 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003617 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 if (action == ML_INSERT)
3619 {
3620 ++(buf->b_ml.ml_locked_lineadd);
3621 ++(buf->b_ml.ml_locked_high);
3622 }
3623 else if (action == ML_DELETE)
3624 {
3625 --(buf->b_ml.ml_locked_lineadd);
3626 --(buf->b_ml.ml_locked_high);
3627 }
3628 return (buf->b_ml.ml_locked);
3629 }
3630
3631 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3632 buf->b_ml.ml_flags & ML_LOCKED_POS);
3633 buf->b_ml.ml_locked = NULL;
3634
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003635 /*
3636 * If lines have been added or deleted in the locked block, need to
3637 * update the line count in pointer blocks.
3638 */
3639 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3641 }
3642
3643 if (action == ML_FLUSH) /* nothing else to do */
3644 return NULL;
3645
3646 bnum = 1; /* start at the root of the tree */
3647 page_count = 1;
3648 low = 1;
3649 high = buf->b_ml.ml_line_count;
3650
3651 if (action == ML_FIND) /* first try stack entries */
3652 {
3653 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3654 {
3655 ip = &(buf->b_ml.ml_stack[top]);
3656 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3657 {
3658 bnum = ip->ip_bnum;
3659 low = ip->ip_low;
3660 high = ip->ip_high;
3661 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3662 break;
3663 }
3664 }
3665 if (top < 0)
3666 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3667 }
3668 else /* ML_DELETE or ML_INSERT */
3669 buf->b_ml.ml_stack_top = 0; /* start at the root */
3670
3671/*
3672 * search downwards in the tree until a data block is found
3673 */
3674 for (;;)
3675 {
3676 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3677 goto error_noblock;
3678
3679 /*
3680 * update high for insert/delete
3681 */
3682 if (action == ML_INSERT)
3683 ++high;
3684 else if (action == ML_DELETE)
3685 --high;
3686
3687 dp = (DATA_BL *)(hp->bh_data);
3688 if (dp->db_id == DATA_ID) /* data block */
3689 {
3690 buf->b_ml.ml_locked = hp;
3691 buf->b_ml.ml_locked_low = low;
3692 buf->b_ml.ml_locked_high = high;
3693 buf->b_ml.ml_locked_lineadd = 0;
3694 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3695 return hp;
3696 }
3697
3698 pp = (PTR_BL *)(dp); /* must be pointer block */
3699 if (pp->pb_id != PTR_ID)
3700 {
3701 EMSG(_("E317: pointer block id wrong"));
3702 goto error_block;
3703 }
3704
3705 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3706 goto error_block;
3707 ip = &(buf->b_ml.ml_stack[top]);
3708 ip->ip_bnum = bnum;
3709 ip->ip_low = low;
3710 ip->ip_high = high;
3711 ip->ip_index = -1; /* index not known yet */
3712
3713 dirty = FALSE;
3714 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3715 {
3716 t = pp->pb_pointer[idx].pe_line_count;
3717 CHECK(t == 0, _("pe_line_count is zero"));
3718 if ((low += t) > lnum)
3719 {
3720 ip->ip_index = idx;
3721 bnum = pp->pb_pointer[idx].pe_bnum;
3722 page_count = pp->pb_pointer[idx].pe_page_count;
3723 high = low - 1;
3724 low -= t;
3725
3726 /*
3727 * a negative block number may have been changed
3728 */
3729 if (bnum < 0)
3730 {
3731 bnum2 = mf_trans_del(mfp, bnum);
3732 if (bnum != bnum2)
3733 {
3734 bnum = bnum2;
3735 pp->pb_pointer[idx].pe_bnum = bnum;
3736 dirty = TRUE;
3737 }
3738 }
3739
3740 break;
3741 }
3742 }
3743 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3744 {
3745 if (lnum > buf->b_ml.ml_line_count)
3746 EMSGN(_("E322: line number out of range: %ld past the end"),
3747 lnum - buf->b_ml.ml_line_count);
3748
3749 else
3750 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3751 goto error_block;
3752 }
3753 if (action == ML_DELETE)
3754 {
3755 pp->pb_pointer[idx].pe_line_count--;
3756 dirty = TRUE;
3757 }
3758 else if (action == ML_INSERT)
3759 {
3760 pp->pb_pointer[idx].pe_line_count++;
3761 dirty = TRUE;
3762 }
3763 mf_put(mfp, hp, dirty, FALSE);
3764 }
3765
3766error_block:
3767 mf_put(mfp, hp, FALSE, FALSE);
3768error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003769 /*
3770 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3771 * the incremented/decremented line counts, because there won't be a line
3772 * inserted/deleted after all.
3773 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 if (action == ML_DELETE)
3775 ml_lineadd(buf, 1);
3776 else if (action == ML_INSERT)
3777 ml_lineadd(buf, -1);
3778 buf->b_ml.ml_stack_top = 0;
3779 return NULL;
3780}
3781
3782/*
3783 * add an entry to the info pointer stack
3784 *
3785 * return -1 for failure, number of the new entry otherwise
3786 */
3787 static int
3788ml_add_stack(buf)
3789 buf_T *buf;
3790{
3791 int top;
3792 infoptr_T *newstack;
3793
3794 top = buf->b_ml.ml_stack_top;
3795
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003796 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797 if (top == buf->b_ml.ml_stack_size)
3798 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003799 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800
3801 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3802 (buf->b_ml.ml_stack_size + STACK_INCR));
3803 if (newstack == NULL)
3804 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003805 mch_memmove(newstack, buf->b_ml.ml_stack,
3806 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807 vim_free(buf->b_ml.ml_stack);
3808 buf->b_ml.ml_stack = newstack;
3809 buf->b_ml.ml_stack_size += STACK_INCR;
3810 }
3811
3812 buf->b_ml.ml_stack_top++;
3813 return top;
3814}
3815
3816/*
3817 * Update the pointer blocks on the stack for inserted/deleted lines.
3818 * The stack itself is also updated.
3819 *
3820 * When a insert/delete line action fails, the line is not inserted/deleted,
3821 * but the pointer blocks have already been updated. That is fixed here by
3822 * walking through the stack.
3823 *
3824 * Count is the number of lines added, negative if lines have been deleted.
3825 */
3826 static void
3827ml_lineadd(buf, count)
3828 buf_T *buf;
3829 int count;
3830{
3831 int idx;
3832 infoptr_T *ip;
3833 PTR_BL *pp;
3834 memfile_T *mfp = buf->b_ml.ml_mfp;
3835 bhdr_T *hp;
3836
3837 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3838 {
3839 ip = &(buf->b_ml.ml_stack[idx]);
3840 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3841 break;
3842 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3843 if (pp->pb_id != PTR_ID)
3844 {
3845 mf_put(mfp, hp, FALSE, FALSE);
3846 EMSG(_("E317: pointer block id wrong 2"));
3847 break;
3848 }
3849 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3850 ip->ip_high += count;
3851 mf_put(mfp, hp, TRUE, FALSE);
3852 }
3853}
3854
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003855#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003856/*
3857 * Resolve a symlink in the last component of a file name.
3858 * Note that f_resolve() does it for every part of the path, we don't do that
3859 * here.
3860 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3861 * Otherwise returns FAIL.
3862 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003863 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003864resolve_symlink(fname, buf)
3865 char_u *fname;
3866 char_u *buf;
3867{
3868 char_u tmp[MAXPATHL];
3869 int ret;
3870 int depth = 0;
3871
3872 if (fname == NULL)
3873 return FAIL;
3874
3875 /* Put the result so far in tmp[], starting with the original name. */
3876 vim_strncpy(tmp, fname, MAXPATHL - 1);
3877
3878 for (;;)
3879 {
3880 /* Limit symlink depth to 100, catch recursive loops. */
3881 if (++depth == 100)
3882 {
3883 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3884 return FAIL;
3885 }
3886
3887 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3888 if (ret <= 0)
3889 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003890 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003891 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003892 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003893 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003894 * call to vim_FullName(). */
3895 if (depth == 1)
3896 return FAIL;
3897
3898 /* Use the resolved name in tmp[]. */
3899 break;
3900 }
3901
3902 /* There must be some error reading links, use original name. */
3903 return FAIL;
3904 }
3905 buf[ret] = NUL;
3906
3907 /*
3908 * Check whether the symlink is relative or absolute.
3909 * If it's relative, build a new path based on the directory
3910 * portion of the filename (if any) and the path the symlink
3911 * points to.
3912 */
3913 if (mch_isFullName(buf))
3914 STRCPY(tmp, buf);
3915 else
3916 {
3917 char_u *tail;
3918
3919 tail = gettail(tmp);
3920 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3921 return FAIL;
3922 STRCPY(tail, buf);
3923 }
3924 }
3925
3926 /*
3927 * Try to resolve the full name of the file so that the swapfile name will
3928 * be consistent even when opening a relative symlink from different
3929 * working directories.
3930 */
3931 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3932}
3933#endif
3934
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003936 * Make swap file name out of the file name and a directory name.
3937 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003939 char_u *
3940makeswapname(fname, ffname, buf, dir_name)
3941 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003942 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 buf_T *buf;
3944 char_u *dir_name;
3945{
3946 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003947 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003948#ifdef HAVE_READLINK
3949 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003950#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951
3952#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3953 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003954 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955 { /* Ends with '//', Use Full path */
3956 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003957 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 {
3959 r = modname(s, (char_u *)".swp", FALSE);
3960 vim_free(s);
3961 }
3962 return r;
3963 }
3964#endif
3965
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003966#ifdef HAVE_READLINK
3967 /* Expand symlink in the file name, so that we put the swap file with the
3968 * actual file instead of with the symlink. */
3969 if (resolve_symlink(fname, fname_buf) == OK)
3970 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003971#endif
3972
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 r = buf_modname(
3974#ifdef SHORT_FNAME
3975 TRUE,
3976#else
3977 (buf->b_p_sn || buf->b_shortname),
3978#endif
Bram Moolenaar38323e42007-03-06 19:22:53 +00003979#ifdef RISCOS
3980 /* Avoid problems if fname has special chars, eg <Wimp$Scrap> */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003981 ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982#else
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003983 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984#endif
3985 (char_u *)
3986#if defined(VMS) || defined(RISCOS)
3987 "_swp",
3988#else
3989 ".swp",
3990#endif
3991#ifdef SHORT_FNAME /* always 8.3 file name */
3992 FALSE
3993#else
3994 /* Prepend a '.' to the swap file name for the current directory. */
3995 dir_name[0] == '.' && dir_name[1] == NUL
3996#endif
3997 );
3998 if (r == NULL) /* out of memory */
3999 return NULL;
4000
4001 s = get_file_in_dir(r, dir_name);
4002 vim_free(r);
4003 return s;
4004}
4005
4006/*
4007 * Get file name to use for swap file or backup file.
4008 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
4009 * option "dname".
4010 * - If "dname" is ".", return "fname" (swap file in dir of file).
4011 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
4012 * relative to dir of file).
4013 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
4014 * dir).
4015 *
4016 * The return value is an allocated string and can be NULL.
4017 */
4018 char_u *
4019get_file_in_dir(fname, dname)
4020 char_u *fname;
4021 char_u *dname; /* don't use "dirname", it is a global for Alpha */
4022{
4023 char_u *t;
4024 char_u *tail;
4025 char_u *retval;
4026 int save_char;
4027
4028 tail = gettail(fname);
4029
4030 if (dname[0] == '.' && dname[1] == NUL)
4031 retval = vim_strsave(fname);
4032 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
4033 {
4034 if (tail == fname) /* no path before file name */
4035 retval = concat_fnames(dname + 2, tail, TRUE);
4036 else
4037 {
4038 save_char = *tail;
4039 *tail = NUL;
4040 t = concat_fnames(fname, dname + 2, TRUE);
4041 *tail = save_char;
4042 if (t == NULL) /* out of memory */
4043 retval = NULL;
4044 else
4045 {
4046 retval = concat_fnames(t, tail, TRUE);
4047 vim_free(t);
4048 }
4049 }
4050 }
4051 else
4052 retval = concat_fnames(dname, tail, TRUE);
4053
4054 return retval;
4055}
4056
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004057static void attention_message __ARGS((buf_T *buf, char_u *fname));
4058
4059/*
4060 * Print the ATTENTION message: info about an existing swap file.
4061 */
4062 static void
4063attention_message(buf, fname)
4064 buf_T *buf; /* buffer being edited */
4065 char_u *fname; /* swap file name */
4066{
4067 struct stat st;
4068 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004069 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004070
4071 ++no_wait_return;
4072 (void)EMSG(_("E325: ATTENTION"));
4073 MSG_PUTS(_("\nFound a swap file by the name \""));
4074 msg_home_replace(fname);
4075 MSG_PUTS("\"\n");
4076 sx = swapfile_info(fname);
4077 MSG_PUTS(_("While opening file \""));
4078 msg_outtrans(buf->b_fname);
4079 MSG_PUTS("\"\n");
4080 if (mch_stat((char *)buf->b_fname, &st) != -1)
4081 {
4082 MSG_PUTS(_(" dated: "));
4083 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004084 p = ctime(&x); /* includes '\n' */
4085 if (p == NULL)
4086 MSG_PUTS("(invalid)\n");
4087 else
4088 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004089 if (sx != 0 && x > sx)
4090 MSG_PUTS(_(" NEWER than swap file!\n"));
4091 }
4092 /* Some of these messages are long to allow translation to
4093 * other languages. */
4094 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"));
4095 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4096 MSG_PUTS(_("\n(2) An edit session for this file crashed.\n"));
4097 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4098 msg_outtrans(buf->b_fname);
4099 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4100 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4101 msg_outtrans(fname);
4102 MSG_PUTS(_("\"\n to avoid this message.\n"));
4103 cmdline_row = msg_row;
4104 --no_wait_return;
4105}
4106
4107#ifdef FEAT_AUTOCMD
4108static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4109
4110/*
4111 * Trigger the SwapExists autocommands.
4112 * Returns a value for equivalent to do_dialog() (see below):
4113 * 0: still need to ask for a choice
4114 * 1: open read-only
4115 * 2: edit anyway
4116 * 3: recover
4117 * 4: delete it
4118 * 5: quit
4119 * 6: abort
4120 */
4121 static int
4122do_swapexists(buf, fname)
4123 buf_T *buf;
4124 char_u *fname;
4125{
4126 set_vim_var_string(VV_SWAPNAME, fname, -1);
4127 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4128
4129 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004130 * edited. Disallow changing directory here. */
4131 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004132 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004133 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004134
4135 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4136
4137 switch (*get_vim_var_str(VV_SWAPCHOICE))
4138 {
4139 case 'o': return 1;
4140 case 'e': return 2;
4141 case 'r': return 3;
4142 case 'd': return 4;
4143 case 'q': return 5;
4144 case 'a': return 6;
4145 }
4146
4147 return 0;
4148}
4149#endif
4150
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151/*
4152 * Find out what name to use for the swap file for buffer 'buf'.
4153 *
4154 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004155 * Returns the name in allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 *
4157 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004158 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004159 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 */
4161 static char_u *
4162findswapname(buf, dirp, old_fname)
4163 buf_T *buf;
4164 char_u **dirp; /* pointer to list of directories */
4165 char_u *old_fname; /* don't give warning for this file name */
4166{
4167 char_u *fname;
4168 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 char_u *dir_name;
4170#ifdef AMIGA
4171 BPTR fh;
4172#endif
4173#ifndef SHORT_FNAME
4174 int r;
4175#endif
4176
4177#if !defined(SHORT_FNAME) \
4178 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
4179# define CREATE_DUMMY_FILE
4180 FILE *dummyfd = NULL;
4181
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004182 /*
4183 * If we start editing a new file, e.g. "test.doc", which resides on an
4184 * MSDOS compatible filesystem, it is possible that the file
4185 * "test.doc.swp" which we create will be exactly the same file. To avoid
4186 * this problem we temporarily create "test.doc". Don't do this when the
4187 * check below for a 8.3 file name is used.
4188 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
4190 && mch_getperm(buf->b_fname) < 0)
4191 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4192#endif
4193
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004194 /*
4195 * Isolate a directory name from *dirp and put it in dir_name.
4196 * First allocate some memory to put the directory name in.
4197 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
4199 if (dir_name != NULL)
4200 (void)copy_option_part(dirp, dir_name, 31000, ",");
4201
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004202 /*
4203 * we try different names until we find one that does not exist yet
4204 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004205 if (dir_name == NULL) /* out of memory */
4206 fname = NULL;
4207 else
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004208 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209
4210 for (;;)
4211 {
4212 if (fname == NULL) /* must be out of memory */
4213 break;
4214 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4215 {
4216 vim_free(fname);
4217 fname = NULL;
4218 break;
4219 }
4220#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4221/*
4222 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4223 * file names. If this is the first try and the swap file name does not fit in
4224 * 8.3, detect if this is the case, set shortname and try again.
4225 */
4226 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4227 && !(buf->b_p_sn || buf->b_shortname))
4228 {
4229 char_u *tail;
4230 char_u *fname2;
4231 struct stat s1, s2;
4232 int f1, f2;
4233 int created1 = FALSE, created2 = FALSE;
4234 int same = FALSE;
4235
4236 /*
4237 * Check if swapfile name does not fit in 8.3:
4238 * It either contains two dots, is longer than 8 chars, or starts
4239 * with a dot.
4240 */
4241 tail = gettail(buf->b_fname);
4242 if ( vim_strchr(tail, '.') != NULL
4243 || STRLEN(tail) > (size_t)8
4244 || *gettail(fname) == '.')
4245 {
4246 fname2 = alloc(n + 2);
4247 if (fname2 != NULL)
4248 {
4249 STRCPY(fname2, fname);
4250 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4251 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4252 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4253 */
4254 if (vim_strchr(tail, '.') != NULL)
4255 fname2[n - 1] = 'x';
4256 else if (*gettail(fname) == '.')
4257 {
4258 fname2[n] = 'x';
4259 fname2[n + 1] = NUL;
4260 }
4261 else
4262 fname2[n - 5] += 1;
4263 /*
4264 * may need to create the files to be able to use mch_stat()
4265 */
4266 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4267 if (f1 < 0)
4268 {
4269 f1 = mch_open_rw((char *)fname,
4270 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4271#if defined(OS2)
4272 if (f1 < 0 && errno == ENOENT)
4273 same = TRUE;
4274#endif
4275 created1 = TRUE;
4276 }
4277 if (f1 >= 0)
4278 {
4279 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4280 if (f2 < 0)
4281 {
4282 f2 = mch_open_rw((char *)fname2,
4283 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4284 created2 = TRUE;
4285 }
4286 if (f2 >= 0)
4287 {
4288 /*
4289 * Both files exist now. If mch_stat() returns the
4290 * same device and inode they are the same file.
4291 */
4292 if (mch_fstat(f1, &s1) != -1
4293 && mch_fstat(f2, &s2) != -1
4294 && s1.st_dev == s2.st_dev
4295 && s1.st_ino == s2.st_ino)
4296 same = TRUE;
4297 close(f2);
4298 if (created2)
4299 mch_remove(fname2);
4300 }
4301 close(f1);
4302 if (created1)
4303 mch_remove(fname);
4304 }
4305 vim_free(fname2);
4306 if (same)
4307 {
4308 buf->b_shortname = TRUE;
4309 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004310 fname = makeswapname(buf->b_fname, buf->b_ffname,
4311 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004312 continue; /* try again with b_shortname set */
4313 }
4314 }
4315 }
4316 }
4317#endif
4318 /*
4319 * check if the swapfile already exists
4320 */
4321 if (mch_getperm(fname) < 0) /* it does not exist */
4322 {
4323#ifdef HAVE_LSTAT
4324 struct stat sb;
4325
4326 /*
4327 * Extra security check: When a swap file is a symbolic link, this
4328 * is most likely a symlink attack.
4329 */
4330 if (mch_lstat((char *)fname, &sb) < 0)
4331#else
4332# ifdef AMIGA
4333 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4334 /*
4335 * on the Amiga mch_getperm() will return -1 when the file exists
4336 * but is being used by another program. This happens if you edit
4337 * a file twice.
4338 */
4339 if (fh != (BPTR)NULL) /* can open file, OK */
4340 {
4341 Close(fh);
4342 mch_remove(fname);
4343 break;
4344 }
4345 if (IoErr() != ERROR_OBJECT_IN_USE
4346 && IoErr() != ERROR_OBJECT_EXISTS)
4347# endif
4348#endif
4349 break;
4350 }
4351
4352 /*
4353 * A file name equal to old_fname is OK to use.
4354 */
4355 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4356 break;
4357
4358 /*
4359 * get here when file already exists
4360 */
4361 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4362 {
4363#ifndef SHORT_FNAME
4364 /*
4365 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4366 * and file.doc are the same file. To guess if this problem is
4367 * present try if file.doc.swx exists. If it does, we set
4368 * buf->b_shortname and try file_doc.swp (dots replaced by
4369 * underscores for this file), and try again. If it doesn't we
4370 * assume that "file.doc.swp" already exists.
4371 */
4372 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4373 {
4374 fname[n - 1] = 'x';
4375 r = mch_getperm(fname); /* try "file.swx" */
4376 fname[n - 1] = 'p';
4377 if (r >= 0) /* "file.swx" seems to exist */
4378 {
4379 buf->b_shortname = TRUE;
4380 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004381 fname = makeswapname(buf->b_fname, buf->b_ffname,
4382 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 continue; /* try again with '.' replaced with '_' */
4384 }
4385 }
4386#endif
4387 /*
4388 * If we get here the ".swp" file really exists.
4389 * Give an error message, unless recovering, no file name, we are
4390 * viewing a help file or when the path of the file is different
4391 * (happens when all .swp files are in one directory).
4392 */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004393 if (!recoverymode && buf->b_fname != NULL
4394 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004395 {
4396 int fd;
4397 struct block0 b0;
4398 int differ = FALSE;
4399
4400 /*
4401 * Try to read block 0 from the swap file to get the original
4402 * file name (and inode number).
4403 */
4404 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4405 if (fd >= 0)
4406 {
4407 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
4408 {
4409 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004410 * If the swapfile has the same directory as the
4411 * buffer don't compare the directory names, they can
4412 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004414 if (b0.b0_flags & B0_SAME_DIR)
4415 {
4416 if (fnamecmp(gettail(buf->b_ffname),
4417 gettail(b0.b0_fname)) != 0
4418 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004419 {
4420#ifdef CHECK_INODE
4421 /* Symlinks may point to the same file even
4422 * when the name differs, need to check the
4423 * inode too. */
4424 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4425 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4426 char_to_long(b0.b0_ino)))
4427#endif
4428 differ = TRUE;
4429 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004430 }
4431 else
4432 {
4433 /*
4434 * The name in the swap file may be
4435 * "~user/path/file". Expand it first.
4436 */
4437 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004439 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004440 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004441 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004443 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4444 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004446 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 }
4448 close(fd);
4449 }
4450#ifdef RISCOS
4451 else
4452 /* Can't open swap file, though it does exist.
4453 * Assume that the user is editing two files with
4454 * the same name in different directories. No error.
4455 */
4456 differ = TRUE;
4457#endif
4458
4459 /* give the ATTENTION message when there is an old swap file
4460 * for the current file, and the buffer was not recovered. */
4461 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4462 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4463 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004464#if defined(HAS_SWAP_EXISTS_ACTION)
4465 int choice = 0;
4466#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467#ifdef CREATE_DUMMY_FILE
4468 int did_use_dummy = FALSE;
4469
4470 /* Avoid getting a warning for the file being created
4471 * outside of Vim, it was created at the start of this
4472 * function. Delete the file now, because Vim might exit
4473 * here if the window is closed. */
4474 if (dummyfd != NULL)
4475 {
4476 fclose(dummyfd);
4477 dummyfd = NULL;
4478 mch_remove(buf->b_fname);
4479 did_use_dummy = TRUE;
4480 }
4481#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482
4483#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4484 process_still_running = FALSE;
4485#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004486#ifdef FEAT_AUTOCMD
4487 /*
4488 * If there is an SwapExists autocommand and we can handle
4489 * the response, trigger it. It may return 0 to ask the
4490 * user anyway.
4491 */
4492 if (swap_exists_action != SEA_NONE
4493 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4494 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004496 if (choice == 0)
4497#endif
4498 {
4499#ifdef FEAT_GUI
4500 /* If we are supposed to start the GUI but it wasn't
4501 * completely started yet, start it now. This makes
4502 * the messages displayed in the Vim window when
4503 * loading a session from the .gvimrc file. */
4504 if (gui.starting && !gui.in_use)
4505 gui_start();
4506#endif
4507 /* Show info about the existing swap file. */
4508 attention_message(buf, fname);
4509
4510 /* We don't want a 'q' typed at the more-prompt
4511 * interrupt loading a file. */
4512 got_int = FALSE;
4513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514
4515#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004516 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 {
4518 char_u *name;
4519
4520 name = alloc((unsigned)(STRLEN(fname)
4521 + STRLEN(_("Swap file \""))
4522 + STRLEN(_("\" already exists!")) + 5));
4523 if (name != NULL)
4524 {
4525 STRCPY(name, _("Swap file \""));
4526 home_replace(NULL, fname, name + STRLEN(name),
4527 1000, TRUE);
4528 STRCAT(name, _("\" already exists!"));
4529 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004530 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 (char_u *)_("VIM - ATTENTION"),
4532 name == NULL
4533 ? (char_u *)_("Swap file already exists!")
4534 : name,
4535# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4536 process_still_running
4537 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4538# endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004539 (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL);
4540
4541# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4542 if (process_still_running && choice >= 4)
4543 choice++; /* Skip missing "Delete it" button */
4544# endif
4545 vim_free(name);
4546
4547 /* pretend screen didn't scroll, need redraw anyway */
4548 msg_scrolled = 0;
4549 redraw_all_later(NOT_VALID);
4550 }
4551#endif
4552
4553#if defined(HAS_SWAP_EXISTS_ACTION)
4554 if (choice > 0)
4555 {
4556 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 {
4558 case 1:
4559 buf->b_p_ro = TRUE;
4560 break;
4561 case 2:
4562 break;
4563 case 3:
4564 swap_exists_action = SEA_RECOVER;
4565 break;
4566 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004567 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568 break;
4569 case 5:
4570 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 break;
4572 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004573 swap_exists_action = SEA_QUIT;
4574 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004575 break;
4576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577
4578 /* If the file was deleted this fname can be used. */
4579 if (mch_getperm(fname) < 0)
4580 break;
4581 }
4582 else
4583#endif
4584 {
4585 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004586 if (msg_silent == 0)
4587 /* call wait_return() later */
4588 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589 }
4590
4591#ifdef CREATE_DUMMY_FILE
4592 /* Going to try another name, need the dummy file again. */
4593 if (did_use_dummy)
4594 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4595#endif
4596 }
4597 }
4598 }
4599
4600 /*
4601 * Change the ".swp" extension to find another file that can be used.
4602 * First decrement the last char: ".swo", ".swn", etc.
4603 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004604 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605 */
4606 if (fname[n - 1] == 'a') /* ".s?a" */
4607 {
4608 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4609 {
4610 EMSG(_("E326: Too many swap files found"));
4611 vim_free(fname);
4612 fname = NULL;
4613 break;
4614 }
4615 --fname[n - 2]; /* ".svz", ".suz", etc. */
4616 fname[n - 1] = 'z' + 1;
4617 }
4618 --fname[n - 1]; /* ".swo", ".swn", etc. */
4619 }
4620
4621 vim_free(dir_name);
4622#ifdef CREATE_DUMMY_FILE
4623 if (dummyfd != NULL) /* file has been created temporarily */
4624 {
4625 fclose(dummyfd);
4626 mch_remove(buf->b_fname);
4627 }
4628#endif
4629 return fname;
4630}
4631
4632 static int
4633b0_magic_wrong(b0p)
4634 ZERO_BL *b0p;
4635{
4636 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4637 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4638 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4639 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4640}
4641
4642#ifdef CHECK_INODE
4643/*
4644 * Compare current file name with file name from swap file.
4645 * Try to use inode numbers when possible.
4646 * Return non-zero when files are different.
4647 *
4648 * When comparing file names a few things have to be taken into consideration:
4649 * - When working over a network the full path of a file depends on the host.
4650 * We check the inode number if possible. It is not 100% reliable though,
4651 * because the device number cannot be used over a network.
4652 * - When a file does not exist yet (editing a new file) there is no inode
4653 * number.
4654 * - The file name in a swap file may not be valid on the current host. The
4655 * "~user" form is used whenever possible to avoid this.
4656 *
4657 * This is getting complicated, let's make a table:
4658 *
4659 * ino_c ino_s fname_c fname_s differ =
4660 *
4661 * both files exist -> compare inode numbers:
4662 * != 0 != 0 X X ino_c != ino_s
4663 *
4664 * inode number(s) unknown, file names available -> compare file names
4665 * == 0 X OK OK fname_c != fname_s
4666 * X == 0 OK OK fname_c != fname_s
4667 *
4668 * current file doesn't exist, file for swap file exist, file name(s) not
4669 * available -> probably different
4670 * == 0 != 0 FAIL X TRUE
4671 * == 0 != 0 X FAIL TRUE
4672 *
4673 * current file exists, inode for swap unknown, file name(s) not
4674 * available -> probably different
4675 * != 0 == 0 FAIL X TRUE
4676 * != 0 == 0 X FAIL TRUE
4677 *
4678 * current file doesn't exist, inode for swap unknown, one file name not
4679 * available -> probably different
4680 * == 0 == 0 FAIL OK TRUE
4681 * == 0 == 0 OK FAIL TRUE
4682 *
4683 * current file doesn't exist, inode for swap unknown, both file names not
4684 * available -> probably same file
4685 * == 0 == 0 FAIL FAIL FALSE
4686 *
4687 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4688 * can't be changed without making the block 0 incompatible with 32 bit
4689 * versions.
4690 */
4691
4692 static int
4693fnamecmp_ino(fname_c, fname_s, ino_block0)
4694 char_u *fname_c; /* current file name */
4695 char_u *fname_s; /* file name from swap file */
4696 long ino_block0;
4697{
4698 struct stat st;
4699 ino_t ino_c = 0; /* ino of current file */
4700 ino_t ino_s; /* ino of file from swap file */
4701 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4702 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4703 int retval_c; /* flag: buf_c valid */
4704 int retval_s; /* flag: buf_s valid */
4705
4706 if (mch_stat((char *)fname_c, &st) == 0)
4707 ino_c = (ino_t)st.st_ino;
4708
4709 /*
4710 * First we try to get the inode from the file name, because the inode in
4711 * the swap file may be outdated. If that fails (e.g. this path is not
4712 * valid on this machine), use the inode from block 0.
4713 */
4714 if (mch_stat((char *)fname_s, &st) == 0)
4715 ino_s = (ino_t)st.st_ino;
4716 else
4717 ino_s = (ino_t)ino_block0;
4718
4719 if (ino_c && ino_s)
4720 return (ino_c != ino_s);
4721
4722 /*
4723 * One of the inode numbers is unknown, try a forced vim_FullName() and
4724 * compare the file names.
4725 */
4726 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4727 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4728 if (retval_c == OK && retval_s == OK)
4729 return (STRCMP(buf_c, buf_s) != 0);
4730
4731 /*
4732 * Can't compare inodes or file names, guess that the files are different,
4733 * unless both appear not to exist at all.
4734 */
4735 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4736 return FALSE;
4737 return TRUE;
4738}
4739#endif /* CHECK_INODE */
4740
4741/*
4742 * Move a long integer into a four byte character array.
4743 * Used for machine independency in block zero.
4744 */
4745 static void
4746long_to_char(n, s)
4747 long n;
4748 char_u *s;
4749{
4750 s[0] = (char_u)(n & 0xff);
4751 n = (unsigned)n >> 8;
4752 s[1] = (char_u)(n & 0xff);
4753 n = (unsigned)n >> 8;
4754 s[2] = (char_u)(n & 0xff);
4755 n = (unsigned)n >> 8;
4756 s[3] = (char_u)(n & 0xff);
4757}
4758
4759 static long
4760char_to_long(s)
4761 char_u *s;
4762{
4763 long retval;
4764
4765 retval = s[3];
4766 retval <<= 8;
4767 retval |= s[2];
4768 retval <<= 8;
4769 retval |= s[1];
4770 retval <<= 8;
4771 retval |= s[0];
4772
4773 return retval;
4774}
4775
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004776/*
4777 * Set the flags in the first block of the swap file:
4778 * - file is modified or not: buf->b_changed
4779 * - 'fileformat'
4780 * - 'fileencoding'
4781 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004783ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785{
4786 bhdr_T *hp;
4787 ZERO_BL *b0p;
4788
4789 if (!buf->b_ml.ml_mfp)
4790 return;
4791 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4792 {
4793 if (hp->bh_bnum == 0)
4794 {
4795 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004796 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4797 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4798 | (get_fileformat(buf) + 1);
4799#ifdef FEAT_MBYTE
4800 add_b0_fenc(b0p, buf);
4801#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 hp->bh_flags |= BH_DIRTY;
4803 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4804 break;
4805 }
4806 }
4807}
4808
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004809#if defined(FEAT_CRYPT) || defined(PROTO)
4810/*
4811 * If "data" points to a data block encrypt the text in it and return a copy
4812 * in allocated memory. Return NULL when out of memory.
4813 * Otherwise return "data".
4814 */
4815 char_u *
4816ml_encrypt_data(mfp, data, offset, size)
4817 memfile_T *mfp;
4818 char_u *data;
4819 off_t offset;
4820 unsigned size;
4821{
4822 DATA_BL *dp = (DATA_BL *)data;
4823 char_u *head_end;
4824 char_u *text_start;
4825 char_u *new_data;
4826 int text_len;
4827
4828 if (dp->db_id != DATA_ID)
4829 return data;
4830
4831 new_data = (char_u *)alloc(size);
4832 if (new_data == NULL)
4833 return NULL;
4834 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4835 text_start = (char_u *)dp + dp->db_txt_start;
4836 text_len = size - dp->db_txt_start;
4837
4838 /* Copy the header and the text. */
4839 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4840
4841 /* Encrypt the text. */
4842 crypt_push_state();
4843 ml_crypt_prepare(mfp, offset, FALSE);
4844 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4845 crypt_pop_state();
4846
4847 /* Clear the gap. */
4848 if (head_end < text_start)
4849 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4850
4851 return new_data;
4852}
4853
4854/*
4855 * Decrypt the text in "data" if it points to a data block.
4856 */
4857 void
4858ml_decrypt_data(mfp, data, offset, size)
4859 memfile_T *mfp;
4860 char_u *data;
4861 off_t offset;
4862 unsigned size;
4863{
4864 DATA_BL *dp = (DATA_BL *)data;
4865 char_u *head_end;
4866 char_u *text_start;
4867 int text_len;
4868
4869 if (dp->db_id == DATA_ID)
4870 {
4871 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4872 text_start = (char_u *)dp + dp->db_txt_start;
4873 text_len = dp->db_txt_end - dp->db_txt_start;
4874
4875 if (head_end > text_start || dp->db_txt_start > size
4876 || dp->db_txt_end > size)
4877 return; /* data was messed up */
4878
4879 /* Decrypt the text in place. */
4880 crypt_push_state();
4881 ml_crypt_prepare(mfp, offset, TRUE);
4882 crypt_decode(text_start, text_len);
4883 crypt_pop_state();
4884 }
4885}
4886
4887/*
4888 * Prepare for encryption/decryption, using the key, seed and offset.
4889 */
4890 static void
4891ml_crypt_prepare(mfp, offset, reading)
4892 memfile_T *mfp;
4893 off_t offset;
4894 int reading;
4895{
4896 buf_T *buf = mfp->mf_buffer;
4897 char_u salt[50];
4898 int method;
4899 char_u *key;
4900 char_u *seed;
4901
4902 if (reading && mfp->mf_old_key != NULL)
4903 {
4904 /* Reading back blocks with the previous key/method/seed. */
4905 method = mfp->mf_old_cm;
4906 key = mfp->mf_old_key;
4907 seed = mfp->mf_old_seed;
4908 }
4909 else
4910 {
4911 method = buf->b_p_cm;
4912 key = buf->b_p_key;
4913 seed = mfp->mf_seed;
4914 }
4915
4916 use_crypt_method = method; /* select pkzip or blowfish */
4917 if (method == 0)
4918 {
4919 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4920 crypt_init_keys(salt);
4921 }
4922 else
4923 {
4924 /* Using blowfish, add salt and seed. We use the byte offset of the
4925 * block for the salt. */
4926 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004927 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004928 bf_ofb_init(seed, MF_SEED_LEN);
4929 }
4930}
4931
4932#endif
4933
4934
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935#if defined(FEAT_BYTEOFF) || defined(PROTO)
4936
4937#define MLCS_MAXL 800 /* max no of lines in chunk */
4938#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4939
4940/*
4941 * Keep information for finding byte offset of a line, updtytpe may be one of:
4942 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4943 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4944 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4945 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4946 */
4947 static void
4948ml_updatechunk(buf, line, len, updtype)
4949 buf_T *buf;
4950 linenr_T line;
4951 long len;
4952 int updtype;
4953{
4954 static buf_T *ml_upd_lastbuf = NULL;
4955 static linenr_T ml_upd_lastline;
4956 static linenr_T ml_upd_lastcurline;
4957 static int ml_upd_lastcurix;
4958
4959 linenr_T curline = ml_upd_lastcurline;
4960 int curix = ml_upd_lastcurix;
4961 long size;
4962 chunksize_T *curchnk;
4963 int rest;
4964 bhdr_T *hp;
4965 DATA_BL *dp;
4966
4967 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4968 return;
4969 if (buf->b_ml.ml_chunksize == NULL)
4970 {
4971 buf->b_ml.ml_chunksize = (chunksize_T *)
4972 alloc((unsigned)sizeof(chunksize_T) * 100);
4973 if (buf->b_ml.ml_chunksize == NULL)
4974 {
4975 buf->b_ml.ml_usedchunks = -1;
4976 return;
4977 }
4978 buf->b_ml.ml_numchunks = 100;
4979 buf->b_ml.ml_usedchunks = 1;
4980 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4981 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4982 }
4983
4984 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4985 {
4986 /*
4987 * First line in empty buffer from ml_flush_line() -- reset
4988 */
4989 buf->b_ml.ml_usedchunks = 1;
4990 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4991 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4992 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4993 return;
4994 }
4995
4996 /*
4997 * Find chunk that our line belongs to, curline will be at start of the
4998 * chunk.
4999 */
5000 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
5001 || updtype != ML_CHNK_ADDLINE)
5002 {
5003 for (curline = 1, curix = 0;
5004 curix < buf->b_ml.ml_usedchunks - 1
5005 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5006 curix++)
5007 {
5008 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5009 }
5010 }
5011 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
5012 && curix < buf->b_ml.ml_usedchunks - 1)
5013 {
5014 /* Adjust cached curix & curline */
5015 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5016 curix++;
5017 }
5018 curchnk = buf->b_ml.ml_chunksize + curix;
5019
5020 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00005021 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022 curchnk->mlcs_totalsize += len;
5023 if (updtype == ML_CHNK_ADDLINE)
5024 {
5025 curchnk->mlcs_numlines++;
5026
5027 /* May resize here so we don't have to do it in both cases below */
5028 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5029 {
5030 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5031 buf->b_ml.ml_chunksize = (chunksize_T *)
5032 vim_realloc(buf->b_ml.ml_chunksize,
5033 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5034 if (buf->b_ml.ml_chunksize == NULL)
5035 {
5036 /* Hmmmm, Give up on offset for this buffer */
5037 buf->b_ml.ml_usedchunks = -1;
5038 return;
5039 }
5040 }
5041
5042 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5043 {
5044 int count; /* number of entries in block */
5045 int idx;
5046 int text_end;
5047 int linecnt;
5048
5049 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5050 buf->b_ml.ml_chunksize + curix,
5051 (buf->b_ml.ml_usedchunks - curix) *
5052 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005053 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054 size = 0;
5055 linecnt = 0;
5056 while (curline < buf->b_ml.ml_line_count
5057 && linecnt < MLCS_MINL)
5058 {
5059 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5060 {
5061 buf->b_ml.ml_usedchunks = -1;
5062 return;
5063 }
5064 dp = (DATA_BL *)(hp->bh_data);
5065 count = (long)(buf->b_ml.ml_locked_high) -
5066 (long)(buf->b_ml.ml_locked_low) + 1;
5067 idx = curline - buf->b_ml.ml_locked_low;
5068 curline = buf->b_ml.ml_locked_high + 1;
5069 if (idx == 0)/* first line in block, text at the end */
5070 text_end = dp->db_txt_end;
5071 else
5072 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5073 /* Compute index of last line to use in this MEMLINE */
5074 rest = count - idx;
5075 if (linecnt + rest > MLCS_MINL)
5076 {
5077 idx += MLCS_MINL - linecnt - 1;
5078 linecnt = MLCS_MINL;
5079 }
5080 else
5081 {
5082 idx = count - 1;
5083 linecnt += rest;
5084 }
5085 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5086 }
5087 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5088 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5089 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5090 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5091 buf->b_ml.ml_usedchunks++;
5092 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5093 return;
5094 }
5095 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5096 && curix == buf->b_ml.ml_usedchunks - 1
5097 && buf->b_ml.ml_line_count - line <= 1)
5098 {
5099 /*
5100 * We are in the last chunk and it is cheap to crate a new one
5101 * after this. Do it now to avoid the loop above later on
5102 */
5103 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5104 buf->b_ml.ml_usedchunks++;
5105 if (line == buf->b_ml.ml_line_count)
5106 {
5107 curchnk->mlcs_numlines = 0;
5108 curchnk->mlcs_totalsize = 0;
5109 }
5110 else
5111 {
5112 /*
5113 * Line is just prior to last, move count for last
5114 * This is the common case when loading a new file
5115 */
5116 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5117 if (hp == NULL)
5118 {
5119 buf->b_ml.ml_usedchunks = -1;
5120 return;
5121 }
5122 dp = (DATA_BL *)(hp->bh_data);
5123 if (dp->db_line_count == 1)
5124 rest = dp->db_txt_end - dp->db_txt_start;
5125 else
5126 rest =
5127 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5128 - dp->db_txt_start;
5129 curchnk->mlcs_totalsize = rest;
5130 curchnk->mlcs_numlines = 1;
5131 curchnk[-1].mlcs_totalsize -= rest;
5132 curchnk[-1].mlcs_numlines -= 1;
5133 }
5134 }
5135 }
5136 else if (updtype == ML_CHNK_DELLINE)
5137 {
5138 curchnk->mlcs_numlines--;
5139 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5140 if (curix < (buf->b_ml.ml_usedchunks - 1)
5141 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5142 <= MLCS_MINL)
5143 {
5144 curix++;
5145 curchnk = buf->b_ml.ml_chunksize + curix;
5146 }
5147 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5148 {
5149 buf->b_ml.ml_usedchunks--;
5150 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5151 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5152 return;
5153 }
5154 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5155 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5156 > MLCS_MINL))
5157 {
5158 return;
5159 }
5160
5161 /* Collapse chunks */
5162 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5163 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5164 buf->b_ml.ml_usedchunks--;
5165 if (curix < buf->b_ml.ml_usedchunks)
5166 {
5167 mch_memmove(buf->b_ml.ml_chunksize + curix,
5168 buf->b_ml.ml_chunksize + curix + 1,
5169 (buf->b_ml.ml_usedchunks - curix) *
5170 sizeof(chunksize_T));
5171 }
5172 return;
5173 }
5174 ml_upd_lastbuf = buf;
5175 ml_upd_lastline = line;
5176 ml_upd_lastcurline = curline;
5177 ml_upd_lastcurix = curix;
5178}
5179
5180/*
5181 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005182 * Find line with offset if "lnum" is 0; return remaining offset in offp
5183 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184 * return -1 if information is not available
5185 */
5186 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005187ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005189 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190 long *offp;
5191{
5192 linenr_T curline;
5193 int curix;
5194 long size;
5195 bhdr_T *hp;
5196 DATA_BL *dp;
5197 int count; /* number of entries in block */
5198 int idx;
5199 int start_idx;
5200 int text_end;
5201 long offset;
5202 int len;
5203 int ffdos = (get_fileformat(buf) == EOL_DOS);
5204 int extra = 0;
5205
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005206 /* take care of cached line first */
5207 ml_flush_line(curbuf);
5208
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 if (buf->b_ml.ml_usedchunks == -1
5210 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005211 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 return -1;
5213
5214 if (offp == NULL)
5215 offset = 0;
5216 else
5217 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005218 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5220 /*
5221 * Find the last chunk before the one containing our line. Last chunk is
5222 * special because it will never qualify
5223 */
5224 curline = 1;
5225 curix = size = 0;
5226 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005227 && ((lnum != 0
5228 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229 || (offset != 0
5230 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5231 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5232 {
5233 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5234 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5235 if (offset && ffdos)
5236 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5237 curix++;
5238 }
5239
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005240 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 {
5242 if (curline > buf->b_ml.ml_line_count
5243 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5244 return -1;
5245 dp = (DATA_BL *)(hp->bh_data);
5246 count = (long)(buf->b_ml.ml_locked_high) -
5247 (long)(buf->b_ml.ml_locked_low) + 1;
5248 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5249 if (idx == 0)/* first line in block, text at the end */
5250 text_end = dp->db_txt_end;
5251 else
5252 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5253 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005254 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005255 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005256 if (curline + (count - idx) >= lnum)
5257 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258 else
5259 idx = count - 1;
5260 }
5261 else
5262 {
5263 extra = 0;
5264 while (offset >= size
5265 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5266 + ffdos)
5267 {
5268 if (ffdos)
5269 size++;
5270 if (idx == count - 1)
5271 {
5272 extra = 1;
5273 break;
5274 }
5275 idx++;
5276 }
5277 }
5278 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5279 size += len;
5280 if (offset != 0 && size >= offset)
5281 {
5282 if (size + ffdos == offset)
5283 *offp = 0;
5284 else if (idx == start_idx)
5285 *offp = offset - size + len;
5286 else
5287 *offp = offset - size + len
5288 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5289 curline += idx - start_idx + extra;
5290 if (curline > buf->b_ml.ml_line_count)
5291 return -1; /* exactly one byte beyond the end */
5292 return curline;
5293 }
5294 curline = buf->b_ml.ml_locked_high + 1;
5295 }
5296
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005297 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005298 {
5299 /* Count extra CR characters. */
5300 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005301 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005302
5303 /* Don't count the last line break if 'bin' and 'noeol'. */
5304 if (buf->b_p_bin && !buf->b_p_eol)
5305 size -= ffdos + 1;
5306 }
5307
Bram Moolenaar071d4272004-06-13 20:20:40 +00005308 return size;
5309}
5310
5311/*
5312 * Goto byte in buffer with offset 'cnt'.
5313 */
5314 void
5315goto_byte(cnt)
5316 long cnt;
5317{
5318 long boff = cnt;
5319 linenr_T lnum;
5320
5321 ml_flush_line(curbuf); /* cached line may be dirty */
5322 setpcmark();
5323 if (boff)
5324 --boff;
5325 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5326 if (lnum < 1) /* past the end */
5327 {
5328 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5329 curwin->w_curswant = MAXCOL;
5330 coladvance((colnr_T)MAXCOL);
5331 }
5332 else
5333 {
5334 curwin->w_cursor.lnum = lnum;
5335 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005336# ifdef FEAT_VIRTUALEDIT
5337 curwin->w_cursor.coladd = 0;
5338# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339 curwin->w_set_curswant = TRUE;
5340 }
5341 check_cursor();
5342
5343# ifdef FEAT_MBYTE
5344 /* Make sure the cursor is on the first byte of a multi-byte char. */
5345 if (has_mbyte)
5346 mb_adjust_cursor();
5347# endif
5348}
5349#endif