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