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