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