blob: c3fdba313768a3633d0a4b3df194c113249a9d25 [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
68#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
73/*
74 * pointer to a block, used in a pointer block
75 */
76struct pointer_entry
77{
78 blocknr_T pe_bnum; /* block number */
79 linenr_T pe_line_count; /* number of lines in this branch */
80 linenr_T pe_old_lnum; /* lnum for this block (for recovery) */
81 int pe_page_count; /* number of pages in block pe_bnum */
82};
83
84/*
85 * A pointer block contains a list of branches in the tree.
86 */
87struct pointer_block
88{
89 short_u pb_id; /* ID for pointer block: PTR_ID */
90 short_u pb_count; /* number of pointer in this block */
91 short_u pb_count_max; /* maximum value for pb_count */
92 PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer)
93 * followed by empty space until end of page */
94};
95
96/*
97 * A data block is a leaf in the tree.
98 *
99 * The text of the lines is at the end of the block. The text of the first line
100 * in the block is put at the end, the text of the second line in front of it,
101 * etc. Thus the order of the lines is the opposite of the line number.
102 */
103struct data_block
104{
105 short_u db_id; /* ID for data block: DATA_ID */
106 unsigned db_free; /* free space available */
107 unsigned db_txt_start; /* byte where text starts */
108 unsigned db_txt_end; /* byte just after data block */
109 linenr_T db_line_count; /* number of lines in this block */
110 unsigned db_index[1]; /* index for start of line (actually bigger)
111 * followed by empty space upto db_txt_start
112 * followed by the text in the lines until
113 * end of page */
114};
115
116/*
117 * The low bits of db_index hold the actual index. The topmost bit is
118 * used for the global command to be able to mark a line.
119 * This method is not clean, but otherwise there would be at least one extra
120 * byte used for each line.
121 * The mark has to be in this place to keep it with the correct line when other
122 * lines are inserted or deleted.
123 */
124#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
125#define DB_INDEX_MASK (~DB_MARKED)
126
127#define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */
128#define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */
129
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000130#define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */
131#define B0_FNAME_SIZE 898
132#define B0_UNAME_SIZE 40
133#define B0_HNAME_SIZE 40
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134/*
135 * Restrict the numbers to 32 bits, otherwise most compilers will complain.
136 * This won't detect a 64 bit machine that only swaps a byte in the top 32
137 * bits, but that is crazy anyway.
138 */
139#define B0_MAGIC_LONG 0x30313233L
140#define B0_MAGIC_INT 0x20212223L
141#define B0_MAGIC_SHORT 0x10111213L
142#define B0_MAGIC_CHAR 0x55
143
144/*
145 * Block zero holds all info about the swap file.
146 *
147 * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
148 * swap files unusable!
149 *
150 * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
151 *
Bram Moolenaarbae0c162007-05-10 19:30:25 +0000152 * This block is built up of single bytes, to make it portable across
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153 * different machines. b0_magic_* is used to check the byte order and size of
154 * variables, because the rest of the swap file is not portable.
155 */
156struct block0
157{
158 char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1 */
159 char_u b0_version[10]; /* Vim version string */
160 char_u b0_page_size[4];/* number of bytes per page */
161 char_u b0_mtime[4]; /* last modification time of file */
162 char_u b0_ino[4]; /* inode of b0_fname */
163 char_u b0_pid[4]; /* process id of creator (or 0) */
164 char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */
165 char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000166 char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167 long b0_magic_long; /* check for byte order of long */
168 int b0_magic_int; /* check for byte order of int */
169 short b0_magic_short; /* check for byte order of short */
170 char_u b0_magic_char; /* check for last char */
171};
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000172
173/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000174 * Note: b0_dirty and b0_flags are put at the end of the file name. For very
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000175 * long file names in older versions of Vim they are invalid.
176 * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
177 * when there is room, for very long file names it's omitted.
178 */
179#define B0_DIRTY 0x55
180#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG-1]
181
182/*
183 * The b0_flags field is new in Vim 7.0.
184 */
185#define b0_flags b0_fname[B0_FNAME_SIZE_ORG-2]
186
187/* The lowest two bits contain the fileformat. Zero means it's not set
188 * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
189 * EOL_MAC + 1. */
190#define B0_FF_MASK 3
191
192/* Swap file is in directory of edited file. Used to find the file from
193 * different mount points. */
194#define B0_SAME_DIR 4
195
196/* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
197 * When empty there is only the NUL. */
198#define B0_HAS_FENC 8
Bram Moolenaar071d4272004-06-13 20:20:40 +0000199
200#define STACK_INCR 5 /* nr of entries added to ml_stack at a time */
201
202/*
203 * The line number where the first mark may be is remembered.
204 * If it is 0 there are no marks at all.
205 * (always used for the current buffer only, no buffer change possible while
206 * executing a global command).
207 */
208static linenr_T lowest_marked = 0;
209
210/*
211 * arguments for ml_find_line()
212 */
213#define ML_DELETE 0x11 /* delete line */
214#define ML_INSERT 0x12 /* insert line */
215#define ML_FIND 0x13 /* just find the line */
216#define ML_FLUSH 0x02 /* flush locked block */
217#define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */
218
Bram Moolenaar89d40322006-08-29 15:30:07 +0000219static void ml_upd_block0 __ARGS((buf_T *buf, int set_fname));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220static void set_b0_fname __ARGS((ZERO_BL *, buf_T *buf));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000221static void set_b0_dir_flag __ARGS((ZERO_BL *b0p, buf_T *buf));
222#ifdef FEAT_MBYTE
223static void add_b0_fenc __ARGS((ZERO_BL *b0p, buf_T *buf));
224#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000225static time_t swapfile_info __ARGS((char_u *));
226static int recov_file_names __ARGS((char_u **, char_u *, int prepend_dot));
227static int ml_append_int __ARGS((buf_T *, linenr_T, char_u *, colnr_T, int, int));
228static int ml_delete_int __ARGS((buf_T *, linenr_T, int));
229static char_u *findswapname __ARGS((buf_T *, char_u **, char_u *));
230static void ml_flush_line __ARGS((buf_T *));
231static bhdr_T *ml_new_data __ARGS((memfile_T *, int, int));
232static bhdr_T *ml_new_ptr __ARGS((memfile_T *));
233static bhdr_T *ml_find_line __ARGS((buf_T *, linenr_T, int));
234static int ml_add_stack __ARGS((buf_T *));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000235static void ml_lineadd __ARGS((buf_T *, int));
236static int b0_magic_wrong __ARGS((ZERO_BL *));
237#ifdef CHECK_INODE
238static int fnamecmp_ino __ARGS((char_u *, char_u *, long));
239#endif
240static void long_to_char __ARGS((long, char_u *));
241static long char_to_long __ARGS((char_u *));
242#if defined(UNIX) || defined(WIN3264)
243static char_u *make_percent_swname __ARGS((char_u *dir, char_u *name));
244#endif
245#ifdef FEAT_BYTEOFF
246static void ml_updatechunk __ARGS((buf_T *buf, long line, long len, int updtype));
247#endif
248
249/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000250 * Open a new memline for "buf".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000251 *
Bram Moolenaar4770d092006-01-12 23:22:24 +0000252 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253 */
254 int
Bram Moolenaar4770d092006-01-12 23:22:24 +0000255ml_open(buf)
256 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257{
258 memfile_T *mfp;
259 bhdr_T *hp = NULL;
260 ZERO_BL *b0p;
261 PTR_BL *pp;
262 DATA_BL *dp;
263
Bram Moolenaar4770d092006-01-12 23:22:24 +0000264 /*
265 * init fields in memline struct
266 */
267 buf->b_ml.ml_stack_size = 0; /* no stack yet */
268 buf->b_ml.ml_stack = NULL; /* no stack yet */
269 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
270 buf->b_ml.ml_locked = NULL; /* no cached block */
271 buf->b_ml.ml_line_lnum = 0; /* no cached line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000272#ifdef FEAT_BYTEOFF
Bram Moolenaar4770d092006-01-12 23:22:24 +0000273 buf->b_ml.ml_chunksize = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274#endif
275
Bram Moolenaar4770d092006-01-12 23:22:24 +0000276 /*
277 * When 'updatecount' is non-zero swap file may be opened later.
278 */
279 if (p_uc && buf->b_p_swf)
280 buf->b_may_swap = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000281 else
Bram Moolenaar4770d092006-01-12 23:22:24 +0000282 buf->b_may_swap = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000283
Bram Moolenaar4770d092006-01-12 23:22:24 +0000284 /*
285 * Open the memfile. No swap file is created yet.
286 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 mfp = mf_open(NULL, 0);
288 if (mfp == NULL)
289 goto error;
290
Bram Moolenaar4770d092006-01-12 23:22:24 +0000291 buf->b_ml.ml_mfp = mfp;
292 buf->b_ml.ml_flags = ML_EMPTY;
293 buf->b_ml.ml_line_count = 1;
Bram Moolenaar592e0a22004-07-03 16:05:59 +0000294#ifdef FEAT_LINEBREAK
295 curwin->w_nrwidth_line_count = 0;
296#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297
298#if defined(MSDOS) && !defined(DJGPP)
299 /* for 16 bit MS-DOS create a swapfile now, because we run out of
300 * memory very quickly */
301 if (p_uc != 0)
Bram Moolenaar4770d092006-01-12 23:22:24 +0000302 ml_open_file(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303#endif
304
305/*
306 * fill block0 struct and write page 0
307 */
308 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
309 goto error;
310 if (hp->bh_bnum != 0)
311 {
312 EMSG(_("E298: Didn't get block nr 0?"));
313 goto error;
314 }
315 b0p = (ZERO_BL *)(hp->bh_data);
316
317 b0p->b0_id[0] = BLOCK0_ID0;
318 b0p->b0_id[1] = BLOCK0_ID1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000319 b0p->b0_magic_long = (long)B0_MAGIC_LONG;
320 b0p->b0_magic_int = (int)B0_MAGIC_INT;
321 b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
322 b0p->b0_magic_char = B0_MAGIC_CHAR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323 STRNCPY(b0p->b0_version, "VIM ", 4);
324 STRNCPY(b0p->b0_version + 4, Version, 6);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000326
Bram Moolenaar76b92b22006-03-24 22:46:53 +0000327#ifdef FEAT_SPELL
328 if (!buf->b_spell)
329#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000330 {
331 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
332 b0p->b0_flags = get_fileformat(buf) + 1;
333 set_b0_fname(b0p, buf);
334 (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
335 b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
336 mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
337 b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
338 long_to_char(mch_get_pid(), b0p->b0_pid);
339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340
341 /*
342 * Always sync block number 0 to disk, so we can check the file name in
Bram Moolenaar4770d092006-01-12 23:22:24 +0000343 * the swap file in findswapname(). Don't do this for help files though
344 * and spell buffer though.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000345 * Only works when there's a swapfile, otherwise it's done when the file
346 * is created.
347 */
348 mf_put(mfp, hp, TRUE, FALSE);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000349 if (!buf->b_help && !B_SPELL(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 (void)mf_sync(mfp, 0);
351
Bram Moolenaar4770d092006-01-12 23:22:24 +0000352 /*
353 * Fill in root pointer block and write page 1.
354 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000355 if ((hp = ml_new_ptr(mfp)) == NULL)
356 goto error;
357 if (hp->bh_bnum != 1)
358 {
359 EMSG(_("E298: Didn't get block nr 1?"));
360 goto error;
361 }
362 pp = (PTR_BL *)(hp->bh_data);
363 pp->pb_count = 1;
364 pp->pb_pointer[0].pe_bnum = 2;
365 pp->pb_pointer[0].pe_page_count = 1;
366 pp->pb_pointer[0].pe_old_lnum = 1;
367 pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */
368 mf_put(mfp, hp, TRUE, FALSE);
369
Bram Moolenaar4770d092006-01-12 23:22:24 +0000370 /*
371 * Allocate first data block and create an empty line 1.
372 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373 if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
374 goto error;
375 if (hp->bh_bnum != 2)
376 {
377 EMSG(_("E298: Didn't get block nr 2?"));
378 goto error;
379 }
380
381 dp = (DATA_BL *)(hp->bh_data);
382 dp->db_index[0] = --dp->db_txt_start; /* at end of block */
383 dp->db_free -= 1 + INDEX_SIZE;
384 dp->db_line_count = 1;
Bram Moolenaarf05da212009-11-17 16:13:15 +0000385 *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386
387 return OK;
388
389error:
390 if (mfp != NULL)
391 {
392 if (hp)
393 mf_put(mfp, hp, FALSE, FALSE);
394 mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */
395 }
Bram Moolenaar4770d092006-01-12 23:22:24 +0000396 buf->b_ml.ml_mfp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 return FAIL;
398}
399
400/*
401 * ml_setname() is called when the file name of "buf" has been changed.
402 * It may rename the swap file.
403 */
404 void
405ml_setname(buf)
406 buf_T *buf;
407{
408 int success = FALSE;
409 memfile_T *mfp;
410 char_u *fname;
411 char_u *dirp;
412#if defined(MSDOS) || defined(MSWIN)
413 char_u *p;
414#endif
415
416 mfp = buf->b_ml.ml_mfp;
417 if (mfp->mf_fd < 0) /* there is no swap file yet */
418 {
419 /*
420 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
421 * For help files we will make a swap file now.
422 */
423 if (p_uc != 0)
424 ml_open_file(buf); /* create a swap file */
425 return;
426 }
427
428 /*
429 * Try all directories in the 'directory' option.
430 */
431 dirp = p_dir;
432 for (;;)
433 {
434 if (*dirp == NUL) /* tried all directories, fail */
435 break;
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000436 fname = findswapname(buf, &dirp, mfp->mf_fname);
437 /* alloc's fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000438 if (fname == NULL) /* no file name found for this dir */
439 continue;
440
441#if defined(MSDOS) || defined(MSWIN)
442 /*
443 * Set full pathname for swap file now, because a ":!cd dir" may
444 * change directory without us knowing it.
445 */
446 p = FullName_save(fname, FALSE);
447 vim_free(fname);
448 fname = p;
449 if (fname == NULL)
450 continue;
451#endif
452 /* if the file name is the same we don't have to do anything */
453 if (fnamecmp(fname, mfp->mf_fname) == 0)
454 {
455 vim_free(fname);
456 success = TRUE;
457 break;
458 }
459 /* need to close the swap file before renaming */
460 if (mfp->mf_fd >= 0)
461 {
462 close(mfp->mf_fd);
463 mfp->mf_fd = -1;
464 }
465
466 /* try to rename the swap file */
467 if (vim_rename(mfp->mf_fname, fname) == 0)
468 {
469 success = TRUE;
470 vim_free(mfp->mf_fname);
471 mfp->mf_fname = fname;
472 vim_free(mfp->mf_ffname);
473#if defined(MSDOS) || defined(MSWIN)
474 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
475#else
476 mf_set_ffname(mfp);
477#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000478 ml_upd_block0(buf, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 break;
480 }
481 vim_free(fname); /* this fname didn't work, try another */
482 }
483
484 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
485 {
486 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
487 if (mfp->mf_fd < 0)
488 {
489 /* could not (re)open the swap file, what can we do???? */
490 EMSG(_("E301: Oops, lost the swap file!!!"));
491 return;
492 }
Bram Moolenaarf05da212009-11-17 16:13:15 +0000493#ifdef HAVE_FD_CLOEXEC
494 {
495 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
496 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
497 fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
498 }
499#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000500 }
501 if (!success)
502 EMSG(_("E302: Could not rename swap file"));
503}
504
505/*
506 * Open a file for the memfile for all buffers that are not readonly or have
507 * been modified.
508 * Used when 'updatecount' changes from zero to non-zero.
509 */
510 void
511ml_open_files()
512{
513 buf_T *buf;
514
515 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
516 if (!buf->b_p_ro || buf->b_changed)
517 ml_open_file(buf);
518}
519
520/*
521 * Open a swap file for an existing memfile, if there is no swap file yet.
522 * If we are unable to find a file name, mf_fname will be NULL
523 * and the memfile will be in memory only (no recovery possible).
524 */
525 void
526ml_open_file(buf)
527 buf_T *buf;
528{
529 memfile_T *mfp;
530 char_u *fname;
531 char_u *dirp;
532
533 mfp = buf->b_ml.ml_mfp;
534 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf)
535 return; /* nothing to do */
536
Bram Moolenaara1956f62006-03-12 22:18:00 +0000537#ifdef FEAT_SPELL
Bram Moolenaar4770d092006-01-12 23:22:24 +0000538 /* For a spell buffer use a temp file name. */
539 if (buf->b_spell)
540 {
541 fname = vim_tempname('s');
542 if (fname != NULL)
543 (void)mf_open_file(mfp, fname); /* consumes fname! */
544 buf->b_may_swap = FALSE;
545 return;
546 }
547#endif
548
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 /*
550 * Try all directories in 'directory' option.
551 */
552 dirp = p_dir;
553 for (;;)
554 {
555 if (*dirp == NUL)
556 break;
557 /* There is a small chance that between chosing the swap file name and
558 * creating it, another Vim creates the file. In that case the
559 * creation will fail and we will use another directory. */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000560 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561 if (fname == NULL)
562 continue;
563 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
564 {
565#if defined(MSDOS) || defined(MSWIN) || defined(RISCOS)
566 /*
567 * set full pathname for swap file now, because a ":!cd dir" may
568 * change directory without us knowing it.
569 */
570 mf_fullname(mfp);
571#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000572 ml_upd_block0(buf, FALSE);
573
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574 /* Flush block zero, so others can read it */
575 if (mf_sync(mfp, MFS_ZERO) == OK)
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000576 {
577 /* Mark all blocks that should be in the swapfile as dirty.
578 * Needed for when the 'swapfile' option was reset, so that
579 * the swap file was deleted, and then on again. */
580 mf_set_dirty(mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581 break;
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000582 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583 /* Writing block 0 failed: close the file and try another dir */
584 mf_close_file(buf, FALSE);
585 }
586 }
587
588 if (mfp->mf_fname == NULL) /* Failed! */
589 {
590 need_wait_return = TRUE; /* call wait_return later */
591 ++no_wait_return;
592 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
593 buf_spname(buf) != NULL
594 ? (char_u *)buf_spname(buf)
595 : buf->b_fname);
596 --no_wait_return;
597 }
598
599 /* don't try to open a swap file again */
600 buf->b_may_swap = FALSE;
601}
602
603/*
604 * If still need to create a swap file, and starting to edit a not-readonly
605 * file, or reading into an existing buffer, create a swap file now.
606 */
607 void
608check_need_swap(newfile)
609 int newfile; /* reading file into new buffer */
610{
611 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
612 ml_open_file(curbuf);
613}
614
615/*
616 * Close memline for buffer 'buf'.
617 * If 'del_file' is TRUE, delete the swap file
618 */
619 void
620ml_close(buf, del_file)
621 buf_T *buf;
622 int del_file;
623{
624 if (buf->b_ml.ml_mfp == NULL) /* not open */
625 return;
626 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
627 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
628 vim_free(buf->b_ml.ml_line_ptr);
629 vim_free(buf->b_ml.ml_stack);
630#ifdef FEAT_BYTEOFF
631 vim_free(buf->b_ml.ml_chunksize);
632 buf->b_ml.ml_chunksize = NULL;
633#endif
634 buf->b_ml.ml_mfp = NULL;
635
636 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
637 * this buffer is loaded. */
638 buf->b_flags &= ~BF_RECOVERED;
639}
640
641/*
642 * Close all existing memlines and memfiles.
643 * Only used when exiting.
644 * When 'del_file' is TRUE, delete the memfiles.
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000645 * But don't delete files that were ":preserve"d when we are POSIX compatible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646 */
647 void
648ml_close_all(del_file)
649 int del_file;
650{
651 buf_T *buf;
652
653 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000654 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
655 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656#ifdef TEMPDIRNAMES
657 vim_deltempdir(); /* delete created temp directory */
658#endif
659}
660
661/*
662 * Close all memfiles for not modified buffers.
663 * Only use just before exiting!
664 */
665 void
666ml_close_notmod()
667{
668 buf_T *buf;
669
670 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
671 if (!bufIsChanged(buf))
672 ml_close(buf, TRUE); /* close all not-modified buffers */
673}
674
675/*
676 * Update the timestamp in the .swp file.
677 * Used when the file has been written.
678 */
679 void
680ml_timestamp(buf)
681 buf_T *buf;
682{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000683 ml_upd_block0(buf, TRUE);
684}
685
686/*
687 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
688 */
689 static void
Bram Moolenaar89d40322006-08-29 15:30:07 +0000690ml_upd_block0(buf, set_fname)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000691 buf_T *buf;
Bram Moolenaar89d40322006-08-29 15:30:07 +0000692 int set_fname;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000693{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694 memfile_T *mfp;
695 bhdr_T *hp;
696 ZERO_BL *b0p;
697
698 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
700 return;
701 b0p = (ZERO_BL *)(hp->bh_data);
702 if (b0p->b0_id[0] != BLOCK0_ID0 || b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000703 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000705 {
Bram Moolenaar89d40322006-08-29 15:30:07 +0000706 if (set_fname)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000707 set_b0_fname(b0p, buf);
708 else
709 set_b0_dir_flag(b0p, buf);
710 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711 mf_put(mfp, hp, TRUE, FALSE);
712}
713
714/*
715 * Write file name and timestamp into block 0 of a swap file.
716 * Also set buf->b_mtime.
717 * Don't use NameBuff[]!!!
718 */
719 static void
720set_b0_fname(b0p, buf)
721 ZERO_BL *b0p;
722 buf_T *buf;
723{
724 struct stat st;
725
726 if (buf->b_ffname == NULL)
727 b0p->b0_fname[0] = NUL;
728 else
729 {
730#if defined(MSDOS) || defined(MSWIN) || defined(AMIGA) || defined(RISCOS)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000731 /* Systems that cannot translate "~user" back into a path: copy the
732 * file name unmodified. Do use slashes instead of backslashes for
733 * portability. */
Bram Moolenaarce0842a2005-07-18 21:58:11 +0000734 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000735# ifdef BACKSLASH_IN_FILENAME
736 forward_slash(b0p->b0_fname);
737# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738#else
739 size_t flen, ulen;
740 char_u uname[B0_UNAME_SIZE];
741
742 /*
743 * For a file under the home directory of the current user, we try to
744 * replace the home directory path with "~user". This helps when
745 * editing the same file on different machines over a network.
746 * First replace home dir path with "~/" with home_replace().
747 * Then insert the user name to get "~user/".
748 */
749 home_replace(NULL, buf->b_ffname, b0p->b0_fname, B0_FNAME_SIZE, TRUE);
750 if (b0p->b0_fname[0] == '~')
751 {
752 flen = STRLEN(b0p->b0_fname);
753 /* If there is no user name or it is too long, don't use "~/" */
754 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
755 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE - 1)
Bram Moolenaarce0842a2005-07-18 21:58:11 +0000756 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 else
758 {
759 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
760 mch_memmove(b0p->b0_fname + 1, uname, ulen);
761 }
762 }
763#endif
764 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
765 {
766 long_to_char((long)st.st_mtime, b0p->b0_mtime);
767#ifdef CHECK_INODE
768 long_to_char((long)st.st_ino, b0p->b0_ino);
769#endif
770 buf_store_time(buf, &st, buf->b_ffname);
771 buf->b_mtime_read = buf->b_mtime;
772 }
773 else
774 {
775 long_to_char(0L, b0p->b0_mtime);
776#ifdef CHECK_INODE
777 long_to_char(0L, b0p->b0_ino);
778#endif
779 buf->b_mtime = 0;
780 buf->b_mtime_read = 0;
781 buf->b_orig_size = 0;
782 buf->b_orig_mode = 0;
783 }
784 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000785
786#ifdef FEAT_MBYTE
787 /* Also add the 'fileencoding' if there is room. */
788 add_b0_fenc(b0p, curbuf);
789#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790}
791
792/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000793 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
794 * swapfile for "buf" are in the same directory.
795 * This is fail safe: if we are not sure the directories are equal the flag is
796 * not set.
797 */
798 static void
799set_b0_dir_flag(b0p, buf)
800 ZERO_BL *b0p;
801 buf_T *buf;
802{
803 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
804 b0p->b0_flags |= B0_SAME_DIR;
805 else
806 b0p->b0_flags &= ~B0_SAME_DIR;
807}
808
809#ifdef FEAT_MBYTE
810/*
811 * When there is room, add the 'fileencoding' to block zero.
812 */
813 static void
814add_b0_fenc(b0p, buf)
815 ZERO_BL *b0p;
816 buf_T *buf;
817{
818 int n;
819
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000820 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000821 if (STRLEN(b0p->b0_fname) + n + 1 > B0_FNAME_SIZE)
822 b0p->b0_flags &= ~B0_HAS_FENC;
823 else
824 {
825 mch_memmove((char *)b0p->b0_fname + B0_FNAME_SIZE - n,
826 (char *)buf->b_p_fenc, (size_t)n);
827 *(b0p->b0_fname + B0_FNAME_SIZE - n - 1) = NUL;
828 b0p->b0_flags |= B0_HAS_FENC;
829 }
830}
831#endif
832
833
834/*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835 * try to recover curbuf from the .swp file
836 */
837 void
838ml_recover()
839{
840 buf_T *buf = NULL;
841 memfile_T *mfp = NULL;
842 char_u *fname;
843 bhdr_T *hp = NULL;
844 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000845 int b0_ff;
846 char_u *b0_fenc = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 PTR_BL *pp;
848 DATA_BL *dp;
849 infoptr_T *ip;
850 blocknr_T bnum;
851 int page_count;
852 struct stat org_stat, swp_stat;
853 int len;
854 int directly;
855 linenr_T lnum;
856 char_u *p;
857 int i;
858 long error;
859 int cannot_open;
860 linenr_T line_count;
861 int has_error;
862 int idx;
863 int top;
864 int txt_start;
865 off_t size;
866 int called_from_main;
867 int serious_error = TRUE;
868 long mtime;
869 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +0200870 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871
872 recoverymode = TRUE;
873 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
874 attr = hl_attr(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +0000875
876 /*
877 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
878 * Otherwise a search is done to find the swap file(s).
879 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880 fname = curbuf->b_fname;
881 if (fname == NULL) /* When there is no file name */
882 fname = (char_u *)"";
883 len = (int)STRLEN(fname);
884 if (len >= 4 &&
885#if defined(VMS) || defined(RISCOS)
Bram Moolenaard0ba34a2009-11-03 12:06:23 +0000886 STRNICMP(fname + len - 4, "_s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887#else
Bram Moolenaard0ba34a2009-11-03 12:06:23 +0000888 STRNICMP(fname + len - 4, ".s" , 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889#endif
Bram Moolenaard0ba34a2009-11-03 12:06:23 +0000890 == 0
891 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
892 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893 {
894 directly = TRUE;
895 fname = vim_strsave(fname); /* make a copy for mf_open() */
896 }
897 else
898 {
899 directly = FALSE;
900
901 /* count the number of matching swap files */
902 len = recover_names(&fname, FALSE, 0);
903 if (len == 0) /* no swap files found */
904 {
905 EMSG2(_("E305: No swap file found for %s"), fname);
906 goto theend;
907 }
908 if (len == 1) /* one swap file found, use it */
909 i = 1;
910 else /* several swap files found, choose */
911 {
912 /* list the names of the swap files */
913 (void)recover_names(&fname, TRUE, 0);
914 msg_putchar('\n');
915 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +0000916 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917 if (i < 1 || i > len)
918 goto theend;
919 }
920 /* get the swap file name that will be used */
921 (void)recover_names(&fname, FALSE, i);
922 }
923 if (fname == NULL)
924 goto theend; /* out of memory */
925
926 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +0000927 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928 getout(1);
929
930/*
931 * allocate a buffer structure (only the memline in it is really used)
932 */
933 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
934 if (buf == NULL)
935 {
936 vim_free(fname);
937 goto theend;
938 }
939
940/*
941 * init fields in memline struct
942 */
943 buf->b_ml.ml_stack_size = 0; /* no stack yet */
944 buf->b_ml.ml_stack = NULL; /* no stack yet */
945 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
946 buf->b_ml.ml_line_lnum = 0; /* no cached line */
947 buf->b_ml.ml_locked = NULL; /* no locked block */
948 buf->b_ml.ml_flags = 0;
949
950/*
951 * open the memfile from the old swap file
952 */
953 p = vim_strsave(fname); /* save fname for the message
954 (mf_open() may free fname) */
955 mfp = mf_open(fname, O_RDONLY); /* consumes fname! */
956 if (mfp == NULL || mfp->mf_fd < 0)
957 {
958 if (p != NULL)
959 {
960 EMSG2(_("E306: Cannot open %s"), p);
961 vim_free(p);
962 }
963 goto theend;
964 }
965 vim_free(p);
966 buf->b_ml.ml_mfp = mfp;
967
968 /*
969 * The page size set in mf_open() might be different from the page size
970 * used in the swap file, we must get it from block 0. But to read block
971 * 0 we need a page size. Use the minimal size for block 0 here, it will
972 * be set to the real value below.
973 */
974 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
975
976/*
977 * try to read block 0
978 */
979 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
980 {
981 msg_start();
982 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
983 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
984 MSG_PUTS_ATTR(
985 _("\nMaybe no changes were made or Vim did not update the swap file."),
986 attr | MSG_HIST);
987 msg_end();
988 goto theend;
989 }
990 b0p = (ZERO_BL *)(hp->bh_data);
991 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
992 {
993 msg_start();
994 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
995 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
996 MSG_HIST);
997 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
998 msg_end();
999 goto theend;
1000 }
1001 if (b0p->b0_id[0] != BLOCK0_ID0 || b0p->b0_id[1] != BLOCK0_ID1)
1002 {
1003 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1004 goto theend;
1005 }
1006 if (b0_magic_wrong(b0p))
1007 {
1008 msg_start();
1009 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1010#if defined(MSDOS) || defined(MSWIN)
1011 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1012 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1013 attr | MSG_HIST);
1014 else
1015#endif
1016 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1017 attr | MSG_HIST);
1018 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
1019 /* avoid going past the end of a currupted hostname */
1020 b0p->b0_fname[0] = NUL;
1021 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1022 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1023 msg_end();
1024 goto theend;
1025 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001026
Bram Moolenaar071d4272004-06-13 20:20:40 +00001027 /*
1028 * If we guessed the wrong page size, we have to recalculate the
1029 * highest block number in the file.
1030 */
1031 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1032 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001033 unsigned previous_page_size = mfp->mf_page_size;
1034
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001036 if (mfp->mf_page_size < previous_page_size)
1037 {
1038 msg_start();
1039 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1040 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1041 attr | MSG_HIST);
1042 msg_end();
1043 goto theend;
1044 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001045 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1046 mfp->mf_blocknr_max = 0; /* no file or empty file */
1047 else
1048 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1049 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001050
1051 /* need to reallocate the memory used to store the data */
1052 p = alloc(mfp->mf_page_size);
1053 if (p == NULL)
1054 goto theend;
1055 mch_memmove(p, hp->bh_data, previous_page_size);
1056 vim_free(hp->bh_data);
1057 hp->bh_data = p;
1058 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 }
1060
1061/*
1062 * If .swp file name given directly, use name from swap file for buffer.
1063 */
1064 if (directly)
1065 {
1066 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1067 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1068 goto theend;
1069 }
1070
1071 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001072 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073
1074 if (buf_spname(curbuf) != NULL)
1075 STRCPY(NameBuff, buf_spname(curbuf));
1076 else
1077 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001078 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079 msg_putchar('\n');
1080
1081/*
1082 * check date of swap file and original file
1083 */
1084 mtime = char_to_long(b0p->b0_mtime);
1085 if (curbuf->b_ffname != NULL
1086 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1087 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1088 && org_stat.st_mtime > swp_stat.st_mtime)
1089 || org_stat.st_mtime != mtime))
1090 {
1091 EMSG(_("E308: Warning: Original file may have been changed"));
1092 }
1093 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001094
1095 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1096 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1097 if (b0p->b0_flags & B0_HAS_FENC)
1098 {
1099 for (p = b0p->b0_fname + B0_FNAME_SIZE;
1100 p > b0p->b0_fname && p[-1] != NUL; --p)
1101 ;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001102 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + B0_FNAME_SIZE - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001103 }
1104
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1106 hp = NULL;
1107
1108 /*
1109 * Now that we are sure that the file is going to be recovered, clear the
1110 * contents of the current buffer.
1111 */
1112 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1113 ml_delete((linenr_T)1, FALSE);
1114
1115 /*
1116 * Try reading the original file to obtain the values of 'fileformat',
1117 * 'fileencoding', etc. Ignore errors. The text itself is not used.
1118 */
1119 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001120 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001123 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1124 if (b0_ff != 0)
1125 set_fileformat(b0_ff - 1, OPT_LOCAL);
1126 if (b0_fenc != NULL)
1127 {
1128 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1129 vim_free(b0_fenc);
1130 }
1131 unchanged(curbuf, TRUE);
1132
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133 bnum = 1; /* start with block 1 */
1134 page_count = 1; /* which is 1 page */
1135 lnum = 0; /* append after line 0 in curbuf */
1136 line_count = 0;
1137 idx = 0; /* start with first index in block 1 */
1138 error = 0;
1139 buf->b_ml.ml_stack_top = 0;
1140 buf->b_ml.ml_stack = NULL;
1141 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1142
1143 if (curbuf->b_ffname == NULL)
1144 cannot_open = TRUE;
1145 else
1146 cannot_open = FALSE;
1147
1148 serious_error = FALSE;
1149 for ( ; !got_int; line_breakcheck())
1150 {
1151 if (hp != NULL)
1152 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1153
1154 /*
1155 * get block
1156 */
1157 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1158 {
1159 if (bnum == 1)
1160 {
1161 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1162 goto theend;
1163 }
1164 ++error;
1165 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1166 (colnr_T)0, TRUE);
1167 }
1168 else /* there is a block */
1169 {
1170 pp = (PTR_BL *)(hp->bh_data);
1171 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1172 {
1173 /* check line count when using pointer block first time */
1174 if (idx == 0 && line_count != 0)
1175 {
1176 for (i = 0; i < (int)pp->pb_count; ++i)
1177 line_count -= pp->pb_pointer[i].pe_line_count;
1178 if (line_count != 0)
1179 {
1180 ++error;
1181 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1182 (colnr_T)0, TRUE);
1183 }
1184 }
1185
1186 if (pp->pb_count == 0)
1187 {
1188 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1189 (colnr_T)0, TRUE);
1190 ++error;
1191 }
1192 else if (idx < (int)pp->pb_count) /* go a block deeper */
1193 {
1194 if (pp->pb_pointer[idx].pe_bnum < 0)
1195 {
1196 /*
1197 * Data block with negative block number.
1198 * Try to read lines from the original file.
1199 * This is slow, but it works.
1200 */
1201 if (!cannot_open)
1202 {
1203 line_count = pp->pb_pointer[idx].pe_line_count;
1204 if (readfile(curbuf->b_ffname, NULL, lnum,
1205 pp->pb_pointer[idx].pe_old_lnum - 1,
1206 line_count, NULL, 0) == FAIL)
1207 cannot_open = TRUE;
1208 else
1209 lnum += line_count;
1210 }
1211 if (cannot_open)
1212 {
1213 ++error;
1214 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1215 (colnr_T)0, TRUE);
1216 }
1217 ++idx; /* get same block again for next index */
1218 continue;
1219 }
1220
1221 /*
1222 * going one block deeper in the tree
1223 */
1224 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1225 {
1226 ++error;
1227 break; /* out of memory */
1228 }
1229 ip = &(buf->b_ml.ml_stack[top]);
1230 ip->ip_bnum = bnum;
1231 ip->ip_index = idx;
1232
1233 bnum = pp->pb_pointer[idx].pe_bnum;
1234 line_count = pp->pb_pointer[idx].pe_line_count;
1235 page_count = pp->pb_pointer[idx].pe_page_count;
1236 continue;
1237 }
1238 }
1239 else /* not a pointer block */
1240 {
1241 dp = (DATA_BL *)(hp->bh_data);
1242 if (dp->db_id != DATA_ID) /* block id wrong */
1243 {
1244 if (bnum == 1)
1245 {
1246 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1247 mfp->mf_fname);
1248 goto theend;
1249 }
1250 ++error;
1251 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1252 (colnr_T)0, TRUE);
1253 }
1254 else
1255 {
1256 /*
1257 * it is a data block
1258 * Append all the lines in this block
1259 */
1260 has_error = FALSE;
1261 /*
1262 * check length of block
1263 * if wrong, use length in pointer block
1264 */
1265 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1266 {
1267 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1268 (colnr_T)0, TRUE);
1269 ++error;
1270 has_error = TRUE;
1271 dp->db_txt_end = page_count * mfp->mf_page_size;
1272 }
1273
1274 /* make sure there is a NUL at the end of the block */
1275 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1276
1277 /*
1278 * check number of lines in block
1279 * if wrong, use count in data block
1280 */
1281 if (line_count != dp->db_line_count)
1282 {
1283 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1284 (colnr_T)0, TRUE);
1285 ++error;
1286 has_error = TRUE;
1287 }
1288
1289 for (i = 0; i < dp->db_line_count; ++i)
1290 {
1291 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001292 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293 || txt_start >= (int)dp->db_txt_end)
1294 {
1295 p = (char_u *)"???";
1296 ++error;
1297 }
1298 else
1299 p = (char_u *)dp + txt_start;
1300 ml_append(lnum++, p, (colnr_T)0, TRUE);
1301 }
1302 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001303 ml_append(lnum++, (char_u *)_("???END"),
1304 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001305 }
1306 }
1307 }
1308
1309 if (buf->b_ml.ml_stack_top == 0) /* finished */
1310 break;
1311
1312 /*
1313 * go one block up in the tree
1314 */
1315 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1316 bnum = ip->ip_bnum;
1317 idx = ip->ip_index + 1; /* go to next index */
1318 page_count = 1;
1319 }
1320
1321 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001322 * Compare the buffer contents with the original file. When they differ
1323 * set the 'modified' flag.
1324 * Lines 1 - lnum are the new contents.
1325 * Lines lnum + 1 to ml_line_count are the original contents.
1326 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001328 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1329 {
1330 /* Recovering an empty file results in two lines and the first line is
1331 * empty. Don't set the modified flag then. */
1332 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1333 {
1334 changed_int();
1335 ++curbuf->b_changedtick;
1336 }
1337 }
1338 else
1339 {
1340 for (idx = 1; idx <= lnum; ++idx)
1341 {
1342 /* Need to copy one line, fetching the other one may flush it. */
1343 p = vim_strsave(ml_get(idx));
1344 i = STRCMP(p, ml_get(idx + lnum));
1345 vim_free(p);
1346 if (i != 0)
1347 {
1348 changed_int();
1349 ++curbuf->b_changedtick;
1350 break;
1351 }
1352 }
1353 }
1354
1355 /*
1356 * Delete the lines from the original file and the dummy line from the
1357 * empty buffer. These will now be after the last line in the buffer.
1358 */
1359 while (curbuf->b_ml.ml_line_count > lnum
1360 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1361 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 curbuf->b_flags |= BF_RECOVERED;
1363
1364 recoverymode = FALSE;
1365 if (got_int)
1366 EMSG(_("E311: Recovery Interrupted"));
1367 else if (error)
1368 {
1369 ++no_wait_return;
1370 MSG(">>>>>>>>>>>>>");
1371 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1372 --no_wait_return;
1373 MSG(_("See \":help E312\" for more information."));
1374 MSG(">>>>>>>>>>>>>");
1375 }
1376 else
1377 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001378 if (curbuf->b_changed)
1379 {
1380 MSG(_("Recovery completed. You should check if everything is OK."));
1381 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1382 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1383 }
1384 else
1385 MSG(_("Recovery completed. Buffer contents equals file contents."));
1386 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001387 cmdline_row = msg_row;
1388 }
1389 redraw_curbuf_later(NOT_VALID);
1390
1391theend:
1392 recoverymode = FALSE;
1393 if (mfp != NULL)
1394 {
1395 if (hp != NULL)
1396 mf_put(mfp, hp, FALSE, FALSE);
1397 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1398 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001399 if (buf != NULL)
1400 {
1401 vim_free(buf->b_ml.ml_stack);
1402 vim_free(buf);
1403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001404 if (serious_error && called_from_main)
1405 ml_close(curbuf, TRUE);
1406#ifdef FEAT_AUTOCMD
1407 else
1408 {
1409 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1410 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1411 }
1412#endif
1413 return;
1414}
1415
1416/*
1417 * Find the names of swap files in current directory and the directory given
1418 * with the 'directory' option.
1419 *
1420 * Used to:
1421 * - list the swap files for "vim -r"
1422 * - count the number of swap files when recovering
1423 * - list the swap files when recovering
1424 * - find the name of the n'th swap file when recovering
1425 */
1426 int
1427recover_names(fname, list, nr)
1428 char_u **fname; /* base for swap file name */
1429 int list; /* when TRUE, list the swap file names */
1430 int nr; /* when non-zero, return nr'th swap file name */
1431{
1432 int num_names;
1433 char_u *(names[6]);
1434 char_u *tail;
1435 char_u *p;
1436 int num_files;
1437 int file_count = 0;
1438 char_u **files;
1439 int i;
1440 char_u *dirp;
1441 char_u *dir_name;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001442 char_u *fname_res = *fname;
1443#ifdef HAVE_READLINK
1444 char_u fname_buf[MAXPATHL];
1445
1446 /* Expand symlink in the file name, because the swap file is created with
1447 * the actual file instead of with the symlink. */
1448 if (resolve_symlink(*fname, fname_buf) == OK)
1449 fname_res = fname_buf;
1450#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001451
1452 if (list)
1453 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001454 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 msg((char_u *)_("Swap files found:"));
1456 msg_putchar('\n');
1457 }
1458
1459 /*
1460 * Do the loop for every directory in 'directory'.
1461 * First allocate some memory to put the directory name in.
1462 */
1463 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1464 dirp = p_dir;
1465 while (dir_name != NULL && *dirp)
1466 {
1467 /*
1468 * Isolate a directory name from *dirp and put it in dir_name (we know
1469 * it is large enough, so use 31000 for length).
1470 * Advance dirp to next directory name.
1471 */
1472 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1473
1474 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1475 {
1476 if (fname == NULL || *fname == NULL)
1477 {
1478#ifdef VMS
1479 names[0] = vim_strsave((char_u *)"*_sw%");
1480#else
1481# ifdef RISCOS
1482 names[0] = vim_strsave((char_u *)"*_sw#");
1483# else
1484 names[0] = vim_strsave((char_u *)"*.sw?");
1485# endif
1486#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001487#if defined(UNIX) || defined(WIN3264)
1488 /* For Unix names starting with a dot are special. MS-Windows
1489 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 names[1] = vim_strsave((char_u *)".*.sw?");
1491 names[2] = vim_strsave((char_u *)".sw?");
1492 num_names = 3;
1493#else
1494# ifdef VMS
1495 names[1] = vim_strsave((char_u *)".*_sw%");
1496 num_names = 2;
1497# else
1498 num_names = 1;
1499# endif
1500#endif
1501 }
1502 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001503 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 }
1505 else /* check directory dir_name */
1506 {
1507 if (fname == NULL || *fname == NULL)
1508 {
1509#ifdef VMS
1510 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1511#else
1512# ifdef RISCOS
1513 names[0] = concat_fnames(dir_name, (char_u *)"*_sw#", TRUE);
1514# else
1515 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
1516# endif
1517#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001518#if defined(UNIX) || defined(WIN3264)
1519 /* For Unix names starting with a dot are special. MS-Windows
1520 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001521 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1522 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1523 num_names = 3;
1524#else
1525# ifdef VMS
1526 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1527 num_names = 2;
1528# else
1529 num_names = 1;
1530# endif
1531#endif
1532 }
1533 else
1534 {
1535#if defined(UNIX) || defined(WIN3264)
1536 p = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001537 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 {
1539 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001540 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 }
1542 else
1543#endif
1544 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001545 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 tail = concat_fnames(dir_name, tail, TRUE);
1547 }
1548 if (tail == NULL)
1549 num_names = 0;
1550 else
1551 {
1552 num_names = recov_file_names(names, tail, FALSE);
1553 vim_free(tail);
1554 }
1555 }
1556 }
1557
1558 /* check for out-of-memory */
1559 for (i = 0; i < num_names; ++i)
1560 {
1561 if (names[i] == NULL)
1562 {
1563 for (i = 0; i < num_names; ++i)
1564 vim_free(names[i]);
1565 num_names = 0;
1566 }
1567 }
1568 if (num_names == 0)
1569 num_files = 0;
1570 else if (expand_wildcards(num_names, names, &num_files, &files,
1571 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1572 num_files = 0;
1573
1574 /*
1575 * When no swap file found, wildcard expansion might have failed (e.g.
1576 * not able to execute the shell).
1577 * Try finding a swap file by simply adding ".swp" to the file name.
1578 */
1579 if (*dirp == NUL && file_count + num_files == 0
1580 && fname != NULL && *fname != NULL)
1581 {
1582 struct stat st;
1583 char_u *swapname;
1584
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001585 swapname = modname(fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586#if defined(VMS) || defined(RISCOS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001587 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001589 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001591 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 if (swapname != NULL)
1593 {
1594 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1595 {
1596 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1597 if (files != NULL)
1598 {
1599 files[0] = swapname;
1600 swapname = NULL;
1601 num_files = 1;
1602 }
1603 }
1604 vim_free(swapname);
1605 }
1606 }
1607
1608 /*
1609 * remove swapfile name of the current buffer, it must be ignored
1610 */
1611 if (curbuf->b_ml.ml_mfp != NULL
1612 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1613 {
1614 for (i = 0; i < num_files; ++i)
1615 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1616 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001617 /* Remove the name from files[i]. Move further entries
1618 * down. When the array becomes empty free it here, since
1619 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001621 if (--num_files == 0)
1622 vim_free(files);
1623 else
1624 for ( ; i < num_files; ++i)
1625 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 }
1627 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001628 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629 {
1630 file_count += num_files;
1631 if (nr <= file_count)
1632 {
1633 *fname = vim_strsave(files[nr - 1 + num_files - file_count]);
1634 dirp = (char_u *)""; /* stop searching */
1635 }
1636 }
1637 else if (list)
1638 {
1639 if (dir_name[0] == '.' && dir_name[1] == NUL)
1640 {
1641 if (fname == NULL || *fname == NULL)
1642 MSG_PUTS(_(" In current directory:\n"));
1643 else
1644 MSG_PUTS(_(" Using specified name:\n"));
1645 }
1646 else
1647 {
1648 MSG_PUTS(_(" In directory "));
1649 msg_home_replace(dir_name);
1650 MSG_PUTS(":\n");
1651 }
1652
1653 if (num_files)
1654 {
1655 for (i = 0; i < num_files; ++i)
1656 {
1657 /* print the swap file name */
1658 msg_outnum((long)++file_count);
1659 MSG_PUTS(". ");
1660 msg_puts(gettail(files[i]));
1661 msg_putchar('\n');
1662 (void)swapfile_info(files[i]);
1663 }
1664 }
1665 else
1666 MSG_PUTS(_(" -- none --\n"));
1667 out_flush();
1668 }
1669 else
1670 file_count += num_files;
1671
1672 for (i = 0; i < num_names; ++i)
1673 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001674 if (num_files > 0)
1675 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 }
1677 vim_free(dir_name);
1678 return file_count;
1679}
1680
1681#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1682/*
1683 * Append the full path to name with path separators made into percent
1684 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1685 */
1686 static char_u *
1687make_percent_swname(dir, name)
1688 char_u *dir;
1689 char_u *name;
1690{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001691 char_u *d, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001692
1693 f = fix_fname(name != NULL ? name : (char_u *) "");
1694 d = NULL;
1695 if (f != NULL)
1696 {
1697 s = alloc((unsigned)(STRLEN(f) + 1));
1698 if (s != NULL)
1699 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001700 STRCPY(s, f);
1701 for (d = s; *d != NUL; mb_ptr_adv(d))
1702 if (vim_ispathsep(*d))
1703 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 d = concat_fnames(dir, s, TRUE);
1705 vim_free(s);
1706 }
1707 vim_free(f);
1708 }
1709 return d;
1710}
1711#endif
1712
1713#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
1714static int process_still_running;
1715#endif
1716
1717/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00001718 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 * Returns timestamp (0 when unknown).
1720 */
1721 static time_t
1722swapfile_info(fname)
1723 char_u *fname;
1724{
1725 struct stat st;
1726 int fd;
1727 struct block0 b0;
1728 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00001729 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730#ifdef UNIX
1731 char_u uname[B0_UNAME_SIZE];
1732#endif
1733
1734 /* print the swap file date */
1735 if (mch_stat((char *)fname, &st) != -1)
1736 {
1737#ifdef UNIX
1738 /* print name of owner of the file */
1739 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
1740 {
1741 MSG_PUTS(_(" owned by: "));
1742 msg_outtrans(uname);
1743 MSG_PUTS(_(" dated: "));
1744 }
1745 else
1746#endif
1747 MSG_PUTS(_(" dated: "));
1748 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00001749 p = ctime(&x); /* includes '\n' */
1750 if (p == NULL)
1751 MSG_PUTS("(invalid)\n");
1752 else
1753 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 }
1755
1756 /*
1757 * print the original file name
1758 */
1759 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
1760 if (fd >= 0)
1761 {
1762 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
1763 {
1764 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
1765 {
1766 MSG_PUTS(_(" [from Vim version 3.0]"));
1767 }
1768 else if (b0.b0_id[0] != BLOCK0_ID0 || b0.b0_id[1] != BLOCK0_ID1)
1769 {
1770 MSG_PUTS(_(" [does not look like a Vim swap file]"));
1771 }
1772 else
1773 {
1774 MSG_PUTS(_(" file name: "));
1775 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001776 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 else
1778 msg_outtrans(b0.b0_fname);
1779
1780 MSG_PUTS(_("\n modified: "));
1781 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
1782
1783 if (*(b0.b0_uname) != NUL)
1784 {
1785 MSG_PUTS(_("\n user name: "));
1786 msg_outtrans(b0.b0_uname);
1787 }
1788
1789 if (*(b0.b0_hname) != NUL)
1790 {
1791 if (*(b0.b0_uname) != NUL)
1792 MSG_PUTS(_(" host name: "));
1793 else
1794 MSG_PUTS(_("\n host name: "));
1795 msg_outtrans(b0.b0_hname);
1796 }
1797
1798 if (char_to_long(b0.b0_pid) != 0L)
1799 {
1800 MSG_PUTS(_("\n process ID: "));
1801 msg_outnum(char_to_long(b0.b0_pid));
1802#if defined(UNIX) || defined(__EMX__)
1803 /* EMX kill() not working correctly, it seems */
1804 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
1805 {
1806 MSG_PUTS(_(" (still running)"));
1807# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1808 process_still_running = TRUE;
1809# endif
1810 }
1811#endif
1812 }
1813
1814 if (b0_magic_wrong(&b0))
1815 {
1816#if defined(MSDOS) || defined(MSWIN)
1817 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
1818 MSG_PUTS(_("\n [not usable with this version of Vim]"));
1819 else
1820#endif
1821 MSG_PUTS(_("\n [not usable on this computer]"));
1822 }
1823 }
1824 }
1825 else
1826 MSG_PUTS(_(" [cannot be read]"));
1827 close(fd);
1828 }
1829 else
1830 MSG_PUTS(_(" [cannot be opened]"));
1831 msg_putchar('\n');
1832
1833 return x;
1834}
1835
1836 static int
1837recov_file_names(names, path, prepend_dot)
1838 char_u **names;
1839 char_u *path;
1840 int prepend_dot;
1841{
1842 int num_names;
1843
1844#ifdef SHORT_FNAME
1845 /*
1846 * (MS-DOS) always short names
1847 */
1848 names[0] = modname(path, (char_u *)".sw?", FALSE);
1849 num_names = 1;
1850#else /* !SHORT_FNAME */
1851 /*
1852 * (Win32 and Win64) never short names, but do prepend a dot.
1853 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
1854 * Only use the short name if it is different.
1855 */
1856 char_u *p;
1857 int i;
1858# ifndef WIN3264
1859 int shortname = curbuf->b_shortname;
1860
1861 curbuf->b_shortname = FALSE;
1862# endif
1863
1864 num_names = 0;
1865
1866 /*
1867 * May also add the file name with a dot prepended, for swap file in same
1868 * dir as original file.
1869 */
1870 if (prepend_dot)
1871 {
1872 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
1873 if (names[num_names] == NULL)
1874 goto end;
1875 ++num_names;
1876 }
1877
1878 /*
1879 * Form the normal swap file name pattern by appending ".sw?".
1880 */
1881#ifdef VMS
1882 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
1883#else
1884# ifdef RISCOS
1885 names[num_names] = concat_fnames(path, (char_u *)"_sw#", FALSE);
1886# else
1887 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
1888# endif
1889#endif
1890 if (names[num_names] == NULL)
1891 goto end;
1892 if (num_names >= 1) /* check if we have the same name twice */
1893 {
1894 p = names[num_names - 1];
1895 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
1896 if (i > 0)
1897 p += i; /* file name has been expanded to full path */
1898
1899 if (STRCMP(p, names[num_names]) != 0)
1900 ++num_names;
1901 else
1902 vim_free(names[num_names]);
1903 }
1904 else
1905 ++num_names;
1906
1907# ifndef WIN3264
1908 /*
1909 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
1910 */
1911 curbuf->b_shortname = TRUE;
1912#ifdef VMS
1913 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
1914#else
1915# ifdef RISCOS
1916 names[num_names] = modname(path, (char_u *)"_sw#", FALSE);
1917# else
1918 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
1919# endif
1920#endif
1921 if (names[num_names] == NULL)
1922 goto end;
1923
1924 /*
1925 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
1926 */
1927 p = names[num_names];
1928 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
1929 if (i > 0)
1930 p += i; /* file name has been expanded to full path */
1931 if (STRCMP(names[num_names - 1], p) == 0)
1932 vim_free(names[num_names]);
1933 else
1934 ++num_names;
1935# endif
1936
1937end:
1938# ifndef WIN3264
1939 curbuf->b_shortname = shortname;
1940# endif
1941
1942#endif /* !SHORT_FNAME */
1943
1944 return num_names;
1945}
1946
1947/*
1948 * sync all memlines
1949 *
1950 * If 'check_file' is TRUE, check if original file exists and was not changed.
1951 * If 'check_char' is TRUE, stop syncing when character becomes available, but
1952 * always sync at least one block.
1953 */
1954 void
1955ml_sync_all(check_file, check_char)
1956 int check_file;
1957 int check_char;
1958{
1959 buf_T *buf;
1960 struct stat st;
1961
1962 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1963 {
1964 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
1965 continue; /* no file */
1966
1967 ml_flush_line(buf); /* flush buffered line */
1968 /* flush locked block */
1969 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
1970 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
1971 && buf->b_ffname != NULL)
1972 {
1973 /*
1974 * If the original file does not exist anymore or has been changed
1975 * call ml_preserve() to get rid of all negative numbered blocks.
1976 */
1977 if (mch_stat((char *)buf->b_ffname, &st) == -1
1978 || st.st_mtime != buf->b_mtime_read
1979 || (size_t)st.st_size != buf->b_orig_size)
1980 {
1981 ml_preserve(buf, FALSE);
1982 did_check_timestamps = FALSE;
1983 need_check_timestamps = TRUE; /* give message later */
1984 }
1985 }
1986 if (buf->b_ml.ml_mfp->mf_dirty)
1987 {
1988 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
1989 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
1990 if (check_char && ui_char_avail()) /* character available now */
1991 break;
1992 }
1993 }
1994}
1995
1996/*
1997 * sync one buffer, including negative blocks
1998 *
1999 * after this all the blocks are in the swap file
2000 *
2001 * Used for the :preserve command and when the original file has been
2002 * changed or deleted.
2003 *
2004 * when message is TRUE the success of preserving is reported
2005 */
2006 void
2007ml_preserve(buf, message)
2008 buf_T *buf;
2009 int message;
2010{
2011 bhdr_T *hp;
2012 linenr_T lnum;
2013 memfile_T *mfp = buf->b_ml.ml_mfp;
2014 int status;
2015 int got_int_save = got_int;
2016
2017 if (mfp == NULL || mfp->mf_fname == NULL)
2018 {
2019 if (message)
2020 EMSG(_("E313: Cannot preserve, there is no swap file"));
2021 return;
2022 }
2023
2024 /* We only want to stop when interrupted here, not when interrupted
2025 * before. */
2026 got_int = FALSE;
2027
2028 ml_flush_line(buf); /* flush buffered line */
2029 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2030 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2031
2032 /* stack is invalid after mf_sync(.., MFS_ALL) */
2033 buf->b_ml.ml_stack_top = 0;
2034
2035 /*
2036 * Some of the data blocks may have been changed from negative to
2037 * positive block number. In that case the pointer blocks need to be
2038 * updated.
2039 *
2040 * We don't know in which pointer block the references are, so we visit
2041 * all data blocks until there are no more translations to be done (or
2042 * we hit the end of the file, which can only happen in case a write fails,
2043 * e.g. when file system if full).
2044 * ml_find_line() does the work by translating the negative block numbers
2045 * when getting the first line of each data block.
2046 */
2047 if (mf_need_trans(mfp) && !got_int)
2048 {
2049 lnum = 1;
2050 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2051 {
2052 hp = ml_find_line(buf, lnum, ML_FIND);
2053 if (hp == NULL)
2054 {
2055 status = FAIL;
2056 goto theend;
2057 }
2058 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2059 lnum = buf->b_ml.ml_locked_high + 1;
2060 }
2061 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2062 /* sync the updated pointer blocks */
2063 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2064 status = FAIL;
2065 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2066 }
2067theend:
2068 got_int |= got_int_save;
2069
2070 if (message)
2071 {
2072 if (status == OK)
2073 MSG(_("File preserved"));
2074 else
2075 EMSG(_("E314: Preserve failed"));
2076 }
2077}
2078
2079/*
2080 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2081 * until the next call!
2082 * line1 = ml_get(1);
2083 * line2 = ml_get(2); // line1 is now invalid!
2084 * Make a copy of the line if necessary.
2085 */
2086/*
2087 * get a pointer to a (read-only copy of a) line
2088 *
2089 * On failure an error message is given and IObuff is returned (to avoid
2090 * having to check for error everywhere).
2091 */
2092 char_u *
2093ml_get(lnum)
2094 linenr_T lnum;
2095{
2096 return ml_get_buf(curbuf, lnum, FALSE);
2097}
2098
2099/*
2100 * ml_get_pos: get pointer to position 'pos'
2101 */
2102 char_u *
2103ml_get_pos(pos)
2104 pos_T *pos;
2105{
2106 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2107}
2108
2109/*
2110 * ml_get_curline: get pointer to cursor line.
2111 */
2112 char_u *
2113ml_get_curline()
2114{
2115 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2116}
2117
2118/*
2119 * ml_get_cursor: get pointer to cursor position
2120 */
2121 char_u *
2122ml_get_cursor()
2123{
2124 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2125 curwin->w_cursor.col);
2126}
2127
2128/*
2129 * get a pointer to a line in a specific buffer
2130 *
2131 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2132 * changed)
2133 */
2134 char_u *
2135ml_get_buf(buf, lnum, will_change)
2136 buf_T *buf;
2137 linenr_T lnum;
2138 int will_change; /* line will be changed */
2139{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002140 bhdr_T *hp;
2141 DATA_BL *dp;
2142 char_u *ptr;
2143 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144
2145 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2146 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002147 if (recursive == 0)
2148 {
2149 /* Avoid giving this message for a recursive call, may happen when
2150 * the GUI redraws part of the text. */
2151 ++recursive;
2152 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2153 --recursive;
2154 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155errorret:
2156 STRCPY(IObuff, "???");
2157 return IObuff;
2158 }
2159 if (lnum <= 0) /* pretend line 0 is line 1 */
2160 lnum = 1;
2161
2162 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2163 return (char_u *)"";
2164
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002165 /*
2166 * See if it is the same line as requested last time.
2167 * Otherwise may need to flush last used line.
2168 * Don't use the last used line when 'swapfile' is reset, need to load all
2169 * blocks.
2170 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002171 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002172 {
2173 ml_flush_line(buf);
2174
2175 /*
2176 * Find the data block containing the line.
2177 * This also fills the stack with the blocks from the root to the data
2178 * block and releases any locked block.
2179 */
2180 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2181 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002182 if (recursive == 0)
2183 {
2184 /* Avoid giving this message for a recursive call, may happen
2185 * when the GUI redraws part of the text. */
2186 ++recursive;
2187 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2188 --recursive;
2189 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 goto errorret;
2191 }
2192
2193 dp = (DATA_BL *)(hp->bh_data);
2194
2195 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2196 buf->b_ml.ml_line_ptr = ptr;
2197 buf->b_ml.ml_line_lnum = lnum;
2198 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2199 }
2200 if (will_change)
2201 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2202
2203 return buf->b_ml.ml_line_ptr;
2204}
2205
2206/*
2207 * Check if a line that was just obtained by a call to ml_get
2208 * is in allocated memory.
2209 */
2210 int
2211ml_line_alloced()
2212{
2213 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2214}
2215
2216/*
2217 * Append a line after lnum (may be 0 to insert a line in front of the file).
2218 * "line" does not need to be allocated, but can't be another line in a
2219 * buffer, unlocking may make it invalid.
2220 *
2221 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2222 * will be set for recovery
2223 * Check: The caller of this function should probably also call
2224 * appended_lines().
2225 *
2226 * return FAIL for failure, OK otherwise
2227 */
2228 int
2229ml_append(lnum, line, len, newfile)
2230 linenr_T lnum; /* append after this line (can be 0) */
2231 char_u *line; /* text of the new line */
2232 colnr_T len; /* length of new line, including NUL, or 0 */
2233 int newfile; /* flag, see above */
2234{
2235 /* When starting up, we might still need to create the memfile */
2236 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL) == FAIL)
2237 return FAIL;
2238
2239 if (curbuf->b_ml.ml_line_lnum != 0)
2240 ml_flush_line(curbuf);
2241 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2242}
2243
Bram Moolenaara1956f62006-03-12 22:18:00 +00002244#if defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002245/*
2246 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2247 * a memline.
2248 */
2249 int
2250ml_append_buf(buf, lnum, line, len, newfile)
2251 buf_T *buf;
2252 linenr_T lnum; /* append after this line (can be 0) */
2253 char_u *line; /* text of the new line */
2254 colnr_T len; /* length of new line, including NUL, or 0 */
2255 int newfile; /* flag, see above */
2256{
2257 if (buf->b_ml.ml_mfp == NULL)
2258 return FAIL;
2259
2260 if (buf->b_ml.ml_line_lnum != 0)
2261 ml_flush_line(buf);
2262 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2263}
2264#endif
2265
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266 static int
2267ml_append_int(buf, lnum, line, len, newfile, mark)
2268 buf_T *buf;
2269 linenr_T lnum; /* append after this line (can be 0) */
2270 char_u *line; /* text of the new line */
2271 colnr_T len; /* length of line, including NUL, or 0 */
2272 int newfile; /* flag, see above */
2273 int mark; /* mark the new line */
2274{
2275 int i;
2276 int line_count; /* number of indexes in current block */
2277 int offset;
2278 int from, to;
2279 int space_needed; /* space needed for new line */
2280 int page_size;
2281 int page_count;
2282 int db_idx; /* index for lnum in data block */
2283 bhdr_T *hp;
2284 memfile_T *mfp;
2285 DATA_BL *dp;
2286 PTR_BL *pp;
2287 infoptr_T *ip;
2288
2289 /* lnum out of range */
2290 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2291 return FAIL;
2292
2293 if (lowest_marked && lowest_marked > lnum)
2294 lowest_marked = lnum + 1;
2295
2296 if (len == 0)
2297 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2298 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2299
2300 mfp = buf->b_ml.ml_mfp;
2301 page_size = mfp->mf_page_size;
2302
2303/*
2304 * find the data block containing the previous line
2305 * This also fills the stack with the blocks from the root to the data block
2306 * This also releases any locked block.
2307 */
2308 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2309 ML_INSERT)) == NULL)
2310 return FAIL;
2311
2312 buf->b_ml.ml_flags &= ~ML_EMPTY;
2313
2314 if (lnum == 0) /* got line one instead, correct db_idx */
2315 db_idx = -1; /* careful, it is negative! */
2316 else
2317 db_idx = lnum - buf->b_ml.ml_locked_low;
2318 /* get line count before the insertion */
2319 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2320
2321 dp = (DATA_BL *)(hp->bh_data);
2322
2323/*
2324 * If
2325 * - there is not enough room in the current block
2326 * - appending to the last line in the block
2327 * - not appending to the last line in the file
2328 * insert in front of the next block.
2329 */
2330 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2331 && lnum < buf->b_ml.ml_line_count)
2332 {
2333 /*
2334 * Now that the line is not going to be inserted in the block that we
2335 * expected, the line count has to be adjusted in the pointer blocks
2336 * by using ml_locked_lineadd.
2337 */
2338 --(buf->b_ml.ml_locked_lineadd);
2339 --(buf->b_ml.ml_locked_high);
2340 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2341 return FAIL;
2342
2343 db_idx = -1; /* careful, it is negative! */
2344 /* get line count before the insertion */
2345 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2346 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2347
2348 dp = (DATA_BL *)(hp->bh_data);
2349 }
2350
2351 ++buf->b_ml.ml_line_count;
2352
2353 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2354 {
2355/*
2356 * Insert new line in existing data block, or in data block allocated above.
2357 */
2358 dp->db_txt_start -= len;
2359 dp->db_free -= space_needed;
2360 ++(dp->db_line_count);
2361
2362 /*
2363 * move the text of the lines that follow to the front
2364 * adjust the indexes of the lines that follow
2365 */
2366 if (line_count > db_idx + 1) /* if there are following lines */
2367 {
2368 /*
2369 * Offset is the start of the previous line.
2370 * This will become the character just after the new line.
2371 */
2372 if (db_idx < 0)
2373 offset = dp->db_txt_end;
2374 else
2375 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2376 mch_memmove((char *)dp + dp->db_txt_start,
2377 (char *)dp + dp->db_txt_start + len,
2378 (size_t)(offset - (dp->db_txt_start + len)));
2379 for (i = line_count - 1; i > db_idx; --i)
2380 dp->db_index[i + 1] = dp->db_index[i] - len;
2381 dp->db_index[db_idx + 1] = offset - len;
2382 }
2383 else /* add line at the end */
2384 dp->db_index[db_idx + 1] = dp->db_txt_start;
2385
2386 /*
2387 * copy the text into the block
2388 */
2389 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2390 if (mark)
2391 dp->db_index[db_idx + 1] |= DB_MARKED;
2392
2393 /*
2394 * Mark the block dirty.
2395 */
2396 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2397 if (!newfile)
2398 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2399 }
2400 else /* not enough space in data block */
2401 {
2402/*
2403 * If there is not enough room we have to create a new data block and copy some
2404 * lines into it.
2405 * Then we have to insert an entry in the pointer block.
2406 * If this pointer block also is full, we go up another block, and so on, up
2407 * to the root if necessary.
2408 * The line counts in the pointer blocks have already been adjusted by
2409 * ml_find_line().
2410 */
2411 long line_count_left, line_count_right;
2412 int page_count_left, page_count_right;
2413 bhdr_T *hp_left;
2414 bhdr_T *hp_right;
2415 bhdr_T *hp_new;
2416 int lines_moved;
2417 int data_moved = 0; /* init to shut up gcc */
2418 int total_moved = 0; /* init to shut up gcc */
2419 DATA_BL *dp_right, *dp_left;
2420 int stack_idx;
2421 int in_left;
2422 int lineadd;
2423 blocknr_T bnum_left, bnum_right;
2424 linenr_T lnum_left, lnum_right;
2425 int pb_idx;
2426 PTR_BL *pp_new;
2427
2428 /*
2429 * We are going to allocate a new data block. Depending on the
2430 * situation it will be put to the left or right of the existing
2431 * block. If possible we put the new line in the left block and move
2432 * the lines after it to the right block. Otherwise the new line is
2433 * also put in the right block. This method is more efficient when
2434 * inserting a lot of lines at one place.
2435 */
2436 if (db_idx < 0) /* left block is new, right block is existing */
2437 {
2438 lines_moved = 0;
2439 in_left = TRUE;
2440 /* space_needed does not change */
2441 }
2442 else /* left block is existing, right block is new */
2443 {
2444 lines_moved = line_count - db_idx - 1;
2445 if (lines_moved == 0)
2446 in_left = FALSE; /* put new line in right block */
2447 /* space_needed does not change */
2448 else
2449 {
2450 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2451 dp->db_txt_start;
2452 total_moved = data_moved + lines_moved * INDEX_SIZE;
2453 if ((int)dp->db_free + total_moved >= space_needed)
2454 {
2455 in_left = TRUE; /* put new line in left block */
2456 space_needed = total_moved;
2457 }
2458 else
2459 {
2460 in_left = FALSE; /* put new line in right block */
2461 space_needed += total_moved;
2462 }
2463 }
2464 }
2465
2466 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2467 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2468 {
2469 /* correct line counts in pointer blocks */
2470 --(buf->b_ml.ml_locked_lineadd);
2471 --(buf->b_ml.ml_locked_high);
2472 return FAIL;
2473 }
2474 if (db_idx < 0) /* left block is new */
2475 {
2476 hp_left = hp_new;
2477 hp_right = hp;
2478 line_count_left = 0;
2479 line_count_right = line_count;
2480 }
2481 else /* right block is new */
2482 {
2483 hp_left = hp;
2484 hp_right = hp_new;
2485 line_count_left = line_count;
2486 line_count_right = 0;
2487 }
2488 dp_right = (DATA_BL *)(hp_right->bh_data);
2489 dp_left = (DATA_BL *)(hp_left->bh_data);
2490 bnum_left = hp_left->bh_bnum;
2491 bnum_right = hp_right->bh_bnum;
2492 page_count_left = hp_left->bh_page_count;
2493 page_count_right = hp_right->bh_page_count;
2494
2495 /*
2496 * May move the new line into the right/new block.
2497 */
2498 if (!in_left)
2499 {
2500 dp_right->db_txt_start -= len;
2501 dp_right->db_free -= len + INDEX_SIZE;
2502 dp_right->db_index[0] = dp_right->db_txt_start;
2503 if (mark)
2504 dp_right->db_index[0] |= DB_MARKED;
2505
2506 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2507 line, (size_t)len);
2508 ++line_count_right;
2509 }
2510 /*
2511 * may move lines from the left/old block to the right/new one.
2512 */
2513 if (lines_moved)
2514 {
2515 /*
2516 */
2517 dp_right->db_txt_start -= data_moved;
2518 dp_right->db_free -= total_moved;
2519 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2520 (char *)dp_left + dp_left->db_txt_start,
2521 (size_t)data_moved);
2522 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2523 dp_left->db_txt_start += data_moved;
2524 dp_left->db_free += total_moved;
2525
2526 /*
2527 * update indexes in the new block
2528 */
2529 for (to = line_count_right, from = db_idx + 1;
2530 from < line_count_left; ++from, ++to)
2531 dp_right->db_index[to] = dp->db_index[from] + offset;
2532 line_count_right += lines_moved;
2533 line_count_left -= lines_moved;
2534 }
2535
2536 /*
2537 * May move the new line into the left (old or new) block.
2538 */
2539 if (in_left)
2540 {
2541 dp_left->db_txt_start -= len;
2542 dp_left->db_free -= len + INDEX_SIZE;
2543 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2544 if (mark)
2545 dp_left->db_index[line_count_left] |= DB_MARKED;
2546 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2547 line, (size_t)len);
2548 ++line_count_left;
2549 }
2550
2551 if (db_idx < 0) /* left block is new */
2552 {
2553 lnum_left = lnum + 1;
2554 lnum_right = 0;
2555 }
2556 else /* right block is new */
2557 {
2558 lnum_left = 0;
2559 if (in_left)
2560 lnum_right = lnum + 2;
2561 else
2562 lnum_right = lnum + 1;
2563 }
2564 dp_left->db_line_count = line_count_left;
2565 dp_right->db_line_count = line_count_right;
2566
2567 /*
2568 * release the two data blocks
2569 * The new one (hp_new) already has a correct blocknumber.
2570 * The old one (hp, in ml_locked) gets a positive blocknumber if
2571 * we changed it and we are not editing a new file.
2572 */
2573 if (lines_moved || in_left)
2574 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2575 if (!newfile && db_idx >= 0 && in_left)
2576 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2577 mf_put(mfp, hp_new, TRUE, FALSE);
2578
2579 /*
2580 * flush the old data block
2581 * set ml_locked_lineadd to 0, because the updating of the
2582 * pointer blocks is done below
2583 */
2584 lineadd = buf->b_ml.ml_locked_lineadd;
2585 buf->b_ml.ml_locked_lineadd = 0;
2586 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2587
2588 /*
2589 * update pointer blocks for the new data block
2590 */
2591 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2592 --stack_idx)
2593 {
2594 ip = &(buf->b_ml.ml_stack[stack_idx]);
2595 pb_idx = ip->ip_index;
2596 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2597 return FAIL;
2598 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2599 if (pp->pb_id != PTR_ID)
2600 {
2601 EMSG(_("E317: pointer block id wrong 3"));
2602 mf_put(mfp, hp, FALSE, FALSE);
2603 return FAIL;
2604 }
2605 /*
2606 * TODO: If the pointer block is full and we are adding at the end
2607 * try to insert in front of the next block
2608 */
2609 /* block not full, add one entry */
2610 if (pp->pb_count < pp->pb_count_max)
2611 {
2612 if (pb_idx + 1 < (int)pp->pb_count)
2613 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2614 &pp->pb_pointer[pb_idx + 1],
2615 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2616 ++pp->pb_count;
2617 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2618 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2619 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2620 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2621 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2622 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2623
2624 if (lnum_left != 0)
2625 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2626 if (lnum_right != 0)
2627 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2628
2629 mf_put(mfp, hp, TRUE, FALSE);
2630 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2631
2632 if (lineadd)
2633 {
2634 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002635 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636 ml_lineadd(buf, lineadd);
2637 /* fix stack itself */
2638 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2639 lineadd;
2640 ++(buf->b_ml.ml_stack_top);
2641 }
2642
2643 /*
2644 * We are finished, break the loop here.
2645 */
2646 break;
2647 }
2648 else /* pointer block full */
2649 {
2650 /*
2651 * split the pointer block
2652 * allocate a new pointer block
2653 * move some of the pointer into the new block
2654 * prepare for updating the parent block
2655 */
2656 for (;;) /* do this twice when splitting block 1 */
2657 {
2658 hp_new = ml_new_ptr(mfp);
2659 if (hp_new == NULL) /* TODO: try to fix tree */
2660 return FAIL;
2661 pp_new = (PTR_BL *)(hp_new->bh_data);
2662
2663 if (hp->bh_bnum != 1)
2664 break;
2665
2666 /*
2667 * if block 1 becomes full the tree is given an extra level
2668 * The pointers from block 1 are moved into the new block.
2669 * block 1 is updated to point to the new block
2670 * then continue to split the new block
2671 */
2672 mch_memmove(pp_new, pp, (size_t)page_size);
2673 pp->pb_count = 1;
2674 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2675 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2676 pp->pb_pointer[0].pe_old_lnum = 1;
2677 pp->pb_pointer[0].pe_page_count = 1;
2678 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2679 hp = hp_new; /* new block is to be split */
2680 pp = pp_new;
2681 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2682 ip->ip_index = 0;
2683 ++stack_idx; /* do block 1 again later */
2684 }
2685 /*
2686 * move the pointers after the current one to the new block
2687 * If there are none, the new entry will be in the new block.
2688 */
2689 total_moved = pp->pb_count - pb_idx - 1;
2690 if (total_moved)
2691 {
2692 mch_memmove(&pp_new->pb_pointer[0],
2693 &pp->pb_pointer[pb_idx + 1],
2694 (size_t)(total_moved) * sizeof(PTR_EN));
2695 pp_new->pb_count = total_moved;
2696 pp->pb_count -= total_moved - 1;
2697 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2698 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2699 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2700 if (lnum_right)
2701 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2702 }
2703 else
2704 {
2705 pp_new->pb_count = 1;
2706 pp_new->pb_pointer[0].pe_bnum = bnum_right;
2707 pp_new->pb_pointer[0].pe_line_count = line_count_right;
2708 pp_new->pb_pointer[0].pe_page_count = page_count_right;
2709 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
2710 }
2711 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2712 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2713 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2714 if (lnum_left)
2715 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2716 lnum_left = 0;
2717 lnum_right = 0;
2718
2719 /*
2720 * recompute line counts
2721 */
2722 line_count_right = 0;
2723 for (i = 0; i < (int)pp_new->pb_count; ++i)
2724 line_count_right += pp_new->pb_pointer[i].pe_line_count;
2725 line_count_left = 0;
2726 for (i = 0; i < (int)pp->pb_count; ++i)
2727 line_count_left += pp->pb_pointer[i].pe_line_count;
2728
2729 bnum_left = hp->bh_bnum;
2730 bnum_right = hp_new->bh_bnum;
2731 page_count_left = 1;
2732 page_count_right = 1;
2733 mf_put(mfp, hp, TRUE, FALSE);
2734 mf_put(mfp, hp_new, TRUE, FALSE);
2735 }
2736 }
2737
2738 /*
2739 * Safety check: fallen out of for loop?
2740 */
2741 if (stack_idx < 0)
2742 {
2743 EMSG(_("E318: Updated too many blocks?"));
2744 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
2745 }
2746 }
2747
2748#ifdef FEAT_BYTEOFF
2749 /* The line was inserted below 'lnum' */
2750 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
2751#endif
2752#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002753 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 {
2755 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002756 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00002757 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002758 (char_u *)"\n", 1);
2759 }
2760#endif
2761 return OK;
2762}
2763
2764/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00002765 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00002767 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768 * copied to allocated memory already.
2769 *
2770 * Check: The caller of this function should probably also call
2771 * changed_lines(), unless update_screen(NOT_VALID) is used.
2772 *
2773 * return FAIL for failure, OK otherwise
2774 */
2775 int
2776ml_replace(lnum, line, copy)
2777 linenr_T lnum;
2778 char_u *line;
2779 int copy;
2780{
2781 if (line == NULL) /* just checking... */
2782 return FAIL;
2783
2784 /* When starting up, we might still need to create the memfile */
2785 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL) == FAIL)
2786 return FAIL;
2787
2788 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
2789 return FAIL;
2790#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002791 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 {
2793 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002794 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 }
2796#endif
2797 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
2798 ml_flush_line(curbuf); /* flush it */
2799 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
2800 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
2801 curbuf->b_ml.ml_line_ptr = line;
2802 curbuf->b_ml.ml_line_lnum = lnum;
2803 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
2804
2805 return OK;
2806}
2807
2808/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00002809 * Delete line 'lnum' in the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 *
2811 * Check: The caller of this function should probably also call
2812 * deleted_lines() after this.
2813 *
2814 * return FAIL for failure, OK otherwise
2815 */
2816 int
2817ml_delete(lnum, message)
2818 linenr_T lnum;
2819 int message;
2820{
2821 ml_flush_line(curbuf);
2822 return ml_delete_int(curbuf, lnum, message);
2823}
2824
2825 static int
2826ml_delete_int(buf, lnum, message)
2827 buf_T *buf;
2828 linenr_T lnum;
2829 int message;
2830{
2831 bhdr_T *hp;
2832 memfile_T *mfp;
2833 DATA_BL *dp;
2834 PTR_BL *pp;
2835 infoptr_T *ip;
2836 int count; /* number of entries in block */
2837 int idx;
2838 int stack_idx;
2839 int text_start;
2840 int line_start;
2841 long line_size;
2842 int i;
2843
2844 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
2845 return FAIL;
2846
2847 if (lowest_marked && lowest_marked > lnum)
2848 lowest_marked--;
2849
2850/*
2851 * If the file becomes empty the last line is replaced by an empty line.
2852 */
2853 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
2854 {
2855 if (message
2856#ifdef FEAT_NETBEANS_INTG
2857 && !netbeansSuppressNoLines
2858#endif
2859 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00002860 set_keep_msg((char_u *)_(no_lines_msg), 0);
2861
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
2863 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
2864 buf->b_ml.ml_flags |= ML_EMPTY;
2865
2866 return i;
2867 }
2868
2869/*
2870 * find the data block containing the line
2871 * This also fills the stack with the blocks from the root to the data block
2872 * This also releases any locked block.
2873 */
2874 mfp = buf->b_ml.ml_mfp;
2875 if (mfp == NULL)
2876 return FAIL;
2877
2878 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
2879 return FAIL;
2880
2881 dp = (DATA_BL *)(hp->bh_data);
2882 /* compute line count before the delete */
2883 count = (long)(buf->b_ml.ml_locked_high)
2884 - (long)(buf->b_ml.ml_locked_low) + 2;
2885 idx = lnum - buf->b_ml.ml_locked_low;
2886
2887 --buf->b_ml.ml_line_count;
2888
2889 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
2890 if (idx == 0) /* first line in block, text at the end */
2891 line_size = dp->db_txt_end - line_start;
2892 else
2893 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
2894
2895#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002896 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00002897 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898#endif
2899
2900/*
2901 * special case: If there is only one line in the data block it becomes empty.
2902 * Then we have to remove the entry, pointing to this data block, from the
2903 * pointer block. If this pointer block also becomes empty, we go up another
2904 * block, and so on, up to the root if necessary.
2905 * The line counts in the pointer blocks have already been adjusted by
2906 * ml_find_line().
2907 */
2908 if (count == 1)
2909 {
2910 mf_free(mfp, hp); /* free the data block */
2911 buf->b_ml.ml_locked = NULL;
2912
2913 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx)
2914 {
2915 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
2916 ip = &(buf->b_ml.ml_stack[stack_idx]);
2917 idx = ip->ip_index;
2918 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2919 return FAIL;
2920 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2921 if (pp->pb_id != PTR_ID)
2922 {
2923 EMSG(_("E317: pointer block id wrong 4"));
2924 mf_put(mfp, hp, FALSE, FALSE);
2925 return FAIL;
2926 }
2927 count = --(pp->pb_count);
2928 if (count == 0) /* the pointer block becomes empty! */
2929 mf_free(mfp, hp);
2930 else
2931 {
2932 if (count != idx) /* move entries after the deleted one */
2933 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
2934 (size_t)(count - idx) * sizeof(PTR_EN));
2935 mf_put(mfp, hp, TRUE, FALSE);
2936
2937 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002938 /* fix line count for rest of blocks in the stack */
2939 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 {
2941 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
2942 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002943 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 }
2945 ++(buf->b_ml.ml_stack_top);
2946
2947 break;
2948 }
2949 }
2950 CHECK(stack_idx < 0, _("deleted block 1?"));
2951 }
2952 else
2953 {
2954 /*
2955 * delete the text by moving the next lines forwards
2956 */
2957 text_start = dp->db_txt_start;
2958 mch_memmove((char *)dp + text_start + line_size,
2959 (char *)dp + text_start, (size_t)(line_start - text_start));
2960
2961 /*
2962 * delete the index by moving the next indexes backwards
2963 * Adjust the indexes for the text movement.
2964 */
2965 for (i = idx; i < count - 1; ++i)
2966 dp->db_index[i] = dp->db_index[i + 1] + line_size;
2967
2968 dp->db_free += line_size + INDEX_SIZE;
2969 dp->db_txt_start += line_size;
2970 --(dp->db_line_count);
2971
2972 /*
2973 * mark the block dirty and make sure it is in the file (for recovery)
2974 */
2975 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2976 }
2977
2978#ifdef FEAT_BYTEOFF
2979 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
2980#endif
2981 return OK;
2982}
2983
2984/*
2985 * set the B_MARKED flag for line 'lnum'
2986 */
2987 void
2988ml_setmarked(lnum)
2989 linenr_T lnum;
2990{
2991 bhdr_T *hp;
2992 DATA_BL *dp;
2993 /* invalid line number */
2994 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
2995 || curbuf->b_ml.ml_mfp == NULL)
2996 return; /* give error message? */
2997
2998 if (lowest_marked == 0 || lowest_marked > lnum)
2999 lowest_marked = lnum;
3000
3001 /*
3002 * find the data block containing the line
3003 * This also fills the stack with the blocks from the root to the data block
3004 * This also releases any locked block.
3005 */
3006 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3007 return; /* give error message? */
3008
3009 dp = (DATA_BL *)(hp->bh_data);
3010 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3011 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3012}
3013
3014/*
3015 * find the first line with its B_MARKED flag set
3016 */
3017 linenr_T
3018ml_firstmarked()
3019{
3020 bhdr_T *hp;
3021 DATA_BL *dp;
3022 linenr_T lnum;
3023 int i;
3024
3025 if (curbuf->b_ml.ml_mfp == NULL)
3026 return (linenr_T) 0;
3027
3028 /*
3029 * The search starts with lowest_marked line. This is the last line where
3030 * a mark was found, adjusted by inserting/deleting lines.
3031 */
3032 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3033 {
3034 /*
3035 * Find the data block containing the line.
3036 * This also fills the stack with the blocks from the root to the data
3037 * block This also releases any locked block.
3038 */
3039 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3040 return (linenr_T)0; /* give error message? */
3041
3042 dp = (DATA_BL *)(hp->bh_data);
3043
3044 for (i = lnum - curbuf->b_ml.ml_locked_low;
3045 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3046 if ((dp->db_index[i]) & DB_MARKED)
3047 {
3048 (dp->db_index[i]) &= DB_INDEX_MASK;
3049 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3050 lowest_marked = lnum + 1;
3051 return lnum;
3052 }
3053 }
3054
3055 return (linenr_T) 0;
3056}
3057
3058#if 0 /* not used */
3059/*
3060 * return TRUE if line 'lnum' has a mark
3061 */
3062 int
3063ml_has_mark(lnum)
3064 linenr_T lnum;
3065{
3066 bhdr_T *hp;
3067 DATA_BL *dp;
3068
3069 if (curbuf->b_ml.ml_mfp == NULL
3070 || (hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3071 return FALSE;
3072
3073 dp = (DATA_BL *)(hp->bh_data);
3074 return (int)((dp->db_index[lnum - curbuf->b_ml.ml_locked_low]) & DB_MARKED);
3075}
3076#endif
3077
3078/*
3079 * clear all DB_MARKED flags
3080 */
3081 void
3082ml_clearmarked()
3083{
3084 bhdr_T *hp;
3085 DATA_BL *dp;
3086 linenr_T lnum;
3087 int i;
3088
3089 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3090 return;
3091
3092 /*
3093 * The search starts with line lowest_marked.
3094 */
3095 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3096 {
3097 /*
3098 * Find the data block containing the line.
3099 * This also fills the stack with the blocks from the root to the data
3100 * block and releases any locked block.
3101 */
3102 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3103 return; /* give error message? */
3104
3105 dp = (DATA_BL *)(hp->bh_data);
3106
3107 for (i = lnum - curbuf->b_ml.ml_locked_low;
3108 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3109 if ((dp->db_index[i]) & DB_MARKED)
3110 {
3111 (dp->db_index[i]) &= DB_INDEX_MASK;
3112 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3113 }
3114 }
3115
3116 lowest_marked = 0;
3117 return;
3118}
3119
3120/*
3121 * flush ml_line if necessary
3122 */
3123 static void
3124ml_flush_line(buf)
3125 buf_T *buf;
3126{
3127 bhdr_T *hp;
3128 DATA_BL *dp;
3129 linenr_T lnum;
3130 char_u *new_line;
3131 char_u *old_line;
3132 colnr_T new_len;
3133 int old_len;
3134 int extra;
3135 int idx;
3136 int start;
3137 int count;
3138 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003139 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140
3141 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3142 return; /* nothing to do */
3143
3144 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3145 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003146 /* This code doesn't work recursively, but Netbeans may call back here
3147 * when obtaining the cursor position. */
3148 if (entered)
3149 return;
3150 entered = TRUE;
3151
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152 lnum = buf->b_ml.ml_line_lnum;
3153 new_line = buf->b_ml.ml_line_ptr;
3154
3155 hp = ml_find_line(buf, lnum, ML_FIND);
3156 if (hp == NULL)
3157 EMSGN(_("E320: Cannot find line %ld"), lnum);
3158 else
3159 {
3160 dp = (DATA_BL *)(hp->bh_data);
3161 idx = lnum - buf->b_ml.ml_locked_low;
3162 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3163 old_line = (char_u *)dp + start;
3164 if (idx == 0) /* line is last in block */
3165 old_len = dp->db_txt_end - start;
3166 else /* text of previous line follows */
3167 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3168 new_len = (colnr_T)STRLEN(new_line) + 1;
3169 extra = new_len - old_len; /* negative if lines gets smaller */
3170
3171 /*
3172 * if new line fits in data block, replace directly
3173 */
3174 if ((int)dp->db_free >= extra)
3175 {
3176 /* if the length changes and there are following lines */
3177 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3178 if (extra != 0 && idx < count - 1)
3179 {
3180 /* move text of following lines */
3181 mch_memmove((char *)dp + dp->db_txt_start - extra,
3182 (char *)dp + dp->db_txt_start,
3183 (size_t)(start - dp->db_txt_start));
3184
3185 /* adjust pointers of this and following lines */
3186 for (i = idx + 1; i < count; ++i)
3187 dp->db_index[i] -= extra;
3188 }
3189 dp->db_index[idx] -= extra;
3190
3191 /* adjust free space */
3192 dp->db_free -= extra;
3193 dp->db_txt_start -= extra;
3194
3195 /* copy new line into the data block */
3196 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3197 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3198#ifdef FEAT_BYTEOFF
3199 /* The else case is already covered by the insert and delete */
3200 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3201#endif
3202 }
3203 else
3204 {
3205 /*
3206 * Cannot do it in one data block: Delete and append.
3207 * Append first, because ml_delete_int() cannot delete the
3208 * last line in a buffer, which causes trouble for a buffer
3209 * that has only one line.
3210 * Don't forget to copy the mark!
3211 */
3212 /* How about handling errors??? */
3213 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3214 (dp->db_index[idx] & DB_MARKED));
3215 (void)ml_delete_int(buf, lnum, FALSE);
3216 }
3217 }
3218 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003219
3220 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 }
3222
3223 buf->b_ml.ml_line_lnum = 0;
3224}
3225
3226/*
3227 * create a new, empty, data block
3228 */
3229 static bhdr_T *
3230ml_new_data(mfp, negative, page_count)
3231 memfile_T *mfp;
3232 int negative;
3233 int page_count;
3234{
3235 bhdr_T *hp;
3236 DATA_BL *dp;
3237
3238 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3239 return NULL;
3240
3241 dp = (DATA_BL *)(hp->bh_data);
3242 dp->db_id = DATA_ID;
3243 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3244 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3245 dp->db_line_count = 0;
3246
3247 return hp;
3248}
3249
3250/*
3251 * create a new, empty, pointer block
3252 */
3253 static bhdr_T *
3254ml_new_ptr(mfp)
3255 memfile_T *mfp;
3256{
3257 bhdr_T *hp;
3258 PTR_BL *pp;
3259
3260 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3261 return NULL;
3262
3263 pp = (PTR_BL *)(hp->bh_data);
3264 pp->pb_id = PTR_ID;
3265 pp->pb_count = 0;
3266 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL)) / sizeof(PTR_EN) + 1);
3267
3268 return hp;
3269}
3270
3271/*
3272 * lookup line 'lnum' in a memline
3273 *
3274 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3275 * if ML_FLUSH only flush a locked block
3276 * if ML_FIND just find the line
3277 *
3278 * If the block was found it is locked and put in ml_locked.
3279 * The stack is updated to lead to the locked block. The ip_high field in
3280 * the stack is updated to reflect the last line in the block AFTER the
3281 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003282 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283 *
3284 * return: NULL for failure, pointer to block header otherwise
3285 */
3286 static bhdr_T *
3287ml_find_line(buf, lnum, action)
3288 buf_T *buf;
3289 linenr_T lnum;
3290 int action;
3291{
3292 DATA_BL *dp;
3293 PTR_BL *pp;
3294 infoptr_T *ip;
3295 bhdr_T *hp;
3296 memfile_T *mfp;
3297 linenr_T t;
3298 blocknr_T bnum, bnum2;
3299 int dirty;
3300 linenr_T low, high;
3301 int top;
3302 int page_count;
3303 int idx;
3304
3305 mfp = buf->b_ml.ml_mfp;
3306
3307 /*
3308 * If there is a locked block check if the wanted line is in it.
3309 * If not, flush and release the locked block.
3310 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3311 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003312 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313 */
3314 if (buf->b_ml.ml_locked)
3315 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003316 if (ML_SIMPLE(action)
3317 && buf->b_ml.ml_locked_low <= lnum
3318 && buf->b_ml.ml_locked_high >= lnum
3319 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003321 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 if (action == ML_INSERT)
3323 {
3324 ++(buf->b_ml.ml_locked_lineadd);
3325 ++(buf->b_ml.ml_locked_high);
3326 }
3327 else if (action == ML_DELETE)
3328 {
3329 --(buf->b_ml.ml_locked_lineadd);
3330 --(buf->b_ml.ml_locked_high);
3331 }
3332 return (buf->b_ml.ml_locked);
3333 }
3334
3335 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3336 buf->b_ml.ml_flags & ML_LOCKED_POS);
3337 buf->b_ml.ml_locked = NULL;
3338
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003339 /*
3340 * If lines have been added or deleted in the locked block, need to
3341 * update the line count in pointer blocks.
3342 */
3343 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3345 }
3346
3347 if (action == ML_FLUSH) /* nothing else to do */
3348 return NULL;
3349
3350 bnum = 1; /* start at the root of the tree */
3351 page_count = 1;
3352 low = 1;
3353 high = buf->b_ml.ml_line_count;
3354
3355 if (action == ML_FIND) /* first try stack entries */
3356 {
3357 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3358 {
3359 ip = &(buf->b_ml.ml_stack[top]);
3360 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3361 {
3362 bnum = ip->ip_bnum;
3363 low = ip->ip_low;
3364 high = ip->ip_high;
3365 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3366 break;
3367 }
3368 }
3369 if (top < 0)
3370 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3371 }
3372 else /* ML_DELETE or ML_INSERT */
3373 buf->b_ml.ml_stack_top = 0; /* start at the root */
3374
3375/*
3376 * search downwards in the tree until a data block is found
3377 */
3378 for (;;)
3379 {
3380 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3381 goto error_noblock;
3382
3383 /*
3384 * update high for insert/delete
3385 */
3386 if (action == ML_INSERT)
3387 ++high;
3388 else if (action == ML_DELETE)
3389 --high;
3390
3391 dp = (DATA_BL *)(hp->bh_data);
3392 if (dp->db_id == DATA_ID) /* data block */
3393 {
3394 buf->b_ml.ml_locked = hp;
3395 buf->b_ml.ml_locked_low = low;
3396 buf->b_ml.ml_locked_high = high;
3397 buf->b_ml.ml_locked_lineadd = 0;
3398 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3399 return hp;
3400 }
3401
3402 pp = (PTR_BL *)(dp); /* must be pointer block */
3403 if (pp->pb_id != PTR_ID)
3404 {
3405 EMSG(_("E317: pointer block id wrong"));
3406 goto error_block;
3407 }
3408
3409 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3410 goto error_block;
3411 ip = &(buf->b_ml.ml_stack[top]);
3412 ip->ip_bnum = bnum;
3413 ip->ip_low = low;
3414 ip->ip_high = high;
3415 ip->ip_index = -1; /* index not known yet */
3416
3417 dirty = FALSE;
3418 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3419 {
3420 t = pp->pb_pointer[idx].pe_line_count;
3421 CHECK(t == 0, _("pe_line_count is zero"));
3422 if ((low += t) > lnum)
3423 {
3424 ip->ip_index = idx;
3425 bnum = pp->pb_pointer[idx].pe_bnum;
3426 page_count = pp->pb_pointer[idx].pe_page_count;
3427 high = low - 1;
3428 low -= t;
3429
3430 /*
3431 * a negative block number may have been changed
3432 */
3433 if (bnum < 0)
3434 {
3435 bnum2 = mf_trans_del(mfp, bnum);
3436 if (bnum != bnum2)
3437 {
3438 bnum = bnum2;
3439 pp->pb_pointer[idx].pe_bnum = bnum;
3440 dirty = TRUE;
3441 }
3442 }
3443
3444 break;
3445 }
3446 }
3447 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3448 {
3449 if (lnum > buf->b_ml.ml_line_count)
3450 EMSGN(_("E322: line number out of range: %ld past the end"),
3451 lnum - buf->b_ml.ml_line_count);
3452
3453 else
3454 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3455 goto error_block;
3456 }
3457 if (action == ML_DELETE)
3458 {
3459 pp->pb_pointer[idx].pe_line_count--;
3460 dirty = TRUE;
3461 }
3462 else if (action == ML_INSERT)
3463 {
3464 pp->pb_pointer[idx].pe_line_count++;
3465 dirty = TRUE;
3466 }
3467 mf_put(mfp, hp, dirty, FALSE);
3468 }
3469
3470error_block:
3471 mf_put(mfp, hp, FALSE, FALSE);
3472error_noblock:
3473/*
3474 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3475 * the incremented/decremented line counts, because there won't be a line
3476 * inserted/deleted after all.
3477 */
3478 if (action == ML_DELETE)
3479 ml_lineadd(buf, 1);
3480 else if (action == ML_INSERT)
3481 ml_lineadd(buf, -1);
3482 buf->b_ml.ml_stack_top = 0;
3483 return NULL;
3484}
3485
3486/*
3487 * add an entry to the info pointer stack
3488 *
3489 * return -1 for failure, number of the new entry otherwise
3490 */
3491 static int
3492ml_add_stack(buf)
3493 buf_T *buf;
3494{
3495 int top;
3496 infoptr_T *newstack;
3497
3498 top = buf->b_ml.ml_stack_top;
3499
3500 /* may have to increase the stack size */
3501 if (top == buf->b_ml.ml_stack_size)
3502 {
3503 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
3504
3505 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3506 (buf->b_ml.ml_stack_size + STACK_INCR));
3507 if (newstack == NULL)
3508 return -1;
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003509 mch_memmove(newstack, buf->b_ml.ml_stack,
3510 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 vim_free(buf->b_ml.ml_stack);
3512 buf->b_ml.ml_stack = newstack;
3513 buf->b_ml.ml_stack_size += STACK_INCR;
3514 }
3515
3516 buf->b_ml.ml_stack_top++;
3517 return top;
3518}
3519
3520/*
3521 * Update the pointer blocks on the stack for inserted/deleted lines.
3522 * The stack itself is also updated.
3523 *
3524 * When a insert/delete line action fails, the line is not inserted/deleted,
3525 * but the pointer blocks have already been updated. That is fixed here by
3526 * walking through the stack.
3527 *
3528 * Count is the number of lines added, negative if lines have been deleted.
3529 */
3530 static void
3531ml_lineadd(buf, count)
3532 buf_T *buf;
3533 int count;
3534{
3535 int idx;
3536 infoptr_T *ip;
3537 PTR_BL *pp;
3538 memfile_T *mfp = buf->b_ml.ml_mfp;
3539 bhdr_T *hp;
3540
3541 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3542 {
3543 ip = &(buf->b_ml.ml_stack[idx]);
3544 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3545 break;
3546 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3547 if (pp->pb_id != PTR_ID)
3548 {
3549 mf_put(mfp, hp, FALSE, FALSE);
3550 EMSG(_("E317: pointer block id wrong 2"));
3551 break;
3552 }
3553 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3554 ip->ip_high += count;
3555 mf_put(mfp, hp, TRUE, FALSE);
3556 }
3557}
3558
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003559#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003560/*
3561 * Resolve a symlink in the last component of a file name.
3562 * Note that f_resolve() does it for every part of the path, we don't do that
3563 * here.
3564 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3565 * Otherwise returns FAIL.
3566 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003567 int
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003568resolve_symlink(fname, buf)
3569 char_u *fname;
3570 char_u *buf;
3571{
3572 char_u tmp[MAXPATHL];
3573 int ret;
3574 int depth = 0;
3575
3576 if (fname == NULL)
3577 return FAIL;
3578
3579 /* Put the result so far in tmp[], starting with the original name. */
3580 vim_strncpy(tmp, fname, MAXPATHL - 1);
3581
3582 for (;;)
3583 {
3584 /* Limit symlink depth to 100, catch recursive loops. */
3585 if (++depth == 100)
3586 {
3587 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3588 return FAIL;
3589 }
3590
3591 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3592 if (ret <= 0)
3593 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003594 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003595 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003596 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003597 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003598 * call to vim_FullName(). */
3599 if (depth == 1)
3600 return FAIL;
3601
3602 /* Use the resolved name in tmp[]. */
3603 break;
3604 }
3605
3606 /* There must be some error reading links, use original name. */
3607 return FAIL;
3608 }
3609 buf[ret] = NUL;
3610
3611 /*
3612 * Check whether the symlink is relative or absolute.
3613 * If it's relative, build a new path based on the directory
3614 * portion of the filename (if any) and the path the symlink
3615 * points to.
3616 */
3617 if (mch_isFullName(buf))
3618 STRCPY(tmp, buf);
3619 else
3620 {
3621 char_u *tail;
3622
3623 tail = gettail(tmp);
3624 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3625 return FAIL;
3626 STRCPY(tail, buf);
3627 }
3628 }
3629
3630 /*
3631 * Try to resolve the full name of the file so that the swapfile name will
3632 * be consistent even when opening a relative symlink from different
3633 * working directories.
3634 */
3635 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3636}
3637#endif
3638
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003640 * Make swap file name out of the file name and a directory name.
3641 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003642 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003643 char_u *
3644makeswapname(fname, ffname, buf, dir_name)
3645 char_u *fname;
Bram Moolenaar740885b2009-11-03 14:33:17 +00003646 char_u *ffname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 buf_T *buf;
3648 char_u *dir_name;
3649{
3650 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003651 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003652#ifdef HAVE_READLINK
3653 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003654#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655
3656#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3657 s = dir_name + STRLEN(dir_name);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003658 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003659 { /* Ends with '//', Use Full path */
3660 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003661 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662 {
3663 r = modname(s, (char_u *)".swp", FALSE);
3664 vim_free(s);
3665 }
3666 return r;
3667 }
3668#endif
3669
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003670#ifdef HAVE_READLINK
3671 /* Expand symlink in the file name, so that we put the swap file with the
3672 * actual file instead of with the symlink. */
3673 if (resolve_symlink(fname, fname_buf) == OK)
3674 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003675#endif
3676
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 r = buf_modname(
3678#ifdef SHORT_FNAME
3679 TRUE,
3680#else
3681 (buf->b_p_sn || buf->b_shortname),
3682#endif
Bram Moolenaar38323e42007-03-06 19:22:53 +00003683#ifdef RISCOS
3684 /* Avoid problems if fname has special chars, eg <Wimp$Scrap> */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003685 ffname,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686#else
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003687 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003688#endif
3689 (char_u *)
3690#if defined(VMS) || defined(RISCOS)
3691 "_swp",
3692#else
3693 ".swp",
3694#endif
3695#ifdef SHORT_FNAME /* always 8.3 file name */
3696 FALSE
3697#else
3698 /* Prepend a '.' to the swap file name for the current directory. */
3699 dir_name[0] == '.' && dir_name[1] == NUL
3700#endif
3701 );
3702 if (r == NULL) /* out of memory */
3703 return NULL;
3704
3705 s = get_file_in_dir(r, dir_name);
3706 vim_free(r);
3707 return s;
3708}
3709
3710/*
3711 * Get file name to use for swap file or backup file.
3712 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3713 * option "dname".
3714 * - If "dname" is ".", return "fname" (swap file in dir of file).
3715 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3716 * relative to dir of file).
3717 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
3718 * dir).
3719 *
3720 * The return value is an allocated string and can be NULL.
3721 */
3722 char_u *
3723get_file_in_dir(fname, dname)
3724 char_u *fname;
3725 char_u *dname; /* don't use "dirname", it is a global for Alpha */
3726{
3727 char_u *t;
3728 char_u *tail;
3729 char_u *retval;
3730 int save_char;
3731
3732 tail = gettail(fname);
3733
3734 if (dname[0] == '.' && dname[1] == NUL)
3735 retval = vim_strsave(fname);
3736 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
3737 {
3738 if (tail == fname) /* no path before file name */
3739 retval = concat_fnames(dname + 2, tail, TRUE);
3740 else
3741 {
3742 save_char = *tail;
3743 *tail = NUL;
3744 t = concat_fnames(fname, dname + 2, TRUE);
3745 *tail = save_char;
3746 if (t == NULL) /* out of memory */
3747 retval = NULL;
3748 else
3749 {
3750 retval = concat_fnames(t, tail, TRUE);
3751 vim_free(t);
3752 }
3753 }
3754 }
3755 else
3756 retval = concat_fnames(dname, tail, TRUE);
3757
3758 return retval;
3759}
3760
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003761static void attention_message __ARGS((buf_T *buf, char_u *fname));
3762
3763/*
3764 * Print the ATTENTION message: info about an existing swap file.
3765 */
3766 static void
3767attention_message(buf, fname)
3768 buf_T *buf; /* buffer being edited */
3769 char_u *fname; /* swap file name */
3770{
3771 struct stat st;
3772 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00003773 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003774
3775 ++no_wait_return;
3776 (void)EMSG(_("E325: ATTENTION"));
3777 MSG_PUTS(_("\nFound a swap file by the name \""));
3778 msg_home_replace(fname);
3779 MSG_PUTS("\"\n");
3780 sx = swapfile_info(fname);
3781 MSG_PUTS(_("While opening file \""));
3782 msg_outtrans(buf->b_fname);
3783 MSG_PUTS("\"\n");
3784 if (mch_stat((char *)buf->b_fname, &st) != -1)
3785 {
3786 MSG_PUTS(_(" dated: "));
3787 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00003788 p = ctime(&x); /* includes '\n' */
3789 if (p == NULL)
3790 MSG_PUTS("(invalid)\n");
3791 else
3792 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003793 if (sx != 0 && x > sx)
3794 MSG_PUTS(_(" NEWER than swap file!\n"));
3795 }
3796 /* Some of these messages are long to allow translation to
3797 * other languages. */
3798 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"));
3799 MSG_PUTS(_(" Quit, or continue with caution.\n"));
3800 MSG_PUTS(_("\n(2) An edit session for this file crashed.\n"));
3801 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
3802 msg_outtrans(buf->b_fname);
3803 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
3804 MSG_PUTS(_(" If you did this already, delete the swap file \""));
3805 msg_outtrans(fname);
3806 MSG_PUTS(_("\"\n to avoid this message.\n"));
3807 cmdline_row = msg_row;
3808 --no_wait_return;
3809}
3810
3811#ifdef FEAT_AUTOCMD
3812static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
3813
3814/*
3815 * Trigger the SwapExists autocommands.
3816 * Returns a value for equivalent to do_dialog() (see below):
3817 * 0: still need to ask for a choice
3818 * 1: open read-only
3819 * 2: edit anyway
3820 * 3: recover
3821 * 4: delete it
3822 * 5: quit
3823 * 6: abort
3824 */
3825 static int
3826do_swapexists(buf, fname)
3827 buf_T *buf;
3828 char_u *fname;
3829{
3830 set_vim_var_string(VV_SWAPNAME, fname, -1);
3831 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
3832
3833 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00003834 * edited. Disallow changing directory here. */
3835 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003836 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00003837 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00003838
3839 set_vim_var_string(VV_SWAPNAME, NULL, -1);
3840
3841 switch (*get_vim_var_str(VV_SWAPCHOICE))
3842 {
3843 case 'o': return 1;
3844 case 'e': return 2;
3845 case 'r': return 3;
3846 case 'd': return 4;
3847 case 'q': return 5;
3848 case 'a': return 6;
3849 }
3850
3851 return 0;
3852}
3853#endif
3854
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855/*
3856 * Find out what name to use for the swap file for buffer 'buf'.
3857 *
3858 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003859 * Returns the name in allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 *
3861 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003862 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00003863 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864 */
3865 static char_u *
3866findswapname(buf, dirp, old_fname)
3867 buf_T *buf;
3868 char_u **dirp; /* pointer to list of directories */
3869 char_u *old_fname; /* don't give warning for this file name */
3870{
3871 char_u *fname;
3872 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873 char_u *dir_name;
3874#ifdef AMIGA
3875 BPTR fh;
3876#endif
3877#ifndef SHORT_FNAME
3878 int r;
3879#endif
3880
3881#if !defined(SHORT_FNAME) \
3882 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
3883# define CREATE_DUMMY_FILE
3884 FILE *dummyfd = NULL;
3885
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003886 /*
3887 * If we start editing a new file, e.g. "test.doc", which resides on an
3888 * MSDOS compatible filesystem, it is possible that the file
3889 * "test.doc.swp" which we create will be exactly the same file. To avoid
3890 * this problem we temporarily create "test.doc". Don't do this when the
3891 * check below for a 8.3 file name is used.
3892 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003893 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
3894 && mch_getperm(buf->b_fname) < 0)
3895 dummyfd = mch_fopen((char *)buf->b_fname, "w");
3896#endif
3897
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003898 /*
3899 * Isolate a directory name from *dirp and put it in dir_name.
3900 * First allocate some memory to put the directory name in.
3901 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
3903 if (dir_name != NULL)
3904 (void)copy_option_part(dirp, dir_name, 31000, ",");
3905
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003906 /*
3907 * we try different names until we find one that does not exist yet
3908 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 if (dir_name == NULL) /* out of memory */
3910 fname = NULL;
3911 else
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003912 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913
3914 for (;;)
3915 {
3916 if (fname == NULL) /* must be out of memory */
3917 break;
3918 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
3919 {
3920 vim_free(fname);
3921 fname = NULL;
3922 break;
3923 }
3924#if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
3925/*
3926 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
3927 * file names. If this is the first try and the swap file name does not fit in
3928 * 8.3, detect if this is the case, set shortname and try again.
3929 */
3930 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
3931 && !(buf->b_p_sn || buf->b_shortname))
3932 {
3933 char_u *tail;
3934 char_u *fname2;
3935 struct stat s1, s2;
3936 int f1, f2;
3937 int created1 = FALSE, created2 = FALSE;
3938 int same = FALSE;
3939
3940 /*
3941 * Check if swapfile name does not fit in 8.3:
3942 * It either contains two dots, is longer than 8 chars, or starts
3943 * with a dot.
3944 */
3945 tail = gettail(buf->b_fname);
3946 if ( vim_strchr(tail, '.') != NULL
3947 || STRLEN(tail) > (size_t)8
3948 || *gettail(fname) == '.')
3949 {
3950 fname2 = alloc(n + 2);
3951 if (fname2 != NULL)
3952 {
3953 STRCPY(fname2, fname);
3954 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
3955 * if fname == ".xx.swp", fname2 = ".xx.swpx"
3956 * if fname == "123456789.swp", fname2 = "12345678x.swp"
3957 */
3958 if (vim_strchr(tail, '.') != NULL)
3959 fname2[n - 1] = 'x';
3960 else if (*gettail(fname) == '.')
3961 {
3962 fname2[n] = 'x';
3963 fname2[n + 1] = NUL;
3964 }
3965 else
3966 fname2[n - 5] += 1;
3967 /*
3968 * may need to create the files to be able to use mch_stat()
3969 */
3970 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
3971 if (f1 < 0)
3972 {
3973 f1 = mch_open_rw((char *)fname,
3974 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
3975#if defined(OS2)
3976 if (f1 < 0 && errno == ENOENT)
3977 same = TRUE;
3978#endif
3979 created1 = TRUE;
3980 }
3981 if (f1 >= 0)
3982 {
3983 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
3984 if (f2 < 0)
3985 {
3986 f2 = mch_open_rw((char *)fname2,
3987 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
3988 created2 = TRUE;
3989 }
3990 if (f2 >= 0)
3991 {
3992 /*
3993 * Both files exist now. If mch_stat() returns the
3994 * same device and inode they are the same file.
3995 */
3996 if (mch_fstat(f1, &s1) != -1
3997 && mch_fstat(f2, &s2) != -1
3998 && s1.st_dev == s2.st_dev
3999 && s1.st_ino == s2.st_ino)
4000 same = TRUE;
4001 close(f2);
4002 if (created2)
4003 mch_remove(fname2);
4004 }
4005 close(f1);
4006 if (created1)
4007 mch_remove(fname);
4008 }
4009 vim_free(fname2);
4010 if (same)
4011 {
4012 buf->b_shortname = TRUE;
4013 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004014 fname = makeswapname(buf->b_fname, buf->b_ffname,
4015 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016 continue; /* try again with b_shortname set */
4017 }
4018 }
4019 }
4020 }
4021#endif
4022 /*
4023 * check if the swapfile already exists
4024 */
4025 if (mch_getperm(fname) < 0) /* it does not exist */
4026 {
4027#ifdef HAVE_LSTAT
4028 struct stat sb;
4029
4030 /*
4031 * Extra security check: When a swap file is a symbolic link, this
4032 * is most likely a symlink attack.
4033 */
4034 if (mch_lstat((char *)fname, &sb) < 0)
4035#else
4036# ifdef AMIGA
4037 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4038 /*
4039 * on the Amiga mch_getperm() will return -1 when the file exists
4040 * but is being used by another program. This happens if you edit
4041 * a file twice.
4042 */
4043 if (fh != (BPTR)NULL) /* can open file, OK */
4044 {
4045 Close(fh);
4046 mch_remove(fname);
4047 break;
4048 }
4049 if (IoErr() != ERROR_OBJECT_IN_USE
4050 && IoErr() != ERROR_OBJECT_EXISTS)
4051# endif
4052#endif
4053 break;
4054 }
4055
4056 /*
4057 * A file name equal to old_fname is OK to use.
4058 */
4059 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4060 break;
4061
4062 /*
4063 * get here when file already exists
4064 */
4065 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4066 {
4067#ifndef SHORT_FNAME
4068 /*
4069 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4070 * and file.doc are the same file. To guess if this problem is
4071 * present try if file.doc.swx exists. If it does, we set
4072 * buf->b_shortname and try file_doc.swp (dots replaced by
4073 * underscores for this file), and try again. If it doesn't we
4074 * assume that "file.doc.swp" already exists.
4075 */
4076 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4077 {
4078 fname[n - 1] = 'x';
4079 r = mch_getperm(fname); /* try "file.swx" */
4080 fname[n - 1] = 'p';
4081 if (r >= 0) /* "file.swx" seems to exist */
4082 {
4083 buf->b_shortname = TRUE;
4084 vim_free(fname);
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004085 fname = makeswapname(buf->b_fname, buf->b_ffname,
4086 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087 continue; /* try again with '.' replaced with '_' */
4088 }
4089 }
4090#endif
4091 /*
4092 * If we get here the ".swp" file really exists.
4093 * Give an error message, unless recovering, no file name, we are
4094 * viewing a help file or when the path of the file is different
4095 * (happens when all .swp files are in one directory).
4096 */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004097 if (!recoverymode && buf->b_fname != NULL
4098 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004099 {
4100 int fd;
4101 struct block0 b0;
4102 int differ = FALSE;
4103
4104 /*
4105 * Try to read block 0 from the swap file to get the original
4106 * file name (and inode number).
4107 */
4108 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4109 if (fd >= 0)
4110 {
4111 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
4112 {
4113 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004114 * If the swapfile has the same directory as the
4115 * buffer don't compare the directory names, they can
4116 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004118 if (b0.b0_flags & B0_SAME_DIR)
4119 {
4120 if (fnamecmp(gettail(buf->b_ffname),
4121 gettail(b0.b0_fname)) != 0
4122 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004123 {
4124#ifdef CHECK_INODE
4125 /* Symlinks may point to the same file even
4126 * when the name differs, need to check the
4127 * inode too. */
4128 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4129 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4130 char_to_long(b0.b0_ino)))
4131#endif
4132 differ = TRUE;
4133 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004134 }
4135 else
4136 {
4137 /*
4138 * The name in the swap file may be
4139 * "~user/path/file". Expand it first.
4140 */
4141 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004143 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004144 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004145 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004147 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4148 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004150 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151 }
4152 close(fd);
4153 }
4154#ifdef RISCOS
4155 else
4156 /* Can't open swap file, though it does exist.
4157 * Assume that the user is editing two files with
4158 * the same name in different directories. No error.
4159 */
4160 differ = TRUE;
4161#endif
4162
4163 /* give the ATTENTION message when there is an old swap file
4164 * for the current file, and the buffer was not recovered. */
4165 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4166 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4167 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004168#if defined(HAS_SWAP_EXISTS_ACTION)
4169 int choice = 0;
4170#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171#ifdef CREATE_DUMMY_FILE
4172 int did_use_dummy = FALSE;
4173
4174 /* Avoid getting a warning for the file being created
4175 * outside of Vim, it was created at the start of this
4176 * function. Delete the file now, because Vim might exit
4177 * here if the window is closed. */
4178 if (dummyfd != NULL)
4179 {
4180 fclose(dummyfd);
4181 dummyfd = NULL;
4182 mch_remove(buf->b_fname);
4183 did_use_dummy = TRUE;
4184 }
4185#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186
4187#if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4188 process_still_running = FALSE;
4189#endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004190#ifdef FEAT_AUTOCMD
4191 /*
4192 * If there is an SwapExists autocommand and we can handle
4193 * the response, trigger it. It may return 0 to ask the
4194 * user anyway.
4195 */
4196 if (swap_exists_action != SEA_NONE
4197 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4198 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004200 if (choice == 0)
4201#endif
4202 {
4203#ifdef FEAT_GUI
4204 /* If we are supposed to start the GUI but it wasn't
4205 * completely started yet, start it now. This makes
4206 * the messages displayed in the Vim window when
4207 * loading a session from the .gvimrc file. */
4208 if (gui.starting && !gui.in_use)
4209 gui_start();
4210#endif
4211 /* Show info about the existing swap file. */
4212 attention_message(buf, fname);
4213
4214 /* We don't want a 'q' typed at the more-prompt
4215 * interrupt loading a file. */
4216 got_int = FALSE;
4217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218
4219#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004220 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 {
4222 char_u *name;
4223
4224 name = alloc((unsigned)(STRLEN(fname)
4225 + STRLEN(_("Swap file \""))
4226 + STRLEN(_("\" already exists!")) + 5));
4227 if (name != NULL)
4228 {
4229 STRCPY(name, _("Swap file \""));
4230 home_replace(NULL, fname, name + STRLEN(name),
4231 1000, TRUE);
4232 STRCAT(name, _("\" already exists!"));
4233 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004234 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 (char_u *)_("VIM - ATTENTION"),
4236 name == NULL
4237 ? (char_u *)_("Swap file already exists!")
4238 : name,
4239# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4240 process_still_running
4241 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4242# endif
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004243 (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL);
4244
4245# if defined(UNIX) || defined(__EMX__) || defined(VMS)
4246 if (process_still_running && choice >= 4)
4247 choice++; /* Skip missing "Delete it" button */
4248# endif
4249 vim_free(name);
4250
4251 /* pretend screen didn't scroll, need redraw anyway */
4252 msg_scrolled = 0;
4253 redraw_all_later(NOT_VALID);
4254 }
4255#endif
4256
4257#if defined(HAS_SWAP_EXISTS_ACTION)
4258 if (choice > 0)
4259 {
4260 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 {
4262 case 1:
4263 buf->b_p_ro = TRUE;
4264 break;
4265 case 2:
4266 break;
4267 case 3:
4268 swap_exists_action = SEA_RECOVER;
4269 break;
4270 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004271 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 break;
4273 case 5:
4274 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 break;
4276 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004277 swap_exists_action = SEA_QUIT;
4278 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279 break;
4280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281
4282 /* If the file was deleted this fname can be used. */
4283 if (mch_getperm(fname) < 0)
4284 break;
4285 }
4286 else
4287#endif
4288 {
4289 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004290 if (msg_silent == 0)
4291 /* call wait_return() later */
4292 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 }
4294
4295#ifdef CREATE_DUMMY_FILE
4296 /* Going to try another name, need the dummy file again. */
4297 if (did_use_dummy)
4298 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4299#endif
4300 }
4301 }
4302 }
4303
4304 /*
4305 * Change the ".swp" extension to find another file that can be used.
4306 * First decrement the last char: ".swo", ".swn", etc.
4307 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004308 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 */
4310 if (fname[n - 1] == 'a') /* ".s?a" */
4311 {
4312 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4313 {
4314 EMSG(_("E326: Too many swap files found"));
4315 vim_free(fname);
4316 fname = NULL;
4317 break;
4318 }
4319 --fname[n - 2]; /* ".svz", ".suz", etc. */
4320 fname[n - 1] = 'z' + 1;
4321 }
4322 --fname[n - 1]; /* ".swo", ".swn", etc. */
4323 }
4324
4325 vim_free(dir_name);
4326#ifdef CREATE_DUMMY_FILE
4327 if (dummyfd != NULL) /* file has been created temporarily */
4328 {
4329 fclose(dummyfd);
4330 mch_remove(buf->b_fname);
4331 }
4332#endif
4333 return fname;
4334}
4335
4336 static int
4337b0_magic_wrong(b0p)
4338 ZERO_BL *b0p;
4339{
4340 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4341 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4342 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4343 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4344}
4345
4346#ifdef CHECK_INODE
4347/*
4348 * Compare current file name with file name from swap file.
4349 * Try to use inode numbers when possible.
4350 * Return non-zero when files are different.
4351 *
4352 * When comparing file names a few things have to be taken into consideration:
4353 * - When working over a network the full path of a file depends on the host.
4354 * We check the inode number if possible. It is not 100% reliable though,
4355 * because the device number cannot be used over a network.
4356 * - When a file does not exist yet (editing a new file) there is no inode
4357 * number.
4358 * - The file name in a swap file may not be valid on the current host. The
4359 * "~user" form is used whenever possible to avoid this.
4360 *
4361 * This is getting complicated, let's make a table:
4362 *
4363 * ino_c ino_s fname_c fname_s differ =
4364 *
4365 * both files exist -> compare inode numbers:
4366 * != 0 != 0 X X ino_c != ino_s
4367 *
4368 * inode number(s) unknown, file names available -> compare file names
4369 * == 0 X OK OK fname_c != fname_s
4370 * X == 0 OK OK fname_c != fname_s
4371 *
4372 * current file doesn't exist, file for swap file exist, file name(s) not
4373 * available -> probably different
4374 * == 0 != 0 FAIL X TRUE
4375 * == 0 != 0 X FAIL TRUE
4376 *
4377 * current file exists, inode for swap unknown, file name(s) not
4378 * available -> probably different
4379 * != 0 == 0 FAIL X TRUE
4380 * != 0 == 0 X FAIL TRUE
4381 *
4382 * current file doesn't exist, inode for swap unknown, one file name not
4383 * available -> probably different
4384 * == 0 == 0 FAIL OK TRUE
4385 * == 0 == 0 OK FAIL TRUE
4386 *
4387 * current file doesn't exist, inode for swap unknown, both file names not
4388 * available -> probably same file
4389 * == 0 == 0 FAIL FAIL FALSE
4390 *
4391 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4392 * can't be changed without making the block 0 incompatible with 32 bit
4393 * versions.
4394 */
4395
4396 static int
4397fnamecmp_ino(fname_c, fname_s, ino_block0)
4398 char_u *fname_c; /* current file name */
4399 char_u *fname_s; /* file name from swap file */
4400 long ino_block0;
4401{
4402 struct stat st;
4403 ino_t ino_c = 0; /* ino of current file */
4404 ino_t ino_s; /* ino of file from swap file */
4405 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4406 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4407 int retval_c; /* flag: buf_c valid */
4408 int retval_s; /* flag: buf_s valid */
4409
4410 if (mch_stat((char *)fname_c, &st) == 0)
4411 ino_c = (ino_t)st.st_ino;
4412
4413 /*
4414 * First we try to get the inode from the file name, because the inode in
4415 * the swap file may be outdated. If that fails (e.g. this path is not
4416 * valid on this machine), use the inode from block 0.
4417 */
4418 if (mch_stat((char *)fname_s, &st) == 0)
4419 ino_s = (ino_t)st.st_ino;
4420 else
4421 ino_s = (ino_t)ino_block0;
4422
4423 if (ino_c && ino_s)
4424 return (ino_c != ino_s);
4425
4426 /*
4427 * One of the inode numbers is unknown, try a forced vim_FullName() and
4428 * compare the file names.
4429 */
4430 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4431 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4432 if (retval_c == OK && retval_s == OK)
4433 return (STRCMP(buf_c, buf_s) != 0);
4434
4435 /*
4436 * Can't compare inodes or file names, guess that the files are different,
4437 * unless both appear not to exist at all.
4438 */
4439 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4440 return FALSE;
4441 return TRUE;
4442}
4443#endif /* CHECK_INODE */
4444
4445/*
4446 * Move a long integer into a four byte character array.
4447 * Used for machine independency in block zero.
4448 */
4449 static void
4450long_to_char(n, s)
4451 long n;
4452 char_u *s;
4453{
4454 s[0] = (char_u)(n & 0xff);
4455 n = (unsigned)n >> 8;
4456 s[1] = (char_u)(n & 0xff);
4457 n = (unsigned)n >> 8;
4458 s[2] = (char_u)(n & 0xff);
4459 n = (unsigned)n >> 8;
4460 s[3] = (char_u)(n & 0xff);
4461}
4462
4463 static long
4464char_to_long(s)
4465 char_u *s;
4466{
4467 long retval;
4468
4469 retval = s[3];
4470 retval <<= 8;
4471 retval |= s[2];
4472 retval <<= 8;
4473 retval |= s[1];
4474 retval <<= 8;
4475 retval |= s[0];
4476
4477 return retval;
4478}
4479
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004480/*
4481 * Set the flags in the first block of the swap file:
4482 * - file is modified or not: buf->b_changed
4483 * - 'fileformat'
4484 * - 'fileencoding'
4485 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 void
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004487ml_setflags(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489{
4490 bhdr_T *hp;
4491 ZERO_BL *b0p;
4492
4493 if (!buf->b_ml.ml_mfp)
4494 return;
4495 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4496 {
4497 if (hp->bh_bnum == 0)
4498 {
4499 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004500 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4501 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4502 | (get_fileformat(buf) + 1);
4503#ifdef FEAT_MBYTE
4504 add_b0_fenc(b0p, buf);
4505#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 hp->bh_flags |= BH_DIRTY;
4507 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4508 break;
4509 }
4510 }
4511}
4512
4513#if defined(FEAT_BYTEOFF) || defined(PROTO)
4514
4515#define MLCS_MAXL 800 /* max no of lines in chunk */
4516#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4517
4518/*
4519 * Keep information for finding byte offset of a line, updtytpe may be one of:
4520 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4521 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4522 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4523 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4524 */
4525 static void
4526ml_updatechunk(buf, line, len, updtype)
4527 buf_T *buf;
4528 linenr_T line;
4529 long len;
4530 int updtype;
4531{
4532 static buf_T *ml_upd_lastbuf = NULL;
4533 static linenr_T ml_upd_lastline;
4534 static linenr_T ml_upd_lastcurline;
4535 static int ml_upd_lastcurix;
4536
4537 linenr_T curline = ml_upd_lastcurline;
4538 int curix = ml_upd_lastcurix;
4539 long size;
4540 chunksize_T *curchnk;
4541 int rest;
4542 bhdr_T *hp;
4543 DATA_BL *dp;
4544
4545 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4546 return;
4547 if (buf->b_ml.ml_chunksize == NULL)
4548 {
4549 buf->b_ml.ml_chunksize = (chunksize_T *)
4550 alloc((unsigned)sizeof(chunksize_T) * 100);
4551 if (buf->b_ml.ml_chunksize == NULL)
4552 {
4553 buf->b_ml.ml_usedchunks = -1;
4554 return;
4555 }
4556 buf->b_ml.ml_numchunks = 100;
4557 buf->b_ml.ml_usedchunks = 1;
4558 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4559 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4560 }
4561
4562 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4563 {
4564 /*
4565 * First line in empty buffer from ml_flush_line() -- reset
4566 */
4567 buf->b_ml.ml_usedchunks = 1;
4568 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4569 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4570 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4571 return;
4572 }
4573
4574 /*
4575 * Find chunk that our line belongs to, curline will be at start of the
4576 * chunk.
4577 */
4578 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4579 || updtype != ML_CHNK_ADDLINE)
4580 {
4581 for (curline = 1, curix = 0;
4582 curix < buf->b_ml.ml_usedchunks - 1
4583 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4584 curix++)
4585 {
4586 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4587 }
4588 }
4589 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
4590 && curix < buf->b_ml.ml_usedchunks - 1)
4591 {
4592 /* Adjust cached curix & curline */
4593 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4594 curix++;
4595 }
4596 curchnk = buf->b_ml.ml_chunksize + curix;
4597
4598 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00004599 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004600 curchnk->mlcs_totalsize += len;
4601 if (updtype == ML_CHNK_ADDLINE)
4602 {
4603 curchnk->mlcs_numlines++;
4604
4605 /* May resize here so we don't have to do it in both cases below */
4606 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
4607 {
4608 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
4609 buf->b_ml.ml_chunksize = (chunksize_T *)
4610 vim_realloc(buf->b_ml.ml_chunksize,
4611 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
4612 if (buf->b_ml.ml_chunksize == NULL)
4613 {
4614 /* Hmmmm, Give up on offset for this buffer */
4615 buf->b_ml.ml_usedchunks = -1;
4616 return;
4617 }
4618 }
4619
4620 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
4621 {
4622 int count; /* number of entries in block */
4623 int idx;
4624 int text_end;
4625 int linecnt;
4626
4627 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
4628 buf->b_ml.ml_chunksize + curix,
4629 (buf->b_ml.ml_usedchunks - curix) *
4630 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00004631 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 size = 0;
4633 linecnt = 0;
4634 while (curline < buf->b_ml.ml_line_count
4635 && linecnt < MLCS_MINL)
4636 {
4637 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
4638 {
4639 buf->b_ml.ml_usedchunks = -1;
4640 return;
4641 }
4642 dp = (DATA_BL *)(hp->bh_data);
4643 count = (long)(buf->b_ml.ml_locked_high) -
4644 (long)(buf->b_ml.ml_locked_low) + 1;
4645 idx = curline - buf->b_ml.ml_locked_low;
4646 curline = buf->b_ml.ml_locked_high + 1;
4647 if (idx == 0)/* first line in block, text at the end */
4648 text_end = dp->db_txt_end;
4649 else
4650 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
4651 /* Compute index of last line to use in this MEMLINE */
4652 rest = count - idx;
4653 if (linecnt + rest > MLCS_MINL)
4654 {
4655 idx += MLCS_MINL - linecnt - 1;
4656 linecnt = MLCS_MINL;
4657 }
4658 else
4659 {
4660 idx = count - 1;
4661 linecnt += rest;
4662 }
4663 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
4664 }
4665 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
4666 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
4667 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
4668 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
4669 buf->b_ml.ml_usedchunks++;
4670 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
4671 return;
4672 }
4673 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
4674 && curix == buf->b_ml.ml_usedchunks - 1
4675 && buf->b_ml.ml_line_count - line <= 1)
4676 {
4677 /*
4678 * We are in the last chunk and it is cheap to crate a new one
4679 * after this. Do it now to avoid the loop above later on
4680 */
4681 curchnk = buf->b_ml.ml_chunksize + curix + 1;
4682 buf->b_ml.ml_usedchunks++;
4683 if (line == buf->b_ml.ml_line_count)
4684 {
4685 curchnk->mlcs_numlines = 0;
4686 curchnk->mlcs_totalsize = 0;
4687 }
4688 else
4689 {
4690 /*
4691 * Line is just prior to last, move count for last
4692 * This is the common case when loading a new file
4693 */
4694 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
4695 if (hp == NULL)
4696 {
4697 buf->b_ml.ml_usedchunks = -1;
4698 return;
4699 }
4700 dp = (DATA_BL *)(hp->bh_data);
4701 if (dp->db_line_count == 1)
4702 rest = dp->db_txt_end - dp->db_txt_start;
4703 else
4704 rest =
4705 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
4706 - dp->db_txt_start;
4707 curchnk->mlcs_totalsize = rest;
4708 curchnk->mlcs_numlines = 1;
4709 curchnk[-1].mlcs_totalsize -= rest;
4710 curchnk[-1].mlcs_numlines -= 1;
4711 }
4712 }
4713 }
4714 else if (updtype == ML_CHNK_DELLINE)
4715 {
4716 curchnk->mlcs_numlines--;
4717 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
4718 if (curix < (buf->b_ml.ml_usedchunks - 1)
4719 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
4720 <= MLCS_MINL)
4721 {
4722 curix++;
4723 curchnk = buf->b_ml.ml_chunksize + curix;
4724 }
4725 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
4726 {
4727 buf->b_ml.ml_usedchunks--;
4728 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
4729 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
4730 return;
4731 }
4732 else if (curix == 0 || (curchnk->mlcs_numlines > 10
4733 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
4734 > MLCS_MINL))
4735 {
4736 return;
4737 }
4738
4739 /* Collapse chunks */
4740 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
4741 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
4742 buf->b_ml.ml_usedchunks--;
4743 if (curix < buf->b_ml.ml_usedchunks)
4744 {
4745 mch_memmove(buf->b_ml.ml_chunksize + curix,
4746 buf->b_ml.ml_chunksize + curix + 1,
4747 (buf->b_ml.ml_usedchunks - curix) *
4748 sizeof(chunksize_T));
4749 }
4750 return;
4751 }
4752 ml_upd_lastbuf = buf;
4753 ml_upd_lastline = line;
4754 ml_upd_lastcurline = curline;
4755 ml_upd_lastcurix = curix;
4756}
4757
4758/*
4759 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004760 * Find line with offset if "lnum" is 0; return remaining offset in offp
4761 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762 * return -1 if information is not available
4763 */
4764 long
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004765ml_find_line_or_offset(buf, lnum, offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 buf_T *buf;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004767 linenr_T lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 long *offp;
4769{
4770 linenr_T curline;
4771 int curix;
4772 long size;
4773 bhdr_T *hp;
4774 DATA_BL *dp;
4775 int count; /* number of entries in block */
4776 int idx;
4777 int start_idx;
4778 int text_end;
4779 long offset;
4780 int len;
4781 int ffdos = (get_fileformat(buf) == EOL_DOS);
4782 int extra = 0;
4783
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004784 /* take care of cached line first */
4785 ml_flush_line(curbuf);
4786
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 if (buf->b_ml.ml_usedchunks == -1
4788 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004789 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 return -1;
4791
4792 if (offp == NULL)
4793 offset = 0;
4794 else
4795 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004796 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
4798 /*
4799 * Find the last chunk before the one containing our line. Last chunk is
4800 * special because it will never qualify
4801 */
4802 curline = 1;
4803 curix = size = 0;
4804 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004805 && ((lnum != 0
4806 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 || (offset != 0
4808 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
4809 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
4810 {
4811 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4812 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
4813 if (offset && ffdos)
4814 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4815 curix++;
4816 }
4817
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004818 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 {
4820 if (curline > buf->b_ml.ml_line_count
4821 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
4822 return -1;
4823 dp = (DATA_BL *)(hp->bh_data);
4824 count = (long)(buf->b_ml.ml_locked_high) -
4825 (long)(buf->b_ml.ml_locked_low) + 1;
4826 start_idx = idx = curline - buf->b_ml.ml_locked_low;
4827 if (idx == 0)/* first line in block, text at the end */
4828 text_end = dp->db_txt_end;
4829 else
4830 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
4831 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004832 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004834 if (curline + (count - idx) >= lnum)
4835 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 else
4837 idx = count - 1;
4838 }
4839 else
4840 {
4841 extra = 0;
4842 while (offset >= size
4843 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
4844 + ffdos)
4845 {
4846 if (ffdos)
4847 size++;
4848 if (idx == count - 1)
4849 {
4850 extra = 1;
4851 break;
4852 }
4853 idx++;
4854 }
4855 }
4856 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
4857 size += len;
4858 if (offset != 0 && size >= offset)
4859 {
4860 if (size + ffdos == offset)
4861 *offp = 0;
4862 else if (idx == start_idx)
4863 *offp = offset - size + len;
4864 else
4865 *offp = offset - size + len
4866 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
4867 curline += idx - start_idx + extra;
4868 if (curline > buf->b_ml.ml_line_count)
4869 return -1; /* exactly one byte beyond the end */
4870 return curline;
4871 }
4872 curline = buf->b_ml.ml_locked_high + 1;
4873 }
4874
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004875 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004876 {
4877 /* Count extra CR characters. */
4878 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00004879 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004880
4881 /* Don't count the last line break if 'bin' and 'noeol'. */
4882 if (buf->b_p_bin && !buf->b_p_eol)
4883 size -= ffdos + 1;
4884 }
4885
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 return size;
4887}
4888
4889/*
4890 * Goto byte in buffer with offset 'cnt'.
4891 */
4892 void
4893goto_byte(cnt)
4894 long cnt;
4895{
4896 long boff = cnt;
4897 linenr_T lnum;
4898
4899 ml_flush_line(curbuf); /* cached line may be dirty */
4900 setpcmark();
4901 if (boff)
4902 --boff;
4903 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
4904 if (lnum < 1) /* past the end */
4905 {
4906 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4907 curwin->w_curswant = MAXCOL;
4908 coladvance((colnr_T)MAXCOL);
4909 }
4910 else
4911 {
4912 curwin->w_cursor.lnum = lnum;
4913 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00004914# ifdef FEAT_VIRTUALEDIT
4915 curwin->w_cursor.coladd = 0;
4916# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 curwin->w_set_curswant = TRUE;
4918 }
4919 check_cursor();
4920
4921# ifdef FEAT_MBYTE
4922 /* Make sure the cursor is on the first byte of a multi-byte char. */
4923 if (has_mbyte)
4924 mb_adjust_cursor();
4925# endif
4926}
4927#endif