blob: 148da61d0a17fc309910f95611cc1e1bc1ae9da1 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/* for debugging */
11/* #define CHECK(c, s) if (c) EMSG(s) */
12#define CHECK(c, s)
13
14/*
15 * memline.c: Contains the functions for appending, deleting and changing the
Bram Moolenaar4770d092006-01-12 23:22:24 +000016 * text lines. The memfile functions are used to store the information in
17 * blocks of memory, backed up by a file. The structure of the information is
18 * a tree. The root of the tree is a pointer block. The leaves of the tree
19 * are data blocks. In between may be several layers of pointer blocks,
20 * forming branches.
Bram Moolenaar071d4272004-06-13 20:20:40 +000021 *
22 * Three types of blocks are used:
23 * - Block nr 0 contains information for recovery
24 * - Pointer blocks contain list of pointers to other blocks.
25 * - Data blocks contain the actual text.
26 *
27 * Block nr 0 contains the block0 structure (see below).
28 *
29 * Block nr 1 is the first pointer block. It is the root of the tree.
30 * Other pointer blocks are branches.
31 *
32 * If a line is too big to fit in a single page, the block containing that
33 * line is made big enough to hold the line. It may span several pages.
34 * Otherwise all blocks are one page.
35 *
36 * A data block that was filled when starting to edit a file and was not
37 * changed since then, can have a negative block number. This means that it
38 * has not yet been assigned a place in the file. When recovering, the lines
39 * in this data block can be read from the original file. When the block is
40 * changed (lines appended/deleted/changed) or when it is flushed it gets a
41 * positive number. Use mf_trans_del() to get the new number, before calling
42 * mf_get().
43 */
44
Bram Moolenaarc236c162008-07-13 17:41:49 +000045#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
Bram Moolenaar8c8de832008-06-24 22:58:06 +000046# include "vimio.h" /* for mch_open(), must be before vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#endif
48
49#include "vim.h"
50
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#ifndef UNIX /* it's in os_unix.h for Unix */
52# include <time.h>
53#endif
54
Bram Moolenaar5a6404c2006-11-01 17:12:57 +000055#if defined(SASC) || defined(__amigaos4__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000056# include <proto/dos.h> /* for Open() and Close() */
57#endif
58
Bram Moolenaar5a6404c2006-11-01 17:12:57 +000059#ifdef HAVE_ERRNO_H
60# include <errno.h>
61#endif
62
Bram Moolenaar071d4272004-06-13 20:20:40 +000063typedef struct block0 ZERO_BL; /* contents of the first block */
64typedef struct pointer_block PTR_BL; /* contents of a pointer block */
65typedef struct data_block DATA_BL; /* contents of a data block */
66typedef struct pointer_entry PTR_EN; /* block/line-count pair */
67
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020068#define DATA_ID (('d' << 8) + 'a') /* data block id */
69#define PTR_ID (('p' << 8) + 't') /* pointer block id */
70#define BLOCK0_ID0 'b' /* block 0 id 0 */
71#define BLOCK0_ID1 '0' /* block 0 id 1 */
72#define BLOCK0_ID1_C0 'c' /* block 0 id 1 'cm' 0 */
73#define BLOCK0_ID1_C1 'C' /* block 0 id 1 'cm' 1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000074
75/*
76 * pointer to a block, used in a pointer block
77 */
78struct pointer_entry
79{
80 blocknr_T pe_bnum; /* block number */
81 linenr_T pe_line_count; /* number of lines in this branch */
82 linenr_T pe_old_lnum; /* lnum for this block (for recovery) */
83 int pe_page_count; /* number of pages in block pe_bnum */
84};
85
86/*
87 * A pointer block contains a list of branches in the tree.
88 */
89struct pointer_block
90{
91 short_u pb_id; /* ID for pointer block: PTR_ID */
Bram Moolenaar20a825a2010-05-31 21:27:30 +020092 short_u pb_count; /* number of pointers in this block */
Bram Moolenaar071d4272004-06-13 20:20:40 +000093 short_u pb_count_max; /* maximum value for pb_count */
94 PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer)
95 * followed by empty space until end of page */
96};
97
98/*
99 * A data block is a leaf in the tree.
100 *
101 * The text of the lines is at the end of the block. The text of the first line
102 * in the block is put at the end, the text of the second line in front of it,
103 * etc. Thus the order of the lines is the opposite of the line number.
104 */
105struct data_block
106{
107 short_u db_id; /* ID for data block: DATA_ID */
108 unsigned db_free; /* free space available */
109 unsigned db_txt_start; /* byte where text starts */
110 unsigned db_txt_end; /* byte just after data block */
111 linenr_T db_line_count; /* number of lines in this block */
112 unsigned db_index[1]; /* index for start of line (actually bigger)
113 * followed by empty space upto db_txt_start
114 * followed by the text in the lines until
115 * end of page */
116};
117
118/*
119 * The low bits of db_index hold the actual index. The topmost bit is
120 * used for the global command to be able to mark a line.
121 * This method is not clean, but otherwise there would be at least one extra
122 * byte used for each line.
123 * The mark has to be in this place to keep it with the correct line when other
124 * lines are inserted or deleted.
125 */
126#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
127#define DB_INDEX_MASK (~DB_MARKED)
128
129#define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */
130#define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */
131
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000132#define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200133#define B0_FNAME_SIZE_NOCRYPT 898 /* 2 bytes used for other things */
134#define B0_FNAME_SIZE_CRYPT 890 /* 10 bytes used for other things */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000135#define B0_UNAME_SIZE 40
136#define B0_HNAME_SIZE 40
Bram Moolenaar071d4272004-06-13 20:20:40 +0000137/*
138 * Restrict the numbers to 32 bits, otherwise most compilers will complain.
139 * This won't detect a 64 bit machine that only swaps a byte in the top 32
140 * bits, but that is crazy anyway.
141 */
142#define B0_MAGIC_LONG 0x30313233L
143#define B0_MAGIC_INT 0x20212223L
144#define B0_MAGIC_SHORT 0x10111213L
145#define B0_MAGIC_CHAR 0x55
146
147/*
148 * Block zero holds all info about the swap file.
149 *
150 * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
151 * swap files unusable!
152 *
153 * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
154 *
Bram Moolenaarbae0c162007-05-10 19:30:25 +0000155 * This block is built up of single bytes, to make it portable across
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156 * different machines. b0_magic_* is used to check the byte order and size of
157 * variables, because the rest of the swap file is not portable.
158 */
159struct block0
160{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200161 char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1,
162 * BLOCK0_ID1_C0, BLOCK0_ID1_C1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163 char_u b0_version[10]; /* Vim version string */
164 char_u b0_page_size[4];/* number of bytes per page */
165 char_u b0_mtime[4]; /* last modification time of file */
166 char_u b0_ino[4]; /* inode of b0_fname */
167 char_u b0_pid[4]; /* process id of creator (or 0) */
168 char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */
169 char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000170 char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171 long b0_magic_long; /* check for byte order of long */
172 int b0_magic_int; /* check for byte order of int */
173 short b0_magic_short; /* check for byte order of short */
174 char_u b0_magic_char; /* check for last char */
175};
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000176
177/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000178 * Note: b0_dirty and b0_flags are put at the end of the file name. For very
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000179 * long file names in older versions of Vim they are invalid.
180 * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
181 * when there is room, for very long file names it's omitted.
182 */
183#define B0_DIRTY 0x55
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200184#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000185
186/*
187 * The b0_flags field is new in Vim 7.0.
188 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200189#define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2]
190
191/*
192 * Crypt seed goes here, 8 bytes. New in Vim 7.3.
193 * Without encryption these bytes may be used for 'fenc'.
194 */
195#define b0_seed b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000196
197/* The lowest two bits contain the fileformat. Zero means it's not set
198 * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
199 * EOL_MAC + 1. */
200#define B0_FF_MASK 3
201
202/* Swap file is in directory of edited file. Used to find the file from
203 * different mount points. */
204#define B0_SAME_DIR 4
205
206/* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
207 * When empty there is only the NUL. */
208#define B0_HAS_FENC 8
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209
210#define STACK_INCR 5 /* nr of entries added to ml_stack at a time */
211
212/*
213 * The line number where the first mark may be is remembered.
214 * If it is 0 there are no marks at all.
215 * (always used for the current buffer only, no buffer change possible while
216 * executing a global command).
217 */
218static linenr_T lowest_marked = 0;
219
220/*
221 * arguments for ml_find_line()
222 */
223#define ML_DELETE 0x11 /* delete line */
224#define ML_INSERT 0x12 /* insert line */
225#define ML_FIND 0x13 /* just find the line */
226#define ML_FLUSH 0x02 /* flush locked block */
227#define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */
228
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200229/* argument for ml_upd_block0() */
230typedef enum {
231 UB_FNAME = 0 /* update timestamp and filename */
232 , UB_SAME_DIR /* update the B0_SAME_DIR flag */
233 , UB_CRYPT /* update crypt key */
234} upd_block0_T;
235
236#ifdef FEAT_CRYPT
237static void ml_set_b0_crypt __ARGS((buf_T *buf, ZERO_BL *b0p));
238#endif
239static int ml_check_b0_id __ARGS((ZERO_BL *b0p));
240static void ml_upd_block0 __ARGS((buf_T *buf, upd_block0_T what));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241static void set_b0_fname __ARGS((ZERO_BL *, buf_T *buf));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000242static void set_b0_dir_flag __ARGS((ZERO_BL *b0p, buf_T *buf));
243#ifdef FEAT_MBYTE
244static void add_b0_fenc __ARGS((ZERO_BL *b0p, buf_T *buf));
245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246static time_t swapfile_info __ARGS((char_u *));
247static int recov_file_names __ARGS((char_u **, char_u *, int prepend_dot));
248static int ml_append_int __ARGS((buf_T *, linenr_T, char_u *, colnr_T, int, int));
249static int ml_delete_int __ARGS((buf_T *, linenr_T, int));
250static char_u *findswapname __ARGS((buf_T *, char_u **, char_u *));
251static void ml_flush_line __ARGS((buf_T *));
252static bhdr_T *ml_new_data __ARGS((memfile_T *, int, int));
253static bhdr_T *ml_new_ptr __ARGS((memfile_T *));
254static bhdr_T *ml_find_line __ARGS((buf_T *, linenr_T, int));
255static int ml_add_stack __ARGS((buf_T *));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256static void ml_lineadd __ARGS((buf_T *, int));
257static int b0_magic_wrong __ARGS((ZERO_BL *));
258#ifdef CHECK_INODE
259static int fnamecmp_ino __ARGS((char_u *, char_u *, long));
260#endif
261static void long_to_char __ARGS((long, char_u *));
262static long char_to_long __ARGS((char_u *));
263#if defined(UNIX) || defined(WIN3264)
264static char_u *make_percent_swname __ARGS((char_u *dir, char_u *name));
265#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200266#ifdef FEAT_CRYPT
267static void ml_crypt_prepare __ARGS((memfile_T *mfp, off_t offset, int reading));
268#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000269#ifdef FEAT_BYTEOFF
270static void ml_updatechunk __ARGS((buf_T *buf, long line, long len, int updtype));
271#endif
272
273/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000274 * Open a new memline for "buf".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275 *
Bram Moolenaar4770d092006-01-12 23:22:24 +0000276 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277 */
278 int
Bram Moolenaar4770d092006-01-12 23:22:24 +0000279ml_open(buf)
280 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000281{
282 memfile_T *mfp;
283 bhdr_T *hp = NULL;
284 ZERO_BL *b0p;
285 PTR_BL *pp;
286 DATA_BL *dp;
287
Bram Moolenaar4770d092006-01-12 23:22:24 +0000288 /*
289 * init fields in memline struct
290 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200291 buf->b_ml.ml_stack_size = 0; /* no stack yet */
Bram Moolenaar4770d092006-01-12 23:22:24 +0000292 buf->b_ml.ml_stack = NULL; /* no stack yet */
293 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
294 buf->b_ml.ml_locked = NULL; /* no cached block */
295 buf->b_ml.ml_line_lnum = 0; /* no cached line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000296#ifdef FEAT_BYTEOFF
Bram Moolenaar4770d092006-01-12 23:22:24 +0000297 buf->b_ml.ml_chunksize = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298#endif
299
Bram Moolenaar4770d092006-01-12 23:22:24 +0000300 /*
301 * When 'updatecount' is non-zero swap file may be opened later.
302 */
303 if (p_uc && buf->b_p_swf)
304 buf->b_may_swap = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000305 else
Bram Moolenaar4770d092006-01-12 23:22:24 +0000306 buf->b_may_swap = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307
Bram Moolenaar4770d092006-01-12 23:22:24 +0000308 /*
309 * Open the memfile. No swap file is created yet.
310 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000311 mfp = mf_open(NULL, 0);
312 if (mfp == NULL)
313 goto error;
314
Bram Moolenaar4770d092006-01-12 23:22:24 +0000315 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200316#ifdef FEAT_CRYPT
317 mfp->mf_buffer = buf;
318#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000319 buf->b_ml.ml_flags = ML_EMPTY;
320 buf->b_ml.ml_line_count = 1;
Bram Moolenaar592e0a22004-07-03 16:05:59 +0000321#ifdef FEAT_LINEBREAK
322 curwin->w_nrwidth_line_count = 0;
323#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324
325#if defined(MSDOS) && !defined(DJGPP)
326 /* for 16 bit MS-DOS create a swapfile now, because we run out of
327 * memory very quickly */
328 if (p_uc != 0)
Bram Moolenaar4770d092006-01-12 23:22:24 +0000329 ml_open_file(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000330#endif
331
332/*
333 * fill block0 struct and write page 0
334 */
335 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
336 goto error;
337 if (hp->bh_bnum != 0)
338 {
339 EMSG(_("E298: Didn't get block nr 0?"));
340 goto error;
341 }
342 b0p = (ZERO_BL *)(hp->bh_data);
343
344 b0p->b0_id[0] = BLOCK0_ID0;
345 b0p->b0_id[1] = BLOCK0_ID1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 b0p->b0_magic_long = (long)B0_MAGIC_LONG;
347 b0p->b0_magic_int = (int)B0_MAGIC_INT;
348 b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
349 b0p->b0_magic_char = B0_MAGIC_CHAR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 STRNCPY(b0p->b0_version, "VIM ", 4);
351 STRNCPY(b0p->b0_version + 4, Version, 6);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000352 long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000353
Bram Moolenaar76b92b22006-03-24 22:46:53 +0000354#ifdef FEAT_SPELL
355 if (!buf->b_spell)
356#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000357 {
358 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
359 b0p->b0_flags = get_fileformat(buf) + 1;
360 set_b0_fname(b0p, buf);
361 (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
362 b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
363 mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
364 b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
365 long_to_char(mch_get_pid(), b0p->b0_pid);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200366#ifdef FEAT_CRYPT
367 if (*buf->b_p_key != NUL)
368 ml_set_b0_crypt(buf, b0p);
369#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371
372 /*
373 * Always sync block number 0 to disk, so we can check the file name in
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200374 * the swap file in findswapname(). Don't do this for a help files or
375 * a spell buffer though.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 * Only works when there's a swapfile, otherwise it's done when the file
377 * is created.
378 */
379 mf_put(mfp, hp, TRUE, FALSE);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000380 if (!buf->b_help && !B_SPELL(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 (void)mf_sync(mfp, 0);
382
Bram Moolenaar4770d092006-01-12 23:22:24 +0000383 /*
384 * Fill in root pointer block and write page 1.
385 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386 if ((hp = ml_new_ptr(mfp)) == NULL)
387 goto error;
388 if (hp->bh_bnum != 1)
389 {
390 EMSG(_("E298: Didn't get block nr 1?"));
391 goto error;
392 }
393 pp = (PTR_BL *)(hp->bh_data);
394 pp->pb_count = 1;
395 pp->pb_pointer[0].pe_bnum = 2;
396 pp->pb_pointer[0].pe_page_count = 1;
397 pp->pb_pointer[0].pe_old_lnum = 1;
398 pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */
399 mf_put(mfp, hp, TRUE, FALSE);
400
Bram Moolenaar4770d092006-01-12 23:22:24 +0000401 /*
402 * Allocate first data block and create an empty line 1.
403 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
405 goto error;
406 if (hp->bh_bnum != 2)
407 {
408 EMSG(_("E298: Didn't get block nr 2?"));
409 goto error;
410 }
411
412 dp = (DATA_BL *)(hp->bh_data);
413 dp->db_index[0] = --dp->db_txt_start; /* at end of block */
414 dp->db_free -= 1 + INDEX_SIZE;
415 dp->db_line_count = 1;
Bram Moolenaarf05da212009-11-17 16:13:15 +0000416 *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000417
418 return OK;
419
420error:
421 if (mfp != NULL)
422 {
423 if (hp)
424 mf_put(mfp, hp, FALSE, FALSE);
425 mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */
426 }
Bram Moolenaar4770d092006-01-12 23:22:24 +0000427 buf->b_ml.ml_mfp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 return FAIL;
429}
430
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200431#if defined(FEAT_CRYPT) || defined(PROTO)
432/*
433 * Prepare encryption for "buf" with block 0 "b0p".
434 */
435 static void
436ml_set_b0_crypt(buf, b0p)
437 buf_T *buf;
438 ZERO_BL *b0p;
439{
440 if (*buf->b_p_key == NUL)
441 b0p->b0_id[1] = BLOCK0_ID1;
442 else
443 {
Bram Moolenaar49771f42010-07-20 17:32:38 +0200444 if (get_crypt_method(buf) == 0)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200445 b0p->b0_id[1] = BLOCK0_ID1_C0;
446 else
447 {
448 b0p->b0_id[1] = BLOCK0_ID1_C1;
449 /* Generate a seed and store it in block 0 and in the memfile. */
450 sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0);
451 mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
452 }
453 }
454}
455
456/*
457 * Called after the crypt key or 'cryptmethod' was changed for "buf".
458 * Will apply this to the swapfile.
459 * "old_key" is the previous key. It is equal to buf->b_p_key when
460 * 'cryptmethod' is changed.
Bram Moolenaar49771f42010-07-20 17:32:38 +0200461 * "old_cm" is the previous 'cryptmethod'. It is equal to the current
462 * 'cryptmethod' when 'key' is changed.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200463 */
464 void
465ml_set_crypt_key(buf, old_key, old_cm)
466 buf_T *buf;
467 char_u *old_key;
468 int old_cm;
469{
470 memfile_T *mfp = buf->b_ml.ml_mfp;
471 bhdr_T *hp;
472 int page_count;
473 int idx;
474 long error;
475 infoptr_T *ip;
476 PTR_BL *pp;
477 DATA_BL *dp;
478 blocknr_T bnum;
479 int top;
480
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.
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001158 * Only the memline and crypt information in it are really used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001159 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1161 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001162 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001164 /*
1165 * init fields in memline struct
1166 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1168 buf->b_ml.ml_stack = NULL; /* no stack yet */
1169 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1170 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1171 buf->b_ml.ml_locked = NULL; /* no locked block */
1172 buf->b_ml.ml_flags = 0;
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;
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001191 buf->b_p_cm = empty_option;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001192#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193
1194 /*
1195 * The page size set in mf_open() might be different from the page size
1196 * used in the swap file, we must get it from block 0. But to read block
1197 * 0 we need a page size. Use the minimal size for block 0 here, it will
1198 * be set to the real value below.
1199 */
1200 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1201
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001202 /*
1203 * try to read block 0
1204 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1206 {
1207 msg_start();
1208 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1209 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001210 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 attr | MSG_HIST);
1212 msg_end();
1213 goto theend;
1214 }
1215 b0p = (ZERO_BL *)(hp->bh_data);
1216 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1217 {
1218 msg_start();
1219 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1220 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1221 MSG_HIST);
1222 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1223 msg_end();
1224 goto theend;
1225 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001226 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 {
1228 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1229 goto theend;
1230 }
1231 if (b0_magic_wrong(b0p))
1232 {
1233 msg_start();
1234 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1235#if defined(MSDOS) || defined(MSWIN)
1236 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1237 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1238 attr | MSG_HIST);
1239 else
1240#endif
1241 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1242 attr | MSG_HIST);
1243 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001244 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001245 b0p->b0_fname[0] = NUL;
1246 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1247 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1248 msg_end();
1249 goto theend;
1250 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001251
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001252#ifdef FEAT_CRYPT
1253 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
Bram Moolenaar49771f42010-07-20 17:32:38 +02001254 b0_cm = 0;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001255 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1256 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02001257 b0_cm = 1;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001258 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1259 }
Bram Moolenaar49771f42010-07-20 17:32:38 +02001260 set_crypt_method(buf, b0_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001261#else
1262 if (b0p->b0_id[1] != BLOCK0_ID1)
1263 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001264 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001265 goto theend;
1266 }
1267#endif
1268
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 /*
1270 * If we guessed the wrong page size, we have to recalculate the
1271 * highest block number in the file.
1272 */
1273 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1274 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001275 unsigned previous_page_size = mfp->mf_page_size;
1276
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001278 if (mfp->mf_page_size < previous_page_size)
1279 {
1280 msg_start();
1281 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1282 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1283 attr | MSG_HIST);
1284 msg_end();
1285 goto theend;
1286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1288 mfp->mf_blocknr_max = 0; /* no file or empty file */
1289 else
1290 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1291 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001292
1293 /* need to reallocate the memory used to store the data */
1294 p = alloc(mfp->mf_page_size);
1295 if (p == NULL)
1296 goto theend;
1297 mch_memmove(p, hp->bh_data, previous_page_size);
1298 vim_free(hp->bh_data);
1299 hp->bh_data = p;
1300 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301 }
1302
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001303 /*
1304 * If .swp file name given directly, use name from swap file for buffer.
1305 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001306 if (directly)
1307 {
1308 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1309 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1310 goto theend;
1311 }
1312
1313 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001314 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315
1316 if (buf_spname(curbuf) != NULL)
1317 STRCPY(NameBuff, buf_spname(curbuf));
1318 else
1319 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001320 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321 msg_putchar('\n');
1322
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001323 /*
1324 * check date of swap file and original file
1325 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326 mtime = char_to_long(b0p->b0_mtime);
1327 if (curbuf->b_ffname != NULL
1328 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1329 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1330 && org_stat.st_mtime > swp_stat.st_mtime)
1331 || org_stat.st_mtime != mtime))
1332 {
1333 EMSG(_("E308: Warning: Original file may have been changed"));
1334 }
1335 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001336
1337 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1338 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1339 if (b0p->b0_flags & B0_HAS_FENC)
1340 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001341 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001342
1343#ifdef FEAT_CRYPT
1344 /* Use the same size as in add_b0_fenc(). */
1345 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001346 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001347#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001348 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001349 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001350 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001351 }
1352
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1354 hp = NULL;
1355
1356 /*
1357 * Now that we are sure that the file is going to be recovered, clear the
1358 * contents of the current buffer.
1359 */
1360 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1361 ml_delete((linenr_T)1, FALSE);
1362
1363 /*
1364 * Try reading the original file to obtain the values of 'fileformat',
1365 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001366 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 */
1368 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001369 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001372#ifdef FEAT_CRYPT
1373 if (b0_cm >= 0)
1374 {
1375 /* Need to ask the user for the crypt key. If this fails we continue
1376 * without a key, will probably get garbage text. */
1377 if (*curbuf->b_p_key != NUL)
1378 {
1379 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1380 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1381 MSG_PUTS(_("\nenter the new crypt key."));
1382 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1383 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1384 }
1385 else
1386 smsg((char_u *)_(need_key_msg), fname_used);
1387 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1388 if (buf->b_p_key == NULL)
1389 buf->b_p_key = curbuf->b_p_key;
1390 else if (*buf->b_p_key == NUL)
1391 {
1392 vim_free(buf->b_p_key);
1393 buf->b_p_key = curbuf->b_p_key;
1394 }
1395 if (buf->b_p_key == NULL)
1396 buf->b_p_key = empty_option;
1397 }
1398#endif
1399
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001400 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1401 if (b0_ff != 0)
1402 set_fileformat(b0_ff - 1, OPT_LOCAL);
1403 if (b0_fenc != NULL)
1404 {
1405 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1406 vim_free(b0_fenc);
1407 }
1408 unchanged(curbuf, TRUE);
1409
Bram Moolenaar071d4272004-06-13 20:20:40 +00001410 bnum = 1; /* start with block 1 */
1411 page_count = 1; /* which is 1 page */
1412 lnum = 0; /* append after line 0 in curbuf */
1413 line_count = 0;
1414 idx = 0; /* start with first index in block 1 */
1415 error = 0;
1416 buf->b_ml.ml_stack_top = 0;
1417 buf->b_ml.ml_stack = NULL;
1418 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1419
1420 if (curbuf->b_ffname == NULL)
1421 cannot_open = TRUE;
1422 else
1423 cannot_open = FALSE;
1424
1425 serious_error = FALSE;
1426 for ( ; !got_int; line_breakcheck())
1427 {
1428 if (hp != NULL)
1429 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1430
1431 /*
1432 * get block
1433 */
1434 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1435 {
1436 if (bnum == 1)
1437 {
1438 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1439 goto theend;
1440 }
1441 ++error;
1442 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1443 (colnr_T)0, TRUE);
1444 }
1445 else /* there is a block */
1446 {
1447 pp = (PTR_BL *)(hp->bh_data);
1448 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1449 {
1450 /* check line count when using pointer block first time */
1451 if (idx == 0 && line_count != 0)
1452 {
1453 for (i = 0; i < (int)pp->pb_count; ++i)
1454 line_count -= pp->pb_pointer[i].pe_line_count;
1455 if (line_count != 0)
1456 {
1457 ++error;
1458 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1459 (colnr_T)0, TRUE);
1460 }
1461 }
1462
1463 if (pp->pb_count == 0)
1464 {
1465 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1466 (colnr_T)0, TRUE);
1467 ++error;
1468 }
1469 else if (idx < (int)pp->pb_count) /* go a block deeper */
1470 {
1471 if (pp->pb_pointer[idx].pe_bnum < 0)
1472 {
1473 /*
1474 * Data block with negative block number.
1475 * Try to read lines from the original file.
1476 * This is slow, but it works.
1477 */
1478 if (!cannot_open)
1479 {
1480 line_count = pp->pb_pointer[idx].pe_line_count;
1481 if (readfile(curbuf->b_ffname, NULL, lnum,
1482 pp->pb_pointer[idx].pe_old_lnum - 1,
1483 line_count, NULL, 0) == FAIL)
1484 cannot_open = TRUE;
1485 else
1486 lnum += line_count;
1487 }
1488 if (cannot_open)
1489 {
1490 ++error;
1491 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1492 (colnr_T)0, TRUE);
1493 }
1494 ++idx; /* get same block again for next index */
1495 continue;
1496 }
1497
1498 /*
1499 * going one block deeper in the tree
1500 */
1501 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1502 {
1503 ++error;
1504 break; /* out of memory */
1505 }
1506 ip = &(buf->b_ml.ml_stack[top]);
1507 ip->ip_bnum = bnum;
1508 ip->ip_index = idx;
1509
1510 bnum = pp->pb_pointer[idx].pe_bnum;
1511 line_count = pp->pb_pointer[idx].pe_line_count;
1512 page_count = pp->pb_pointer[idx].pe_page_count;
1513 continue;
1514 }
1515 }
1516 else /* not a pointer block */
1517 {
1518 dp = (DATA_BL *)(hp->bh_data);
1519 if (dp->db_id != DATA_ID) /* block id wrong */
1520 {
1521 if (bnum == 1)
1522 {
1523 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1524 mfp->mf_fname);
1525 goto theend;
1526 }
1527 ++error;
1528 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1529 (colnr_T)0, TRUE);
1530 }
1531 else
1532 {
1533 /*
1534 * it is a data block
1535 * Append all the lines in this block
1536 */
1537 has_error = FALSE;
1538 /*
1539 * check length of block
1540 * if wrong, use length in pointer block
1541 */
1542 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1543 {
1544 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1545 (colnr_T)0, TRUE);
1546 ++error;
1547 has_error = TRUE;
1548 dp->db_txt_end = page_count * mfp->mf_page_size;
1549 }
1550
1551 /* make sure there is a NUL at the end of the block */
1552 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1553
1554 /*
1555 * check number of lines in block
1556 * if wrong, use count in data block
1557 */
1558 if (line_count != dp->db_line_count)
1559 {
1560 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1561 (colnr_T)0, TRUE);
1562 ++error;
1563 has_error = TRUE;
1564 }
1565
1566 for (i = 0; i < dp->db_line_count; ++i)
1567 {
1568 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001569 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 || txt_start >= (int)dp->db_txt_end)
1571 {
1572 p = (char_u *)"???";
1573 ++error;
1574 }
1575 else
1576 p = (char_u *)dp + txt_start;
1577 ml_append(lnum++, p, (colnr_T)0, TRUE);
1578 }
1579 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001580 ml_append(lnum++, (char_u *)_("???END"),
1581 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 }
1583 }
1584 }
1585
1586 if (buf->b_ml.ml_stack_top == 0) /* finished */
1587 break;
1588
1589 /*
1590 * go one block up in the tree
1591 */
1592 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1593 bnum = ip->ip_bnum;
1594 idx = ip->ip_index + 1; /* go to next index */
1595 page_count = 1;
1596 }
1597
1598 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001599 * Compare the buffer contents with the original file. When they differ
1600 * set the 'modified' flag.
1601 * Lines 1 - lnum are the new contents.
1602 * Lines lnum + 1 to ml_line_count are the original contents.
1603 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001605 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1606 {
1607 /* Recovering an empty file results in two lines and the first line is
1608 * empty. Don't set the modified flag then. */
1609 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1610 {
1611 changed_int();
1612 ++curbuf->b_changedtick;
1613 }
1614 }
1615 else
1616 {
1617 for (idx = 1; idx <= lnum; ++idx)
1618 {
1619 /* Need to copy one line, fetching the other one may flush it. */
1620 p = vim_strsave(ml_get(idx));
1621 i = STRCMP(p, ml_get(idx + lnum));
1622 vim_free(p);
1623 if (i != 0)
1624 {
1625 changed_int();
1626 ++curbuf->b_changedtick;
1627 break;
1628 }
1629 }
1630 }
1631
1632 /*
1633 * Delete the lines from the original file and the dummy line from the
1634 * empty buffer. These will now be after the last line in the buffer.
1635 */
1636 while (curbuf->b_ml.ml_line_count > lnum
1637 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1638 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 curbuf->b_flags |= BF_RECOVERED;
1640
1641 recoverymode = FALSE;
1642 if (got_int)
1643 EMSG(_("E311: Recovery Interrupted"));
1644 else if (error)
1645 {
1646 ++no_wait_return;
1647 MSG(">>>>>>>>>>>>>");
1648 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1649 --no_wait_return;
1650 MSG(_("See \":help E312\" for more information."));
1651 MSG(">>>>>>>>>>>>>");
1652 }
1653 else
1654 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001655 if (curbuf->b_changed)
1656 {
1657 MSG(_("Recovery completed. You should check if everything is OK."));
1658 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1659 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1660 }
1661 else
1662 MSG(_("Recovery completed. Buffer contents equals file contents."));
1663 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001664 cmdline_row = msg_row;
1665 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001666#ifdef FEAT_CRYPT
1667 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1668 {
1669 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1670 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1671 }
1672#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673 redraw_curbuf_later(NOT_VALID);
1674
1675theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001676 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 recoverymode = FALSE;
1678 if (mfp != NULL)
1679 {
1680 if (hp != NULL)
1681 mf_put(mfp, hp, FALSE, FALSE);
1682 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1683 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001684 if (buf != NULL)
1685 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001686#ifdef FEAT_CRYPT
1687 if (buf->b_p_key != curbuf->b_p_key)
1688 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001689 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001690#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001691 vim_free(buf->b_ml.ml_stack);
1692 vim_free(buf);
1693 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 if (serious_error && called_from_main)
1695 ml_close(curbuf, TRUE);
1696#ifdef FEAT_AUTOCMD
1697 else
1698 {
1699 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1700 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1701 }
1702#endif
1703 return;
1704}
1705
1706/*
1707 * Find the names of swap files in current directory and the directory given
1708 * with the 'directory' option.
1709 *
1710 * Used to:
1711 * - list the swap files for "vim -r"
1712 * - count the number of swap files when recovering
1713 * - list the swap files when recovering
1714 * - find the name of the n'th swap file when recovering
1715 */
1716 int
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001717recover_names(fname, list, nr, fname_out)
1718 char_u *fname; /* base for swap file name */
1719 int list; /* when TRUE, list the swap file names */
1720 int nr; /* when non-zero, return nr'th swap file name */
1721 char_u **fname_out; /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722{
1723 int num_names;
1724 char_u *(names[6]);
1725 char_u *tail;
1726 char_u *p;
1727 int num_files;
1728 int file_count = 0;
1729 char_u **files;
1730 int i;
1731 char_u *dirp;
1732 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001733 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001734#ifdef HAVE_READLINK
1735 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001736#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001737
Bram Moolenaar64354da2010-05-25 21:37:17 +02001738 if (fname != NULL)
1739 {
1740#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001741 /* Expand symlink in the file name, because the swap file is created
1742 * with the actual file instead of with the symlink. */
1743 if (resolve_symlink(fname, fname_buf) == OK)
1744 fname_res = fname_buf;
1745 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001746#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001747 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749
1750 if (list)
1751 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001752 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001753 msg((char_u *)_("Swap files found:"));
1754 msg_putchar('\n');
1755 }
1756
1757 /*
1758 * Do the loop for every directory in 'directory'.
1759 * First allocate some memory to put the directory name in.
1760 */
1761 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1762 dirp = p_dir;
1763 while (dir_name != NULL && *dirp)
1764 {
1765 /*
1766 * Isolate a directory name from *dirp and put it in dir_name (we know
1767 * it is large enough, so use 31000 for length).
1768 * Advance dirp to next directory name.
1769 */
1770 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1771
1772 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1773 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001774 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 {
1776#ifdef VMS
1777 names[0] = vim_strsave((char_u *)"*_sw%");
1778#else
1779# ifdef RISCOS
1780 names[0] = vim_strsave((char_u *)"*_sw#");
1781# else
1782 names[0] = vim_strsave((char_u *)"*.sw?");
1783# endif
1784#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001785#if defined(UNIX) || defined(WIN3264)
1786 /* For Unix names starting with a dot are special. MS-Windows
1787 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 names[1] = vim_strsave((char_u *)".*.sw?");
1789 names[2] = vim_strsave((char_u *)".sw?");
1790 num_names = 3;
1791#else
1792# ifdef VMS
1793 names[1] = vim_strsave((char_u *)".*_sw%");
1794 num_names = 2;
1795# else
1796 num_names = 1;
1797# endif
1798#endif
1799 }
1800 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001801 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 }
1803 else /* check directory dir_name */
1804 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001805 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 {
1807#ifdef VMS
1808 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1809#else
1810# ifdef RISCOS
1811 names[0] = concat_fnames(dir_name, (char_u *)"*_sw#", TRUE);
1812# else
1813 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
1814# endif
1815#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001816#if defined(UNIX) || defined(WIN3264)
1817 /* For Unix names starting with a dot are special. MS-Windows
1818 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1820 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1821 num_names = 3;
1822#else
1823# ifdef VMS
1824 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1825 num_names = 2;
1826# else
1827 num_names = 1;
1828# endif
1829#endif
1830 }
1831 else
1832 {
1833#if defined(UNIX) || defined(WIN3264)
1834 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001835 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 {
1837 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001838 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839 }
1840 else
1841#endif
1842 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001843 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 tail = concat_fnames(dir_name, tail, TRUE);
1845 }
1846 if (tail == NULL)
1847 num_names = 0;
1848 else
1849 {
1850 num_names = recov_file_names(names, tail, FALSE);
1851 vim_free(tail);
1852 }
1853 }
1854 }
1855
1856 /* check for out-of-memory */
1857 for (i = 0; i < num_names; ++i)
1858 {
1859 if (names[i] == NULL)
1860 {
1861 for (i = 0; i < num_names; ++i)
1862 vim_free(names[i]);
1863 num_names = 0;
1864 }
1865 }
1866 if (num_names == 0)
1867 num_files = 0;
1868 else if (expand_wildcards(num_names, names, &num_files, &files,
1869 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1870 num_files = 0;
1871
1872 /*
1873 * When no swap file found, wildcard expansion might have failed (e.g.
1874 * not able to execute the shell).
1875 * Try finding a swap file by simply adding ".swp" to the file name.
1876 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001877 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 {
1879 struct stat st;
1880 char_u *swapname;
1881
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001882 swapname = modname(fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883#if defined(VMS) || defined(RISCOS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001884 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001886 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001888 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 if (swapname != NULL)
1890 {
1891 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1892 {
1893 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1894 if (files != NULL)
1895 {
1896 files[0] = swapname;
1897 swapname = NULL;
1898 num_files = 1;
1899 }
1900 }
1901 vim_free(swapname);
1902 }
1903 }
1904
1905 /*
1906 * remove swapfile name of the current buffer, it must be ignored
1907 */
1908 if (curbuf->b_ml.ml_mfp != NULL
1909 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1910 {
1911 for (i = 0; i < num_files; ++i)
1912 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1913 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001914 /* Remove the name from files[i]. Move further entries
1915 * down. When the array becomes empty free it here, since
1916 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001918 if (--num_files == 0)
1919 vim_free(files);
1920 else
1921 for ( ; i < num_files; ++i)
1922 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 }
1924 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001925 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 {
1927 file_count += num_files;
1928 if (nr <= file_count)
1929 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001930 *fname_out = vim_strsave(
1931 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 dirp = (char_u *)""; /* stop searching */
1933 }
1934 }
1935 else if (list)
1936 {
1937 if (dir_name[0] == '.' && dir_name[1] == NUL)
1938 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001939 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 MSG_PUTS(_(" In current directory:\n"));
1941 else
1942 MSG_PUTS(_(" Using specified name:\n"));
1943 }
1944 else
1945 {
1946 MSG_PUTS(_(" In directory "));
1947 msg_home_replace(dir_name);
1948 MSG_PUTS(":\n");
1949 }
1950
1951 if (num_files)
1952 {
1953 for (i = 0; i < num_files; ++i)
1954 {
1955 /* print the swap file name */
1956 msg_outnum((long)++file_count);
1957 MSG_PUTS(". ");
1958 msg_puts(gettail(files[i]));
1959 msg_putchar('\n');
1960 (void)swapfile_info(files[i]);
1961 }
1962 }
1963 else
1964 MSG_PUTS(_(" -- none --\n"));
1965 out_flush();
1966 }
1967 else
1968 file_count += num_files;
1969
1970 for (i = 0; i < num_names; ++i)
1971 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001972 if (num_files > 0)
1973 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 }
1975 vim_free(dir_name);
1976 return file_count;
1977}
1978
1979#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1980/*
1981 * Append the full path to name with path separators made into percent
1982 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1983 */
1984 static char_u *
1985make_percent_swname(dir, name)
1986 char_u *dir;
1987 char_u *name;
1988{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001989 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990
1991 f = fix_fname(name != NULL ? name : (char_u *) "");
1992 d = NULL;
1993 if (f != NULL)
1994 {
1995 s = alloc((unsigned)(STRLEN(f) + 1));
1996 if (s != NULL)
1997 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001998 STRCPY(s, f);
1999 for (d = s; *d != NUL; mb_ptr_adv(d))
2000 if (vim_ispathsep(*d))
2001 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 d = concat_fnames(dir, s, TRUE);
2003 vim_free(s);
2004 }
2005 vim_free(f);
2006 }
2007 return d;
2008}
2009#endif
2010
2011#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2012static int process_still_running;
2013#endif
2014
2015/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002016 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 * Returns timestamp (0 when unknown).
2018 */
2019 static time_t
2020swapfile_info(fname)
2021 char_u *fname;
2022{
2023 struct stat st;
2024 int fd;
2025 struct block0 b0;
2026 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002027 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028#ifdef UNIX
2029 char_u uname[B0_UNAME_SIZE];
2030#endif
2031
2032 /* print the swap file date */
2033 if (mch_stat((char *)fname, &st) != -1)
2034 {
2035#ifdef UNIX
2036 /* print name of owner of the file */
2037 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2038 {
2039 MSG_PUTS(_(" owned by: "));
2040 msg_outtrans(uname);
2041 MSG_PUTS(_(" dated: "));
2042 }
2043 else
2044#endif
2045 MSG_PUTS(_(" dated: "));
2046 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002047 p = ctime(&x); /* includes '\n' */
2048 if (p == NULL)
2049 MSG_PUTS("(invalid)\n");
2050 else
2051 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 }
2053
2054 /*
2055 * print the original file name
2056 */
2057 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2058 if (fd >= 0)
2059 {
2060 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
2061 {
2062 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2063 {
2064 MSG_PUTS(_(" [from Vim version 3.0]"));
2065 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002066 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 {
2068 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2069 }
2070 else
2071 {
2072 MSG_PUTS(_(" file name: "));
2073 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075 else
2076 msg_outtrans(b0.b0_fname);
2077
2078 MSG_PUTS(_("\n modified: "));
2079 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2080
2081 if (*(b0.b0_uname) != NUL)
2082 {
2083 MSG_PUTS(_("\n user name: "));
2084 msg_outtrans(b0.b0_uname);
2085 }
2086
2087 if (*(b0.b0_hname) != NUL)
2088 {
2089 if (*(b0.b0_uname) != NUL)
2090 MSG_PUTS(_(" host name: "));
2091 else
2092 MSG_PUTS(_("\n host name: "));
2093 msg_outtrans(b0.b0_hname);
2094 }
2095
2096 if (char_to_long(b0.b0_pid) != 0L)
2097 {
2098 MSG_PUTS(_("\n process ID: "));
2099 msg_outnum(char_to_long(b0.b0_pid));
2100#if defined(UNIX) || defined(__EMX__)
2101 /* EMX kill() not working correctly, it seems */
2102 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2103 {
2104 MSG_PUTS(_(" (still running)"));
2105# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2106 process_still_running = TRUE;
2107# endif
2108 }
2109#endif
2110 }
2111
2112 if (b0_magic_wrong(&b0))
2113 {
2114#if defined(MSDOS) || defined(MSWIN)
2115 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2116 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2117 else
2118#endif
2119 MSG_PUTS(_("\n [not usable on this computer]"));
2120 }
2121 }
2122 }
2123 else
2124 MSG_PUTS(_(" [cannot be read]"));
2125 close(fd);
2126 }
2127 else
2128 MSG_PUTS(_(" [cannot be opened]"));
2129 msg_putchar('\n');
2130
2131 return x;
2132}
2133
2134 static int
2135recov_file_names(names, path, prepend_dot)
2136 char_u **names;
2137 char_u *path;
2138 int prepend_dot;
2139{
2140 int num_names;
2141
2142#ifdef SHORT_FNAME
2143 /*
2144 * (MS-DOS) always short names
2145 */
2146 names[0] = modname(path, (char_u *)".sw?", FALSE);
2147 num_names = 1;
2148#else /* !SHORT_FNAME */
2149 /*
2150 * (Win32 and Win64) never short names, but do prepend a dot.
2151 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2152 * Only use the short name if it is different.
2153 */
2154 char_u *p;
2155 int i;
2156# ifndef WIN3264
2157 int shortname = curbuf->b_shortname;
2158
2159 curbuf->b_shortname = FALSE;
2160# endif
2161
2162 num_names = 0;
2163
2164 /*
2165 * May also add the file name with a dot prepended, for swap file in same
2166 * dir as original file.
2167 */
2168 if (prepend_dot)
2169 {
2170 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2171 if (names[num_names] == NULL)
2172 goto end;
2173 ++num_names;
2174 }
2175
2176 /*
2177 * Form the normal swap file name pattern by appending ".sw?".
2178 */
2179#ifdef VMS
2180 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2181#else
2182# ifdef RISCOS
2183 names[num_names] = concat_fnames(path, (char_u *)"_sw#", FALSE);
2184# else
2185 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
2186# endif
2187#endif
2188 if (names[num_names] == NULL)
2189 goto end;
2190 if (num_names >= 1) /* check if we have the same name twice */
2191 {
2192 p = names[num_names - 1];
2193 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2194 if (i > 0)
2195 p += i; /* file name has been expanded to full path */
2196
2197 if (STRCMP(p, names[num_names]) != 0)
2198 ++num_names;
2199 else
2200 vim_free(names[num_names]);
2201 }
2202 else
2203 ++num_names;
2204
2205# ifndef WIN3264
2206 /*
2207 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2208 */
2209 curbuf->b_shortname = TRUE;
2210#ifdef VMS
2211 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2212#else
2213# ifdef RISCOS
2214 names[num_names] = modname(path, (char_u *)"_sw#", FALSE);
2215# else
2216 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
2217# endif
2218#endif
2219 if (names[num_names] == NULL)
2220 goto end;
2221
2222 /*
2223 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2224 */
2225 p = names[num_names];
2226 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2227 if (i > 0)
2228 p += i; /* file name has been expanded to full path */
2229 if (STRCMP(names[num_names - 1], p) == 0)
2230 vim_free(names[num_names]);
2231 else
2232 ++num_names;
2233# endif
2234
2235end:
2236# ifndef WIN3264
2237 curbuf->b_shortname = shortname;
2238# endif
2239
2240#endif /* !SHORT_FNAME */
2241
2242 return num_names;
2243}
2244
2245/*
2246 * sync all memlines
2247 *
2248 * If 'check_file' is TRUE, check if original file exists and was not changed.
2249 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2250 * always sync at least one block.
2251 */
2252 void
2253ml_sync_all(check_file, check_char)
2254 int check_file;
2255 int check_char;
2256{
2257 buf_T *buf;
2258 struct stat st;
2259
2260 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2261 {
2262 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2263 continue; /* no file */
2264
2265 ml_flush_line(buf); /* flush buffered line */
2266 /* flush locked block */
2267 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2268 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2269 && buf->b_ffname != NULL)
2270 {
2271 /*
2272 * If the original file does not exist anymore or has been changed
2273 * call ml_preserve() to get rid of all negative numbered blocks.
2274 */
2275 if (mch_stat((char *)buf->b_ffname, &st) == -1
2276 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002277 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 {
2279 ml_preserve(buf, FALSE);
2280 did_check_timestamps = FALSE;
2281 need_check_timestamps = TRUE; /* give message later */
2282 }
2283 }
2284 if (buf->b_ml.ml_mfp->mf_dirty)
2285 {
2286 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2287 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2288 if (check_char && ui_char_avail()) /* character available now */
2289 break;
2290 }
2291 }
2292}
2293
2294/*
2295 * sync one buffer, including negative blocks
2296 *
2297 * after this all the blocks are in the swap file
2298 *
2299 * Used for the :preserve command and when the original file has been
2300 * changed or deleted.
2301 *
2302 * when message is TRUE the success of preserving is reported
2303 */
2304 void
2305ml_preserve(buf, message)
2306 buf_T *buf;
2307 int message;
2308{
2309 bhdr_T *hp;
2310 linenr_T lnum;
2311 memfile_T *mfp = buf->b_ml.ml_mfp;
2312 int status;
2313 int got_int_save = got_int;
2314
2315 if (mfp == NULL || mfp->mf_fname == NULL)
2316 {
2317 if (message)
2318 EMSG(_("E313: Cannot preserve, there is no swap file"));
2319 return;
2320 }
2321
2322 /* We only want to stop when interrupted here, not when interrupted
2323 * before. */
2324 got_int = FALSE;
2325
2326 ml_flush_line(buf); /* flush buffered line */
2327 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2328 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2329
2330 /* stack is invalid after mf_sync(.., MFS_ALL) */
2331 buf->b_ml.ml_stack_top = 0;
2332
2333 /*
2334 * Some of the data blocks may have been changed from negative to
2335 * positive block number. In that case the pointer blocks need to be
2336 * updated.
2337 *
2338 * We don't know in which pointer block the references are, so we visit
2339 * all data blocks until there are no more translations to be done (or
2340 * we hit the end of the file, which can only happen in case a write fails,
2341 * e.g. when file system if full).
2342 * ml_find_line() does the work by translating the negative block numbers
2343 * when getting the first line of each data block.
2344 */
2345 if (mf_need_trans(mfp) && !got_int)
2346 {
2347 lnum = 1;
2348 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2349 {
2350 hp = ml_find_line(buf, lnum, ML_FIND);
2351 if (hp == NULL)
2352 {
2353 status = FAIL;
2354 goto theend;
2355 }
2356 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2357 lnum = buf->b_ml.ml_locked_high + 1;
2358 }
2359 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2360 /* sync the updated pointer blocks */
2361 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2362 status = FAIL;
2363 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2364 }
2365theend:
2366 got_int |= got_int_save;
2367
2368 if (message)
2369 {
2370 if (status == OK)
2371 MSG(_("File preserved"));
2372 else
2373 EMSG(_("E314: Preserve failed"));
2374 }
2375}
2376
2377/*
2378 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2379 * until the next call!
2380 * line1 = ml_get(1);
2381 * line2 = ml_get(2); // line1 is now invalid!
2382 * Make a copy of the line if necessary.
2383 */
2384/*
2385 * get a pointer to a (read-only copy of a) line
2386 *
2387 * On failure an error message is given and IObuff is returned (to avoid
2388 * having to check for error everywhere).
2389 */
2390 char_u *
2391ml_get(lnum)
2392 linenr_T lnum;
2393{
2394 return ml_get_buf(curbuf, lnum, FALSE);
2395}
2396
2397/*
2398 * ml_get_pos: get pointer to position 'pos'
2399 */
2400 char_u *
2401ml_get_pos(pos)
2402 pos_T *pos;
2403{
2404 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2405}
2406
2407/*
2408 * ml_get_curline: get pointer to cursor line.
2409 */
2410 char_u *
2411ml_get_curline()
2412{
2413 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2414}
2415
2416/*
2417 * ml_get_cursor: get pointer to cursor position
2418 */
2419 char_u *
2420ml_get_cursor()
2421{
2422 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2423 curwin->w_cursor.col);
2424}
2425
2426/*
2427 * get a pointer to a line in a specific buffer
2428 *
2429 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2430 * changed)
2431 */
2432 char_u *
2433ml_get_buf(buf, lnum, will_change)
2434 buf_T *buf;
2435 linenr_T lnum;
2436 int will_change; /* line will be changed */
2437{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002438 bhdr_T *hp;
2439 DATA_BL *dp;
2440 char_u *ptr;
2441 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442
2443 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2444 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002445 if (recursive == 0)
2446 {
2447 /* Avoid giving this message for a recursive call, may happen when
2448 * the GUI redraws part of the text. */
2449 ++recursive;
2450 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2451 --recursive;
2452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453errorret:
2454 STRCPY(IObuff, "???");
2455 return IObuff;
2456 }
2457 if (lnum <= 0) /* pretend line 0 is line 1 */
2458 lnum = 1;
2459
2460 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2461 return (char_u *)"";
2462
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002463 /*
2464 * See if it is the same line as requested last time.
2465 * Otherwise may need to flush last used line.
2466 * Don't use the last used line when 'swapfile' is reset, need to load all
2467 * blocks.
2468 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002469 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470 {
2471 ml_flush_line(buf);
2472
2473 /*
2474 * Find the data block containing the line.
2475 * This also fills the stack with the blocks from the root to the data
2476 * block and releases any locked block.
2477 */
2478 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2479 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002480 if (recursive == 0)
2481 {
2482 /* Avoid giving this message for a recursive call, may happen
2483 * when the GUI redraws part of the text. */
2484 ++recursive;
2485 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2486 --recursive;
2487 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 goto errorret;
2489 }
2490
2491 dp = (DATA_BL *)(hp->bh_data);
2492
2493 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2494 buf->b_ml.ml_line_ptr = ptr;
2495 buf->b_ml.ml_line_lnum = lnum;
2496 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2497 }
2498 if (will_change)
2499 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2500
2501 return buf->b_ml.ml_line_ptr;
2502}
2503
2504/*
2505 * Check if a line that was just obtained by a call to ml_get
2506 * is in allocated memory.
2507 */
2508 int
2509ml_line_alloced()
2510{
2511 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2512}
2513
2514/*
2515 * Append a line after lnum (may be 0 to insert a line in front of the file).
2516 * "line" does not need to be allocated, but can't be another line in a
2517 * buffer, unlocking may make it invalid.
2518 *
2519 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2520 * will be set for recovery
2521 * Check: The caller of this function should probably also call
2522 * appended_lines().
2523 *
2524 * return FAIL for failure, OK otherwise
2525 */
2526 int
2527ml_append(lnum, line, len, newfile)
2528 linenr_T lnum; /* append after this line (can be 0) */
2529 char_u *line; /* text of the new line */
2530 colnr_T len; /* length of new line, including NUL, or 0 */
2531 int newfile; /* flag, see above */
2532{
2533 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002534 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 return FAIL;
2536
2537 if (curbuf->b_ml.ml_line_lnum != 0)
2538 ml_flush_line(curbuf);
2539 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2540}
2541
Bram Moolenaara1956f62006-03-12 22:18:00 +00002542#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002543/*
2544 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2545 * a memline.
2546 */
2547 int
2548ml_append_buf(buf, lnum, line, len, newfile)
2549 buf_T *buf;
2550 linenr_T lnum; /* append after this line (can be 0) */
2551 char_u *line; /* text of the new line */
2552 colnr_T len; /* length of new line, including NUL, or 0 */
2553 int newfile; /* flag, see above */
2554{
2555 if (buf->b_ml.ml_mfp == NULL)
2556 return FAIL;
2557
2558 if (buf->b_ml.ml_line_lnum != 0)
2559 ml_flush_line(buf);
2560 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2561}
2562#endif
2563
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 static int
2565ml_append_int(buf, lnum, line, len, newfile, mark)
2566 buf_T *buf;
2567 linenr_T lnum; /* append after this line (can be 0) */
2568 char_u *line; /* text of the new line */
2569 colnr_T len; /* length of line, including NUL, or 0 */
2570 int newfile; /* flag, see above */
2571 int mark; /* mark the new line */
2572{
2573 int i;
2574 int line_count; /* number of indexes in current block */
2575 int offset;
2576 int from, to;
2577 int space_needed; /* space needed for new line */
2578 int page_size;
2579 int page_count;
2580 int db_idx; /* index for lnum in data block */
2581 bhdr_T *hp;
2582 memfile_T *mfp;
2583 DATA_BL *dp;
2584 PTR_BL *pp;
2585 infoptr_T *ip;
2586
2587 /* lnum out of range */
2588 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2589 return FAIL;
2590
2591 if (lowest_marked && lowest_marked > lnum)
2592 lowest_marked = lnum + 1;
2593
2594 if (len == 0)
2595 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2596 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2597
2598 mfp = buf->b_ml.ml_mfp;
2599 page_size = mfp->mf_page_size;
2600
2601/*
2602 * find the data block containing the previous line
2603 * This also fills the stack with the blocks from the root to the data block
2604 * This also releases any locked block.
2605 */
2606 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2607 ML_INSERT)) == NULL)
2608 return FAIL;
2609
2610 buf->b_ml.ml_flags &= ~ML_EMPTY;
2611
2612 if (lnum == 0) /* got line one instead, correct db_idx */
2613 db_idx = -1; /* careful, it is negative! */
2614 else
2615 db_idx = lnum - buf->b_ml.ml_locked_low;
2616 /* get line count before the insertion */
2617 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2618
2619 dp = (DATA_BL *)(hp->bh_data);
2620
2621/*
2622 * If
2623 * - there is not enough room in the current block
2624 * - appending to the last line in the block
2625 * - not appending to the last line in the file
2626 * insert in front of the next block.
2627 */
2628 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2629 && lnum < buf->b_ml.ml_line_count)
2630 {
2631 /*
2632 * Now that the line is not going to be inserted in the block that we
2633 * expected, the line count has to be adjusted in the pointer blocks
2634 * by using ml_locked_lineadd.
2635 */
2636 --(buf->b_ml.ml_locked_lineadd);
2637 --(buf->b_ml.ml_locked_high);
2638 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2639 return FAIL;
2640
2641 db_idx = -1; /* careful, it is negative! */
2642 /* get line count before the insertion */
2643 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2644 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2645
2646 dp = (DATA_BL *)(hp->bh_data);
2647 }
2648
2649 ++buf->b_ml.ml_line_count;
2650
2651 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2652 {
2653/*
2654 * Insert new line in existing data block, or in data block allocated above.
2655 */
2656 dp->db_txt_start -= len;
2657 dp->db_free -= space_needed;
2658 ++(dp->db_line_count);
2659
2660 /*
2661 * move the text of the lines that follow to the front
2662 * adjust the indexes of the lines that follow
2663 */
2664 if (line_count > db_idx + 1) /* if there are following lines */
2665 {
2666 /*
2667 * Offset is the start of the previous line.
2668 * This will become the character just after the new line.
2669 */
2670 if (db_idx < 0)
2671 offset = dp->db_txt_end;
2672 else
2673 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2674 mch_memmove((char *)dp + dp->db_txt_start,
2675 (char *)dp + dp->db_txt_start + len,
2676 (size_t)(offset - (dp->db_txt_start + len)));
2677 for (i = line_count - 1; i > db_idx; --i)
2678 dp->db_index[i + 1] = dp->db_index[i] - len;
2679 dp->db_index[db_idx + 1] = offset - len;
2680 }
2681 else /* add line at the end */
2682 dp->db_index[db_idx + 1] = dp->db_txt_start;
2683
2684 /*
2685 * copy the text into the block
2686 */
2687 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2688 if (mark)
2689 dp->db_index[db_idx + 1] |= DB_MARKED;
2690
2691 /*
2692 * Mark the block dirty.
2693 */
2694 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2695 if (!newfile)
2696 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2697 }
2698 else /* not enough space in data block */
2699 {
2700/*
2701 * If there is not enough room we have to create a new data block and copy some
2702 * lines into it.
2703 * Then we have to insert an entry in the pointer block.
2704 * If this pointer block also is full, we go up another block, and so on, up
2705 * to the root if necessary.
2706 * The line counts in the pointer blocks have already been adjusted by
2707 * ml_find_line().
2708 */
2709 long line_count_left, line_count_right;
2710 int page_count_left, page_count_right;
2711 bhdr_T *hp_left;
2712 bhdr_T *hp_right;
2713 bhdr_T *hp_new;
2714 int lines_moved;
2715 int data_moved = 0; /* init to shut up gcc */
2716 int total_moved = 0; /* init to shut up gcc */
2717 DATA_BL *dp_right, *dp_left;
2718 int stack_idx;
2719 int in_left;
2720 int lineadd;
2721 blocknr_T bnum_left, bnum_right;
2722 linenr_T lnum_left, lnum_right;
2723 int pb_idx;
2724 PTR_BL *pp_new;
2725
2726 /*
2727 * We are going to allocate a new data block. Depending on the
2728 * situation it will be put to the left or right of the existing
2729 * block. If possible we put the new line in the left block and move
2730 * the lines after it to the right block. Otherwise the new line is
2731 * also put in the right block. This method is more efficient when
2732 * inserting a lot of lines at one place.
2733 */
2734 if (db_idx < 0) /* left block is new, right block is existing */
2735 {
2736 lines_moved = 0;
2737 in_left = TRUE;
2738 /* space_needed does not change */
2739 }
2740 else /* left block is existing, right block is new */
2741 {
2742 lines_moved = line_count - db_idx - 1;
2743 if (lines_moved == 0)
2744 in_left = FALSE; /* put new line in right block */
2745 /* space_needed does not change */
2746 else
2747 {
2748 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2749 dp->db_txt_start;
2750 total_moved = data_moved + lines_moved * INDEX_SIZE;
2751 if ((int)dp->db_free + total_moved >= space_needed)
2752 {
2753 in_left = TRUE; /* put new line in left block */
2754 space_needed = total_moved;
2755 }
2756 else
2757 {
2758 in_left = FALSE; /* put new line in right block */
2759 space_needed += total_moved;
2760 }
2761 }
2762 }
2763
2764 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2765 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2766 {
2767 /* correct line counts in pointer blocks */
2768 --(buf->b_ml.ml_locked_lineadd);
2769 --(buf->b_ml.ml_locked_high);
2770 return FAIL;
2771 }
2772 if (db_idx < 0) /* left block is new */
2773 {
2774 hp_left = hp_new;
2775 hp_right = hp;
2776 line_count_left = 0;
2777 line_count_right = line_count;
2778 }
2779 else /* right block is new */
2780 {
2781 hp_left = hp;
2782 hp_right = hp_new;
2783 line_count_left = line_count;
2784 line_count_right = 0;
2785 }
2786 dp_right = (DATA_BL *)(hp_right->bh_data);
2787 dp_left = (DATA_BL *)(hp_left->bh_data);
2788 bnum_left = hp_left->bh_bnum;
2789 bnum_right = hp_right->bh_bnum;
2790 page_count_left = hp_left->bh_page_count;
2791 page_count_right = hp_right->bh_page_count;
2792
2793 /*
2794 * May move the new line into the right/new block.
2795 */
2796 if (!in_left)
2797 {
2798 dp_right->db_txt_start -= len;
2799 dp_right->db_free -= len + INDEX_SIZE;
2800 dp_right->db_index[0] = dp_right->db_txt_start;
2801 if (mark)
2802 dp_right->db_index[0] |= DB_MARKED;
2803
2804 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2805 line, (size_t)len);
2806 ++line_count_right;
2807 }
2808 /*
2809 * may move lines from the left/old block to the right/new one.
2810 */
2811 if (lines_moved)
2812 {
2813 /*
2814 */
2815 dp_right->db_txt_start -= data_moved;
2816 dp_right->db_free -= total_moved;
2817 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2818 (char *)dp_left + dp_left->db_txt_start,
2819 (size_t)data_moved);
2820 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2821 dp_left->db_txt_start += data_moved;
2822 dp_left->db_free += total_moved;
2823
2824 /*
2825 * update indexes in the new block
2826 */
2827 for (to = line_count_right, from = db_idx + 1;
2828 from < line_count_left; ++from, ++to)
2829 dp_right->db_index[to] = dp->db_index[from] + offset;
2830 line_count_right += lines_moved;
2831 line_count_left -= lines_moved;
2832 }
2833
2834 /*
2835 * May move the new line into the left (old or new) block.
2836 */
2837 if (in_left)
2838 {
2839 dp_left->db_txt_start -= len;
2840 dp_left->db_free -= len + INDEX_SIZE;
2841 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2842 if (mark)
2843 dp_left->db_index[line_count_left] |= DB_MARKED;
2844 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2845 line, (size_t)len);
2846 ++line_count_left;
2847 }
2848
2849 if (db_idx < 0) /* left block is new */
2850 {
2851 lnum_left = lnum + 1;
2852 lnum_right = 0;
2853 }
2854 else /* right block is new */
2855 {
2856 lnum_left = 0;
2857 if (in_left)
2858 lnum_right = lnum + 2;
2859 else
2860 lnum_right = lnum + 1;
2861 }
2862 dp_left->db_line_count = line_count_left;
2863 dp_right->db_line_count = line_count_right;
2864
2865 /*
2866 * release the two data blocks
2867 * The new one (hp_new) already has a correct blocknumber.
2868 * The old one (hp, in ml_locked) gets a positive blocknumber if
2869 * we changed it and we are not editing a new file.
2870 */
2871 if (lines_moved || in_left)
2872 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2873 if (!newfile && db_idx >= 0 && in_left)
2874 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2875 mf_put(mfp, hp_new, TRUE, FALSE);
2876
2877 /*
2878 * flush the old data block
2879 * set ml_locked_lineadd to 0, because the updating of the
2880 * pointer blocks is done below
2881 */
2882 lineadd = buf->b_ml.ml_locked_lineadd;
2883 buf->b_ml.ml_locked_lineadd = 0;
2884 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2885
2886 /*
2887 * update pointer blocks for the new data block
2888 */
2889 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2890 --stack_idx)
2891 {
2892 ip = &(buf->b_ml.ml_stack[stack_idx]);
2893 pb_idx = ip->ip_index;
2894 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2895 return FAIL;
2896 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2897 if (pp->pb_id != PTR_ID)
2898 {
2899 EMSG(_("E317: pointer block id wrong 3"));
2900 mf_put(mfp, hp, FALSE, FALSE);
2901 return FAIL;
2902 }
2903 /*
2904 * TODO: If the pointer block is full and we are adding at the end
2905 * try to insert in front of the next block
2906 */
2907 /* block not full, add one entry */
2908 if (pp->pb_count < pp->pb_count_max)
2909 {
2910 if (pb_idx + 1 < (int)pp->pb_count)
2911 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2912 &pp->pb_pointer[pb_idx + 1],
2913 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2914 ++pp->pb_count;
2915 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2916 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2917 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2918 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2919 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2920 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2921
2922 if (lnum_left != 0)
2923 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2924 if (lnum_right != 0)
2925 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2926
2927 mf_put(mfp, hp, TRUE, FALSE);
2928 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2929
2930 if (lineadd)
2931 {
2932 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002933 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 ml_lineadd(buf, lineadd);
2935 /* fix stack itself */
2936 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2937 lineadd;
2938 ++(buf->b_ml.ml_stack_top);
2939 }
2940
2941 /*
2942 * We are finished, break the loop here.
2943 */
2944 break;
2945 }
2946 else /* pointer block full */
2947 {
2948 /*
2949 * split the pointer block
2950 * allocate a new pointer block
2951 * move some of the pointer into the new block
2952 * prepare for updating the parent block
2953 */
2954 for (;;) /* do this twice when splitting block 1 */
2955 {
2956 hp_new = ml_new_ptr(mfp);
2957 if (hp_new == NULL) /* TODO: try to fix tree */
2958 return FAIL;
2959 pp_new = (PTR_BL *)(hp_new->bh_data);
2960
2961 if (hp->bh_bnum != 1)
2962 break;
2963
2964 /*
2965 * if block 1 becomes full the tree is given an extra level
2966 * The pointers from block 1 are moved into the new block.
2967 * block 1 is updated to point to the new block
2968 * then continue to split the new block
2969 */
2970 mch_memmove(pp_new, pp, (size_t)page_size);
2971 pp->pb_count = 1;
2972 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2973 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2974 pp->pb_pointer[0].pe_old_lnum = 1;
2975 pp->pb_pointer[0].pe_page_count = 1;
2976 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2977 hp = hp_new; /* new block is to be split */
2978 pp = pp_new;
2979 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2980 ip->ip_index = 0;
2981 ++stack_idx; /* do block 1 again later */
2982 }
2983 /*
2984 * move the pointers after the current one to the new block
2985 * If there are none, the new entry will be in the new block.
2986 */
2987 total_moved = pp->pb_count - pb_idx - 1;
2988 if (total_moved)
2989 {
2990 mch_memmove(&pp_new->pb_pointer[0],
2991 &pp->pb_pointer[pb_idx + 1],
2992 (size_t)(total_moved) * sizeof(PTR_EN));
2993 pp_new->pb_count = total_moved;
2994 pp->pb_count -= total_moved - 1;
2995 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2996 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2997 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2998 if (lnum_right)
2999 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
3000 }
3001 else
3002 {
3003 pp_new->pb_count = 1;
3004 pp_new->pb_pointer[0].pe_bnum = bnum_right;
3005 pp_new->pb_pointer[0].pe_line_count = line_count_right;
3006 pp_new->pb_pointer[0].pe_page_count = page_count_right;
3007 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
3008 }
3009 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3010 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3011 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3012 if (lnum_left)
3013 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3014 lnum_left = 0;
3015 lnum_right = 0;
3016
3017 /*
3018 * recompute line counts
3019 */
3020 line_count_right = 0;
3021 for (i = 0; i < (int)pp_new->pb_count; ++i)
3022 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3023 line_count_left = 0;
3024 for (i = 0; i < (int)pp->pb_count; ++i)
3025 line_count_left += pp->pb_pointer[i].pe_line_count;
3026
3027 bnum_left = hp->bh_bnum;
3028 bnum_right = hp_new->bh_bnum;
3029 page_count_left = 1;
3030 page_count_right = 1;
3031 mf_put(mfp, hp, TRUE, FALSE);
3032 mf_put(mfp, hp_new, TRUE, FALSE);
3033 }
3034 }
3035
3036 /*
3037 * Safety check: fallen out of for loop?
3038 */
3039 if (stack_idx < 0)
3040 {
3041 EMSG(_("E318: Updated too many blocks?"));
3042 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3043 }
3044 }
3045
3046#ifdef FEAT_BYTEOFF
3047 /* The line was inserted below 'lnum' */
3048 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3049#endif
3050#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003051 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 {
3053 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003054 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003055 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003056 (char_u *)"\n", 1);
3057 }
3058#endif
3059 return OK;
3060}
3061
3062/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003063 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003065 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 * copied to allocated memory already.
3067 *
3068 * Check: The caller of this function should probably also call
3069 * changed_lines(), unless update_screen(NOT_VALID) is used.
3070 *
3071 * return FAIL for failure, OK otherwise
3072 */
3073 int
3074ml_replace(lnum, line, copy)
3075 linenr_T lnum;
3076 char_u *line;
3077 int copy;
3078{
3079 if (line == NULL) /* just checking... */
3080 return FAIL;
3081
3082 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003083 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084 return FAIL;
3085
3086 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3087 return FAIL;
3088#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003089 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 {
3091 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003092 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003093 }
3094#endif
3095 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3096 ml_flush_line(curbuf); /* flush it */
3097 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3098 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3099 curbuf->b_ml.ml_line_ptr = line;
3100 curbuf->b_ml.ml_line_lnum = lnum;
3101 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3102
3103 return OK;
3104}
3105
3106/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003107 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 *
3109 * Check: The caller of this function should probably also call
3110 * deleted_lines() after this.
3111 *
3112 * return FAIL for failure, OK otherwise
3113 */
3114 int
3115ml_delete(lnum, message)
3116 linenr_T lnum;
3117 int message;
3118{
3119 ml_flush_line(curbuf);
3120 return ml_delete_int(curbuf, lnum, message);
3121}
3122
3123 static int
3124ml_delete_int(buf, lnum, message)
3125 buf_T *buf;
3126 linenr_T lnum;
3127 int message;
3128{
3129 bhdr_T *hp;
3130 memfile_T *mfp;
3131 DATA_BL *dp;
3132 PTR_BL *pp;
3133 infoptr_T *ip;
3134 int count; /* number of entries in block */
3135 int idx;
3136 int stack_idx;
3137 int text_start;
3138 int line_start;
3139 long line_size;
3140 int i;
3141
3142 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3143 return FAIL;
3144
3145 if (lowest_marked && lowest_marked > lnum)
3146 lowest_marked--;
3147
3148/*
3149 * If the file becomes empty the last line is replaced by an empty line.
3150 */
3151 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3152 {
3153 if (message
3154#ifdef FEAT_NETBEANS_INTG
3155 && !netbeansSuppressNoLines
3156#endif
3157 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003158 set_keep_msg((char_u *)_(no_lines_msg), 0);
3159
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
3161 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3162 buf->b_ml.ml_flags |= ML_EMPTY;
3163
3164 return i;
3165 }
3166
3167/*
3168 * find the data block containing the line
3169 * This also fills the stack with the blocks from the root to the data block
3170 * This also releases any locked block.
3171 */
3172 mfp = buf->b_ml.ml_mfp;
3173 if (mfp == NULL)
3174 return FAIL;
3175
3176 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3177 return FAIL;
3178
3179 dp = (DATA_BL *)(hp->bh_data);
3180 /* compute line count before the delete */
3181 count = (long)(buf->b_ml.ml_locked_high)
3182 - (long)(buf->b_ml.ml_locked_low) + 2;
3183 idx = lnum - buf->b_ml.ml_locked_low;
3184
3185 --buf->b_ml.ml_line_count;
3186
3187 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3188 if (idx == 0) /* first line in block, text at the end */
3189 line_size = dp->db_txt_end - line_start;
3190 else
3191 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3192
3193#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003194 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003195 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196#endif
3197
3198/*
3199 * special case: If there is only one line in the data block it becomes empty.
3200 * Then we have to remove the entry, pointing to this data block, from the
3201 * pointer block. If this pointer block also becomes empty, we go up another
3202 * block, and so on, up to the root if necessary.
3203 * The line counts in the pointer blocks have already been adjusted by
3204 * ml_find_line().
3205 */
3206 if (count == 1)
3207 {
3208 mf_free(mfp, hp); /* free the data block */
3209 buf->b_ml.ml_locked = NULL;
3210
3211 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx)
3212 {
3213 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3214 ip = &(buf->b_ml.ml_stack[stack_idx]);
3215 idx = ip->ip_index;
3216 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3217 return FAIL;
3218 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3219 if (pp->pb_id != PTR_ID)
3220 {
3221 EMSG(_("E317: pointer block id wrong 4"));
3222 mf_put(mfp, hp, FALSE, FALSE);
3223 return FAIL;
3224 }
3225 count = --(pp->pb_count);
3226 if (count == 0) /* the pointer block becomes empty! */
3227 mf_free(mfp, hp);
3228 else
3229 {
3230 if (count != idx) /* move entries after the deleted one */
3231 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3232 (size_t)(count - idx) * sizeof(PTR_EN));
3233 mf_put(mfp, hp, TRUE, FALSE);
3234
3235 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003236 /* fix line count for rest of blocks in the stack */
3237 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238 {
3239 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3240 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003241 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 }
3243 ++(buf->b_ml.ml_stack_top);
3244
3245 break;
3246 }
3247 }
3248 CHECK(stack_idx < 0, _("deleted block 1?"));
3249 }
3250 else
3251 {
3252 /*
3253 * delete the text by moving the next lines forwards
3254 */
3255 text_start = dp->db_txt_start;
3256 mch_memmove((char *)dp + text_start + line_size,
3257 (char *)dp + text_start, (size_t)(line_start - text_start));
3258
3259 /*
3260 * delete the index by moving the next indexes backwards
3261 * Adjust the indexes for the text movement.
3262 */
3263 for (i = idx; i < count - 1; ++i)
3264 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3265
3266 dp->db_free += line_size + INDEX_SIZE;
3267 dp->db_txt_start += line_size;
3268 --(dp->db_line_count);
3269
3270 /*
3271 * mark the block dirty and make sure it is in the file (for recovery)
3272 */
3273 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3274 }
3275
3276#ifdef FEAT_BYTEOFF
3277 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3278#endif
3279 return OK;
3280}
3281
3282/*
3283 * set the B_MARKED flag for line 'lnum'
3284 */
3285 void
3286ml_setmarked(lnum)
3287 linenr_T lnum;
3288{
3289 bhdr_T *hp;
3290 DATA_BL *dp;
3291 /* invalid line number */
3292 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3293 || curbuf->b_ml.ml_mfp == NULL)
3294 return; /* give error message? */
3295
3296 if (lowest_marked == 0 || lowest_marked > lnum)
3297 lowest_marked = lnum;
3298
3299 /*
3300 * find the data block containing the line
3301 * This also fills the stack with the blocks from the root to the data block
3302 * This also releases any locked block.
3303 */
3304 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3305 return; /* give error message? */
3306
3307 dp = (DATA_BL *)(hp->bh_data);
3308 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3309 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3310}
3311
3312/*
3313 * find the first line with its B_MARKED flag set
3314 */
3315 linenr_T
3316ml_firstmarked()
3317{
3318 bhdr_T *hp;
3319 DATA_BL *dp;
3320 linenr_T lnum;
3321 int i;
3322
3323 if (curbuf->b_ml.ml_mfp == NULL)
3324 return (linenr_T) 0;
3325
3326 /*
3327 * The search starts with lowest_marked line. This is the last line where
3328 * a mark was found, adjusted by inserting/deleting lines.
3329 */
3330 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3331 {
3332 /*
3333 * Find the data block containing the line.
3334 * This also fills the stack with the blocks from the root to the data
3335 * block This also releases any locked block.
3336 */
3337 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3338 return (linenr_T)0; /* give error message? */
3339
3340 dp = (DATA_BL *)(hp->bh_data);
3341
3342 for (i = lnum - curbuf->b_ml.ml_locked_low;
3343 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3344 if ((dp->db_index[i]) & DB_MARKED)
3345 {
3346 (dp->db_index[i]) &= DB_INDEX_MASK;
3347 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3348 lowest_marked = lnum + 1;
3349 return lnum;
3350 }
3351 }
3352
3353 return (linenr_T) 0;
3354}
3355
3356#if 0 /* not used */
3357/*
3358 * return TRUE if line 'lnum' has a mark
3359 */
3360 int
3361ml_has_mark(lnum)
3362 linenr_T lnum;
3363{
3364 bhdr_T *hp;
3365 DATA_BL *dp;
3366
3367 if (curbuf->b_ml.ml_mfp == NULL
3368 || (hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3369 return FALSE;
3370
3371 dp = (DATA_BL *)(hp->bh_data);
3372 return (int)((dp->db_index[lnum - curbuf->b_ml.ml_locked_low]) & DB_MARKED);
3373}
3374#endif
3375
3376/*
3377 * clear all DB_MARKED flags
3378 */
3379 void
3380ml_clearmarked()
3381{
3382 bhdr_T *hp;
3383 DATA_BL *dp;
3384 linenr_T lnum;
3385 int i;
3386
3387 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3388 return;
3389
3390 /*
3391 * The search starts with line lowest_marked.
3392 */
3393 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3394 {
3395 /*
3396 * Find the data block containing the line.
3397 * This also fills the stack with the blocks from the root to the data
3398 * block and releases any locked block.
3399 */
3400 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3401 return; /* give error message? */
3402
3403 dp = (DATA_BL *)(hp->bh_data);
3404
3405 for (i = lnum - curbuf->b_ml.ml_locked_low;
3406 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3407 if ((dp->db_index[i]) & DB_MARKED)
3408 {
3409 (dp->db_index[i]) &= DB_INDEX_MASK;
3410 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3411 }
3412 }
3413
3414 lowest_marked = 0;
3415 return;
3416}
3417
3418/*
3419 * flush ml_line if necessary
3420 */
3421 static void
3422ml_flush_line(buf)
3423 buf_T *buf;
3424{
3425 bhdr_T *hp;
3426 DATA_BL *dp;
3427 linenr_T lnum;
3428 char_u *new_line;
3429 char_u *old_line;
3430 colnr_T new_len;
3431 int old_len;
3432 int extra;
3433 int idx;
3434 int start;
3435 int count;
3436 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003437 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438
3439 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3440 return; /* nothing to do */
3441
3442 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3443 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003444 /* This code doesn't work recursively, but Netbeans may call back here
3445 * when obtaining the cursor position. */
3446 if (entered)
3447 return;
3448 entered = TRUE;
3449
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450 lnum = buf->b_ml.ml_line_lnum;
3451 new_line = buf->b_ml.ml_line_ptr;
3452
3453 hp = ml_find_line(buf, lnum, ML_FIND);
3454 if (hp == NULL)
3455 EMSGN(_("E320: Cannot find line %ld"), lnum);
3456 else
3457 {
3458 dp = (DATA_BL *)(hp->bh_data);
3459 idx = lnum - buf->b_ml.ml_locked_low;
3460 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3461 old_line = (char_u *)dp + start;
3462 if (idx == 0) /* line is last in block */
3463 old_len = dp->db_txt_end - start;
3464 else /* text of previous line follows */
3465 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3466 new_len = (colnr_T)STRLEN(new_line) + 1;
3467 extra = new_len - old_len; /* negative if lines gets smaller */
3468
3469 /*
3470 * if new line fits in data block, replace directly
3471 */
3472 if ((int)dp->db_free >= extra)
3473 {
3474 /* if the length changes and there are following lines */
3475 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3476 if (extra != 0 && idx < count - 1)
3477 {
3478 /* move text of following lines */
3479 mch_memmove((char *)dp + dp->db_txt_start - extra,
3480 (char *)dp + dp->db_txt_start,
3481 (size_t)(start - dp->db_txt_start));
3482
3483 /* adjust pointers of this and following lines */
3484 for (i = idx + 1; i < count; ++i)
3485 dp->db_index[i] -= extra;
3486 }
3487 dp->db_index[idx] -= extra;
3488
3489 /* adjust free space */
3490 dp->db_free -= extra;
3491 dp->db_txt_start -= extra;
3492
3493 /* copy new line into the data block */
3494 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3495 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3496#ifdef FEAT_BYTEOFF
3497 /* The else case is already covered by the insert and delete */
3498 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3499#endif
3500 }
3501 else
3502 {
3503 /*
3504 * Cannot do it in one data block: Delete and append.
3505 * Append first, because ml_delete_int() cannot delete the
3506 * last line in a buffer, which causes trouble for a buffer
3507 * that has only one line.
3508 * Don't forget to copy the mark!
3509 */
3510 /* How about handling errors??? */
3511 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3512 (dp->db_index[idx] & DB_MARKED));
3513 (void)ml_delete_int(buf, lnum, FALSE);
3514 }
3515 }
3516 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003517
3518 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 }
3520
3521 buf->b_ml.ml_line_lnum = 0;
3522}
3523
3524/*
3525 * create a new, empty, data block
3526 */
3527 static bhdr_T *
3528ml_new_data(mfp, negative, page_count)
3529 memfile_T *mfp;
3530 int negative;
3531 int page_count;
3532{
3533 bhdr_T *hp;
3534 DATA_BL *dp;
3535
3536 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3537 return NULL;
3538
3539 dp = (DATA_BL *)(hp->bh_data);
3540 dp->db_id = DATA_ID;
3541 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3542 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3543 dp->db_line_count = 0;
3544
3545 return hp;
3546}
3547
3548/*
3549 * create a new, empty, pointer block
3550 */
3551 static bhdr_T *
3552ml_new_ptr(mfp)
3553 memfile_T *mfp;
3554{
3555 bhdr_T *hp;
3556 PTR_BL *pp;
3557
3558 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3559 return NULL;
3560
3561 pp = (PTR_BL *)(hp->bh_data);
3562 pp->pb_id = PTR_ID;
3563 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003564 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3565 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566
3567 return hp;
3568}
3569
3570/*
3571 * lookup line 'lnum' in a memline
3572 *
3573 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3574 * if ML_FLUSH only flush a locked block
3575 * if ML_FIND just find the line
3576 *
3577 * If the block was found it is locked and put in ml_locked.
3578 * The stack is updated to lead to the locked block. The ip_high field in
3579 * the stack is updated to reflect the last line in the block AFTER the
3580 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003581 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 *
3583 * return: NULL for failure, pointer to block header otherwise
3584 */
3585 static bhdr_T *
3586ml_find_line(buf, lnum, action)
3587 buf_T *buf;
3588 linenr_T lnum;
3589 int action;
3590{
3591 DATA_BL *dp;
3592 PTR_BL *pp;
3593 infoptr_T *ip;
3594 bhdr_T *hp;
3595 memfile_T *mfp;
3596 linenr_T t;
3597 blocknr_T bnum, bnum2;
3598 int dirty;
3599 linenr_T low, high;
3600 int top;
3601 int page_count;
3602 int idx;
3603
3604 mfp = buf->b_ml.ml_mfp;
3605
3606 /*
3607 * If there is a locked block check if the wanted line is in it.
3608 * If not, flush and release the locked block.
3609 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3610 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003611 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612 */
3613 if (buf->b_ml.ml_locked)
3614 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003615 if (ML_SIMPLE(action)
3616 && buf->b_ml.ml_locked_low <= lnum
3617 && buf->b_ml.ml_locked_high >= lnum
3618 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003620 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 if (action == ML_INSERT)
3622 {
3623 ++(buf->b_ml.ml_locked_lineadd);
3624 ++(buf->b_ml.ml_locked_high);
3625 }
3626 else if (action == ML_DELETE)
3627 {
3628 --(buf->b_ml.ml_locked_lineadd);
3629 --(buf->b_ml.ml_locked_high);
3630 }
3631 return (buf->b_ml.ml_locked);
3632 }
3633
3634 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3635 buf->b_ml.ml_flags & ML_LOCKED_POS);
3636 buf->b_ml.ml_locked = NULL;
3637
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003638 /*
3639 * If lines have been added or deleted in the locked block, need to
3640 * update the line count in pointer blocks.
3641 */
3642 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003643 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3644 }
3645
3646 if (action == ML_FLUSH) /* nothing else to do */
3647 return NULL;
3648
3649 bnum = 1; /* start at the root of the tree */
3650 page_count = 1;
3651 low = 1;
3652 high = buf->b_ml.ml_line_count;
3653
3654 if (action == ML_FIND) /* first try stack entries */
3655 {
3656 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3657 {
3658 ip = &(buf->b_ml.ml_stack[top]);
3659 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3660 {
3661 bnum = ip->ip_bnum;
3662 low = ip->ip_low;
3663 high = ip->ip_high;
3664 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3665 break;
3666 }
3667 }
3668 if (top < 0)
3669 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3670 }
3671 else /* ML_DELETE or ML_INSERT */
3672 buf->b_ml.ml_stack_top = 0; /* start at the root */
3673
3674/*
3675 * search downwards in the tree until a data block is found
3676 */
3677 for (;;)
3678 {
3679 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3680 goto error_noblock;
3681
3682 /*
3683 * update high for insert/delete
3684 */
3685 if (action == ML_INSERT)
3686 ++high;
3687 else if (action == ML_DELETE)
3688 --high;
3689
3690 dp = (DATA_BL *)(hp->bh_data);
3691 if (dp->db_id == DATA_ID) /* data block */
3692 {
3693 buf->b_ml.ml_locked = hp;
3694 buf->b_ml.ml_locked_low = low;
3695 buf->b_ml.ml_locked_high = high;
3696 buf->b_ml.ml_locked_lineadd = 0;
3697 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3698 return hp;
3699 }
3700
3701 pp = (PTR_BL *)(dp); /* must be pointer block */
3702 if (pp->pb_id != PTR_ID)
3703 {
3704 EMSG(_("E317: pointer block id wrong"));
3705 goto error_block;
3706 }
3707
3708 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3709 goto error_block;
3710 ip = &(buf->b_ml.ml_stack[top]);
3711 ip->ip_bnum = bnum;
3712 ip->ip_low = low;
3713 ip->ip_high = high;
3714 ip->ip_index = -1; /* index not known yet */
3715
3716 dirty = FALSE;
3717 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3718 {
3719 t = pp->pb_pointer[idx].pe_line_count;
3720 CHECK(t == 0, _("pe_line_count is zero"));
3721 if ((low += t) > lnum)
3722 {
3723 ip->ip_index = idx;
3724 bnum = pp->pb_pointer[idx].pe_bnum;
3725 page_count = pp->pb_pointer[idx].pe_page_count;
3726 high = low - 1;
3727 low -= t;
3728
3729 /*
3730 * a negative block number may have been changed
3731 */
3732 if (bnum < 0)
3733 {
3734 bnum2 = mf_trans_del(mfp, bnum);
3735 if (bnum != bnum2)
3736 {
3737 bnum = bnum2;
3738 pp->pb_pointer[idx].pe_bnum = bnum;
3739 dirty = TRUE;
3740 }
3741 }
3742
3743 break;
3744 }
3745 }
3746 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3747 {
3748 if (lnum > buf->b_ml.ml_line_count)
3749 EMSGN(_("E322: line number out of range: %ld past the end"),
3750 lnum - buf->b_ml.ml_line_count);
3751
3752 else
3753 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3754 goto error_block;
3755 }
3756 if (action == ML_DELETE)
3757 {
3758 pp->pb_pointer[idx].pe_line_count--;
3759 dirty = TRUE;
3760 }
3761 else if (action == ML_INSERT)
3762 {
3763 pp->pb_pointer[idx].pe_line_count++;
3764 dirty = TRUE;
3765 }
3766 mf_put(mfp, hp, dirty, FALSE);
3767 }
3768
3769error_block:
3770 mf_put(mfp, hp, FALSE, FALSE);
3771error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003772 /*
3773 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3774 * the incremented/decremented line counts, because there won't be a line
3775 * inserted/deleted after all.
3776 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777 if (action == ML_DELETE)
3778 ml_lineadd(buf, 1);
3779 else if (action == ML_INSERT)
3780 ml_lineadd(buf, -1);
3781 buf->b_ml.ml_stack_top = 0;
3782 return NULL;
3783}
3784
3785/*
3786 * add an entry to the info pointer stack
3787 *
3788 * return -1 for failure, number of the new entry otherwise
3789 */
3790 static int
3791ml_add_stack(buf)
3792 buf_T *buf;
3793{
3794 int top;
3795 infoptr_T *newstack;
3796
3797 top = buf->b_ml.ml_stack_top;
3798
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003799 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 if (top == buf->b_ml.ml_stack_size)
3801 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003802 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803
3804 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3805 (buf->b_ml.ml_stack_size + STACK_INCR));
3806 if (newstack == NULL)
3807 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003808 mch_memmove(newstack, buf->b_ml.ml_stack,
3809 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 vim_free(buf->b_ml.ml_stack);
3811 buf->b_ml.ml_stack = newstack;
3812 buf->b_ml.ml_stack_size += STACK_INCR;
3813 }
3814
3815 buf->b_ml.ml_stack_top++;
3816 return top;
3817}
3818
3819/*
3820 * Update the pointer blocks on the stack for inserted/deleted lines.
3821 * The stack itself is also updated.
3822 *
3823 * When a insert/delete line action fails, the line is not inserted/deleted,
3824 * but the pointer blocks have already been updated. That is fixed here by
3825 * walking through the stack.
3826 *
3827 * Count is the number of lines added, negative if lines have been deleted.
3828 */
3829 static void
3830ml_lineadd(buf, count)
3831 buf_T *buf;
3832 int count;
3833{
3834 int idx;
3835 infoptr_T *ip;
3836 PTR_BL *pp;
3837 memfile_T *mfp = buf->b_ml.ml_mfp;
3838 bhdr_T *hp;
3839
3840 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3841 {
3842 ip = &(buf->b_ml.ml_stack[idx]);
3843 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3844 break;
3845 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3846 if (pp->pb_id != PTR_ID)
3847 {
3848 mf_put(mfp, hp, FALSE, FALSE);
3849 EMSG(_("E317: pointer block id wrong 2"));
3850 break;
3851 }
3852 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3853 ip->ip_high += count;
3854 mf_put(mfp, hp, TRUE, FALSE);
3855 }
3856}
3857
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003858#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003859/*
3860 * Resolve a symlink in the last component of a file name.
3861 * Note that f_resolve() does it for every part of the path, we don't do that
3862 * here.
3863 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3864 * Otherwise returns FAIL.
3865 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003866 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003867resolve_symlink(fname, buf)
3868 char_u *fname;
3869 char_u *buf;
3870{
3871 char_u tmp[MAXPATHL];
3872 int ret;
3873 int depth = 0;
3874
3875 if (fname == NULL)
3876 return FAIL;
3877
3878 /* Put the result so far in tmp[], starting with the original name. */
3879 vim_strncpy(tmp, fname, MAXPATHL - 1);
3880
3881 for (;;)
3882 {
3883 /* Limit symlink depth to 100, catch recursive loops. */
3884 if (++depth == 100)
3885 {
3886 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3887 return FAIL;
3888 }
3889
3890 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3891 if (ret <= 0)
3892 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003893 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003894 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003895 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003896 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003897 * call to vim_FullName(). */
3898 if (depth == 1)
3899 return FAIL;
3900
3901 /* Use the resolved name in tmp[]. */
3902 break;
3903 }
3904
3905 /* There must be some error reading links, use original name. */
3906 return FAIL;
3907 }
3908 buf[ret] = NUL;
3909
3910 /*
3911 * Check whether the symlink is relative or absolute.
3912 * If it's relative, build a new path based on the directory
3913 * portion of the filename (if any) and the path the symlink
3914 * points to.
3915 */
3916 if (mch_isFullName(buf))
3917 STRCPY(tmp, buf);
3918 else
3919 {
3920 char_u *tail;
3921
3922 tail = gettail(tmp);
3923 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3924 return FAIL;
3925 STRCPY(tail, buf);
3926 }
3927 }
3928
3929 /*
3930 * Try to resolve the full name of the file so that the swapfile name will
3931 * be consistent even when opening a relative symlink from different
3932 * working directories.
3933 */
3934 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3935}
3936#endif
3937
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003939 * Make swap file name out of the file name and a directory name.
3940 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003941 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003942 char_u *
3943makeswapname(fname, ffname, buf, dir_name)
3944 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003945 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 buf_T *buf;
3947 char_u *dir_name;
3948{
3949 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003950 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003951#ifdef HAVE_READLINK
3952 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003953#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954
3955#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3956 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003957 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 { /* Ends with '//', Use Full path */
3959 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003960 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 {
3962 r = modname(s, (char_u *)".swp", FALSE);
3963 vim_free(s);
3964 }
3965 return r;
3966 }
3967#endif
3968
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003969#ifdef HAVE_READLINK
3970 /* Expand symlink in the file name, so that we put the swap file with the
3971 * actual file instead of with the symlink. */
3972 if (resolve_symlink(fname, fname_buf) == OK)
3973 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003974#endif
3975
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976 r = buf_modname(
3977#ifdef SHORT_FNAME
3978 TRUE,
3979#else
3980 (buf->b_p_sn || buf->b_shortname),
3981#endif
Bram Moolenaar38323e42007-03-06 19:22:53 +00003982#ifdef RISCOS
3983 /* Avoid problems if fname has special chars, eg <Wimp$Scrap> */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003984 ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985#else
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003986 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987#endif
3988 (char_u *)
3989#if defined(VMS) || defined(RISCOS)
3990 "_swp",
3991#else
3992 ".swp",
3993#endif
3994#ifdef SHORT_FNAME /* always 8.3 file name */
3995 FALSE
3996#else
3997 /* Prepend a '.' to the swap file name for the current directory. */
3998 dir_name[0] == '.' && dir_name[1] == NUL
3999#endif
4000 );
4001 if (r == NULL) /* out of memory */
4002 return NULL;
4003
4004 s = get_file_in_dir(r, dir_name);
4005 vim_free(r);
4006 return s;
4007}
4008
4009/*
4010 * Get file name to use for swap file or backup file.
4011 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
4012 * option "dname".
4013 * - If "dname" is ".", return "fname" (swap file in dir of file).
4014 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
4015 * relative to dir of file).
4016 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
4017 * dir).
4018 *
4019 * The return value is an allocated string and can be NULL.
4020 */
4021 char_u *
4022get_file_in_dir(fname, dname)
4023 char_u *fname;
4024 char_u *dname; /* don't use "dirname", it is a global for Alpha */
4025{
4026 char_u *t;
4027 char_u *tail;
4028 char_u *retval;
4029 int save_char;
4030
4031 tail = gettail(fname);
4032
4033 if (dname[0] == '.' && dname[1] == NUL)
4034 retval = vim_strsave(fname);
4035 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
4036 {
4037 if (tail == fname) /* no path before file name */
4038 retval = concat_fnames(dname + 2, tail, TRUE);
4039 else
4040 {
4041 save_char = *tail;
4042 *tail = NUL;
4043 t = concat_fnames(fname, dname + 2, TRUE);
4044 *tail = save_char;
4045 if (t == NULL) /* out of memory */
4046 retval = NULL;
4047 else
4048 {
4049 retval = concat_fnames(t, tail, TRUE);
4050 vim_free(t);
4051 }
4052 }
4053 }
4054 else
4055 retval = concat_fnames(dname, tail, TRUE);
4056
4057 return retval;
4058}
4059
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004060static void attention_message __ARGS((buf_T *buf, char_u *fname));
4061
4062/*
4063 * Print the ATTENTION message: info about an existing swap file.
4064 */
4065 static void
4066attention_message(buf, fname)
4067 buf_T *buf; /* buffer being edited */
4068 char_u *fname; /* swap file name */
4069{
4070 struct stat st;
4071 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004072 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004073
4074 ++no_wait_return;
4075 (void)EMSG(_("E325: ATTENTION"));
4076 MSG_PUTS(_("\nFound a swap file by the name \""));
4077 msg_home_replace(fname);
4078 MSG_PUTS("\"\n");
4079 sx = swapfile_info(fname);
4080 MSG_PUTS(_("While opening file \""));
4081 msg_outtrans(buf->b_fname);
4082 MSG_PUTS("\"\n");
4083 if (mch_stat((char *)buf->b_fname, &st) != -1)
4084 {
4085 MSG_PUTS(_(" dated: "));
4086 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004087 p = ctime(&x); /* includes '\n' */
4088 if (p == NULL)
4089 MSG_PUTS("(invalid)\n");
4090 else
4091 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004092 if (sx != 0 && x > sx)
4093 MSG_PUTS(_(" NEWER than swap file!\n"));
4094 }
4095 /* Some of these messages are long to allow translation to
4096 * other languages. */
4097 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"));
4098 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4099 MSG_PUTS(_("\n(2) An edit session for this file crashed.\n"));
4100 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4101 msg_outtrans(buf->b_fname);
4102 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4103 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4104 msg_outtrans(fname);
4105 MSG_PUTS(_("\"\n to avoid this message.\n"));
4106 cmdline_row = msg_row;
4107 --no_wait_return;
4108}
4109
4110#ifdef FEAT_AUTOCMD
4111static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4112
4113/*
4114 * Trigger the SwapExists autocommands.
4115 * Returns a value for equivalent to do_dialog() (see below):
4116 * 0: still need to ask for a choice
4117 * 1: open read-only
4118 * 2: edit anyway
4119 * 3: recover
4120 * 4: delete it
4121 * 5: quit
4122 * 6: abort
4123 */
4124 static int
4125do_swapexists(buf, fname)
4126 buf_T *buf;
4127 char_u *fname;
4128{
4129 set_vim_var_string(VV_SWAPNAME, fname, -1);
4130 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4131
4132 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004133 * edited. Disallow changing directory here. */
4134 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004135 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004136 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004137
4138 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4139
4140 switch (*get_vim_var_str(VV_SWAPCHOICE))
4141 {
4142 case 'o': return 1;
4143 case 'e': return 2;
4144 case 'r': return 3;
4145 case 'd': return 4;
4146 case 'q': return 5;
4147 case 'a': return 6;
4148 }
4149
4150 return 0;
4151}
4152#endif
4153
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154/*
4155 * Find out what name to use for the swap file for buffer 'buf'.
4156 *
4157 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004158 * Returns the name in allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 *
4160 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004161 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004162 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 */
4164 static char_u *
4165findswapname(buf, dirp, old_fname)
4166 buf_T *buf;
4167 char_u **dirp; /* pointer to list of directories */
4168 char_u *old_fname; /* don't give warning for this file name */
4169{
4170 char_u *fname;
4171 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 char_u *dir_name;
4173#ifdef AMIGA
4174 BPTR fh;
4175#endif
4176#ifndef SHORT_FNAME
4177 int r;
4178#endif
4179
4180#if !defined(SHORT_FNAME) \
4181 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
4182# define CREATE_DUMMY_FILE
4183 FILE *dummyfd = NULL;
4184
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004185 /*
4186 * If we start editing a new file, e.g. "test.doc", which resides on an
4187 * MSDOS compatible filesystem, it is possible that the file
4188 * "test.doc.swp" which we create will be exactly the same file. To avoid
4189 * this problem we temporarily create "test.doc". Don't do this when the
4190 * check below for a 8.3 file name is used.
4191 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
4193 && mch_getperm(buf->b_fname) < 0)
4194 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4195#endif
4196
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004197 /*
4198 * Isolate a directory name from *dirp and put it in dir_name.
4199 * First allocate some memory to put the directory name in.
4200 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
4202 if (dir_name != NULL)
4203 (void)copy_option_part(dirp, dir_name, 31000, ",");
4204
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004205 /*
4206 * we try different names until we find one that does not exist yet
4207 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 if (dir_name == NULL) /* out of memory */
4209 fname = NULL;
4210 else
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004211 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004212
4213 for (;;)
4214 {
4215 if (fname == NULL) /* must be out of memory */
4216 break;
4217 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4218 {
4219 vim_free(fname);
4220 fname = NULL;
4221 break;
4222 }
4223#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4224/*
4225 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4226 * file names. If this is the first try and the swap file name does not fit in
4227 * 8.3, detect if this is the case, set shortname and try again.
4228 */
4229 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4230 && !(buf->b_p_sn || buf->b_shortname))
4231 {
4232 char_u *tail;
4233 char_u *fname2;
4234 struct stat s1, s2;
4235 int f1, f2;
4236 int created1 = FALSE, created2 = FALSE;
4237 int same = FALSE;
4238
4239 /*
4240 * Check if swapfile name does not fit in 8.3:
4241 * It either contains two dots, is longer than 8 chars, or starts
4242 * with a dot.
4243 */
4244 tail = gettail(buf->b_fname);
4245 if ( vim_strchr(tail, '.') != NULL
4246 || STRLEN(tail) > (size_t)8
4247 || *gettail(fname) == '.')
4248 {
4249 fname2 = alloc(n + 2);
4250 if (fname2 != NULL)
4251 {
4252 STRCPY(fname2, fname);
4253 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4254 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4255 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4256 */
4257 if (vim_strchr(tail, '.') != NULL)
4258 fname2[n - 1] = 'x';
4259 else if (*gettail(fname) == '.')
4260 {
4261 fname2[n] = 'x';
4262 fname2[n + 1] = NUL;
4263 }
4264 else
4265 fname2[n - 5] += 1;
4266 /*
4267 * may need to create the files to be able to use mch_stat()
4268 */
4269 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4270 if (f1 < 0)
4271 {
4272 f1 = mch_open_rw((char *)fname,
4273 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4274#if defined(OS2)
4275 if (f1 < 0 && errno == ENOENT)
4276 same = TRUE;
4277#endif
4278 created1 = TRUE;
4279 }
4280 if (f1 >= 0)
4281 {
4282 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4283 if (f2 < 0)
4284 {
4285 f2 = mch_open_rw((char *)fname2,
4286 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4287 created2 = TRUE;
4288 }
4289 if (f2 >= 0)
4290 {
4291 /*
4292 * Both files exist now. If mch_stat() returns the
4293 * same device and inode they are the same file.
4294 */
4295 if (mch_fstat(f1, &s1) != -1
4296 && mch_fstat(f2, &s2) != -1
4297 && s1.st_dev == s2.st_dev
4298 && s1.st_ino == s2.st_ino)
4299 same = TRUE;
4300 close(f2);
4301 if (created2)
4302 mch_remove(fname2);
4303 }
4304 close(f1);
4305 if (created1)
4306 mch_remove(fname);
4307 }
4308 vim_free(fname2);
4309 if (same)
4310 {
4311 buf->b_shortname = TRUE;
4312 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004313 fname = makeswapname(buf->b_fname, buf->b_ffname,
4314 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315 continue; /* try again with b_shortname set */
4316 }
4317 }
4318 }
4319 }
4320#endif
4321 /*
4322 * check if the swapfile already exists
4323 */
4324 if (mch_getperm(fname) < 0) /* it does not exist */
4325 {
4326#ifdef HAVE_LSTAT
4327 struct stat sb;
4328
4329 /*
4330 * Extra security check: When a swap file is a symbolic link, this
4331 * is most likely a symlink attack.
4332 */
4333 if (mch_lstat((char *)fname, &sb) < 0)
4334#else
4335# ifdef AMIGA
4336 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4337 /*
4338 * on the Amiga mch_getperm() will return -1 when the file exists
4339 * but is being used by another program. This happens if you edit
4340 * a file twice.
4341 */
4342 if (fh != (BPTR)NULL) /* can open file, OK */
4343 {
4344 Close(fh);
4345 mch_remove(fname);
4346 break;
4347 }
4348 if (IoErr() != ERROR_OBJECT_IN_USE
4349 && IoErr() != ERROR_OBJECT_EXISTS)
4350# endif
4351#endif
4352 break;
4353 }
4354
4355 /*
4356 * A file name equal to old_fname is OK to use.
4357 */
4358 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4359 break;
4360
4361 /*
4362 * get here when file already exists
4363 */
4364 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4365 {
4366#ifndef SHORT_FNAME
4367 /*
4368 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4369 * and file.doc are the same file. To guess if this problem is
4370 * present try if file.doc.swx exists. If it does, we set
4371 * buf->b_shortname and try file_doc.swp (dots replaced by
4372 * underscores for this file), and try again. If it doesn't we
4373 * assume that "file.doc.swp" already exists.
4374 */
4375 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4376 {
4377 fname[n - 1] = 'x';
4378 r = mch_getperm(fname); /* try "file.swx" */
4379 fname[n - 1] = 'p';
4380 if (r >= 0) /* "file.swx" seems to exist */
4381 {
4382 buf->b_shortname = TRUE;
4383 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004384 fname = makeswapname(buf->b_fname, buf->b_ffname,
4385 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004386 continue; /* try again with '.' replaced with '_' */
4387 }
4388 }
4389#endif
4390 /*
4391 * If we get here the ".swp" file really exists.
4392 * Give an error message, unless recovering, no file name, we are
4393 * viewing a help file or when the path of the file is different
4394 * (happens when all .swp files are in one directory).
4395 */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004396 if (!recoverymode && buf->b_fname != NULL
4397 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004398 {
4399 int fd;
4400 struct block0 b0;
4401 int differ = FALSE;
4402
4403 /*
4404 * Try to read block 0 from the swap file to get the original
4405 * file name (and inode number).
4406 */
4407 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4408 if (fd >= 0)
4409 {
4410 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
4411 {
4412 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004413 * If the swapfile has the same directory as the
4414 * buffer don't compare the directory names, they can
4415 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004417 if (b0.b0_flags & B0_SAME_DIR)
4418 {
4419 if (fnamecmp(gettail(buf->b_ffname),
4420 gettail(b0.b0_fname)) != 0
4421 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004422 {
4423#ifdef CHECK_INODE
4424 /* Symlinks may point to the same file even
4425 * when the name differs, need to check the
4426 * inode too. */
4427 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4428 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4429 char_to_long(b0.b0_ino)))
4430#endif
4431 differ = TRUE;
4432 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004433 }
4434 else
4435 {
4436 /*
4437 * The name in the swap file may be
4438 * "~user/path/file". Expand it first.
4439 */
4440 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004441#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004442 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004443 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004444 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004446 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4447 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 }
4451 close(fd);
4452 }
4453#ifdef RISCOS
4454 else
4455 /* Can't open swap file, though it does exist.
4456 * Assume that the user is editing two files with
4457 * the same name in different directories. No error.
4458 */
4459 differ = TRUE;
4460#endif
4461
4462 /* give the ATTENTION message when there is an old swap file
4463 * for the current file, and the buffer was not recovered. */
4464 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4465 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4466 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004467#if defined(HAS_SWAP_EXISTS_ACTION)
4468 int choice = 0;
4469#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470#ifdef CREATE_DUMMY_FILE
4471 int did_use_dummy = FALSE;
4472
4473 /* Avoid getting a warning for the file being created
4474 * outside of Vim, it was created at the start of this
4475 * function. Delete the file now, because Vim might exit
4476 * here if the window is closed. */
4477 if (dummyfd != NULL)
4478 {
4479 fclose(dummyfd);
4480 dummyfd = NULL;
4481 mch_remove(buf->b_fname);
4482 did_use_dummy = TRUE;
4483 }
4484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485
4486#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4487 process_still_running = FALSE;
4488#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004489#ifdef FEAT_AUTOCMD
4490 /*
4491 * If there is an SwapExists autocommand and we can handle
4492 * the response, trigger it. It may return 0 to ask the
4493 * user anyway.
4494 */
4495 if (swap_exists_action != SEA_NONE
4496 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4497 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004499 if (choice == 0)
4500#endif
4501 {
4502#ifdef FEAT_GUI
4503 /* If we are supposed to start the GUI but it wasn't
4504 * completely started yet, start it now. This makes
4505 * the messages displayed in the Vim window when
4506 * loading a session from the .gvimrc file. */
4507 if (gui.starting && !gui.in_use)
4508 gui_start();
4509#endif
4510 /* Show info about the existing swap file. */
4511 attention_message(buf, fname);
4512
4513 /* We don't want a 'q' typed at the more-prompt
4514 * interrupt loading a file. */
4515 got_int = FALSE;
4516 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517
4518#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004519 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 {
4521 char_u *name;
4522
4523 name = alloc((unsigned)(STRLEN(fname)
4524 + STRLEN(_("Swap file \""))
4525 + STRLEN(_("\" already exists!")) + 5));
4526 if (name != NULL)
4527 {
4528 STRCPY(name, _("Swap file \""));
4529 home_replace(NULL, fname, name + STRLEN(name),
4530 1000, TRUE);
4531 STRCAT(name, _("\" already exists!"));
4532 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004533 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 (char_u *)_("VIM - ATTENTION"),
4535 name == NULL
4536 ? (char_u *)_("Swap file already exists!")
4537 : name,
4538# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4539 process_still_running
4540 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4541# endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004542 (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL);
4543
4544# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4545 if (process_still_running && choice >= 4)
4546 choice++; /* Skip missing "Delete it" button */
4547# endif
4548 vim_free(name);
4549
4550 /* pretend screen didn't scroll, need redraw anyway */
4551 msg_scrolled = 0;
4552 redraw_all_later(NOT_VALID);
4553 }
4554#endif
4555
4556#if defined(HAS_SWAP_EXISTS_ACTION)
4557 if (choice > 0)
4558 {
4559 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 {
4561 case 1:
4562 buf->b_p_ro = TRUE;
4563 break;
4564 case 2:
4565 break;
4566 case 3:
4567 swap_exists_action = SEA_RECOVER;
4568 break;
4569 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004570 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004571 break;
4572 case 5:
4573 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574 break;
4575 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004576 swap_exists_action = SEA_QUIT;
4577 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004578 break;
4579 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580
4581 /* If the file was deleted this fname can be used. */
4582 if (mch_getperm(fname) < 0)
4583 break;
4584 }
4585 else
4586#endif
4587 {
4588 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004589 if (msg_silent == 0)
4590 /* call wait_return() later */
4591 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 }
4593
4594#ifdef CREATE_DUMMY_FILE
4595 /* Going to try another name, need the dummy file again. */
4596 if (did_use_dummy)
4597 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4598#endif
4599 }
4600 }
4601 }
4602
4603 /*
4604 * Change the ".swp" extension to find another file that can be used.
4605 * First decrement the last char: ".swo", ".swn", etc.
4606 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004607 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608 */
4609 if (fname[n - 1] == 'a') /* ".s?a" */
4610 {
4611 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4612 {
4613 EMSG(_("E326: Too many swap files found"));
4614 vim_free(fname);
4615 fname = NULL;
4616 break;
4617 }
4618 --fname[n - 2]; /* ".svz", ".suz", etc. */
4619 fname[n - 1] = 'z' + 1;
4620 }
4621 --fname[n - 1]; /* ".swo", ".swn", etc. */
4622 }
4623
4624 vim_free(dir_name);
4625#ifdef CREATE_DUMMY_FILE
4626 if (dummyfd != NULL) /* file has been created temporarily */
4627 {
4628 fclose(dummyfd);
4629 mch_remove(buf->b_fname);
4630 }
4631#endif
4632 return fname;
4633}
4634
4635 static int
4636b0_magic_wrong(b0p)
4637 ZERO_BL *b0p;
4638{
4639 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4640 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4641 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4642 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4643}
4644
4645#ifdef CHECK_INODE
4646/*
4647 * Compare current file name with file name from swap file.
4648 * Try to use inode numbers when possible.
4649 * Return non-zero when files are different.
4650 *
4651 * When comparing file names a few things have to be taken into consideration:
4652 * - When working over a network the full path of a file depends on the host.
4653 * We check the inode number if possible. It is not 100% reliable though,
4654 * because the device number cannot be used over a network.
4655 * - When a file does not exist yet (editing a new file) there is no inode
4656 * number.
4657 * - The file name in a swap file may not be valid on the current host. The
4658 * "~user" form is used whenever possible to avoid this.
4659 *
4660 * This is getting complicated, let's make a table:
4661 *
4662 * ino_c ino_s fname_c fname_s differ =
4663 *
4664 * both files exist -> compare inode numbers:
4665 * != 0 != 0 X X ino_c != ino_s
4666 *
4667 * inode number(s) unknown, file names available -> compare file names
4668 * == 0 X OK OK fname_c != fname_s
4669 * X == 0 OK OK fname_c != fname_s
4670 *
4671 * current file doesn't exist, file for swap file exist, file name(s) not
4672 * available -> probably different
4673 * == 0 != 0 FAIL X TRUE
4674 * == 0 != 0 X FAIL TRUE
4675 *
4676 * current file exists, inode for swap unknown, file name(s) not
4677 * available -> probably different
4678 * != 0 == 0 FAIL X TRUE
4679 * != 0 == 0 X FAIL TRUE
4680 *
4681 * current file doesn't exist, inode for swap unknown, one file name not
4682 * available -> probably different
4683 * == 0 == 0 FAIL OK TRUE
4684 * == 0 == 0 OK FAIL TRUE
4685 *
4686 * current file doesn't exist, inode for swap unknown, both file names not
4687 * available -> probably same file
4688 * == 0 == 0 FAIL FAIL FALSE
4689 *
4690 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4691 * can't be changed without making the block 0 incompatible with 32 bit
4692 * versions.
4693 */
4694
4695 static int
4696fnamecmp_ino(fname_c, fname_s, ino_block0)
4697 char_u *fname_c; /* current file name */
4698 char_u *fname_s; /* file name from swap file */
4699 long ino_block0;
4700{
4701 struct stat st;
4702 ino_t ino_c = 0; /* ino of current file */
4703 ino_t ino_s; /* ino of file from swap file */
4704 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4705 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4706 int retval_c; /* flag: buf_c valid */
4707 int retval_s; /* flag: buf_s valid */
4708
4709 if (mch_stat((char *)fname_c, &st) == 0)
4710 ino_c = (ino_t)st.st_ino;
4711
4712 /*
4713 * First we try to get the inode from the file name, because the inode in
4714 * the swap file may be outdated. If that fails (e.g. this path is not
4715 * valid on this machine), use the inode from block 0.
4716 */
4717 if (mch_stat((char *)fname_s, &st) == 0)
4718 ino_s = (ino_t)st.st_ino;
4719 else
4720 ino_s = (ino_t)ino_block0;
4721
4722 if (ino_c && ino_s)
4723 return (ino_c != ino_s);
4724
4725 /*
4726 * One of the inode numbers is unknown, try a forced vim_FullName() and
4727 * compare the file names.
4728 */
4729 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4730 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4731 if (retval_c == OK && retval_s == OK)
4732 return (STRCMP(buf_c, buf_s) != 0);
4733
4734 /*
4735 * Can't compare inodes or file names, guess that the files are different,
4736 * unless both appear not to exist at all.
4737 */
4738 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4739 return FALSE;
4740 return TRUE;
4741}
4742#endif /* CHECK_INODE */
4743
4744/*
4745 * Move a long integer into a four byte character array.
4746 * Used for machine independency in block zero.
4747 */
4748 static void
4749long_to_char(n, s)
4750 long n;
4751 char_u *s;
4752{
4753 s[0] = (char_u)(n & 0xff);
4754 n = (unsigned)n >> 8;
4755 s[1] = (char_u)(n & 0xff);
4756 n = (unsigned)n >> 8;
4757 s[2] = (char_u)(n & 0xff);
4758 n = (unsigned)n >> 8;
4759 s[3] = (char_u)(n & 0xff);
4760}
4761
4762 static long
4763char_to_long(s)
4764 char_u *s;
4765{
4766 long retval;
4767
4768 retval = s[3];
4769 retval <<= 8;
4770 retval |= s[2];
4771 retval <<= 8;
4772 retval |= s[1];
4773 retval <<= 8;
4774 retval |= s[0];
4775
4776 return retval;
4777}
4778
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004779/*
4780 * Set the flags in the first block of the swap file:
4781 * - file is modified or not: buf->b_changed
4782 * - 'fileformat'
4783 * - 'fileencoding'
4784 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004786ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788{
4789 bhdr_T *hp;
4790 ZERO_BL *b0p;
4791
4792 if (!buf->b_ml.ml_mfp)
4793 return;
4794 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4795 {
4796 if (hp->bh_bnum == 0)
4797 {
4798 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004799 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4800 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4801 | (get_fileformat(buf) + 1);
4802#ifdef FEAT_MBYTE
4803 add_b0_fenc(b0p, buf);
4804#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805 hp->bh_flags |= BH_DIRTY;
4806 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4807 break;
4808 }
4809 }
4810}
4811
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004812#if defined(FEAT_CRYPT) || defined(PROTO)
4813/*
4814 * If "data" points to a data block encrypt the text in it and return a copy
4815 * in allocated memory. Return NULL when out of memory.
4816 * Otherwise return "data".
4817 */
4818 char_u *
4819ml_encrypt_data(mfp, data, offset, size)
4820 memfile_T *mfp;
4821 char_u *data;
4822 off_t offset;
4823 unsigned size;
4824{
4825 DATA_BL *dp = (DATA_BL *)data;
4826 char_u *head_end;
4827 char_u *text_start;
4828 char_u *new_data;
4829 int text_len;
4830
4831 if (dp->db_id != DATA_ID)
4832 return data;
4833
4834 new_data = (char_u *)alloc(size);
4835 if (new_data == NULL)
4836 return NULL;
4837 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4838 text_start = (char_u *)dp + dp->db_txt_start;
4839 text_len = size - dp->db_txt_start;
4840
4841 /* Copy the header and the text. */
4842 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4843
4844 /* Encrypt the text. */
4845 crypt_push_state();
4846 ml_crypt_prepare(mfp, offset, FALSE);
4847 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4848 crypt_pop_state();
4849
4850 /* Clear the gap. */
4851 if (head_end < text_start)
4852 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4853
4854 return new_data;
4855}
4856
4857/*
4858 * Decrypt the text in "data" if it points to a data block.
4859 */
4860 void
4861ml_decrypt_data(mfp, data, offset, size)
4862 memfile_T *mfp;
4863 char_u *data;
4864 off_t offset;
4865 unsigned size;
4866{
4867 DATA_BL *dp = (DATA_BL *)data;
4868 char_u *head_end;
4869 char_u *text_start;
4870 int text_len;
4871
4872 if (dp->db_id == DATA_ID)
4873 {
4874 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4875 text_start = (char_u *)dp + dp->db_txt_start;
4876 text_len = dp->db_txt_end - dp->db_txt_start;
4877
4878 if (head_end > text_start || dp->db_txt_start > size
4879 || dp->db_txt_end > size)
4880 return; /* data was messed up */
4881
4882 /* Decrypt the text in place. */
4883 crypt_push_state();
4884 ml_crypt_prepare(mfp, offset, TRUE);
4885 crypt_decode(text_start, text_len);
4886 crypt_pop_state();
4887 }
4888}
4889
4890/*
4891 * Prepare for encryption/decryption, using the key, seed and offset.
4892 */
4893 static void
4894ml_crypt_prepare(mfp, offset, reading)
4895 memfile_T *mfp;
4896 off_t offset;
4897 int reading;
4898{
4899 buf_T *buf = mfp->mf_buffer;
4900 char_u salt[50];
4901 int method;
4902 char_u *key;
4903 char_u *seed;
4904
4905 if (reading && mfp->mf_old_key != NULL)
4906 {
4907 /* Reading back blocks with the previous key/method/seed. */
4908 method = mfp->mf_old_cm;
4909 key = mfp->mf_old_key;
4910 seed = mfp->mf_old_seed;
4911 }
4912 else
4913 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02004914 method = get_crypt_method(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004915 key = buf->b_p_key;
4916 seed = mfp->mf_seed;
4917 }
4918
4919 use_crypt_method = method; /* select pkzip or blowfish */
4920 if (method == 0)
4921 {
4922 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4923 crypt_init_keys(salt);
4924 }
4925 else
4926 {
4927 /* Using blowfish, add salt and seed. We use the byte offset of the
4928 * block for the salt. */
4929 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
Bram Moolenaare77fb8c2010-06-24 05:20:13 +02004930 bf_key_init(key, salt, (int)STRLEN(salt));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004931 bf_ofb_init(seed, MF_SEED_LEN);
4932 }
4933}
4934
4935#endif
4936
4937
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938#if defined(FEAT_BYTEOFF) || defined(PROTO)
4939
4940#define MLCS_MAXL 800 /* max no of lines in chunk */
4941#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4942
4943/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004944 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4946 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4947 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4948 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4949 */
4950 static void
4951ml_updatechunk(buf, line, len, updtype)
4952 buf_T *buf;
4953 linenr_T line;
4954 long len;
4955 int updtype;
4956{
4957 static buf_T *ml_upd_lastbuf = NULL;
4958 static linenr_T ml_upd_lastline;
4959 static linenr_T ml_upd_lastcurline;
4960 static int ml_upd_lastcurix;
4961
4962 linenr_T curline = ml_upd_lastcurline;
4963 int curix = ml_upd_lastcurix;
4964 long size;
4965 chunksize_T *curchnk;
4966 int rest;
4967 bhdr_T *hp;
4968 DATA_BL *dp;
4969
4970 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4971 return;
4972 if (buf->b_ml.ml_chunksize == NULL)
4973 {
4974 buf->b_ml.ml_chunksize = (chunksize_T *)
4975 alloc((unsigned)sizeof(chunksize_T) * 100);
4976 if (buf->b_ml.ml_chunksize == NULL)
4977 {
4978 buf->b_ml.ml_usedchunks = -1;
4979 return;
4980 }
4981 buf->b_ml.ml_numchunks = 100;
4982 buf->b_ml.ml_usedchunks = 1;
4983 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4984 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4985 }
4986
4987 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4988 {
4989 /*
4990 * First line in empty buffer from ml_flush_line() -- reset
4991 */
4992 buf->b_ml.ml_usedchunks = 1;
4993 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4994 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4995 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4996 return;
4997 }
4998
4999 /*
5000 * Find chunk that our line belongs to, curline will be at start of the
5001 * chunk.
5002 */
5003 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
5004 || updtype != ML_CHNK_ADDLINE)
5005 {
5006 for (curline = 1, curix = 0;
5007 curix < buf->b_ml.ml_usedchunks - 1
5008 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5009 curix++)
5010 {
5011 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5012 }
5013 }
5014 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
5015 && curix < buf->b_ml.ml_usedchunks - 1)
5016 {
5017 /* Adjust cached curix & curline */
5018 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5019 curix++;
5020 }
5021 curchnk = buf->b_ml.ml_chunksize + curix;
5022
5023 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00005024 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 curchnk->mlcs_totalsize += len;
5026 if (updtype == ML_CHNK_ADDLINE)
5027 {
5028 curchnk->mlcs_numlines++;
5029
5030 /* May resize here so we don't have to do it in both cases below */
5031 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5032 {
5033 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5034 buf->b_ml.ml_chunksize = (chunksize_T *)
5035 vim_realloc(buf->b_ml.ml_chunksize,
5036 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5037 if (buf->b_ml.ml_chunksize == NULL)
5038 {
5039 /* Hmmmm, Give up on offset for this buffer */
5040 buf->b_ml.ml_usedchunks = -1;
5041 return;
5042 }
5043 }
5044
5045 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5046 {
5047 int count; /* number of entries in block */
5048 int idx;
5049 int text_end;
5050 int linecnt;
5051
5052 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5053 buf->b_ml.ml_chunksize + curix,
5054 (buf->b_ml.ml_usedchunks - curix) *
5055 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005056 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005057 size = 0;
5058 linecnt = 0;
5059 while (curline < buf->b_ml.ml_line_count
5060 && linecnt < MLCS_MINL)
5061 {
5062 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5063 {
5064 buf->b_ml.ml_usedchunks = -1;
5065 return;
5066 }
5067 dp = (DATA_BL *)(hp->bh_data);
5068 count = (long)(buf->b_ml.ml_locked_high) -
5069 (long)(buf->b_ml.ml_locked_low) + 1;
5070 idx = curline - buf->b_ml.ml_locked_low;
5071 curline = buf->b_ml.ml_locked_high + 1;
5072 if (idx == 0)/* first line in block, text at the end */
5073 text_end = dp->db_txt_end;
5074 else
5075 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5076 /* Compute index of last line to use in this MEMLINE */
5077 rest = count - idx;
5078 if (linecnt + rest > MLCS_MINL)
5079 {
5080 idx += MLCS_MINL - linecnt - 1;
5081 linecnt = MLCS_MINL;
5082 }
5083 else
5084 {
5085 idx = count - 1;
5086 linecnt += rest;
5087 }
5088 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5089 }
5090 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5091 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5092 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5093 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5094 buf->b_ml.ml_usedchunks++;
5095 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5096 return;
5097 }
5098 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5099 && curix == buf->b_ml.ml_usedchunks - 1
5100 && buf->b_ml.ml_line_count - line <= 1)
5101 {
5102 /*
5103 * We are in the last chunk and it is cheap to crate a new one
5104 * after this. Do it now to avoid the loop above later on
5105 */
5106 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5107 buf->b_ml.ml_usedchunks++;
5108 if (line == buf->b_ml.ml_line_count)
5109 {
5110 curchnk->mlcs_numlines = 0;
5111 curchnk->mlcs_totalsize = 0;
5112 }
5113 else
5114 {
5115 /*
5116 * Line is just prior to last, move count for last
5117 * This is the common case when loading a new file
5118 */
5119 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5120 if (hp == NULL)
5121 {
5122 buf->b_ml.ml_usedchunks = -1;
5123 return;
5124 }
5125 dp = (DATA_BL *)(hp->bh_data);
5126 if (dp->db_line_count == 1)
5127 rest = dp->db_txt_end - dp->db_txt_start;
5128 else
5129 rest =
5130 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5131 - dp->db_txt_start;
5132 curchnk->mlcs_totalsize = rest;
5133 curchnk->mlcs_numlines = 1;
5134 curchnk[-1].mlcs_totalsize -= rest;
5135 curchnk[-1].mlcs_numlines -= 1;
5136 }
5137 }
5138 }
5139 else if (updtype == ML_CHNK_DELLINE)
5140 {
5141 curchnk->mlcs_numlines--;
5142 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5143 if (curix < (buf->b_ml.ml_usedchunks - 1)
5144 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5145 <= MLCS_MINL)
5146 {
5147 curix++;
5148 curchnk = buf->b_ml.ml_chunksize + curix;
5149 }
5150 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5151 {
5152 buf->b_ml.ml_usedchunks--;
5153 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5154 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5155 return;
5156 }
5157 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5158 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5159 > MLCS_MINL))
5160 {
5161 return;
5162 }
5163
5164 /* Collapse chunks */
5165 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5166 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5167 buf->b_ml.ml_usedchunks--;
5168 if (curix < buf->b_ml.ml_usedchunks)
5169 {
5170 mch_memmove(buf->b_ml.ml_chunksize + curix,
5171 buf->b_ml.ml_chunksize + curix + 1,
5172 (buf->b_ml.ml_usedchunks - curix) *
5173 sizeof(chunksize_T));
5174 }
5175 return;
5176 }
5177 ml_upd_lastbuf = buf;
5178 ml_upd_lastline = line;
5179 ml_upd_lastcurline = curline;
5180 ml_upd_lastcurix = curix;
5181}
5182
5183/*
5184 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005185 * Find line with offset if "lnum" is 0; return remaining offset in offp
5186 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 * return -1 if information is not available
5188 */
5189 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005190ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005192 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 long *offp;
5194{
5195 linenr_T curline;
5196 int curix;
5197 long size;
5198 bhdr_T *hp;
5199 DATA_BL *dp;
5200 int count; /* number of entries in block */
5201 int idx;
5202 int start_idx;
5203 int text_end;
5204 long offset;
5205 int len;
5206 int ffdos = (get_fileformat(buf) == EOL_DOS);
5207 int extra = 0;
5208
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005209 /* take care of cached line first */
5210 ml_flush_line(curbuf);
5211
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 if (buf->b_ml.ml_usedchunks == -1
5213 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005214 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 return -1;
5216
5217 if (offp == NULL)
5218 offset = 0;
5219 else
5220 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005221 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5223 /*
5224 * Find the last chunk before the one containing our line. Last chunk is
5225 * special because it will never qualify
5226 */
5227 curline = 1;
5228 curix = size = 0;
5229 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005230 && ((lnum != 0
5231 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005232 || (offset != 0
5233 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5234 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5235 {
5236 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5237 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5238 if (offset && ffdos)
5239 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5240 curix++;
5241 }
5242
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005243 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244 {
5245 if (curline > buf->b_ml.ml_line_count
5246 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5247 return -1;
5248 dp = (DATA_BL *)(hp->bh_data);
5249 count = (long)(buf->b_ml.ml_locked_high) -
5250 (long)(buf->b_ml.ml_locked_low) + 1;
5251 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5252 if (idx == 0)/* first line in block, text at the end */
5253 text_end = dp->db_txt_end;
5254 else
5255 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5256 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005257 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005258 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005259 if (curline + (count - idx) >= lnum)
5260 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 else
5262 idx = count - 1;
5263 }
5264 else
5265 {
5266 extra = 0;
5267 while (offset >= size
5268 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5269 + ffdos)
5270 {
5271 if (ffdos)
5272 size++;
5273 if (idx == count - 1)
5274 {
5275 extra = 1;
5276 break;
5277 }
5278 idx++;
5279 }
5280 }
5281 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5282 size += len;
5283 if (offset != 0 && size >= offset)
5284 {
5285 if (size + ffdos == offset)
5286 *offp = 0;
5287 else if (idx == start_idx)
5288 *offp = offset - size + len;
5289 else
5290 *offp = offset - size + len
5291 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5292 curline += idx - start_idx + extra;
5293 if (curline > buf->b_ml.ml_line_count)
5294 return -1; /* exactly one byte beyond the end */
5295 return curline;
5296 }
5297 curline = buf->b_ml.ml_locked_high + 1;
5298 }
5299
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005300 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005301 {
5302 /* Count extra CR characters. */
5303 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005304 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005305
5306 /* Don't count the last line break if 'bin' and 'noeol'. */
5307 if (buf->b_p_bin && !buf->b_p_eol)
5308 size -= ffdos + 1;
5309 }
5310
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311 return size;
5312}
5313
5314/*
5315 * Goto byte in buffer with offset 'cnt'.
5316 */
5317 void
5318goto_byte(cnt)
5319 long cnt;
5320{
5321 long boff = cnt;
5322 linenr_T lnum;
5323
5324 ml_flush_line(curbuf); /* cached line may be dirty */
5325 setpcmark();
5326 if (boff)
5327 --boff;
5328 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5329 if (lnum < 1) /* past the end */
5330 {
5331 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5332 curwin->w_curswant = MAXCOL;
5333 coladvance((colnr_T)MAXCOL);
5334 }
5335 else
5336 {
5337 curwin->w_cursor.lnum = lnum;
5338 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005339# ifdef FEAT_VIRTUALEDIT
5340 curwin->w_cursor.coladd = 0;
5341# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 curwin->w_set_curswant = TRUE;
5343 }
5344 check_cursor();
5345
5346# ifdef FEAT_MBYTE
5347 /* Make sure the cursor is on the first byte of a multi-byte char. */
5348 if (has_mbyte)
5349 mb_adjust_cursor();
5350# endif
5351}
5352#endif