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