1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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.
11 /* #define CHECK(c, s) if (c) EMSG(s) */
15 * memline.c: Contains the functions for appending, deleting and changing the
16 * 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,
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.
27 * Block nr 0 contains the block0 structure (see below).
29 * Block nr 1 is the first pointer block. It is the root of the tree.
30 * Other pointer blocks are branches.
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.
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
45 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
46 # include "vimio.h" /* for mch_open(), must be before vim.h */
51 #ifndef UNIX /* it's in os_unix.h for Unix */
55 #if defined(SASC) || defined(__amigaos4__)
56 # include <proto/dos.h> /* for Open() and Close() */
63 typedef struct block0 ZERO_BL; /* contents of the first block */
64 typedef struct pointer_block PTR_BL; /* contents of a pointer block */
65 typedef struct data_block DATA_BL; /* contents of a data block */
66 typedef struct pointer_entry PTR_EN; /* block/line-count pair */
68 #define DATA_ID (('d' << 8) + 'a') /* data block id */
69 #define PTR_ID (('p' << 8) + 't') /* pointer block id */
70 #define BLOCK0_ID0 'b' /* block 0 id 0 */
71 #define BLOCK0_ID1 '0' /* block 0 id 1 */
72 #define BLOCK0_ID1_C0 'c' /* block 0 id 1 'cm' 0 */
73 #define BLOCK0_ID1_C1 'C' /* block 0 id 1 'cm' 1 */
76 * pointer to a block, used in a pointer block
80 blocknr_T pe_bnum; /* block number */
81 linenr_T pe_line_count; /* number of lines in this branch */
82 linenr_T pe_old_lnum; /* lnum for this block (for recovery) */
83 int pe_page_count; /* number of pages in block pe_bnum */
87 * A pointer block contains a list of branches in the tree.
91 short_u pb_id; /* ID for pointer block: PTR_ID */
92 short_u pb_count; /* number of pointers in this block */
93 short_u pb_count_max; /* maximum value for pb_count */
94 PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer)
95 * followed by empty space until end of page */
99 * A data block is a leaf in the tree.
101 * The text of the lines is at the end of the block. The text of the first line
102 * in the block is put at the end, the text of the second line in front of it,
103 * etc. Thus the order of the lines is the opposite of the line number.
107 short_u db_id; /* ID for data block: DATA_ID */
108 unsigned db_free; /* free space available */
109 unsigned db_txt_start; /* byte where text starts */
110 unsigned db_txt_end; /* byte just after data block */
111 linenr_T db_line_count; /* number of lines in this block */
112 unsigned db_index[1]; /* index for start of line (actually bigger)
113 * followed by empty space upto db_txt_start
114 * followed by the text in the lines until
119 * The low bits of db_index hold the actual index. The topmost bit is
120 * used for the global command to be able to mark a line.
121 * This method is not clean, but otherwise there would be at least one extra
122 * byte used for each line.
123 * The mark has to be in this place to keep it with the correct line when other
124 * lines are inserted or deleted.
126 #define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
127 #define DB_INDEX_MASK (~DB_MARKED)
129 #define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */
130 #define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */
132 #define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */
133 #define B0_FNAME_SIZE_NOCRYPT 898 /* 2 bytes used for other things */
134 #define B0_FNAME_SIZE_CRYPT 890 /* 10 bytes used for other things */
135 #define B0_UNAME_SIZE 40
136 #define B0_HNAME_SIZE 40
138 * Restrict the numbers to 32 bits, otherwise most compilers will complain.
139 * This won't detect a 64 bit machine that only swaps a byte in the top 32
140 * bits, but that is crazy anyway.
142 #define B0_MAGIC_LONG 0x30313233L
143 #define B0_MAGIC_INT 0x20212223L
144 #define B0_MAGIC_SHORT 0x10111213L
145 #define B0_MAGIC_CHAR 0x55
148 * Block zero holds all info about the swap file.
150 * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
151 * swap files unusable!
153 * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
155 * This block is built up of single bytes, to make it portable across
156 * different machines. b0_magic_* is used to check the byte order and size of
157 * variables, because the rest of the swap file is not portable.
161 char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1,
162 * BLOCK0_ID1_C0, BLOCK0_ID1_C1 */
163 char_u b0_version[10]; /* Vim version string */
164 char_u b0_page_size[4];/* number of bytes per page */
165 char_u b0_mtime[4]; /* last modification time of file */
166 char_u b0_ino[4]; /* inode of b0_fname */
167 char_u b0_pid[4]; /* process id of creator (or 0) */
168 char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */
169 char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */
170 char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */
171 long b0_magic_long; /* check for byte order of long */
172 int b0_magic_int; /* check for byte order of int */
173 short b0_magic_short; /* check for byte order of short */
174 char_u b0_magic_char; /* check for last char */
178 * Note: b0_dirty and b0_flags are put at the end of the file name. For very
179 * long file names in older versions of Vim they are invalid.
180 * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
181 * when there is room, for very long file names it's omitted.
183 #define B0_DIRTY 0x55
184 #define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1]
187 * The b0_flags field is new in Vim 7.0.
189 #define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2]
192 * Crypt seed goes here, 8 bytes. New in Vim 7.3.
193 * Without encryption these bytes may be used for 'fenc'.
195 #define b0_seed b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN]
197 /* The lowest two bits contain the fileformat. Zero means it's not set
198 * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
202 /* Swap file is in directory of edited file. Used to find the file from
203 * different mount points. */
204 #define B0_SAME_DIR 4
206 /* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
207 * When empty there is only the NUL. */
208 #define B0_HAS_FENC 8
210 #define STACK_INCR 5 /* nr of entries added to ml_stack at a time */
213 * The line number where the first mark may be is remembered.
214 * If it is 0 there are no marks at all.
215 * (always used for the current buffer only, no buffer change possible while
216 * executing a global command).
218 static linenr_T lowest_marked = 0;
221 * arguments for ml_find_line()
223 #define ML_DELETE 0x11 /* delete line */
224 #define ML_INSERT 0x12 /* insert line */
225 #define ML_FIND 0x13 /* just find the line */
226 #define ML_FLUSH 0x02 /* flush locked block */
227 #define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */
229 /* argument for ml_upd_block0() */
231 UB_FNAME = 0 /* update timestamp and filename */
232 , UB_SAME_DIR /* update the B0_SAME_DIR flag */
233 , UB_CRYPT /* update crypt key */
237 static void ml_set_b0_crypt __ARGS((buf_T *buf, ZERO_BL *b0p));
239 static int ml_check_b0_id __ARGS((ZERO_BL *b0p));
240 static void ml_upd_block0 __ARGS((buf_T *buf, upd_block0_T what));
241 static void set_b0_fname __ARGS((ZERO_BL *, buf_T *buf));
242 static void set_b0_dir_flag __ARGS((ZERO_BL *b0p, buf_T *buf));
244 static void add_b0_fenc __ARGS((ZERO_BL *b0p, buf_T *buf));
246 static time_t swapfile_info __ARGS((char_u *));
247 static int recov_file_names __ARGS((char_u **, char_u *, int prepend_dot));
248 static int ml_append_int __ARGS((buf_T *, linenr_T, char_u *, colnr_T, int, int));
249 static int ml_delete_int __ARGS((buf_T *, linenr_T, int));
250 static char_u *findswapname __ARGS((buf_T *, char_u **, char_u *));
251 static void ml_flush_line __ARGS((buf_T *));
252 static bhdr_T *ml_new_data __ARGS((memfile_T *, int, int));
253 static bhdr_T *ml_new_ptr __ARGS((memfile_T *));
254 static bhdr_T *ml_find_line __ARGS((buf_T *, linenr_T, int));
255 static int ml_add_stack __ARGS((buf_T *));
256 static void ml_lineadd __ARGS((buf_T *, int));
257 static int b0_magic_wrong __ARGS((ZERO_BL *));
259 static int fnamecmp_ino __ARGS((char_u *, char_u *, long));
261 static void long_to_char __ARGS((long, char_u *));
262 static long char_to_long __ARGS((char_u *));
263 #if defined(UNIX) || defined(WIN3264)
264 static char_u *make_percent_swname __ARGS((char_u *dir, char_u *name));
267 static void ml_crypt_prepare __ARGS((memfile_T *mfp, off_t offset, int reading));
270 static void ml_updatechunk __ARGS((buf_T *buf, long line, long len, int updtype));
274 * Open a new memline for "buf".
276 * Return FAIL for failure, OK otherwise.
289 * init fields in memline struct
291 buf->b_ml.ml_stack_size = 0; /* no stack yet */
292 buf->b_ml.ml_stack = NULL; /* no stack yet */
293 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
294 buf->b_ml.ml_locked = NULL; /* no cached block */
295 buf->b_ml.ml_line_lnum = 0; /* no cached line */
297 buf->b_ml.ml_chunksize = NULL;
301 * When 'updatecount' is non-zero swap file may be opened later.
303 if (p_uc && buf->b_p_swf)
304 buf->b_may_swap = TRUE;
306 buf->b_may_swap = FALSE;
309 * Open the memfile. No swap file is created yet.
311 mfp = mf_open(NULL, 0);
315 buf->b_ml.ml_mfp = mfp;
317 mfp->mf_buffer = buf;
319 buf->b_ml.ml_flags = ML_EMPTY;
320 buf->b_ml.ml_line_count = 1;
321 #ifdef FEAT_LINEBREAK
322 curwin->w_nrwidth_line_count = 0;
325 #if defined(MSDOS) && !defined(DJGPP)
326 /* for 16 bit MS-DOS create a swapfile now, because we run out of
327 * memory very quickly */
333 * fill block0 struct and write page 0
335 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
337 if (hp->bh_bnum != 0)
339 EMSG(_("E298: Didn't get block nr 0?"));
342 b0p = (ZERO_BL *)(hp->bh_data);
344 b0p->b0_id[0] = BLOCK0_ID0;
345 b0p->b0_id[1] = BLOCK0_ID1;
346 b0p->b0_magic_long = (long)B0_MAGIC_LONG;
347 b0p->b0_magic_int = (int)B0_MAGIC_INT;
348 b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
349 b0p->b0_magic_char = B0_MAGIC_CHAR;
350 STRNCPY(b0p->b0_version, "VIM ", 4);
351 STRNCPY(b0p->b0_version + 4, Version, 6);
352 long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
358 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
359 b0p->b0_flags = get_fileformat(buf) + 1;
360 set_b0_fname(b0p, buf);
361 (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
362 b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
363 mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
364 b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
365 long_to_char(mch_get_pid(), b0p->b0_pid);
367 if (*buf->b_p_key != NUL)
368 ml_set_b0_crypt(buf, b0p);
373 * Always sync block number 0 to disk, so we can check the file name in
374 * the swap file in findswapname(). Don't do this for a help files or
375 * a spell buffer though.
376 * Only works when there's a swapfile, otherwise it's done when the file
379 mf_put(mfp, hp, TRUE, FALSE);
380 if (!buf->b_help && !B_SPELL(buf))
381 (void)mf_sync(mfp, 0);
384 * Fill in root pointer block and write page 1.
386 if ((hp = ml_new_ptr(mfp)) == NULL)
388 if (hp->bh_bnum != 1)
390 EMSG(_("E298: Didn't get block nr 1?"));
393 pp = (PTR_BL *)(hp->bh_data);
395 pp->pb_pointer[0].pe_bnum = 2;
396 pp->pb_pointer[0].pe_page_count = 1;
397 pp->pb_pointer[0].pe_old_lnum = 1;
398 pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */
399 mf_put(mfp, hp, TRUE, FALSE);
402 * Allocate first data block and create an empty line 1.
404 if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
406 if (hp->bh_bnum != 2)
408 EMSG(_("E298: Didn't get block nr 2?"));
412 dp = (DATA_BL *)(hp->bh_data);
413 dp->db_index[0] = --dp->db_txt_start; /* at end of block */
414 dp->db_free -= 1 + INDEX_SIZE;
415 dp->db_line_count = 1;
416 *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */
424 mf_put(mfp, hp, FALSE, FALSE);
425 mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */
427 buf->b_ml.ml_mfp = NULL;
431 #if defined(FEAT_CRYPT) || defined(PROTO)
433 * Prepare encryption for "buf" with block 0 "b0p".
436 ml_set_b0_crypt(buf, b0p)
440 if (*buf->b_p_key == NUL)
441 b0p->b0_id[1] = BLOCK0_ID1;
444 if (get_crypt_method(buf) == 0)
445 b0p->b0_id[1] = BLOCK0_ID1_C0;
448 b0p->b0_id[1] = BLOCK0_ID1_C1;
449 /* Generate a seed and store it in block 0 and in the memfile. */
450 sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0);
451 mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
457 * Called after the crypt key or 'cryptmethod' was changed for "buf".
458 * Will apply this to the swapfile.
459 * "old_key" is the previous key. It is equal to buf->b_p_key when
460 * 'cryptmethod' is changed.
461 * "old_cm" is the previous 'cryptmethod'. It is equal to the current
462 * 'cryptmethod' when 'key' is changed.
465 ml_set_crypt_key(buf, old_key, old_cm)
470 memfile_T *mfp = buf->b_ml.ml_mfp;
482 return; /* no memfile yet, nothing to do */
484 /* Set the key, method and seed to be used for reading, these must be the
486 mfp->mf_old_key = old_key;
487 mfp->mf_old_cm = old_cm;
489 mch_memmove(mfp->mf_old_seed, mfp->mf_seed, MF_SEED_LEN);
491 /* Update block 0 with the crypt flag and may set a new seed. */
492 ml_upd_block0(buf, UB_CRYPT);
494 if (mfp->mf_infile_count > 2)
497 * Need to read back all data blocks from disk, decrypt them with the
498 * old key/method and mark them to be written. The algorithm is
499 * similar to what happens in ml_recover(), but we skip negative block
502 ml_flush_line(buf); /* flush buffered line */
503 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
506 bnum = 1; /* start with block 1 */
507 page_count = 1; /* which is 1 page */
508 idx = 0; /* start with first index in block 1 */
510 buf->b_ml.ml_stack_top = 0;
511 vim_free(buf->b_ml.ml_stack);
512 buf->b_ml.ml_stack = NULL;
513 buf->b_ml.ml_stack_size = 0; /* no stack yet */
515 for ( ; !got_int; line_breakcheck())
518 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
520 /* get the block (pointer or data) */
521 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
529 pp = (PTR_BL *)(hp->bh_data);
530 if (pp->pb_id == PTR_ID) /* it is a pointer block */
532 if (pp->pb_count == 0)
537 else if (idx < (int)pp->pb_count) /* go a block deeper */
539 if (pp->pb_pointer[idx].pe_bnum < 0)
541 /* Skip data block with negative block number. */
542 ++idx; /* get same block again for next index */
546 /* going one block deeper in the tree, new entry in
548 if ((top = ml_add_stack(buf)) < 0)
551 break; /* out of memory */
553 ip = &(buf->b_ml.ml_stack[top]);
557 bnum = pp->pb_pointer[idx].pe_bnum;
558 page_count = pp->pb_pointer[idx].pe_page_count;
562 else /* not a pointer block */
564 dp = (DATA_BL *)(hp->bh_data);
565 if (dp->db_id != DATA_ID) /* block id wrong */
569 /* It is a data block, need to write it back to disk. */
570 mf_put(mfp, hp, TRUE, FALSE);
576 if (buf->b_ml.ml_stack_top == 0) /* finished */
579 /* go one block up in the tree */
580 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
582 idx = ip->ip_index + 1; /* go to next index */
587 mfp->mf_old_key = NULL;
592 * ml_setname() is called when the file name of "buf" has been changed.
593 * It may rename the swap file.
603 #if defined(MSDOS) || defined(MSWIN)
607 mfp = buf->b_ml.ml_mfp;
608 if (mfp->mf_fd < 0) /* there is no swap file yet */
611 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
612 * For help files we will make a swap file now.
615 ml_open_file(buf); /* create a swap file */
620 * Try all directories in the 'directory' option.
625 if (*dirp == NUL) /* tried all directories, fail */
627 fname = findswapname(buf, &dirp, mfp->mf_fname);
629 if (fname == NULL) /* no file name found for this dir */
632 #if defined(MSDOS) || defined(MSWIN)
634 * Set full pathname for swap file now, because a ":!cd dir" may
635 * change directory without us knowing it.
637 p = FullName_save(fname, FALSE);
643 /* if the file name is the same we don't have to do anything */
644 if (fnamecmp(fname, mfp->mf_fname) == 0)
650 /* need to close the swap file before renaming */
657 /* try to rename the swap file */
658 if (vim_rename(mfp->mf_fname, fname) == 0)
661 vim_free(mfp->mf_fname);
662 mfp->mf_fname = fname;
663 vim_free(mfp->mf_ffname);
664 #if defined(MSDOS) || defined(MSWIN)
665 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
669 ml_upd_block0(buf, UB_SAME_DIR);
672 vim_free(fname); /* this fname didn't work, try another */
675 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
677 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
680 /* could not (re)open the swap file, what can we do???? */
681 EMSG(_("E301: Oops, lost the swap file!!!"));
684 #ifdef HAVE_FD_CLOEXEC
686 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
687 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
688 fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
693 EMSG(_("E302: Could not rename swap file"));
697 * Open a file for the memfile for all buffers that are not readonly or have
699 * Used when 'updatecount' changes from zero to non-zero.
706 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
707 if (!buf->b_p_ro || buf->b_changed)
712 * Open a swap file for an existing memfile, if there is no swap file yet.
713 * If we are unable to find a file name, mf_fname will be NULL
714 * and the memfile will be in memory only (no recovery possible).
724 mfp = buf->b_ml.ml_mfp;
725 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf)
726 return; /* nothing to do */
729 /* For a spell buffer use a temp file name. */
732 fname = vim_tempname('s');
734 (void)mf_open_file(mfp, fname); /* consumes fname! */
735 buf->b_may_swap = FALSE;
741 * Try all directories in 'directory' option.
748 /* There is a small chance that between choosing the swap file name
749 * and creating it, another Vim creates the file. In that case the
750 * creation will fail and we will use another directory. */
751 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
754 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
756 #if defined(MSDOS) || defined(MSWIN) || defined(RISCOS)
758 * set full pathname for swap file now, because a ":!cd dir" may
759 * change directory without us knowing it.
763 ml_upd_block0(buf, UB_SAME_DIR);
765 /* Flush block zero, so others can read it */
766 if (mf_sync(mfp, MFS_ZERO) == OK)
768 /* Mark all blocks that should be in the swapfile as dirty.
769 * Needed for when the 'swapfile' option was reset, so that
770 * the swap file was deleted, and then on again. */
774 /* Writing block 0 failed: close the file and try another dir */
775 mf_close_file(buf, FALSE);
779 if (mfp->mf_fname == NULL) /* Failed! */
781 need_wait_return = TRUE; /* call wait_return later */
783 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
784 buf_spname(buf) != NULL
785 ? (char_u *)buf_spname(buf)
790 /* don't try to open a swap file again */
791 buf->b_may_swap = FALSE;
795 * If still need to create a swap file, and starting to edit a not-readonly
796 * file, or reading into an existing buffer, create a swap file now.
799 check_need_swap(newfile)
800 int newfile; /* reading file into new buffer */
802 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
803 ml_open_file(curbuf);
807 * Close memline for buffer 'buf'.
808 * If 'del_file' is TRUE, delete the swap file
811 ml_close(buf, del_file)
815 if (buf->b_ml.ml_mfp == NULL) /* not open */
817 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
818 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
819 vim_free(buf->b_ml.ml_line_ptr);
820 vim_free(buf->b_ml.ml_stack);
822 vim_free(buf->b_ml.ml_chunksize);
823 buf->b_ml.ml_chunksize = NULL;
825 buf->b_ml.ml_mfp = NULL;
827 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
828 * this buffer is loaded. */
829 buf->b_flags &= ~BF_RECOVERED;
833 * Close all existing memlines and memfiles.
834 * Only used when exiting.
835 * When 'del_file' is TRUE, delete the memfiles.
836 * But don't delete files that were ":preserve"d when we are POSIX compatible.
839 ml_close_all(del_file)
844 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
845 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
846 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
848 vim_deltempdir(); /* delete created temp directory */
853 * Close all memfiles for not modified buffers.
854 * Only use just before exiting!
861 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
862 if (!bufIsChanged(buf))
863 ml_close(buf, TRUE); /* close all not-modified buffers */
867 * Update the timestamp in the .swp file.
868 * Used when the file has been written.
874 ml_upd_block0(buf, UB_FNAME);
878 * Return FAIL when the ID of "b0p" is wrong.
884 if (b0p->b0_id[0] != BLOCK0_ID0
885 || (b0p->b0_id[1] != BLOCK0_ID1
886 && b0p->b0_id[1] != BLOCK0_ID1_C0
887 && b0p->b0_id[1] != BLOCK0_ID1_C1)
894 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
897 ml_upd_block0(buf, what)
905 mfp = buf->b_ml.ml_mfp;
906 if (mfp == NULL || (hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
908 b0p = (ZERO_BL *)(hp->bh_data);
909 if (ml_check_b0_id(b0p) == FAIL)
910 EMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
913 if (what == UB_FNAME)
914 set_b0_fname(b0p, buf);
916 else if (what == UB_CRYPT)
917 ml_set_b0_crypt(buf, b0p);
919 else /* what == UB_SAME_DIR */
920 set_b0_dir_flag(b0p, buf);
922 mf_put(mfp, hp, TRUE, FALSE);
926 * Write file name and timestamp into block 0 of a swap file.
927 * Also set buf->b_mtime.
928 * Don't use NameBuff[]!!!
931 set_b0_fname(b0p, buf)
937 if (buf->b_ffname == NULL)
938 b0p->b0_fname[0] = NUL;
941 #if defined(MSDOS) || defined(MSWIN) || defined(AMIGA) || defined(RISCOS)
942 /* Systems that cannot translate "~user" back into a path: copy the
943 * file name unmodified. Do use slashes instead of backslashes for
945 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
946 # ifdef BACKSLASH_IN_FILENAME
947 forward_slash(b0p->b0_fname);
951 char_u uname[B0_UNAME_SIZE];
954 * For a file under the home directory of the current user, we try to
955 * replace the home directory path with "~user". This helps when
956 * editing the same file on different machines over a network.
957 * First replace home dir path with "~/" with home_replace().
958 * Then insert the user name to get "~user/".
960 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
961 B0_FNAME_SIZE_CRYPT, TRUE);
962 if (b0p->b0_fname[0] == '~')
964 flen = STRLEN(b0p->b0_fname);
965 /* If there is no user name or it is too long, don't use "~/" */
966 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
967 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
968 vim_strncpy(b0p->b0_fname, buf->b_ffname,
969 B0_FNAME_SIZE_CRYPT - 1);
972 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
973 mch_memmove(b0p->b0_fname + 1, uname, ulen);
977 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
979 long_to_char((long)st.st_mtime, b0p->b0_mtime);
981 long_to_char((long)st.st_ino, b0p->b0_ino);
983 buf_store_time(buf, &st, buf->b_ffname);
984 buf->b_mtime_read = buf->b_mtime;
988 long_to_char(0L, b0p->b0_mtime);
990 long_to_char(0L, b0p->b0_ino);
993 buf->b_mtime_read = 0;
994 buf->b_orig_size = 0;
995 buf->b_orig_mode = 0;
1000 /* Also add the 'fileencoding' if there is room. */
1001 add_b0_fenc(b0p, curbuf);
1006 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1007 * swapfile for "buf" are in the same directory.
1008 * This is fail safe: if we are not sure the directories are equal the flag is
1012 set_b0_dir_flag(b0p, buf)
1016 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1017 b0p->b0_flags |= B0_SAME_DIR;
1019 b0p->b0_flags &= ~B0_SAME_DIR;
1024 * When there is room, add the 'fileencoding' to block zero.
1027 add_b0_fenc(b0p, buf)
1032 int size = B0_FNAME_SIZE_NOCRYPT;
1035 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1036 * With encryption it's OK to move elsewhere, the swap file is not
1037 * compatible anyway. */
1038 if (*buf->b_p_key != NUL)
1039 size = B0_FNAME_SIZE_CRYPT;
1042 n = (int)STRLEN(buf->b_p_fenc);
1043 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
1044 b0p->b0_flags &= ~B0_HAS_FENC;
1047 mch_memmove((char *)b0p->b0_fname + size - n,
1048 (char *)buf->b_p_fenc, (size_t)n);
1049 *(b0p->b0_fname + size - n - 1) = NUL;
1050 b0p->b0_flags |= B0_HAS_FENC;
1057 * Try to recover curbuf from the .swp file.
1063 memfile_T *mfp = NULL;
1065 char_u *fname_used = NULL;
1069 char_u *b0_fenc = NULL;
1078 struct stat org_stat, swp_stat;
1086 linenr_T line_count;
1092 int called_from_main;
1093 int serious_error = TRUE;
1096 int orig_file_status = NOTDONE;
1098 recoverymode = TRUE;
1099 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1100 attr = hl_attr(HLF_E);
1103 * If the file name ends in ".s[uvw][a-z]" we assume this is the swap file.
1104 * Otherwise a search is done to find the swap file(s).
1106 fname = curbuf->b_fname;
1107 if (fname == NULL) /* When there is no file name */
1108 fname = (char_u *)"";
1109 len = (int)STRLEN(fname);
1111 #if defined(VMS) || defined(RISCOS)
1112 STRNICMP(fname + len - 4, "_s" , 2)
1114 STRNICMP(fname + len - 4, ".s" , 2)
1117 && vim_strchr((char_u *)"UVWuvw", fname[len - 2]) != NULL
1118 && ASCII_ISALPHA(fname[len - 1]))
1121 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
1127 /* count the number of matching swap files */
1128 len = recover_names(fname, FALSE, 0, NULL);
1129 if (len == 0) /* no swap files found */
1131 EMSG2(_("E305: No swap file found for %s"), fname);
1134 if (len == 1) /* one swap file found, use it */
1136 else /* several swap files found, choose */
1138 /* list the names of the swap files */
1139 (void)recover_names(fname, TRUE, 0, NULL);
1141 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
1142 i = get_number(FALSE, NULL);
1143 if (i < 1 || i > len)
1146 /* get the swap file name that will be used */
1147 (void)recover_names(fname, FALSE, i, &fname_used);
1149 if (fname_used == NULL)
1150 goto theend; /* out of memory */
1152 /* When called from main() still need to initialize storage structure */
1153 if (called_from_main && ml_open(curbuf) == FAIL)
1157 * Allocate a buffer structure for the swap file that is used for recovery.
1158 * Only the memline and crypt information in it are really used.
1160 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1165 * init fields in memline struct
1167 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1168 buf->b_ml.ml_stack = NULL; /* no stack yet */
1169 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1170 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1171 buf->b_ml.ml_locked = NULL; /* no locked block */
1172 buf->b_ml.ml_flags = 0;
1174 buf->b_p_key = empty_option;
1175 buf->b_p_cm = empty_option;
1179 * open the memfile from the old swap file
1181 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1182 mf_open() will consume "fname_used"! */
1183 mfp = mf_open(fname_used, O_RDONLY);
1185 if (mfp == NULL || mfp->mf_fd < 0)
1187 if (fname_used != NULL)
1188 EMSG2(_("E306: Cannot open %s"), fname_used);
1191 buf->b_ml.ml_mfp = mfp;
1193 mfp->mf_buffer = buf;
1197 * The page size set in mf_open() might be different from the page size
1198 * used in the swap file, we must get it from block 0. But to read block
1199 * 0 we need a page size. Use the minimal size for block 0 here, it will
1200 * be set to the real value below.
1202 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1205 * try to read block 0
1207 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1210 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1211 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1212 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
1217 b0p = (ZERO_BL *)(hp->bh_data);
1218 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1221 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1222 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1224 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1228 if (ml_check_b0_id(b0p) == FAIL)
1230 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1233 if (b0_magic_wrong(b0p))
1236 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1237 #if defined(MSDOS) || defined(MSWIN)
1238 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1239 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1243 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1245 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
1246 /* avoid going past the end of a corrupted hostname */
1247 b0p->b0_fname[0] = NUL;
1248 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1249 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1255 if (b0p->b0_id[1] == BLOCK0_ID1_C0)
1257 else if (b0p->b0_id[1] == BLOCK0_ID1_C1)
1260 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1262 set_crypt_method(buf, b0_cm);
1264 if (b0p->b0_id[1] != BLOCK0_ID1)
1266 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
1272 * If we guessed the wrong page size, we have to recalculate the
1273 * highest block number in the file.
1275 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1277 unsigned previous_page_size = mfp->mf_page_size;
1279 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
1280 if (mfp->mf_page_size < previous_page_size)
1283 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1284 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1289 if ((size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
1290 mfp->mf_blocknr_max = 0; /* no file or empty file */
1292 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1293 mfp->mf_infile_count = mfp->mf_blocknr_max;
1295 /* need to reallocate the memory used to store the data */
1296 p = alloc(mfp->mf_page_size);
1299 mch_memmove(p, hp->bh_data, previous_page_size);
1300 vim_free(hp->bh_data);
1302 b0p = (ZERO_BL *)(hp->bh_data);
1306 * If .swp file name given directly, use name from swap file for buffer.
1310 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1311 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1315 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
1316 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
1318 if (buf_spname(curbuf) != NULL)
1319 STRCPY(NameBuff, buf_spname(curbuf));
1321 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
1322 smsg((char_u *)_("Original file \"%s\""), NameBuff);
1326 * check date of swap file and original file
1328 mtime = char_to_long(b0p->b0_mtime);
1329 if (curbuf->b_ffname != NULL
1330 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1331 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1332 && org_stat.st_mtime > swp_stat.st_mtime)
1333 || org_stat.st_mtime != mtime))
1335 EMSG(_("E308: Warning: Original file may have been changed"));
1339 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1340 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1341 if (b0p->b0_flags & B0_HAS_FENC)
1343 int fnsize = B0_FNAME_SIZE_NOCRYPT;
1346 /* Use the same size as in add_b0_fenc(). */
1347 if (b0p->b0_id[1] != BLOCK0_ID1)
1348 fnsize = B0_FNAME_SIZE_CRYPT;
1350 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
1352 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
1355 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1359 * Now that we are sure that the file is going to be recovered, clear the
1360 * contents of the current buffer.
1362 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1363 ml_delete((linenr_T)1, FALSE);
1366 * Try reading the original file to obtain the values of 'fileformat',
1367 * 'fileencoding', etc. Ignore errors. The text itself is not used.
1368 * When the file is encrypted the user is asked to enter the key.
1370 if (curbuf->b_ffname != NULL)
1371 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
1372 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
1377 /* Need to ask the user for the crypt key. If this fails we continue
1378 * without a key, will probably get garbage text. */
1379 if (*curbuf->b_p_key != NUL)
1381 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1382 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1383 MSG_PUTS(_("\nenter the new crypt key."));
1384 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1385 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1388 smsg((char_u *)_(need_key_msg), fname_used);
1389 buf->b_p_key = get_crypt_key(FALSE, FALSE);
1390 if (buf->b_p_key == NULL)
1391 buf->b_p_key = curbuf->b_p_key;
1392 else if (*buf->b_p_key == NUL)
1394 vim_free(buf->b_p_key);
1395 buf->b_p_key = curbuf->b_p_key;
1397 if (buf->b_p_key == NULL)
1398 buf->b_p_key = empty_option;
1402 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1404 set_fileformat(b0_ff - 1, OPT_LOCAL);
1405 if (b0_fenc != NULL)
1407 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1410 unchanged(curbuf, TRUE);
1412 bnum = 1; /* start with block 1 */
1413 page_count = 1; /* which is 1 page */
1414 lnum = 0; /* append after line 0 in curbuf */
1416 idx = 0; /* start with first index in block 1 */
1418 buf->b_ml.ml_stack_top = 0;
1419 buf->b_ml.ml_stack = NULL;
1420 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1422 if (curbuf->b_ffname == NULL)
1425 cannot_open = FALSE;
1427 serious_error = FALSE;
1428 for ( ; !got_int; line_breakcheck())
1431 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1436 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1440 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1444 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1447 else /* there is a block */
1449 pp = (PTR_BL *)(hp->bh_data);
1450 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1452 /* check line count when using pointer block first time */
1453 if (idx == 0 && line_count != 0)
1455 for (i = 0; i < (int)pp->pb_count; ++i)
1456 line_count -= pp->pb_pointer[i].pe_line_count;
1457 if (line_count != 0)
1460 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1465 if (pp->pb_count == 0)
1467 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1471 else if (idx < (int)pp->pb_count) /* go a block deeper */
1473 if (pp->pb_pointer[idx].pe_bnum < 0)
1476 * Data block with negative block number.
1477 * Try to read lines from the original file.
1478 * This is slow, but it works.
1482 line_count = pp->pb_pointer[idx].pe_line_count;
1483 if (readfile(curbuf->b_ffname, NULL, lnum,
1484 pp->pb_pointer[idx].pe_old_lnum - 1,
1485 line_count, NULL, 0) == FAIL)
1493 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1496 ++idx; /* get same block again for next index */
1501 * going one block deeper in the tree
1503 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1506 break; /* out of memory */
1508 ip = &(buf->b_ml.ml_stack[top]);
1512 bnum = pp->pb_pointer[idx].pe_bnum;
1513 line_count = pp->pb_pointer[idx].pe_line_count;
1514 page_count = pp->pb_pointer[idx].pe_page_count;
1518 else /* not a pointer block */
1520 dp = (DATA_BL *)(hp->bh_data);
1521 if (dp->db_id != DATA_ID) /* block id wrong */
1525 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1530 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1536 * it is a data block
1537 * Append all the lines in this block
1541 * check length of block
1542 * if wrong, use length in pointer block
1544 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1546 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1550 dp->db_txt_end = page_count * mfp->mf_page_size;
1553 /* make sure there is a NUL at the end of the block */
1554 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1557 * check number of lines in block
1558 * if wrong, use count in data block
1560 if (line_count != dp->db_line_count)
1562 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1568 for (i = 0; i < dp->db_line_count; ++i)
1570 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
1571 if (txt_start <= (int)HEADER_SIZE
1572 || txt_start >= (int)dp->db_txt_end)
1574 p = (char_u *)"???";
1578 p = (char_u *)dp + txt_start;
1579 ml_append(lnum++, p, (colnr_T)0, TRUE);
1582 ml_append(lnum++, (char_u *)_("???END"),
1588 if (buf->b_ml.ml_stack_top == 0) /* finished */
1592 * go one block up in the tree
1594 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1596 idx = ip->ip_index + 1; /* go to next index */
1601 * Compare the buffer contents with the original file. When they differ
1602 * set the 'modified' flag.
1603 * Lines 1 - lnum are the new contents.
1604 * Lines lnum + 1 to ml_line_count are the original contents.
1605 * Line ml_line_count + 1 in the dummy empty line.
1607 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1609 /* Recovering an empty file results in two lines and the first line is
1610 * empty. Don't set the modified flag then. */
1611 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1614 ++curbuf->b_changedtick;
1619 for (idx = 1; idx <= lnum; ++idx)
1621 /* Need to copy one line, fetching the other one may flush it. */
1622 p = vim_strsave(ml_get(idx));
1623 i = STRCMP(p, ml_get(idx + lnum));
1628 ++curbuf->b_changedtick;
1635 * Delete the lines from the original file and the dummy line from the
1636 * empty buffer. These will now be after the last line in the buffer.
1638 while (curbuf->b_ml.ml_line_count > lnum
1639 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1640 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1641 curbuf->b_flags |= BF_RECOVERED;
1643 recoverymode = FALSE;
1645 EMSG(_("E311: Recovery Interrupted"));
1649 MSG(">>>>>>>>>>>>>");
1650 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1652 MSG(_("See \":help E312\" for more information."));
1653 MSG(">>>>>>>>>>>>>");
1657 if (curbuf->b_changed)
1659 MSG(_("Recovery completed. You should check if everything is OK."));
1660 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1661 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1664 MSG(_("Recovery completed. Buffer contents equals file contents."));
1665 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
1666 cmdline_row = msg_row;
1669 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1671 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1672 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1675 redraw_curbuf_later(NOT_VALID);
1678 vim_free(fname_used);
1679 recoverymode = FALSE;
1683 mf_put(mfp, hp, FALSE, FALSE);
1684 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1689 if (buf->b_p_key != curbuf->b_p_key)
1690 free_string_option(buf->b_p_key);
1691 free_string_option(buf->b_p_cm);
1693 vim_free(buf->b_ml.ml_stack);
1696 if (serious_error && called_from_main)
1697 ml_close(curbuf, TRUE);
1701 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1702 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1709 * Find the names of swap files in current directory and the directory given
1710 * with the 'directory' option.
1713 * - list the swap files for "vim -r"
1714 * - count the number of swap files when recovering
1715 * - list the swap files when recovering
1716 * - find the name of the n'th swap file when recovering
1719 recover_names(fname, list, nr, fname_out)
1720 char_u *fname; /* base for swap file name */
1721 int list; /* when TRUE, list the swap file names */
1722 int nr; /* when non-zero, return nr'th swap file name */
1723 char_u **fname_out; /* result when "nr" > 0 */
1735 char_u *fname_res = NULL;
1736 #ifdef HAVE_READLINK
1737 char_u fname_buf[MAXPATHL];
1742 #ifdef HAVE_READLINK
1743 /* Expand symlink in the file name, because the swap file is created
1744 * with the actual file instead of with the symlink. */
1745 if (resolve_symlink(fname, fname_buf) == OK)
1746 fname_res = fname_buf;
1754 /* use msg() to start the scrolling properly */
1755 msg((char_u *)_("Swap files found:"));
1760 * Do the loop for every directory in 'directory'.
1761 * First allocate some memory to put the directory name in.
1763 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1765 while (dir_name != NULL && *dirp)
1768 * Isolate a directory name from *dirp and put it in dir_name (we know
1769 * it is large enough, so use 31000 for length).
1770 * Advance dirp to next directory name.
1772 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1774 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1779 names[0] = vim_strsave((char_u *)"*_sw%");
1782 names[0] = vim_strsave((char_u *)"*_sw#");
1784 names[0] = vim_strsave((char_u *)"*.sw?");
1787 #if defined(UNIX) || defined(WIN3264)
1788 /* For Unix names starting with a dot are special. MS-Windows
1789 * supports this too, on some file systems. */
1790 names[1] = vim_strsave((char_u *)".*.sw?");
1791 names[2] = vim_strsave((char_u *)".sw?");
1795 names[1] = vim_strsave((char_u *)".*_sw%");
1803 num_names = recov_file_names(names, fname_res, TRUE);
1805 else /* check directory dir_name */
1810 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1813 names[0] = concat_fnames(dir_name, (char_u *)"*_sw#", TRUE);
1815 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
1818 #if defined(UNIX) || defined(WIN3264)
1819 /* For Unix names starting with a dot are special. MS-Windows
1820 * supports this too, on some file systems. */
1821 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1822 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1826 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1835 #if defined(UNIX) || defined(WIN3264)
1836 p = dir_name + STRLEN(dir_name);
1837 if (after_pathsep(dir_name, p) && p[-1] == p[-2])
1839 /* Ends with '//', Use Full path for swap name */
1840 tail = make_percent_swname(dir_name, fname_res);
1845 tail = gettail(fname_res);
1846 tail = concat_fnames(dir_name, tail, TRUE);
1852 num_names = recov_file_names(names, tail, FALSE);
1858 /* check for out-of-memory */
1859 for (i = 0; i < num_names; ++i)
1861 if (names[i] == NULL)
1863 for (i = 0; i < num_names; ++i)
1870 else if (expand_wildcards(num_names, names, &num_files, &files,
1871 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1875 * When no swap file found, wildcard expansion might have failed (e.g.
1876 * not able to execute the shell).
1877 * Try finding a swap file by simply adding ".swp" to the file name.
1879 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
1884 swapname = modname(fname_res,
1885 #if defined(VMS) || defined(RISCOS)
1886 (char_u *)"_swp", FALSE
1888 (char_u *)".swp", TRUE
1891 if (swapname != NULL)
1893 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1895 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1898 files[0] = swapname;
1908 * remove swapfile name of the current buffer, it must be ignored
1910 if (curbuf->b_ml.ml_mfp != NULL
1911 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1913 for (i = 0; i < num_files; ++i)
1914 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1916 /* Remove the name from files[i]. Move further entries
1917 * down. When the array becomes empty free it here, since
1918 * FreeWild() won't be called below. */
1920 if (--num_files == 0)
1923 for ( ; i < num_files; ++i)
1924 files[i] = files[i + 1];
1929 file_count += num_files;
1930 if (nr <= file_count)
1932 *fname_out = vim_strsave(
1933 files[nr - 1 + num_files - file_count]);
1934 dirp = (char_u *)""; /* stop searching */
1939 if (dir_name[0] == '.' && dir_name[1] == NUL)
1942 MSG_PUTS(_(" In current directory:\n"));
1944 MSG_PUTS(_(" Using specified name:\n"));
1948 MSG_PUTS(_(" In directory "));
1949 msg_home_replace(dir_name);
1955 for (i = 0; i < num_files; ++i)
1957 /* print the swap file name */
1958 msg_outnum((long)++file_count);
1960 msg_puts(gettail(files[i]));
1962 (void)swapfile_info(files[i]);
1966 MSG_PUTS(_(" -- none --\n"));
1970 file_count += num_files;
1972 for (i = 0; i < num_names; ++i)
1975 FreeWild(num_files, files);
1981 #if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
1983 * Append the full path to name with path separators made into percent
1984 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1987 make_percent_swname(dir, name)
1993 f = fix_fname(name != NULL ? name : (char_u *) "");
1997 s = alloc((unsigned)(STRLEN(f) + 1));
2001 for (d = s; *d != NUL; mb_ptr_adv(d))
2002 if (vim_ispathsep(*d))
2004 d = concat_fnames(dir, s, TRUE);
2013 #if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2014 static int process_still_running;
2018 * Give information about an existing swap file.
2019 * Returns timestamp (0 when unknown).
2022 swapfile_info(fname)
2028 time_t x = (time_t)0;
2031 char_u uname[B0_UNAME_SIZE];
2034 /* print the swap file date */
2035 if (mch_stat((char *)fname, &st) != -1)
2038 /* print name of owner of the file */
2039 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2041 MSG_PUTS(_(" owned by: "));
2042 msg_outtrans(uname);
2043 MSG_PUTS(_(" dated: "));
2047 MSG_PUTS(_(" dated: "));
2048 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
2049 p = ctime(&x); /* includes '\n' */
2051 MSG_PUTS("(invalid)\n");
2057 * print the original file name
2059 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2062 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
2064 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2066 MSG_PUTS(_(" [from Vim version 3.0]"));
2068 else if (ml_check_b0_id(&b0) == FAIL)
2070 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2074 MSG_PUTS(_(" file name: "));
2075 if (b0.b0_fname[0] == NUL)
2076 MSG_PUTS(_("[No Name]"));
2078 msg_outtrans(b0.b0_fname);
2080 MSG_PUTS(_("\n modified: "));
2081 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2083 if (*(b0.b0_uname) != NUL)
2085 MSG_PUTS(_("\n user name: "));
2086 msg_outtrans(b0.b0_uname);
2089 if (*(b0.b0_hname) != NUL)
2091 if (*(b0.b0_uname) != NUL)
2092 MSG_PUTS(_(" host name: "));
2094 MSG_PUTS(_("\n host name: "));
2095 msg_outtrans(b0.b0_hname);
2098 if (char_to_long(b0.b0_pid) != 0L)
2100 MSG_PUTS(_("\n process ID: "));
2101 msg_outnum(char_to_long(b0.b0_pid));
2102 #if defined(UNIX) || defined(__EMX__)
2103 /* EMX kill() not working correctly, it seems */
2104 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2106 MSG_PUTS(_(" (still running)"));
2107 # if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2108 process_still_running = TRUE;
2114 if (b0_magic_wrong(&b0))
2116 #if defined(MSDOS) || defined(MSWIN)
2117 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2118 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2121 MSG_PUTS(_("\n [not usable on this computer]"));
2126 MSG_PUTS(_(" [cannot be read]"));
2130 MSG_PUTS(_(" [cannot be opened]"));
2137 recov_file_names(names, path, prepend_dot)
2146 * (MS-DOS) always short names
2148 names[0] = modname(path, (char_u *)".sw?", FALSE);
2150 #else /* !SHORT_FNAME */
2152 * (Win32 and Win64) never short names, but do prepend a dot.
2153 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2154 * Only use the short name if it is different.
2159 int shortname = curbuf->b_shortname;
2161 curbuf->b_shortname = FALSE;
2167 * May also add the file name with a dot prepended, for swap file in same
2168 * dir as original file.
2172 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2173 if (names[num_names] == NULL)
2179 * Form the normal swap file name pattern by appending ".sw?".
2182 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2185 names[num_names] = concat_fnames(path, (char_u *)"_sw#", FALSE);
2187 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
2190 if (names[num_names] == NULL)
2192 if (num_names >= 1) /* check if we have the same name twice */
2194 p = names[num_names - 1];
2195 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2197 p += i; /* file name has been expanded to full path */
2199 if (STRCMP(p, names[num_names]) != 0)
2202 vim_free(names[num_names]);
2209 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2211 curbuf->b_shortname = TRUE;
2213 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2216 names[num_names] = modname(path, (char_u *)"_sw#", FALSE);
2218 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
2221 if (names[num_names] == NULL)
2225 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2227 p = names[num_names];
2228 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2230 p += i; /* file name has been expanded to full path */
2231 if (STRCMP(names[num_names - 1], p) == 0)
2232 vim_free(names[num_names]);
2239 curbuf->b_shortname = shortname;
2242 #endif /* !SHORT_FNAME */
2250 * If 'check_file' is TRUE, check if original file exists and was not changed.
2251 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2252 * always sync at least one block.
2255 ml_sync_all(check_file, check_char)
2262 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2264 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2265 continue; /* no file */
2267 ml_flush_line(buf); /* flush buffered line */
2268 /* flush locked block */
2269 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2270 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2271 && buf->b_ffname != NULL)
2274 * If the original file does not exist anymore or has been changed
2275 * call ml_preserve() to get rid of all negative numbered blocks.
2277 if (mch_stat((char *)buf->b_ffname, &st) == -1
2278 || st.st_mtime != buf->b_mtime_read
2279 || st.st_size != buf->b_orig_size)
2281 ml_preserve(buf, FALSE);
2282 did_check_timestamps = FALSE;
2283 need_check_timestamps = TRUE; /* give message later */
2286 if (buf->b_ml.ml_mfp->mf_dirty)
2288 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2289 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2290 if (check_char && ui_char_avail()) /* character available now */
2297 * sync one buffer, including negative blocks
2299 * after this all the blocks are in the swap file
2301 * Used for the :preserve command and when the original file has been
2302 * changed or deleted.
2304 * when message is TRUE the success of preserving is reported
2307 ml_preserve(buf, message)
2313 memfile_T *mfp = buf->b_ml.ml_mfp;
2315 int got_int_save = got_int;
2317 if (mfp == NULL || mfp->mf_fname == NULL)
2320 EMSG(_("E313: Cannot preserve, there is no swap file"));
2324 /* We only want to stop when interrupted here, not when interrupted
2328 ml_flush_line(buf); /* flush buffered line */
2329 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2330 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2332 /* stack is invalid after mf_sync(.., MFS_ALL) */
2333 buf->b_ml.ml_stack_top = 0;
2336 * Some of the data blocks may have been changed from negative to
2337 * positive block number. In that case the pointer blocks need to be
2340 * We don't know in which pointer block the references are, so we visit
2341 * all data blocks until there are no more translations to be done (or
2342 * we hit the end of the file, which can only happen in case a write fails,
2343 * e.g. when file system if full).
2344 * ml_find_line() does the work by translating the negative block numbers
2345 * when getting the first line of each data block.
2347 if (mf_need_trans(mfp) && !got_int)
2350 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2352 hp = ml_find_line(buf, lnum, ML_FIND);
2358 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2359 lnum = buf->b_ml.ml_locked_high + 1;
2361 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2362 /* sync the updated pointer blocks */
2363 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2365 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2368 got_int |= got_int_save;
2373 MSG(_("File preserved"));
2375 EMSG(_("E314: Preserve failed"));
2380 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2381 * until the next call!
2382 * line1 = ml_get(1);
2383 * line2 = ml_get(2); // line1 is now invalid!
2384 * Make a copy of the line if necessary.
2387 * get a pointer to a (read-only copy of a) line
2389 * On failure an error message is given and IObuff is returned (to avoid
2390 * having to check for error everywhere).
2396 return ml_get_buf(curbuf, lnum, FALSE);
2400 * ml_get_pos: get pointer to position 'pos'
2406 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2410 * ml_get_curline: get pointer to cursor line.
2415 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2419 * ml_get_cursor: get pointer to cursor position
2424 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2425 curwin->w_cursor.col);
2429 * get a pointer to a line in a specific buffer
2431 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2435 ml_get_buf(buf, lnum, will_change)
2438 int will_change; /* line will be changed */
2443 static int recursive = 0;
2445 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2449 /* Avoid giving this message for a recursive call, may happen when
2450 * the GUI redraws part of the text. */
2452 EMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
2456 STRCPY(IObuff, "???");
2459 if (lnum <= 0) /* pretend line 0 is line 1 */
2462 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2463 return (char_u *)"";
2466 * See if it is the same line as requested last time.
2467 * Otherwise may need to flush last used line.
2468 * Don't use the last used line when 'swapfile' is reset, need to load all
2471 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
2476 * Find the data block containing the line.
2477 * This also fills the stack with the blocks from the root to the data
2478 * block and releases any locked block.
2480 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2484 /* Avoid giving this message for a recursive call, may happen
2485 * when the GUI redraws part of the text. */
2487 EMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
2493 dp = (DATA_BL *)(hp->bh_data);
2495 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2496 buf->b_ml.ml_line_ptr = ptr;
2497 buf->b_ml.ml_line_lnum = lnum;
2498 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2501 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2503 return buf->b_ml.ml_line_ptr;
2507 * Check if a line that was just obtained by a call to ml_get
2508 * is in allocated memory.
2513 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2517 * Append a line after lnum (may be 0 to insert a line in front of the file).
2518 * "line" does not need to be allocated, but can't be another line in a
2519 * buffer, unlocking may make it invalid.
2521 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2522 * will be set for recovery
2523 * Check: The caller of this function should probably also call
2526 * return FAIL for failure, OK otherwise
2529 ml_append(lnum, line, len, newfile)
2530 linenr_T lnum; /* append after this line (can be 0) */
2531 char_u *line; /* text of the new line */
2532 colnr_T len; /* length of new line, including NUL, or 0 */
2533 int newfile; /* flag, see above */
2535 /* When starting up, we might still need to create the memfile */
2536 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
2539 if (curbuf->b_ml.ml_line_lnum != 0)
2540 ml_flush_line(curbuf);
2541 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2544 #if defined(FEAT_SPELL) || defined(PROTO)
2546 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2550 ml_append_buf(buf, lnum, line, len, newfile)
2552 linenr_T lnum; /* append after this line (can be 0) */
2553 char_u *line; /* text of the new line */
2554 colnr_T len; /* length of new line, including NUL, or 0 */
2555 int newfile; /* flag, see above */
2557 if (buf->b_ml.ml_mfp == NULL)
2560 if (buf->b_ml.ml_line_lnum != 0)
2562 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2567 ml_append_int(buf, lnum, line, len, newfile, mark)
2569 linenr_T lnum; /* append after this line (can be 0) */
2570 char_u *line; /* text of the new line */
2571 colnr_T len; /* length of line, including NUL, or 0 */
2572 int newfile; /* flag, see above */
2573 int mark; /* mark the new line */
2576 int line_count; /* number of indexes in current block */
2579 int space_needed; /* space needed for new line */
2582 int db_idx; /* index for lnum in data block */
2589 /* lnum out of range */
2590 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2593 if (lowest_marked && lowest_marked > lnum)
2594 lowest_marked = lnum + 1;
2597 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2598 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2600 mfp = buf->b_ml.ml_mfp;
2601 page_size = mfp->mf_page_size;
2604 * find the data block containing the previous line
2605 * This also fills the stack with the blocks from the root to the data block
2606 * This also releases any locked block.
2608 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2609 ML_INSERT)) == NULL)
2612 buf->b_ml.ml_flags &= ~ML_EMPTY;
2614 if (lnum == 0) /* got line one instead, correct db_idx */
2615 db_idx = -1; /* careful, it is negative! */
2617 db_idx = lnum - buf->b_ml.ml_locked_low;
2618 /* get line count before the insertion */
2619 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2621 dp = (DATA_BL *)(hp->bh_data);
2625 * - there is not enough room in the current block
2626 * - appending to the last line in the block
2627 * - not appending to the last line in the file
2628 * insert in front of the next block.
2630 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2631 && lnum < buf->b_ml.ml_line_count)
2634 * Now that the line is not going to be inserted in the block that we
2635 * expected, the line count has to be adjusted in the pointer blocks
2636 * by using ml_locked_lineadd.
2638 --(buf->b_ml.ml_locked_lineadd);
2639 --(buf->b_ml.ml_locked_high);
2640 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2643 db_idx = -1; /* careful, it is negative! */
2644 /* get line count before the insertion */
2645 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2646 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2648 dp = (DATA_BL *)(hp->bh_data);
2651 ++buf->b_ml.ml_line_count;
2653 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2656 * Insert new line in existing data block, or in data block allocated above.
2658 dp->db_txt_start -= len;
2659 dp->db_free -= space_needed;
2660 ++(dp->db_line_count);
2663 * move the text of the lines that follow to the front
2664 * adjust the indexes of the lines that follow
2666 if (line_count > db_idx + 1) /* if there are following lines */
2669 * Offset is the start of the previous line.
2670 * This will become the character just after the new line.
2673 offset = dp->db_txt_end;
2675 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2676 mch_memmove((char *)dp + dp->db_txt_start,
2677 (char *)dp + dp->db_txt_start + len,
2678 (size_t)(offset - (dp->db_txt_start + len)));
2679 for (i = line_count - 1; i > db_idx; --i)
2680 dp->db_index[i + 1] = dp->db_index[i] - len;
2681 dp->db_index[db_idx + 1] = offset - len;
2683 else /* add line at the end */
2684 dp->db_index[db_idx + 1] = dp->db_txt_start;
2687 * copy the text into the block
2689 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2691 dp->db_index[db_idx + 1] |= DB_MARKED;
2694 * Mark the block dirty.
2696 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2698 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2700 else /* not enough space in data block */
2703 * If there is not enough room we have to create a new data block and copy some
2705 * Then we have to insert an entry in the pointer block.
2706 * If this pointer block also is full, we go up another block, and so on, up
2707 * to the root if necessary.
2708 * The line counts in the pointer blocks have already been adjusted by
2711 long line_count_left, line_count_right;
2712 int page_count_left, page_count_right;
2717 int data_moved = 0; /* init to shut up gcc */
2718 int total_moved = 0; /* init to shut up gcc */
2719 DATA_BL *dp_right, *dp_left;
2723 blocknr_T bnum_left, bnum_right;
2724 linenr_T lnum_left, lnum_right;
2729 * We are going to allocate a new data block. Depending on the
2730 * situation it will be put to the left or right of the existing
2731 * block. If possible we put the new line in the left block and move
2732 * the lines after it to the right block. Otherwise the new line is
2733 * also put in the right block. This method is more efficient when
2734 * inserting a lot of lines at one place.
2736 if (db_idx < 0) /* left block is new, right block is existing */
2740 /* space_needed does not change */
2742 else /* left block is existing, right block is new */
2744 lines_moved = line_count - db_idx - 1;
2745 if (lines_moved == 0)
2746 in_left = FALSE; /* put new line in right block */
2747 /* space_needed does not change */
2750 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2752 total_moved = data_moved + lines_moved * INDEX_SIZE;
2753 if ((int)dp->db_free + total_moved >= space_needed)
2755 in_left = TRUE; /* put new line in left block */
2756 space_needed = total_moved;
2760 in_left = FALSE; /* put new line in right block */
2761 space_needed += total_moved;
2766 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2767 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2769 /* correct line counts in pointer blocks */
2770 --(buf->b_ml.ml_locked_lineadd);
2771 --(buf->b_ml.ml_locked_high);
2774 if (db_idx < 0) /* left block is new */
2778 line_count_left = 0;
2779 line_count_right = line_count;
2781 else /* right block is new */
2785 line_count_left = line_count;
2786 line_count_right = 0;
2788 dp_right = (DATA_BL *)(hp_right->bh_data);
2789 dp_left = (DATA_BL *)(hp_left->bh_data);
2790 bnum_left = hp_left->bh_bnum;
2791 bnum_right = hp_right->bh_bnum;
2792 page_count_left = hp_left->bh_page_count;
2793 page_count_right = hp_right->bh_page_count;
2796 * May move the new line into the right/new block.
2800 dp_right->db_txt_start -= len;
2801 dp_right->db_free -= len + INDEX_SIZE;
2802 dp_right->db_index[0] = dp_right->db_txt_start;
2804 dp_right->db_index[0] |= DB_MARKED;
2806 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2811 * may move lines from the left/old block to the right/new one.
2817 dp_right->db_txt_start -= data_moved;
2818 dp_right->db_free -= total_moved;
2819 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2820 (char *)dp_left + dp_left->db_txt_start,
2821 (size_t)data_moved);
2822 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2823 dp_left->db_txt_start += data_moved;
2824 dp_left->db_free += total_moved;
2827 * update indexes in the new block
2829 for (to = line_count_right, from = db_idx + 1;
2830 from < line_count_left; ++from, ++to)
2831 dp_right->db_index[to] = dp->db_index[from] + offset;
2832 line_count_right += lines_moved;
2833 line_count_left -= lines_moved;
2837 * May move the new line into the left (old or new) block.
2841 dp_left->db_txt_start -= len;
2842 dp_left->db_free -= len + INDEX_SIZE;
2843 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2845 dp_left->db_index[line_count_left] |= DB_MARKED;
2846 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2851 if (db_idx < 0) /* left block is new */
2853 lnum_left = lnum + 1;
2856 else /* right block is new */
2860 lnum_right = lnum + 2;
2862 lnum_right = lnum + 1;
2864 dp_left->db_line_count = line_count_left;
2865 dp_right->db_line_count = line_count_right;
2868 * release the two data blocks
2869 * The new one (hp_new) already has a correct blocknumber.
2870 * The old one (hp, in ml_locked) gets a positive blocknumber if
2871 * we changed it and we are not editing a new file.
2873 if (lines_moved || in_left)
2874 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2875 if (!newfile && db_idx >= 0 && in_left)
2876 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2877 mf_put(mfp, hp_new, TRUE, FALSE);
2880 * flush the old data block
2881 * set ml_locked_lineadd to 0, because the updating of the
2882 * pointer blocks is done below
2884 lineadd = buf->b_ml.ml_locked_lineadd;
2885 buf->b_ml.ml_locked_lineadd = 0;
2886 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2889 * update pointer blocks for the new data block
2891 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2894 ip = &(buf->b_ml.ml_stack[stack_idx]);
2895 pb_idx = ip->ip_index;
2896 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2898 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2899 if (pp->pb_id != PTR_ID)
2901 EMSG(_("E317: pointer block id wrong 3"));
2902 mf_put(mfp, hp, FALSE, FALSE);
2906 * TODO: If the pointer block is full and we are adding at the end
2907 * try to insert in front of the next block
2909 /* block not full, add one entry */
2910 if (pp->pb_count < pp->pb_count_max)
2912 if (pb_idx + 1 < (int)pp->pb_count)
2913 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2914 &pp->pb_pointer[pb_idx + 1],
2915 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2917 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2918 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2919 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2920 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2921 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2922 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2925 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2926 if (lnum_right != 0)
2927 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2929 mf_put(mfp, hp, TRUE, FALSE);
2930 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2934 --(buf->b_ml.ml_stack_top);
2935 /* fix line count for rest of blocks in the stack */
2936 ml_lineadd(buf, lineadd);
2937 /* fix stack itself */
2938 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2940 ++(buf->b_ml.ml_stack_top);
2944 * We are finished, break the loop here.
2948 else /* pointer block full */
2951 * split the pointer block
2952 * allocate a new pointer block
2953 * move some of the pointer into the new block
2954 * prepare for updating the parent block
2956 for (;;) /* do this twice when splitting block 1 */
2958 hp_new = ml_new_ptr(mfp);
2959 if (hp_new == NULL) /* TODO: try to fix tree */
2961 pp_new = (PTR_BL *)(hp_new->bh_data);
2963 if (hp->bh_bnum != 1)
2967 * if block 1 becomes full the tree is given an extra level
2968 * The pointers from block 1 are moved into the new block.
2969 * block 1 is updated to point to the new block
2970 * then continue to split the new block
2972 mch_memmove(pp_new, pp, (size_t)page_size);
2974 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2975 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2976 pp->pb_pointer[0].pe_old_lnum = 1;
2977 pp->pb_pointer[0].pe_page_count = 1;
2978 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2979 hp = hp_new; /* new block is to be split */
2981 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2983 ++stack_idx; /* do block 1 again later */
2986 * move the pointers after the current one to the new block
2987 * If there are none, the new entry will be in the new block.
2989 total_moved = pp->pb_count - pb_idx - 1;
2992 mch_memmove(&pp_new->pb_pointer[0],
2993 &pp->pb_pointer[pb_idx + 1],
2994 (size_t)(total_moved) * sizeof(PTR_EN));
2995 pp_new->pb_count = total_moved;
2996 pp->pb_count -= total_moved - 1;
2997 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2998 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2999 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
3001 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
3005 pp_new->pb_count = 1;
3006 pp_new->pb_pointer[0].pe_bnum = bnum_right;
3007 pp_new->pb_pointer[0].pe_line_count = line_count_right;
3008 pp_new->pb_pointer[0].pe_page_count = page_count_right;
3009 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
3011 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3012 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3013 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3015 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3020 * recompute line counts
3022 line_count_right = 0;
3023 for (i = 0; i < (int)pp_new->pb_count; ++i)
3024 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3025 line_count_left = 0;
3026 for (i = 0; i < (int)pp->pb_count; ++i)
3027 line_count_left += pp->pb_pointer[i].pe_line_count;
3029 bnum_left = hp->bh_bnum;
3030 bnum_right = hp_new->bh_bnum;
3031 page_count_left = 1;
3032 page_count_right = 1;
3033 mf_put(mfp, hp, TRUE, FALSE);
3034 mf_put(mfp, hp_new, TRUE, FALSE);
3039 * Safety check: fallen out of for loop?
3043 EMSG(_("E318: Updated too many blocks?"));
3044 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3049 /* The line was inserted below 'lnum' */
3050 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3052 #ifdef FEAT_NETBEANS_INTG
3053 if (netbeans_active())
3055 if (STRLEN(line) > 0)
3056 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
3057 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
3065 * Replace line lnum, with buffering, in current buffer.
3067 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
3068 * copied to allocated memory already.
3070 * Check: The caller of this function should probably also call
3071 * changed_lines(), unless update_screen(NOT_VALID) is used.
3073 * return FAIL for failure, OK otherwise
3076 ml_replace(lnum, line, copy)
3081 if (line == NULL) /* just checking... */
3084 /* When starting up, we might still need to create the memfile */
3085 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
3088 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3090 #ifdef FEAT_NETBEANS_INTG
3091 if (netbeans_active())
3093 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
3094 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
3097 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3098 ml_flush_line(curbuf); /* flush it */
3099 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3100 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3101 curbuf->b_ml.ml_line_ptr = line;
3102 curbuf->b_ml.ml_line_lnum = lnum;
3103 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3109 * Delete line 'lnum' in the current buffer.
3111 * Check: The caller of this function should probably also call
3112 * deleted_lines() after this.
3114 * return FAIL for failure, OK otherwise
3117 ml_delete(lnum, message)
3121 ml_flush_line(curbuf);
3122 return ml_delete_int(curbuf, lnum, message);
3126 ml_delete_int(buf, lnum, message)
3136 int count; /* number of entries in block */
3144 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3147 if (lowest_marked && lowest_marked > lnum)
3151 * If the file becomes empty the last line is replaced by an empty line.
3153 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3156 #ifdef FEAT_NETBEANS_INTG
3157 && !netbeansSuppressNoLines
3160 set_keep_msg((char_u *)_(no_lines_msg), 0);
3162 /* FEAT_BYTEOFF already handled in there, dont worry 'bout it below */
3163 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3164 buf->b_ml.ml_flags |= ML_EMPTY;
3170 * find the data block containing the line
3171 * This also fills the stack with the blocks from the root to the data block
3172 * This also releases any locked block.
3174 mfp = buf->b_ml.ml_mfp;
3178 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3181 dp = (DATA_BL *)(hp->bh_data);
3182 /* compute line count before the delete */
3183 count = (long)(buf->b_ml.ml_locked_high)
3184 - (long)(buf->b_ml.ml_locked_low) + 2;
3185 idx = lnum - buf->b_ml.ml_locked_low;
3187 --buf->b_ml.ml_line_count;
3189 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3190 if (idx == 0) /* first line in block, text at the end */
3191 line_size = dp->db_txt_end - line_start;
3193 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3195 #ifdef FEAT_NETBEANS_INTG
3196 if (netbeans_active())
3197 netbeans_removed(buf, lnum, 0, (long)line_size);
3201 * special case: If there is only one line in the data block it becomes empty.
3202 * Then we have to remove the entry, pointing to this data block, from the
3203 * pointer block. If this pointer block also becomes empty, we go up another
3204 * block, and so on, up to the root if necessary.
3205 * The line counts in the pointer blocks have already been adjusted by
3210 mf_free(mfp, hp); /* free the data block */
3211 buf->b_ml.ml_locked = NULL;
3213 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; --stack_idx)
3215 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3216 ip = &(buf->b_ml.ml_stack[stack_idx]);
3218 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3220 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3221 if (pp->pb_id != PTR_ID)
3223 EMSG(_("E317: pointer block id wrong 4"));
3224 mf_put(mfp, hp, FALSE, FALSE);
3227 count = --(pp->pb_count);
3228 if (count == 0) /* the pointer block becomes empty! */
3232 if (count != idx) /* move entries after the deleted one */
3233 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3234 (size_t)(count - idx) * sizeof(PTR_EN));
3235 mf_put(mfp, hp, TRUE, FALSE);
3237 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
3238 /* fix line count for rest of blocks in the stack */
3239 if (buf->b_ml.ml_locked_lineadd != 0)
3241 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3242 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
3243 buf->b_ml.ml_locked_lineadd;
3245 ++(buf->b_ml.ml_stack_top);
3250 CHECK(stack_idx < 0, _("deleted block 1?"));
3255 * delete the text by moving the next lines forwards
3257 text_start = dp->db_txt_start;
3258 mch_memmove((char *)dp + text_start + line_size,
3259 (char *)dp + text_start, (size_t)(line_start - text_start));
3262 * delete the index by moving the next indexes backwards
3263 * Adjust the indexes for the text movement.
3265 for (i = idx; i < count - 1; ++i)
3266 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3268 dp->db_free += line_size + INDEX_SIZE;
3269 dp->db_txt_start += line_size;
3270 --(dp->db_line_count);
3273 * mark the block dirty and make sure it is in the file (for recovery)
3275 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3279 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3285 * set the B_MARKED flag for line 'lnum'
3293 /* invalid line number */
3294 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3295 || curbuf->b_ml.ml_mfp == NULL)
3296 return; /* give error message? */
3298 if (lowest_marked == 0 || lowest_marked > lnum)
3299 lowest_marked = lnum;
3302 * find the data block containing the line
3303 * This also fills the stack with the blocks from the root to the data block
3304 * This also releases any locked block.
3306 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3307 return; /* give error message? */
3309 dp = (DATA_BL *)(hp->bh_data);
3310 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3311 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3315 * find the first line with its B_MARKED flag set
3325 if (curbuf->b_ml.ml_mfp == NULL)
3326 return (linenr_T) 0;
3329 * The search starts with lowest_marked line. This is the last line where
3330 * a mark was found, adjusted by inserting/deleting lines.
3332 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3335 * Find the data block containing the line.
3336 * This also fills the stack with the blocks from the root to the data
3337 * block This also releases any locked block.
3339 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3340 return (linenr_T)0; /* give error message? */
3342 dp = (DATA_BL *)(hp->bh_data);
3344 for (i = lnum - curbuf->b_ml.ml_locked_low;
3345 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3346 if ((dp->db_index[i]) & DB_MARKED)
3348 (dp->db_index[i]) &= DB_INDEX_MASK;
3349 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3350 lowest_marked = lnum + 1;
3355 return (linenr_T) 0;
3359 * clear all DB_MARKED flags
3369 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3373 * The search starts with line lowest_marked.
3375 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3378 * Find the data block containing the line.
3379 * This also fills the stack with the blocks from the root to the data
3380 * block and releases any locked block.
3382 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3383 return; /* give error message? */
3385 dp = (DATA_BL *)(hp->bh_data);
3387 for (i = lnum - curbuf->b_ml.ml_locked_low;
3388 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3389 if ((dp->db_index[i]) & DB_MARKED)
3391 (dp->db_index[i]) &= DB_INDEX_MASK;
3392 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3401 * flush ml_line if necessary
3419 static int entered = FALSE;
3421 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3422 return; /* nothing to do */
3424 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3426 /* This code doesn't work recursively, but Netbeans may call back here
3427 * when obtaining the cursor position. */
3432 lnum = buf->b_ml.ml_line_lnum;
3433 new_line = buf->b_ml.ml_line_ptr;
3435 hp = ml_find_line(buf, lnum, ML_FIND);
3437 EMSGN(_("E320: Cannot find line %ld"), lnum);
3440 dp = (DATA_BL *)(hp->bh_data);
3441 idx = lnum - buf->b_ml.ml_locked_low;
3442 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3443 old_line = (char_u *)dp + start;
3444 if (idx == 0) /* line is last in block */
3445 old_len = dp->db_txt_end - start;
3446 else /* text of previous line follows */
3447 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3448 new_len = (colnr_T)STRLEN(new_line) + 1;
3449 extra = new_len - old_len; /* negative if lines gets smaller */
3452 * if new line fits in data block, replace directly
3454 if ((int)dp->db_free >= extra)
3456 /* if the length changes and there are following lines */
3457 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3458 if (extra != 0 && idx < count - 1)
3460 /* move text of following lines */
3461 mch_memmove((char *)dp + dp->db_txt_start - extra,
3462 (char *)dp + dp->db_txt_start,
3463 (size_t)(start - dp->db_txt_start));
3465 /* adjust pointers of this and following lines */
3466 for (i = idx + 1; i < count; ++i)
3467 dp->db_index[i] -= extra;
3469 dp->db_index[idx] -= extra;
3471 /* adjust free space */
3472 dp->db_free -= extra;
3473 dp->db_txt_start -= extra;
3475 /* copy new line into the data block */
3476 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3477 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3479 /* The else case is already covered by the insert and delete */
3480 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3486 * Cannot do it in one data block: Delete and append.
3487 * Append first, because ml_delete_int() cannot delete the
3488 * last line in a buffer, which causes trouble for a buffer
3489 * that has only one line.
3490 * Don't forget to copy the mark!
3492 /* How about handling errors??? */
3493 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3494 (dp->db_index[idx] & DB_MARKED));
3495 (void)ml_delete_int(buf, lnum, FALSE);
3503 buf->b_ml.ml_line_lnum = 0;
3507 * create a new, empty, data block
3510 ml_new_data(mfp, negative, page_count)
3518 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3521 dp = (DATA_BL *)(hp->bh_data);
3522 dp->db_id = DATA_ID;
3523 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3524 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3525 dp->db_line_count = 0;
3531 * create a new, empty, pointer block
3540 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3543 pp = (PTR_BL *)(hp->bh_data);
3546 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3547 / sizeof(PTR_EN) + 1);
3553 * lookup line 'lnum' in a memline
3555 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3556 * if ML_FLUSH only flush a locked block
3557 * if ML_FIND just find the line
3559 * If the block was found it is locked and put in ml_locked.
3560 * The stack is updated to lead to the locked block. The ip_high field in
3561 * the stack is updated to reflect the last line in the block AFTER the
3562 * insert or delete, also if the pointer block has not been updated yet. But
3563 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
3565 * return: NULL for failure, pointer to block header otherwise
3568 ml_find_line(buf, lnum, action)
3579 blocknr_T bnum, bnum2;
3586 mfp = buf->b_ml.ml_mfp;
3589 * If there is a locked block check if the wanted line is in it.
3590 * If not, flush and release the locked block.
3591 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3592 * Don't do this for ML_FLUSH, because we want to flush the locked block.
3593 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
3595 if (buf->b_ml.ml_locked)
3597 if (ML_SIMPLE(action)
3598 && buf->b_ml.ml_locked_low <= lnum
3599 && buf->b_ml.ml_locked_high >= lnum
3600 && !mf_dont_release)
3602 /* remember to update pointer blocks and stack later */
3603 if (action == ML_INSERT)
3605 ++(buf->b_ml.ml_locked_lineadd);
3606 ++(buf->b_ml.ml_locked_high);
3608 else if (action == ML_DELETE)
3610 --(buf->b_ml.ml_locked_lineadd);
3611 --(buf->b_ml.ml_locked_high);
3613 return (buf->b_ml.ml_locked);
3616 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3617 buf->b_ml.ml_flags & ML_LOCKED_POS);
3618 buf->b_ml.ml_locked = NULL;
3621 * If lines have been added or deleted in the locked block, need to
3622 * update the line count in pointer blocks.
3624 if (buf->b_ml.ml_locked_lineadd != 0)
3625 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3628 if (action == ML_FLUSH) /* nothing else to do */
3631 bnum = 1; /* start at the root of the tree */
3634 high = buf->b_ml.ml_line_count;
3636 if (action == ML_FIND) /* first try stack entries */
3638 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3640 ip = &(buf->b_ml.ml_stack[top]);
3641 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3646 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3651 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3653 else /* ML_DELETE or ML_INSERT */
3654 buf->b_ml.ml_stack_top = 0; /* start at the root */
3657 * search downwards in the tree until a data block is found
3661 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3665 * update high for insert/delete
3667 if (action == ML_INSERT)
3669 else if (action == ML_DELETE)
3672 dp = (DATA_BL *)(hp->bh_data);
3673 if (dp->db_id == DATA_ID) /* data block */
3675 buf->b_ml.ml_locked = hp;
3676 buf->b_ml.ml_locked_low = low;
3677 buf->b_ml.ml_locked_high = high;
3678 buf->b_ml.ml_locked_lineadd = 0;
3679 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3683 pp = (PTR_BL *)(dp); /* must be pointer block */
3684 if (pp->pb_id != PTR_ID)
3686 EMSG(_("E317: pointer block id wrong"));
3690 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3692 ip = &(buf->b_ml.ml_stack[top]);
3696 ip->ip_index = -1; /* index not known yet */
3699 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3701 t = pp->pb_pointer[idx].pe_line_count;
3702 CHECK(t == 0, _("pe_line_count is zero"));
3703 if ((low += t) > lnum)
3706 bnum = pp->pb_pointer[idx].pe_bnum;
3707 page_count = pp->pb_pointer[idx].pe_page_count;
3712 * a negative block number may have been changed
3716 bnum2 = mf_trans_del(mfp, bnum);
3720 pp->pb_pointer[idx].pe_bnum = bnum;
3728 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3730 if (lnum > buf->b_ml.ml_line_count)
3731 EMSGN(_("E322: line number out of range: %ld past the end"),
3732 lnum - buf->b_ml.ml_line_count);
3735 EMSGN(_("E323: line count wrong in block %ld"), bnum);
3738 if (action == ML_DELETE)
3740 pp->pb_pointer[idx].pe_line_count--;
3743 else if (action == ML_INSERT)
3745 pp->pb_pointer[idx].pe_line_count++;
3748 mf_put(mfp, hp, dirty, FALSE);
3752 mf_put(mfp, hp, FALSE, FALSE);
3755 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3756 * the incremented/decremented line counts, because there won't be a line
3757 * inserted/deleted after all.
3759 if (action == ML_DELETE)
3761 else if (action == ML_INSERT)
3762 ml_lineadd(buf, -1);
3763 buf->b_ml.ml_stack_top = 0;
3768 * add an entry to the info pointer stack
3770 * return -1 for failure, number of the new entry otherwise
3777 infoptr_T *newstack;
3779 top = buf->b_ml.ml_stack_top;
3781 /* may have to increase the stack size */
3782 if (top == buf->b_ml.ml_stack_size)
3784 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
3786 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3787 (buf->b_ml.ml_stack_size + STACK_INCR));
3788 if (newstack == NULL)
3790 mch_memmove(newstack, buf->b_ml.ml_stack,
3791 (size_t)top * sizeof(infoptr_T));
3792 vim_free(buf->b_ml.ml_stack);
3793 buf->b_ml.ml_stack = newstack;
3794 buf->b_ml.ml_stack_size += STACK_INCR;
3797 buf->b_ml.ml_stack_top++;
3802 * Update the pointer blocks on the stack for inserted/deleted lines.
3803 * The stack itself is also updated.
3805 * When a insert/delete line action fails, the line is not inserted/deleted,
3806 * but the pointer blocks have already been updated. That is fixed here by
3807 * walking through the stack.
3809 * Count is the number of lines added, negative if lines have been deleted.
3812 ml_lineadd(buf, count)
3819 memfile_T *mfp = buf->b_ml.ml_mfp;
3822 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3824 ip = &(buf->b_ml.ml_stack[idx]);
3825 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3827 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3828 if (pp->pb_id != PTR_ID)
3830 mf_put(mfp, hp, FALSE, FALSE);
3831 EMSG(_("E317: pointer block id wrong 2"));
3834 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3835 ip->ip_high += count;
3836 mf_put(mfp, hp, TRUE, FALSE);
3840 #if defined(HAVE_READLINK) || defined(PROTO)
3842 * Resolve a symlink in the last component of a file name.
3843 * Note that f_resolve() does it for every part of the path, we don't do that
3845 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3846 * Otherwise returns FAIL.
3849 resolve_symlink(fname, buf)
3853 char_u tmp[MAXPATHL];
3860 /* Put the result so far in tmp[], starting with the original name. */
3861 vim_strncpy(tmp, fname, MAXPATHL - 1);
3865 /* Limit symlink depth to 100, catch recursive loops. */
3868 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3872 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3875 if (errno == EINVAL || errno == ENOENT)
3877 /* Found non-symlink or not existing file, stop here.
3878 * When at the first level use the unmodified name, skip the
3879 * call to vim_FullName(). */
3883 /* Use the resolved name in tmp[]. */
3887 /* There must be some error reading links, use original name. */
3893 * Check whether the symlink is relative or absolute.
3894 * If it's relative, build a new path based on the directory
3895 * portion of the filename (if any) and the path the symlink
3898 if (mch_isFullName(buf))
3904 tail = gettail(tmp);
3905 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3912 * Try to resolve the full name of the file so that the swapfile name will
3913 * be consistent even when opening a relative symlink from different
3914 * working directories.
3916 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3921 * Make swap file name out of the file name and a directory name.
3922 * Returns pointer to allocated memory or NULL.
3925 makeswapname(fname, ffname, buf, dir_name)
3927 char_u *ffname UNUSED;
3932 char_u *fname_res = fname;
3933 #ifdef HAVE_READLINK
3934 char_u fname_buf[MAXPATHL];
3937 #if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
3938 s = dir_name + STRLEN(dir_name);
3939 if (after_pathsep(dir_name, s) && s[-1] == s[-2])
3940 { /* Ends with '//', Use Full path */
3942 if ((s = make_percent_swname(dir_name, fname)) != NULL)
3944 r = modname(s, (char_u *)".swp", FALSE);
3951 #ifdef HAVE_READLINK
3952 /* Expand symlink in the file name, so that we put the swap file with the
3953 * actual file instead of with the symlink. */
3954 if (resolve_symlink(fname, fname_buf) == OK)
3955 fname_res = fname_buf;
3962 (buf->b_p_sn || buf->b_shortname),
3965 /* Avoid problems if fname has special chars, eg <Wimp$Scrap> */
3971 #if defined(VMS) || defined(RISCOS)
3976 #ifdef SHORT_FNAME /* always 8.3 file name */
3979 /* Prepend a '.' to the swap file name for the current directory. */
3980 dir_name[0] == '.' && dir_name[1] == NUL
3983 if (r == NULL) /* out of memory */
3986 s = get_file_in_dir(r, dir_name);
3992 * Get file name to use for swap file or backup file.
3993 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3995 * - If "dname" is ".", return "fname" (swap file in dir of file).
3996 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3997 * relative to dir of file).
3998 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
4001 * The return value is an allocated string and can be NULL.
4004 get_file_in_dir(fname, dname)
4006 char_u *dname; /* don't use "dirname", it is a global for Alpha */
4013 tail = gettail(fname);
4015 if (dname[0] == '.' && dname[1] == NUL)
4016 retval = vim_strsave(fname);
4017 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
4019 if (tail == fname) /* no path before file name */
4020 retval = concat_fnames(dname + 2, tail, TRUE);
4025 t = concat_fnames(fname, dname + 2, TRUE);
4027 if (t == NULL) /* out of memory */
4031 retval = concat_fnames(t, tail, TRUE);
4037 retval = concat_fnames(dname, tail, TRUE);
4042 static void attention_message __ARGS((buf_T *buf, char_u *fname));
4045 * Print the ATTENTION message: info about an existing swap file.
4048 attention_message(buf, fname)
4049 buf_T *buf; /* buffer being edited */
4050 char_u *fname; /* swap file name */
4057 (void)EMSG(_("E325: ATTENTION"));
4058 MSG_PUTS(_("\nFound a swap file by the name \""));
4059 msg_home_replace(fname);
4061 sx = swapfile_info(fname);
4062 MSG_PUTS(_("While opening file \""));
4063 msg_outtrans(buf->b_fname);
4065 if (mch_stat((char *)buf->b_fname, &st) != -1)
4067 MSG_PUTS(_(" dated: "));
4068 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
4069 p = ctime(&x); /* includes '\n' */
4071 MSG_PUTS("(invalid)\n");
4074 if (sx != 0 && x > sx)
4075 MSG_PUTS(_(" NEWER than swap file!\n"));
4077 /* Some of these messages are long to allow translation to
4078 * other languages. */
4079 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"));
4080 MSG_PUTS(_(" Quit, or continue with caution.\n"));
4081 MSG_PUTS(_("\n(2) An edit session for this file crashed.\n"));
4082 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4083 msg_outtrans(buf->b_fname);
4084 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4085 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4086 msg_outtrans(fname);
4087 MSG_PUTS(_("\"\n to avoid this message.\n"));
4088 cmdline_row = msg_row;
4093 static int do_swapexists __ARGS((buf_T *buf, char_u *fname));
4096 * Trigger the SwapExists autocommands.
4097 * Returns a value for equivalent to do_dialog() (see below):
4098 * 0: still need to ask for a choice
4107 do_swapexists(buf, fname)
4111 set_vim_var_string(VV_SWAPNAME, fname, -1);
4112 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4114 /* Trigger SwapExists autocommands with <afile> set to the file being
4115 * edited. Disallow changing directory here. */
4117 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
4120 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4122 switch (*get_vim_var_str(VV_SWAPCHOICE))
4137 * Find out what name to use for the swap file for buffer 'buf'.
4139 * Several names are tried to find one that does not exist
4140 * Returns the name in allocated memory or NULL.
4142 * Note: If BASENAMELEN is not correct, you will get error messages for
4143 * not being able to open the swap or undo file
4144 * Note: May trigger SwapExists autocmd, pointers may change!
4147 findswapname(buf, dirp, old_fname)
4149 char_u **dirp; /* pointer to list of directories */
4150 char_u *old_fname; /* don't give warning for this file name */
4162 #if !defined(SHORT_FNAME) \
4163 && ((!defined(UNIX) && !defined(OS2)) || defined(ARCHIE))
4164 # define CREATE_DUMMY_FILE
4165 FILE *dummyfd = NULL;
4168 * If we start editing a new file, e.g. "test.doc", which resides on an
4169 * MSDOS compatible filesystem, it is possible that the file
4170 * "test.doc.swp" which we create will be exactly the same file. To avoid
4171 * this problem we temporarily create "test.doc". Don't do this when the
4172 * check below for a 8.3 file name is used.
4174 if (!(buf->b_p_sn || buf->b_shortname) && buf->b_fname != NULL
4175 && mch_getperm(buf->b_fname) < 0)
4176 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4180 * Isolate a directory name from *dirp and put it in dir_name.
4181 * First allocate some memory to put the directory name in.
4183 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
4184 if (dir_name != NULL)
4185 (void)copy_option_part(dirp, dir_name, 31000, ",");
4188 * we try different names until we find one that does not exist yet
4190 if (dir_name == NULL) /* out of memory */
4193 fname = makeswapname(buf->b_fname, buf->b_ffname, buf, dir_name);
4197 if (fname == NULL) /* must be out of memory */
4199 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4205 #if (defined(UNIX) || defined(OS2)) && !defined(ARCHIE) && !defined(SHORT_FNAME)
4207 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4208 * file names. If this is the first try and the swap file name does not fit in
4209 * 8.3, detect if this is the case, set shortname and try again.
4211 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4212 && !(buf->b_p_sn || buf->b_shortname))
4218 int created1 = FALSE, created2 = FALSE;
4222 * Check if swapfile name does not fit in 8.3:
4223 * It either contains two dots, is longer than 8 chars, or starts
4226 tail = gettail(buf->b_fname);
4227 if ( vim_strchr(tail, '.') != NULL
4228 || STRLEN(tail) > (size_t)8
4229 || *gettail(fname) == '.')
4231 fname2 = alloc(n + 2);
4234 STRCPY(fname2, fname);
4235 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4236 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4237 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4239 if (vim_strchr(tail, '.') != NULL)
4240 fname2[n - 1] = 'x';
4241 else if (*gettail(fname) == '.')
4244 fname2[n + 1] = NUL;
4249 * may need to create the files to be able to use mch_stat()
4251 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4254 f1 = mch_open_rw((char *)fname,
4255 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4257 if (f1 < 0 && errno == ENOENT)
4264 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4267 f2 = mch_open_rw((char *)fname2,
4268 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4274 * Both files exist now. If mch_stat() returns the
4275 * same device and inode they are the same file.
4277 if (mch_fstat(f1, &s1) != -1
4278 && mch_fstat(f2, &s2) != -1
4279 && s1.st_dev == s2.st_dev
4280 && s1.st_ino == s2.st_ino)
4293 buf->b_shortname = TRUE;
4295 fname = makeswapname(buf->b_fname, buf->b_ffname,
4297 continue; /* try again with b_shortname set */
4304 * check if the swapfile already exists
4306 if (mch_getperm(fname) < 0) /* it does not exist */
4312 * Extra security check: When a swap file is a symbolic link, this
4313 * is most likely a symlink attack.
4315 if (mch_lstat((char *)fname, &sb) < 0)
4318 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4320 * on the Amiga mch_getperm() will return -1 when the file exists
4321 * but is being used by another program. This happens if you edit
4324 if (fh != (BPTR)NULL) /* can open file, OK */
4330 if (IoErr() != ERROR_OBJECT_IN_USE
4331 && IoErr() != ERROR_OBJECT_EXISTS)
4338 * A file name equal to old_fname is OK to use.
4340 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4344 * get here when file already exists
4346 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4350 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4351 * and file.doc are the same file. To guess if this problem is
4352 * present try if file.doc.swx exists. If it does, we set
4353 * buf->b_shortname and try file_doc.swp (dots replaced by
4354 * underscores for this file), and try again. If it doesn't we
4355 * assume that "file.doc.swp" already exists.
4357 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4360 r = mch_getperm(fname); /* try "file.swx" */
4362 if (r >= 0) /* "file.swx" seems to exist */
4364 buf->b_shortname = TRUE;
4366 fname = makeswapname(buf->b_fname, buf->b_ffname,
4368 continue; /* try again with '.' replaced with '_' */
4373 * If we get here the ".swp" file really exists.
4374 * Give an error message, unless recovering, no file name, we are
4375 * viewing a help file or when the path of the file is different
4376 * (happens when all .swp files are in one directory).
4378 if (!recoverymode && buf->b_fname != NULL
4379 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
4386 * Try to read block 0 from the swap file to get the original
4387 * file name (and inode number).
4389 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4392 if (read(fd, (char *)&b0, sizeof(b0)) == sizeof(b0))
4395 * If the swapfile has the same directory as the
4396 * buffer don't compare the directory names, they can
4397 * have a different mountpoint.
4399 if (b0.b0_flags & B0_SAME_DIR)
4401 if (fnamecmp(gettail(buf->b_ffname),
4402 gettail(b0.b0_fname)) != 0
4403 || !same_directory(fname, buf->b_ffname))
4406 /* Symlinks may point to the same file even
4407 * when the name differs, need to check the
4409 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4410 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4411 char_to_long(b0.b0_ino)))
4419 * The name in the swap file may be
4420 * "~user/path/file". Expand it first.
4422 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4424 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4425 char_to_long(b0.b0_ino)))
4428 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4437 /* Can't open swap file, though it does exist.
4438 * Assume that the user is editing two files with
4439 * the same name in different directories. No error.
4444 /* give the ATTENTION message when there is an old swap file
4445 * for the current file, and the buffer was not recovered. */
4446 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4447 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4449 #if defined(HAS_SWAP_EXISTS_ACTION)
4452 #ifdef CREATE_DUMMY_FILE
4453 int did_use_dummy = FALSE;
4455 /* Avoid getting a warning for the file being created
4456 * outside of Vim, it was created at the start of this
4457 * function. Delete the file now, because Vim might exit
4458 * here if the window is closed. */
4459 if (dummyfd != NULL)
4463 mch_remove(buf->b_fname);
4464 did_use_dummy = TRUE;
4468 #if (defined(UNIX) || defined(__EMX__) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
4469 process_still_running = FALSE;
4473 * If there is an SwapExists autocommand and we can handle
4474 * the response, trigger it. It may return 0 to ask the
4477 if (swap_exists_action != SEA_NONE
4478 && has_autocmd(EVENT_SWAPEXISTS, buf->b_fname, buf))
4479 choice = do_swapexists(buf, fname);
4485 /* If we are supposed to start the GUI but it wasn't
4486 * completely started yet, start it now. This makes
4487 * the messages displayed in the Vim window when
4488 * loading a session from the .gvimrc file. */
4489 if (gui.starting && !gui.in_use)
4492 /* Show info about the existing swap file. */
4493 attention_message(buf, fname);
4495 /* We don't want a 'q' typed at the more-prompt
4496 * interrupt loading a file. */
4500 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
4501 if (swap_exists_action != SEA_NONE && choice == 0)
4505 name = alloc((unsigned)(STRLEN(fname)
4506 + STRLEN(_("Swap file \""))
4507 + STRLEN(_("\" already exists!")) + 5));
4510 STRCPY(name, _("Swap file \""));
4511 home_replace(NULL, fname, name + STRLEN(name),
4513 STRCAT(name, _("\" already exists!"));
4515 choice = do_dialog(VIM_WARNING,
4516 (char_u *)_("VIM - ATTENTION"),
4518 ? (char_u *)_("Swap file already exists!")
4520 # if defined(UNIX) || defined(__EMX__) || defined(VMS)
4521 process_still_running
4522 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4524 (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL);
4526 # if defined(UNIX) || defined(__EMX__) || defined(VMS)
4527 if (process_still_running && choice >= 4)
4528 choice++; /* Skip missing "Delete it" button */
4532 /* pretend screen didn't scroll, need redraw anyway */
4534 redraw_all_later(NOT_VALID);
4538 #if defined(HAS_SWAP_EXISTS_ACTION)
4549 swap_exists_action = SEA_RECOVER;
4555 swap_exists_action = SEA_QUIT;
4558 swap_exists_action = SEA_QUIT;
4563 /* If the file was deleted this fname can be used. */
4564 if (mch_getperm(fname) < 0)
4571 if (msg_silent == 0)
4572 /* call wait_return() later */
4573 need_wait_return = TRUE;
4576 #ifdef CREATE_DUMMY_FILE
4577 /* Going to try another name, need the dummy file again. */
4579 dummyfd = mch_fopen((char *)buf->b_fname, "w");
4586 * Change the ".swp" extension to find another file that can be used.
4587 * First decrement the last char: ".swo", ".swn", etc.
4588 * If that still isn't enough decrement the last but one char: ".svz"
4589 * Can happen when editing many "No Name" buffers.
4591 if (fname[n - 1] == 'a') /* ".s?a" */
4593 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4595 EMSG(_("E326: Too many swap files found"));
4600 --fname[n - 2]; /* ".svz", ".suz", etc. */
4601 fname[n - 1] = 'z' + 1;
4603 --fname[n - 1]; /* ".swo", ".swn", etc. */
4607 #ifdef CREATE_DUMMY_FILE
4608 if (dummyfd != NULL) /* file has been created temporarily */
4611 mch_remove(buf->b_fname);
4621 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4622 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4623 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4624 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4629 * Compare current file name with file name from swap file.
4630 * Try to use inode numbers when possible.
4631 * Return non-zero when files are different.
4633 * When comparing file names a few things have to be taken into consideration:
4634 * - When working over a network the full path of a file depends on the host.
4635 * We check the inode number if possible. It is not 100% reliable though,
4636 * because the device number cannot be used over a network.
4637 * - When a file does not exist yet (editing a new file) there is no inode
4639 * - The file name in a swap file may not be valid on the current host. The
4640 * "~user" form is used whenever possible to avoid this.
4642 * This is getting complicated, let's make a table:
4644 * ino_c ino_s fname_c fname_s differ =
4646 * both files exist -> compare inode numbers:
4647 * != 0 != 0 X X ino_c != ino_s
4649 * inode number(s) unknown, file names available -> compare file names
4650 * == 0 X OK OK fname_c != fname_s
4651 * X == 0 OK OK fname_c != fname_s
4653 * current file doesn't exist, file for swap file exist, file name(s) not
4654 * available -> probably different
4655 * == 0 != 0 FAIL X TRUE
4656 * == 0 != 0 X FAIL TRUE
4658 * current file exists, inode for swap unknown, file name(s) not
4659 * available -> probably different
4660 * != 0 == 0 FAIL X TRUE
4661 * != 0 == 0 X FAIL TRUE
4663 * current file doesn't exist, inode for swap unknown, one file name not
4664 * available -> probably different
4665 * == 0 == 0 FAIL OK TRUE
4666 * == 0 == 0 OK FAIL TRUE
4668 * current file doesn't exist, inode for swap unknown, both file names not
4669 * available -> probably same file
4670 * == 0 == 0 FAIL FAIL FALSE
4672 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4673 * can't be changed without making the block 0 incompatible with 32 bit
4678 fnamecmp_ino(fname_c, fname_s, ino_block0)
4679 char_u *fname_c; /* current file name */
4680 char_u *fname_s; /* file name from swap file */
4684 ino_t ino_c = 0; /* ino of current file */
4685 ino_t ino_s; /* ino of file from swap file */
4686 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4687 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4688 int retval_c; /* flag: buf_c valid */
4689 int retval_s; /* flag: buf_s valid */
4691 if (mch_stat((char *)fname_c, &st) == 0)
4692 ino_c = (ino_t)st.st_ino;
4695 * First we try to get the inode from the file name, because the inode in
4696 * the swap file may be outdated. If that fails (e.g. this path is not
4697 * valid on this machine), use the inode from block 0.
4699 if (mch_stat((char *)fname_s, &st) == 0)
4700 ino_s = (ino_t)st.st_ino;
4702 ino_s = (ino_t)ino_block0;
4705 return (ino_c != ino_s);
4708 * One of the inode numbers is unknown, try a forced vim_FullName() and
4709 * compare the file names.
4711 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4712 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4713 if (retval_c == OK && retval_s == OK)
4714 return (STRCMP(buf_c, buf_s) != 0);
4717 * Can't compare inodes or file names, guess that the files are different,
4718 * unless both appear not to exist at all.
4720 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
4724 #endif /* CHECK_INODE */
4727 * Move a long integer into a four byte character array.
4728 * Used for machine independency in block zero.
4735 s[0] = (char_u)(n & 0xff);
4736 n = (unsigned)n >> 8;
4737 s[1] = (char_u)(n & 0xff);
4738 n = (unsigned)n >> 8;
4739 s[2] = (char_u)(n & 0xff);
4740 n = (unsigned)n >> 8;
4741 s[3] = (char_u)(n & 0xff);
4762 * Set the flags in the first block of the swap file:
4763 * - file is modified or not: buf->b_changed
4774 if (!buf->b_ml.ml_mfp)
4776 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4778 if (hp->bh_bnum == 0)
4780 b0p = (ZERO_BL *)(hp->bh_data);
4781 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4782 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4783 | (get_fileformat(buf) + 1);
4785 add_b0_fenc(b0p, buf);
4787 hp->bh_flags |= BH_DIRTY;
4788 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4794 #if defined(FEAT_CRYPT) || defined(PROTO)
4796 * If "data" points to a data block encrypt the text in it and return a copy
4797 * in allocated memory. Return NULL when out of memory.
4798 * Otherwise return "data".
4801 ml_encrypt_data(mfp, data, offset, size)
4807 DATA_BL *dp = (DATA_BL *)data;
4813 if (dp->db_id != DATA_ID)
4816 new_data = (char_u *)alloc(size);
4817 if (new_data == NULL)
4819 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4820 text_start = (char_u *)dp + dp->db_txt_start;
4821 text_len = size - dp->db_txt_start;
4823 /* Copy the header and the text. */
4824 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4826 /* Encrypt the text. */
4828 ml_crypt_prepare(mfp, offset, FALSE);
4829 crypt_encode(text_start, text_len, new_data + dp->db_txt_start);
4832 /* Clear the gap. */
4833 if (head_end < text_start)
4834 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4840 * Decrypt the text in "data" if it points to a data block.
4843 ml_decrypt_data(mfp, data, offset, size)
4849 DATA_BL *dp = (DATA_BL *)data;
4854 if (dp->db_id == DATA_ID)
4856 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4857 text_start = (char_u *)dp + dp->db_txt_start;
4858 text_len = dp->db_txt_end - dp->db_txt_start;
4860 if (head_end > text_start || dp->db_txt_start > size
4861 || dp->db_txt_end > size)
4862 return; /* data was messed up */
4864 /* Decrypt the text in place. */
4866 ml_crypt_prepare(mfp, offset, TRUE);
4867 crypt_decode(text_start, text_len);
4873 * Prepare for encryption/decryption, using the key, seed and offset.
4876 ml_crypt_prepare(mfp, offset, reading)
4881 buf_T *buf = mfp->mf_buffer;
4887 if (reading && mfp->mf_old_key != NULL)
4889 /* Reading back blocks with the previous key/method/seed. */
4890 method = mfp->mf_old_cm;
4891 key = mfp->mf_old_key;
4892 seed = mfp->mf_old_seed;
4896 method = get_crypt_method(buf);
4898 seed = mfp->mf_seed;
4901 use_crypt_method = method; /* select pkzip or blowfish */
4904 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
4905 crypt_init_keys(salt);
4909 /* Using blowfish, add salt and seed. We use the byte offset of the
4910 * block for the salt. */
4911 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
4912 bf_key_init(key, salt, (int)STRLEN(salt));
4913 bf_ofb_init(seed, MF_SEED_LEN);
4920 #if defined(FEAT_BYTEOFF) || defined(PROTO)
4922 #define MLCS_MAXL 800 /* max no of lines in chunk */
4923 #define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4926 * Keep information for finding byte offset of a line, updtype may be one of:
4927 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4928 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4929 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4930 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4933 ml_updatechunk(buf, line, len, updtype)
4939 static buf_T *ml_upd_lastbuf = NULL;
4940 static linenr_T ml_upd_lastline;
4941 static linenr_T ml_upd_lastcurline;
4942 static int ml_upd_lastcurix;
4944 linenr_T curline = ml_upd_lastcurline;
4945 int curix = ml_upd_lastcurix;
4947 chunksize_T *curchnk;
4952 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4954 if (buf->b_ml.ml_chunksize == NULL)
4956 buf->b_ml.ml_chunksize = (chunksize_T *)
4957 alloc((unsigned)sizeof(chunksize_T) * 100);
4958 if (buf->b_ml.ml_chunksize == NULL)
4960 buf->b_ml.ml_usedchunks = -1;
4963 buf->b_ml.ml_numchunks = 100;
4964 buf->b_ml.ml_usedchunks = 1;
4965 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4966 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4969 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4972 * First line in empty buffer from ml_flush_line() -- reset
4974 buf->b_ml.ml_usedchunks = 1;
4975 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4976 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4977 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4982 * Find chunk that our line belongs to, curline will be at start of the
4985 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4986 || updtype != ML_CHNK_ADDLINE)
4988 for (curline = 1, curix = 0;
4989 curix < buf->b_ml.ml_usedchunks - 1
4990 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4993 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4996 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
4997 && curix < buf->b_ml.ml_usedchunks - 1)
4999 /* Adjust cached curix & curline */
5000 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5003 curchnk = buf->b_ml.ml_chunksize + curix;
5005 if (updtype == ML_CHNK_DELLINE)
5007 curchnk->mlcs_totalsize += len;
5008 if (updtype == ML_CHNK_ADDLINE)
5010 curchnk->mlcs_numlines++;
5012 /* May resize here so we don't have to do it in both cases below */
5013 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5015 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5016 buf->b_ml.ml_chunksize = (chunksize_T *)
5017 vim_realloc(buf->b_ml.ml_chunksize,
5018 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5019 if (buf->b_ml.ml_chunksize == NULL)
5021 /* Hmmmm, Give up on offset for this buffer */
5022 buf->b_ml.ml_usedchunks = -1;
5027 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5029 int count; /* number of entries in block */
5034 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5035 buf->b_ml.ml_chunksize + curix,
5036 (buf->b_ml.ml_usedchunks - curix) *
5037 sizeof(chunksize_T));
5038 /* Compute length of first half of lines in the split chunk */
5041 while (curline < buf->b_ml.ml_line_count
5042 && linecnt < MLCS_MINL)
5044 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5046 buf->b_ml.ml_usedchunks = -1;
5049 dp = (DATA_BL *)(hp->bh_data);
5050 count = (long)(buf->b_ml.ml_locked_high) -
5051 (long)(buf->b_ml.ml_locked_low) + 1;
5052 idx = curline - buf->b_ml.ml_locked_low;
5053 curline = buf->b_ml.ml_locked_high + 1;
5054 if (idx == 0)/* first line in block, text at the end */
5055 text_end = dp->db_txt_end;
5057 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5058 /* Compute index of last line to use in this MEMLINE */
5060 if (linecnt + rest > MLCS_MINL)
5062 idx += MLCS_MINL - linecnt - 1;
5063 linecnt = MLCS_MINL;
5070 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5072 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5073 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5074 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5075 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5076 buf->b_ml.ml_usedchunks++;
5077 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5080 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5081 && curix == buf->b_ml.ml_usedchunks - 1
5082 && buf->b_ml.ml_line_count - line <= 1)
5085 * We are in the last chunk and it is cheap to crate a new one
5086 * after this. Do it now to avoid the loop above later on
5088 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5089 buf->b_ml.ml_usedchunks++;
5090 if (line == buf->b_ml.ml_line_count)
5092 curchnk->mlcs_numlines = 0;
5093 curchnk->mlcs_totalsize = 0;
5098 * Line is just prior to last, move count for last
5099 * This is the common case when loading a new file
5101 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5104 buf->b_ml.ml_usedchunks = -1;
5107 dp = (DATA_BL *)(hp->bh_data);
5108 if (dp->db_line_count == 1)
5109 rest = dp->db_txt_end - dp->db_txt_start;
5112 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5114 curchnk->mlcs_totalsize = rest;
5115 curchnk->mlcs_numlines = 1;
5116 curchnk[-1].mlcs_totalsize -= rest;
5117 curchnk[-1].mlcs_numlines -= 1;
5121 else if (updtype == ML_CHNK_DELLINE)
5123 curchnk->mlcs_numlines--;
5124 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5125 if (curix < (buf->b_ml.ml_usedchunks - 1)
5126 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5130 curchnk = buf->b_ml.ml_chunksize + curix;
5132 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5134 buf->b_ml.ml_usedchunks--;
5135 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5136 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5139 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5140 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5146 /* Collapse chunks */
5147 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5148 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5149 buf->b_ml.ml_usedchunks--;
5150 if (curix < buf->b_ml.ml_usedchunks)
5152 mch_memmove(buf->b_ml.ml_chunksize + curix,
5153 buf->b_ml.ml_chunksize + curix + 1,
5154 (buf->b_ml.ml_usedchunks - curix) *
5155 sizeof(chunksize_T));
5159 ml_upd_lastbuf = buf;
5160 ml_upd_lastline = line;
5161 ml_upd_lastcurline = curline;
5162 ml_upd_lastcurix = curix;
5166 * Find offset for line or line with offset.
5167 * Find line with offset if "lnum" is 0; return remaining offset in offp
5168 * Find offset of line if "lnum" > 0
5169 * return -1 if information is not available
5172 ml_find_line_or_offset(buf, lnum, offp)
5182 int count; /* number of entries in block */
5188 int ffdos = (get_fileformat(buf) == EOL_DOS);
5191 /* take care of cached line first */
5192 ml_flush_line(curbuf);
5194 if (buf->b_ml.ml_usedchunks == -1
5195 || buf->b_ml.ml_chunksize == NULL
5203 if (lnum == 0 && offset <= 0)
5204 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5206 * Find the last chunk before the one containing our line. Last chunk is
5207 * special because it will never qualify
5211 while (curix < buf->b_ml.ml_usedchunks - 1
5213 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
5215 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5216 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5218 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5219 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5220 if (offset && ffdos)
5221 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5225 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
5227 if (curline > buf->b_ml.ml_line_count
5228 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5230 dp = (DATA_BL *)(hp->bh_data);
5231 count = (long)(buf->b_ml.ml_locked_high) -
5232 (long)(buf->b_ml.ml_locked_low) + 1;
5233 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5234 if (idx == 0)/* first line in block, text at the end */
5235 text_end = dp->db_txt_end;
5237 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5238 /* Compute index of last line to use in this MEMLINE */
5241 if (curline + (count - idx) >= lnum)
5242 idx += lnum - curline - 1;
5249 while (offset >= size
5250 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5255 if (idx == count - 1)
5263 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5265 if (offset != 0 && size >= offset)
5267 if (size + ffdos == offset)
5269 else if (idx == start_idx)
5270 *offp = offset - size + len;
5272 *offp = offset - size + len
5273 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5274 curline += idx - start_idx + extra;
5275 if (curline > buf->b_ml.ml_line_count)
5276 return -1; /* exactly one byte beyond the end */
5279 curline = buf->b_ml.ml_locked_high + 1;
5284 /* Count extra CR characters. */
5288 /* Don't count the last line break if 'bin' and 'noeol'. */
5289 if (buf->b_p_bin && !buf->b_p_eol)
5297 * Goto byte in buffer with offset 'cnt'.
5306 ml_flush_line(curbuf); /* cached line may be dirty */
5310 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5311 if (lnum < 1) /* past the end */
5313 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5314 curwin->w_curswant = MAXCOL;
5315 coladvance((colnr_T)MAXCOL);
5319 curwin->w_cursor.lnum = lnum;
5320 curwin->w_cursor.col = (colnr_T)boff;
5321 # ifdef FEAT_VIRTUALEDIT
5322 curwin->w_cursor.coladd = 0;
5324 curwin->w_set_curswant = TRUE;
5329 /* Make sure the cursor is on the first byte of a multi-byte char. */