xref: /vim-8.2.3635/src/memline.c (revision 8b0e62c9)
1 /* vi:set ts=8 sts=4 sw=4 noet:
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)	do { if (c) emsg((s)); } while (0)
12 #define CHECK(c, s)	do { /**/ } while (0)
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
17  * blocks of memory, backed up by a file. The structure of the information is
18  * a tree.  The root of the tree is a pointer block. The leaves of the tree
19  * are data blocks. In between may be several layers of pointer blocks,
20  * forming branches.
21  *
22  * Three types of blocks are used:
23  * - Block nr 0 contains information for recovery
24  * - Pointer blocks contain list of pointers to other blocks.
25  * - Data blocks contain the actual text.
26  *
27  * Block nr 0 contains the block0 structure (see below).
28  *
29  * Block nr 1 is the first pointer block. It is the root of the tree.
30  * Other pointer blocks are branches.
31  *
32  *  If a line is too big to fit in a single page, the block containing that
33  *  line is made big enough to hold the line. It may span several pages.
34  *  Otherwise all blocks are one page.
35  *
36  *  A data block that was filled when starting to edit a file and was not
37  *  changed since then, can have a negative block number. This means that it
38  *  has not yet been assigned a place in the file. When recovering, the lines
39  *  in this data block can be read from the original file. When the block is
40  *  changed (lines appended/deleted/changed) or when it is flushed it gets a
41  *  positive number. Use mf_trans_del() to get the new number, before calling
42  *  mf_get().
43  */
44 
45 #include "vim.h"
46 
47 #ifndef UNIX		// it's in os_unix.h for Unix
48 # include <time.h>
49 #endif
50 
51 #if defined(SASC) || defined(__amigaos4__)
52 # include <proto/dos.h>	    // for Open() and Close()
53 #endif
54 
55 typedef struct block0		ZERO_BL;    // contents of the first block
56 typedef struct pointer_block	PTR_BL;	    // contents of a pointer block
57 typedef struct data_block	DATA_BL;    // contents of a data block
58 typedef struct pointer_entry	PTR_EN;	    // block/line-count pair
59 
60 #define DATA_ID	       (('d' << 8) + 'a')   // data block id
61 #define PTR_ID	       (('p' << 8) + 't')   // pointer block id
62 #define BLOCK0_ID0     'b'		    // block 0 id 0
63 #define BLOCK0_ID1     '0'		    // block 0 id 1
64 #define BLOCK0_ID1_C0  'c'		    // block 0 id 1 'cm' 0
65 #define BLOCK0_ID1_C1  'C'		    // block 0 id 1 'cm' 1
66 #define BLOCK0_ID1_C2  'd'		    // block 0 id 1 'cm' 2
67 #define BLOCK0_ID1_C3  'S'		    // block 0 id 1 'cm' 3 - but not actually used
68 
69 #if defined(FEAT_CRYPT)
70 static int id1_codes[] = {
71     BLOCK0_ID1_C0,  // CRYPT_M_ZIP
72     BLOCK0_ID1_C1,  // CRYPT_M_BF
73     BLOCK0_ID1_C2,  // CRYPT_M_BF2
74     BLOCK0_ID1_C3,  // CRYPT_M_SOD  - Unused!
75 };
76 #endif
77 
78 /*
79  * pointer to a block, used in a pointer block
80  */
81 struct pointer_entry
82 {
83     blocknr_T	pe_bnum;	// block number
84     linenr_T	pe_line_count;	// number of lines in this branch
85     linenr_T	pe_old_lnum;	// lnum for this block (for recovery)
86     int		pe_page_count;	// number of pages in block pe_bnum
87 };
88 
89 /*
90  * A pointer block contains a list of branches in the tree.
91  */
92 struct pointer_block
93 {
94     short_u	pb_id;		// ID for pointer block: PTR_ID
95     short_u	pb_count;	// number of pointers in this block
96     short_u	pb_count_max;	// maximum value for pb_count
97     PTR_EN	pb_pointer[1];	// list of pointers to blocks (actually longer)
98 				// followed by empty space until end of page
99 };
100 
101 /*
102  * A data block is a leaf in the tree.
103  *
104  * The text of the lines is at the end of the block. The text of the first line
105  * in the block is put at the end, the text of the second line in front of it,
106  * etc. Thus the order of the lines is the opposite of the line number.
107  */
108 struct data_block
109 {
110     short_u	db_id;		// ID for data block: DATA_ID
111     unsigned	db_free;	// free space available
112     unsigned	db_txt_start;	// byte where text starts
113     unsigned	db_txt_end;	// byte just after data block
114     linenr_T	db_line_count;	// number of lines in this block
115     unsigned	db_index[1];	// index for start of line (actually bigger)
116 				// followed by empty space up to db_txt_start
117 				// followed by the text in the lines until
118 				// end of page
119 };
120 
121 /*
122  * The low bits of db_index hold the actual index. The topmost bit is
123  * used for the global command to be able to mark a line.
124  * This method is not clean, but otherwise there would be at least one extra
125  * byte used for each line.
126  * The mark has to be in this place to keep it with the correct line when other
127  * lines are inserted or deleted.
128  */
129 #define DB_MARKED	((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
130 #define DB_INDEX_MASK	(~DB_MARKED)
131 
132 #define INDEX_SIZE  (sizeof(unsigned))	    // size of one db_index entry
133 #define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE)  // size of data block header
134 
135 #define B0_FNAME_SIZE_ORG	900	// what it was in older versions
136 #define B0_FNAME_SIZE_NOCRYPT	898	// 2 bytes used for other things
137 #define B0_FNAME_SIZE_CRYPT	890	// 10 bytes used for other things
138 #define B0_UNAME_SIZE		40
139 #define B0_HNAME_SIZE		40
140 /*
141  * Restrict the numbers to 32 bits, otherwise most compilers will complain.
142  * This won't detect a 64 bit machine that only swaps a byte in the top 32
143  * bits, but that is crazy anyway.
144  */
145 #define B0_MAGIC_LONG	0x30313233L
146 #define B0_MAGIC_INT	0x20212223L
147 #define B0_MAGIC_SHORT	0x10111213L
148 #define B0_MAGIC_CHAR	0x55
149 
150 /*
151  * Block zero holds all info about the swap file.
152  *
153  * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
154  * swap files unusable!
155  *
156  * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
157  *
158  * This block is built up of single bytes, to make it portable across
159  * different machines. b0_magic_* is used to check the byte order and size of
160  * variables, because the rest of the swap file is not portable.
161  */
162 struct block0
163 {
164     char_u	b0_id[2];	// id for block 0: BLOCK0_ID0 and BLOCK0_ID1,
165 				// BLOCK0_ID1_C0, BLOCK0_ID1_C1, etc.
166     char_u	b0_version[10];	// Vim version string
167     char_u	b0_page_size[4];// number of bytes per page
168     char_u	b0_mtime[4];	// last modification time of file
169     char_u	b0_ino[4];	// inode of b0_fname
170     char_u	b0_pid[4];	// process id of creator (or 0)
171     char_u	b0_uname[B0_UNAME_SIZE]; // name of user (uid if no name)
172     char_u	b0_hname[B0_HNAME_SIZE]; // host name (if it has a name)
173     char_u	b0_fname[B0_FNAME_SIZE_ORG]; // name of file being edited
174     long	b0_magic_long;	// check for byte order of long
175     int		b0_magic_int;	// check for byte order of int
176     short	b0_magic_short;	// check for byte order of short
177     char_u	b0_magic_char;	// check for last char
178 };
179 
180 /*
181  * Note: b0_dirty and b0_flags are put at the end of the file name.  For very
182  * long file names in older versions of Vim they are invalid.
183  * The 'fileencoding' comes before b0_flags, with a NUL in front.  But only
184  * when there is room, for very long file names it's omitted.
185  */
186 #define B0_DIRTY	0x55
187 #define b0_dirty	b0_fname[B0_FNAME_SIZE_ORG - 1]
188 
189 /*
190  * The b0_flags field is new in Vim 7.0.
191  */
192 #define b0_flags	b0_fname[B0_FNAME_SIZE_ORG - 2]
193 
194 /*
195  * Crypt seed goes here, 8 bytes.  New in Vim 7.3.
196  * Without encryption these bytes may be used for 'fenc'.
197  */
198 #define b0_seed		b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN]
199 
200 // The lowest two bits contain the fileformat.  Zero means it's not set
201 // (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
202 // EOL_MAC + 1.
203 #define B0_FF_MASK	3
204 
205 // Swap file is in directory of edited file.  Used to find the file from
206 // different mount points.
207 #define B0_SAME_DIR	4
208 
209 // The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
210 // When empty there is only the NUL.
211 #define B0_HAS_FENC	8
212 
213 #define STACK_INCR	5	// nr of entries added to ml_stack at a time
214 
215 /*
216  * The line number where the first mark may be is remembered.
217  * If it is 0 there are no marks at all.
218  * (always used for the current buffer only, no buffer change possible while
219  * executing a global command).
220  */
221 static linenr_T	lowest_marked = 0;
222 
223 /*
224  * arguments for ml_find_line()
225  */
226 #define ML_DELETE	0x11	    // delete line
227 #define ML_INSERT	0x12	    // insert line
228 #define ML_FIND		0x13	    // just find the line
229 #define ML_FLUSH	0x02	    // flush locked block
230 #define ML_SIMPLE(x)	(x & 0x10)  // DEL, INS or FIND
231 
232 // argument for ml_upd_block0()
233 typedef enum {
234       UB_FNAME = 0	// update timestamp and filename
235     , UB_SAME_DIR       // update the B0_SAME_DIR flag
236     , UB_CRYPT		// update crypt key
237 } upd_block0_T;
238 
239 #ifdef FEAT_CRYPT
240 static void ml_set_b0_crypt(buf_T *buf, ZERO_BL *b0p);
241 #endif
242 static void ml_upd_block0(buf_T *buf, upd_block0_T what);
243 static void set_b0_fname(ZERO_BL *, buf_T *buf);
244 static void set_b0_dir_flag(ZERO_BL *b0p, buf_T *buf);
245 static void add_b0_fenc(ZERO_BL *b0p, buf_T *buf);
246 static time_t swapfile_info(char_u *);
247 static int recov_file_names(char_u **, char_u *, int prepend_dot);
248 static char_u *findswapname(buf_T *, char_u **, char_u *);
249 static void ml_flush_line(buf_T *);
250 static bhdr_T *ml_new_data(memfile_T *, int, int);
251 static bhdr_T *ml_new_ptr(memfile_T *);
252 static bhdr_T *ml_find_line(buf_T *, linenr_T, int);
253 static int ml_add_stack(buf_T *);
254 static void ml_lineadd(buf_T *, int);
255 static int b0_magic_wrong(ZERO_BL *);
256 #ifdef CHECK_INODE
257 static int fnamecmp_ino(char_u *, char_u *, long);
258 #endif
259 static void long_to_char(long, char_u *);
260 static long char_to_long(char_u *);
261 #ifdef FEAT_CRYPT
262 static cryptstate_T *ml_crypt_prepare(memfile_T *mfp, off_T offset, int reading);
263 #endif
264 #ifdef FEAT_BYTEOFF
265 static void ml_updatechunk(buf_T *buf, long line, long len, int updtype);
266 #endif
267 
268 /*
269  * Open a new memline for "buf".
270  *
271  * Return FAIL for failure, OK otherwise.
272  */
273     int
ml_open(buf_T * buf)274 ml_open(buf_T *buf)
275 {
276     memfile_T	*mfp;
277     bhdr_T	*hp = NULL;
278     ZERO_BL	*b0p;
279     PTR_BL	*pp;
280     DATA_BL	*dp;
281 
282     /*
283      * init fields in memline struct
284      */
285     buf->b_ml.ml_stack_size = 0; // no stack yet
286     buf->b_ml.ml_stack = NULL;	// no stack yet
287     buf->b_ml.ml_stack_top = 0;	// nothing in the stack
288     buf->b_ml.ml_locked = NULL;	// no cached block
289     buf->b_ml.ml_line_lnum = 0;	// no cached line
290 #ifdef FEAT_BYTEOFF
291     buf->b_ml.ml_chunksize = NULL;
292     buf->b_ml.ml_usedchunks = 0;
293 #endif
294 
295     if (cmdmod.cmod_flags & CMOD_NOSWAPFILE)
296 	buf->b_p_swf = FALSE;
297 
298     /*
299      * When 'updatecount' is non-zero swap file may be opened later.
300      */
301     if (p_uc && buf->b_p_swf)
302 	buf->b_may_swap = TRUE;
303     else
304 	buf->b_may_swap = FALSE;
305 
306     /*
307      * Open the memfile.  No swap file is created yet.
308      */
309     mfp = mf_open(NULL, 0);
310     if (mfp == NULL)
311 	goto error;
312 
313     buf->b_ml.ml_mfp = mfp;
314 #ifdef FEAT_CRYPT
315     mfp->mf_buffer = buf;
316 #endif
317     buf->b_ml.ml_flags = ML_EMPTY;
318     buf->b_ml.ml_line_count = 1;
319 #ifdef FEAT_LINEBREAK
320     curwin->w_nrwidth_line_count = 0;
321 #endif
322 
323 /*
324  * fill block0 struct and write page 0
325  */
326     if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
327 	goto error;
328     if (hp->bh_bnum != 0)
329     {
330 	iemsg(_("E298: Didn't get block nr 0?"));
331 	goto error;
332     }
333     b0p = (ZERO_BL *)(hp->bh_data);
334 
335     b0p->b0_id[0] = BLOCK0_ID0;
336     b0p->b0_id[1] = BLOCK0_ID1;
337     b0p->b0_magic_long = (long)B0_MAGIC_LONG;
338     b0p->b0_magic_int = (int)B0_MAGIC_INT;
339     b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
340     b0p->b0_magic_char = B0_MAGIC_CHAR;
341     mch_memmove(b0p->b0_version, "VIM ", 4);
342     STRNCPY(b0p->b0_version + 4, Version, 6);
343     long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
344 
345 #ifdef FEAT_SPELL
346     if (!buf->b_spell)
347 #endif
348     {
349 	b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
350 	b0p->b0_flags = get_fileformat(buf) + 1;
351 	set_b0_fname(b0p, buf);
352 	(void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
353 	b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
354 	mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
355 	b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
356 	long_to_char(mch_get_pid(), b0p->b0_pid);
357 #ifdef FEAT_CRYPT
358 	ml_set_b0_crypt(buf, b0p);
359 #endif
360     }
361 
362     /*
363      * Always sync block number 0 to disk, so we can check the file name in
364      * the swap file in findswapname(). Don't do this for a help files or
365      * a spell buffer though.
366      * Only works when there's a swapfile, otherwise it's done when the file
367      * is created.
368      */
369     mf_put(mfp, hp, TRUE, FALSE);
370     if (!buf->b_help && !B_SPELL(buf))
371 	(void)mf_sync(mfp, 0);
372 
373     /*
374      * Fill in root pointer block and write page 1.
375      */
376     if ((hp = ml_new_ptr(mfp)) == NULL)
377 	goto error;
378     if (hp->bh_bnum != 1)
379     {
380 	iemsg(_("E298: Didn't get block nr 1?"));
381 	goto error;
382     }
383     pp = (PTR_BL *)(hp->bh_data);
384     pp->pb_count = 1;
385     pp->pb_pointer[0].pe_bnum = 2;
386     pp->pb_pointer[0].pe_page_count = 1;
387     pp->pb_pointer[0].pe_old_lnum = 1;
388     pp->pb_pointer[0].pe_line_count = 1;    // line count after insertion
389     mf_put(mfp, hp, TRUE, FALSE);
390 
391     /*
392      * Allocate first data block and create an empty line 1.
393      */
394     if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
395 	goto error;
396     if (hp->bh_bnum != 2)
397     {
398 	iemsg(_("E298: Didn't get block nr 2?"));
399 	goto error;
400     }
401 
402     dp = (DATA_BL *)(hp->bh_data);
403     dp->db_index[0] = --dp->db_txt_start;	// at end of block
404     dp->db_free -= 1 + INDEX_SIZE;
405     dp->db_line_count = 1;
406     *((char_u *)dp + dp->db_txt_start) = NUL;	// empty line
407 
408     return OK;
409 
410 error:
411     if (mfp != NULL)
412     {
413 	if (hp)
414 	    mf_put(mfp, hp, FALSE, FALSE);
415 	mf_close(mfp, TRUE);	    // will also free(mfp->mf_fname)
416     }
417     buf->b_ml.ml_mfp = NULL;
418     return FAIL;
419 }
420 
421 #if defined(FEAT_CRYPT) || defined(PROTO)
422 /*
423  * Prepare encryption for "buf" for the current key and method.
424  */
425     static void
ml_set_mfp_crypt(buf_T * buf)426 ml_set_mfp_crypt(buf_T *buf)
427 {
428     if (*buf->b_p_key != NUL)
429     {
430 	int method_nr = crypt_get_method_nr(buf);
431 
432 	if (method_nr > CRYPT_M_ZIP && method_nr < CRYPT_M_SOD)
433 	{
434 	    // Generate a seed and store it in the memfile.
435 	    sha2_seed(buf->b_ml.ml_mfp->mf_seed, MF_SEED_LEN, NULL, 0);
436 	}
437 #ifdef FEAT_SODIUM
438 	else if (method_nr == CRYPT_M_SOD)
439 	    randombytes_buf(buf->b_ml.ml_mfp->mf_seed, MF_SEED_LEN);
440  #endif
441     }
442 }
443 
444 /*
445  * Prepare encryption for "buf" with block 0 "b0p".
446  */
447     static void
ml_set_b0_crypt(buf_T * buf,ZERO_BL * b0p)448 ml_set_b0_crypt(buf_T *buf, ZERO_BL *b0p)
449 {
450     if (*buf->b_p_key == NUL)
451 	b0p->b0_id[1] = BLOCK0_ID1;
452     else
453     {
454 	int method_nr = crypt_get_method_nr(buf);
455 
456 	b0p->b0_id[1] = id1_codes[method_nr];
457 	if (method_nr > CRYPT_M_ZIP && method_nr < CRYPT_M_SOD)
458 	{
459 	    // Generate a seed and store it in block 0 and in the memfile.
460 	    sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0);
461 	    mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
462 	}
463     }
464 }
465 
466 /*
467  * Called after the crypt key or 'cryptmethod' was changed for "buf".
468  * Will apply this to the swapfile.
469  * "old_key" is the previous key.  It is equal to buf->b_p_key when
470  * 'cryptmethod' is changed.
471  * "old_cm" is the previous 'cryptmethod'.  It is equal to the current
472  * 'cryptmethod' when 'key' is changed.
473  */
474     void
ml_set_crypt_key(buf_T * buf,char_u * old_key,char_u * old_cm)475 ml_set_crypt_key(
476     buf_T	*buf,
477     char_u	*old_key,
478     char_u	*old_cm)
479 {
480     memfile_T	*mfp = buf->b_ml.ml_mfp;
481     bhdr_T	*hp;
482     int		page_count;
483     int		idx;
484     long	error;
485     infoptr_T	*ip;
486     PTR_BL	*pp;
487     DATA_BL	*dp;
488     blocknr_T	bnum;
489     int		top;
490     int		old_method;
491 
492     if (mfp == NULL || mfp->mf_fd < 0)
493 	return;  // no memfile yet, nothing to do
494     old_method = crypt_method_nr_from_name(old_cm);
495 
496     // Swapfile encryption not supported by XChaCha20
497     if (crypt_get_method_nr(buf) == CRYPT_M_SOD && *buf->b_p_key != NUL)
498     {
499 	// close the swapfile
500 	mf_close_file(buf, TRUE);
501 	buf->b_p_swf = FALSE;
502 	return;
503     }
504     // First make sure the swapfile is in a consistent state, using the old
505     // key and method.
506     {
507 	char_u *new_key = buf->b_p_key;
508 	char_u *new_buf_cm = buf->b_p_cm;
509 
510 	buf->b_p_key = old_key;
511 	buf->b_p_cm = old_cm;
512 	ml_preserve(buf, FALSE);
513 	buf->b_p_key = new_key;
514 	buf->b_p_cm = new_buf_cm;
515     }
516 
517     // Set the key, method and seed to be used for reading, these must be the
518     // old values.
519     mfp->mf_old_key = old_key;
520     mfp->mf_old_cm = old_method;
521     if (old_method > 0 && *old_key != NUL)
522 	mch_memmove(mfp->mf_old_seed, mfp->mf_seed, MF_SEED_LEN);
523 
524     // Update block 0 with the crypt flag and may set a new seed.
525     ml_upd_block0(buf, UB_CRYPT);
526 
527     if (mfp->mf_infile_count > 2)
528     {
529 	/*
530 	 * Need to read back all data blocks from disk, decrypt them with the
531 	 * old key/method and mark them to be written. The algorithm is
532 	 * similar to what happens in ml_recover(), but we skip negative block
533 	 * numbers.
534 	 */
535 	ml_flush_line(buf);		    // flush buffered line
536 	(void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); // flush locked block
537 
538 	hp = NULL;
539 	bnum = 1;		// start with block 1
540 	page_count = 1;		// which is 1 page
541 	idx = 0;		// start with first index in block 1
542 	error = 0;
543 	buf->b_ml.ml_stack_top = 0;
544 	VIM_CLEAR(buf->b_ml.ml_stack);
545 	buf->b_ml.ml_stack_size = 0;	// no stack yet
546 
547 	for ( ; !got_int; line_breakcheck())
548 	{
549 	    if (hp != NULL)
550 		mf_put(mfp, hp, FALSE, FALSE);	// release previous block
551 
552 	    // get the block (pointer or data)
553 	    if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
554 	    {
555 		if (bnum == 1)
556 		    break;
557 		++error;
558 	    }
559 	    else
560 	    {
561 		pp = (PTR_BL *)(hp->bh_data);
562 		if (pp->pb_id == PTR_ID)	// it is a pointer block
563 		{
564 		    if (pp->pb_count == 0)
565 		    {
566 			// empty block?
567 			++error;
568 		    }
569 		    else if (idx < (int)pp->pb_count)	// go a block deeper
570 		    {
571 			if (pp->pb_pointer[idx].pe_bnum < 0)
572 			{
573 			    // Skip data block with negative block number.
574 			    // Should not happen, because of the ml_preserve()
575 			    // above. Get same block again for next index.
576 			    ++idx;
577 			    continue;
578 			}
579 
580 			// going one block deeper in the tree, new entry in
581 			// stack
582 			if ((top = ml_add_stack(buf)) < 0)
583 			{
584 			    ++error;
585 			    break;		    // out of memory
586 			}
587 			ip = &(buf->b_ml.ml_stack[top]);
588 			ip->ip_bnum = bnum;
589 			ip->ip_index = idx;
590 
591 			bnum = pp->pb_pointer[idx].pe_bnum;
592 			page_count = pp->pb_pointer[idx].pe_page_count;
593 			idx = 0;
594 			continue;
595 		    }
596 		}
597 		else	    // not a pointer block
598 		{
599 		    dp = (DATA_BL *)(hp->bh_data);
600 		    if (dp->db_id != DATA_ID)	// block id wrong
601 			++error;
602 		    else
603 		    {
604 			// It is a data block, need to write it back to disk.
605 			mf_put(mfp, hp, TRUE, FALSE);
606 			hp = NULL;
607 		    }
608 		}
609 	    }
610 
611 	    if (buf->b_ml.ml_stack_top == 0)	// finished
612 		break;
613 
614 	    // go one block up in the tree
615 	    ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
616 	    bnum = ip->ip_bnum;
617 	    idx = ip->ip_index + 1;	    // go to next index
618 	    page_count = 1;
619 	}
620 	if (hp != NULL)
621 	    mf_put(mfp, hp, FALSE, FALSE);  // release previous block
622 
623 	if (error > 0)
624 	    emsg(_("E843: Error while updating swap file crypt"));
625     }
626 
627     mfp->mf_old_key = NULL;
628 }
629 #endif
630 
631 /*
632  * ml_setname() is called when the file name of "buf" has been changed.
633  * It may rename the swap file.
634  */
635     void
ml_setname(buf_T * buf)636 ml_setname(buf_T *buf)
637 {
638     int		success = FALSE;
639     memfile_T	*mfp;
640     char_u	*fname;
641     char_u	*dirp;
642 #if defined(MSWIN)
643     char_u	*p;
644 #endif
645 
646     mfp = buf->b_ml.ml_mfp;
647     if (mfp->mf_fd < 0)		    // there is no swap file yet
648     {
649 	/*
650 	 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
651 	 * For help files we will make a swap file now.
652 	 */
653 	if (p_uc != 0 && (cmdmod.cmod_flags & CMOD_NOSWAPFILE) == 0)
654 	    ml_open_file(buf);	    // create a swap file
655 	return;
656     }
657 
658     /*
659      * Try all directories in the 'directory' option.
660      */
661     dirp = p_dir;
662     for (;;)
663     {
664 	if (*dirp == NUL)	    // tried all directories, fail
665 	    break;
666 	fname = findswapname(buf, &dirp, mfp->mf_fname);
667 						    // alloc's fname
668 	if (dirp == NULL)	    // out of memory
669 	    break;
670 	if (fname == NULL)	    // no file name found for this dir
671 	    continue;
672 
673 #if defined(MSWIN)
674 	/*
675 	 * Set full pathname for swap file now, because a ":!cd dir" may
676 	 * change directory without us knowing it.
677 	 */
678 	p = FullName_save(fname, FALSE);
679 	vim_free(fname);
680 	fname = p;
681 	if (fname == NULL)
682 	    continue;
683 #endif
684 	// if the file name is the same we don't have to do anything
685 	if (fnamecmp(fname, mfp->mf_fname) == 0)
686 	{
687 	    vim_free(fname);
688 	    success = TRUE;
689 	    break;
690 	}
691 	// need to close the swap file before renaming
692 	if (mfp->mf_fd >= 0)
693 	{
694 	    close(mfp->mf_fd);
695 	    mfp->mf_fd = -1;
696 	}
697 
698 	// try to rename the swap file
699 	if (vim_rename(mfp->mf_fname, fname) == 0)
700 	{
701 	    success = TRUE;
702 	    vim_free(mfp->mf_fname);
703 	    mfp->mf_fname = fname;
704 	    vim_free(mfp->mf_ffname);
705 #if defined(MSWIN)
706 	    mfp->mf_ffname = NULL;  // mf_fname is full pathname already
707 #else
708 	    mf_set_ffname(mfp);
709 #endif
710 	    ml_upd_block0(buf, UB_SAME_DIR);
711 	    break;
712 	}
713 	vim_free(fname);	    // this fname didn't work, try another
714     }
715 
716     if (mfp->mf_fd == -1)	    // need to (re)open the swap file
717     {
718 	mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
719 	if (mfp->mf_fd < 0)
720 	{
721 	    // could not (re)open the swap file, what can we do????
722 	    emsg(_("E301: Oops, lost the swap file!!!"));
723 	    return;
724 	}
725 #ifdef HAVE_FD_CLOEXEC
726 	{
727 	    int fdflags = fcntl(mfp->mf_fd, F_GETFD);
728 	    if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
729 		(void)fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
730 	}
731 #endif
732     }
733     if (!success)
734 	emsg(_("E302: Could not rename swap file"));
735 }
736 
737 /*
738  * Open a file for the memfile for all buffers that are not readonly or have
739  * been modified.
740  * Used when 'updatecount' changes from zero to non-zero.
741  */
742     void
ml_open_files(void)743 ml_open_files(void)
744 {
745     buf_T	*buf;
746 
747     FOR_ALL_BUFFERS(buf)
748 	if (!buf->b_p_ro || buf->b_changed)
749 	    ml_open_file(buf);
750 }
751 
752 /*
753  * Open a swap file for an existing memfile, if there is no swap file yet.
754  * If we are unable to find a file name, mf_fname will be NULL
755  * and the memfile will be in memory only (no recovery possible).
756  */
757     void
ml_open_file(buf_T * buf)758 ml_open_file(buf_T *buf)
759 {
760     memfile_T	*mfp;
761     char_u	*fname;
762     char_u	*dirp;
763 
764     mfp = buf->b_ml.ml_mfp;
765     if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf
766 				      || (cmdmod.cmod_flags & CMOD_NOSWAPFILE))
767 	return;		// nothing to do
768 
769 #ifdef FEAT_SPELL
770     // For a spell buffer use a temp file name.
771     if (buf->b_spell)
772     {
773 	fname = vim_tempname('s', FALSE);
774 	if (fname != NULL)
775 	    (void)mf_open_file(mfp, fname);	// consumes fname!
776 	buf->b_may_swap = FALSE;
777 	return;
778     }
779 #endif
780 
781     /*
782      * Try all directories in 'directory' option.
783      */
784     dirp = p_dir;
785     for (;;)
786     {
787 	if (*dirp == NUL)
788 	    break;
789 	// There is a small chance that between choosing the swap file name
790 	// and creating it, another Vim creates the file.  In that case the
791 	// creation will fail and we will use another directory.
792 	fname = findswapname(buf, &dirp, NULL); // allocates fname
793 	if (dirp == NULL)
794 	    break;  // out of memory
795 	if (fname == NULL)
796 	    continue;
797 	if (mf_open_file(mfp, fname) == OK)	// consumes fname!
798 	{
799 #if defined(MSWIN)
800 	    /*
801 	     * set full pathname for swap file now, because a ":!cd dir" may
802 	     * change directory without us knowing it.
803 	     */
804 	    mf_fullname(mfp);
805 #endif
806 	    ml_upd_block0(buf, UB_SAME_DIR);
807 
808 	    // Flush block zero, so others can read it
809 	    if (mf_sync(mfp, MFS_ZERO) == OK)
810 	    {
811 		// Mark all blocks that should be in the swapfile as dirty.
812 		// Needed for when the 'swapfile' option was reset, so that
813 		// the swap file was deleted, and then on again.
814 		mf_set_dirty(mfp);
815 		break;
816 	    }
817 	    // Writing block 0 failed: close the file and try another dir
818 	    mf_close_file(buf, FALSE);
819 	}
820     }
821 
822     if (*p_dir != NUL && mfp->mf_fname == NULL)
823     {
824 	need_wait_return = TRUE;	// call wait_return later
825 	++no_wait_return;
826 	(void)semsg(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
827 		    buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname);
828 	--no_wait_return;
829     }
830 
831     // don't try to open a swap file again
832     buf->b_may_swap = FALSE;
833 }
834 
835 /*
836  * If still need to create a swap file, and starting to edit a not-readonly
837  * file, or reading into an existing buffer, create a swap file now.
838  */
839     void
check_need_swap(int newfile)840 check_need_swap(
841     int	    newfile)		// reading file into new buffer
842 {
843     int old_msg_silent = msg_silent; // might be reset by an E325 message
844 
845     if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
846 	ml_open_file(curbuf);
847     msg_silent = old_msg_silent;
848 }
849 
850 /*
851  * Close memline for buffer 'buf'.
852  * If 'del_file' is TRUE, delete the swap file
853  */
854     void
ml_close(buf_T * buf,int del_file)855 ml_close(buf_T *buf, int del_file)
856 {
857     if (buf->b_ml.ml_mfp == NULL)		// not open
858 	return;
859     mf_close(buf->b_ml.ml_mfp, del_file);	// close the .swp file
860     if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
861 	vim_free(buf->b_ml.ml_line_ptr);
862     vim_free(buf->b_ml.ml_stack);
863 #ifdef FEAT_BYTEOFF
864     VIM_CLEAR(buf->b_ml.ml_chunksize);
865 #endif
866     buf->b_ml.ml_mfp = NULL;
867 
868     // Reset the "recovered" flag, give the ATTENTION prompt the next time
869     // this buffer is loaded.
870     buf->b_flags &= ~BF_RECOVERED;
871 }
872 
873 /*
874  * Close all existing memlines and memfiles.
875  * Only used when exiting.
876  * When 'del_file' is TRUE, delete the memfiles.
877  * But don't delete files that were ":preserve"d when we are POSIX compatible.
878  */
879     void
ml_close_all(int del_file)880 ml_close_all(int del_file)
881 {
882     buf_T	*buf;
883 
884     FOR_ALL_BUFFERS(buf)
885 	ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
886 				 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
887 #ifdef FEAT_SPELL
888     spell_delete_wordlist();	// delete the internal wordlist
889 #endif
890 #ifdef TEMPDIRNAMES
891     vim_deltempdir();		// delete created temp directory
892 #endif
893 }
894 
895 /*
896  * Close all memfiles for not modified buffers.
897  * Only use just before exiting!
898  */
899     void
ml_close_notmod(void)900 ml_close_notmod(void)
901 {
902     buf_T	*buf;
903 
904     FOR_ALL_BUFFERS(buf)
905 	if (!bufIsChanged(buf))
906 	    ml_close(buf, TRUE);    // close all not-modified buffers
907 }
908 
909 /*
910  * Update the timestamp in the .swp file.
911  * Used when the file has been written.
912  */
913     void
ml_timestamp(buf_T * buf)914 ml_timestamp(buf_T *buf)
915 {
916     ml_upd_block0(buf, UB_FNAME);
917 }
918 
919 /*
920  * Return FAIL when the ID of "b0p" is wrong.
921  */
922     static int
ml_check_b0_id(ZERO_BL * b0p)923 ml_check_b0_id(ZERO_BL *b0p)
924 {
925     if (b0p->b0_id[0] != BLOCK0_ID0
926 	    || (b0p->b0_id[1] != BLOCK0_ID1
927 		&& b0p->b0_id[1] != BLOCK0_ID1_C0
928 		&& b0p->b0_id[1] != BLOCK0_ID1_C1
929 		&& b0p->b0_id[1] != BLOCK0_ID1_C2
930 		&& b0p->b0_id[1] != BLOCK0_ID1_C3)
931 	    )
932 	return FAIL;
933     return OK;
934 }
935 
936 /*
937  * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
938  */
939     static void
ml_upd_block0(buf_T * buf,upd_block0_T what)940 ml_upd_block0(buf_T *buf, upd_block0_T what)
941 {
942     memfile_T	*mfp;
943     bhdr_T	*hp;
944     ZERO_BL	*b0p;
945 
946     mfp = buf->b_ml.ml_mfp;
947     if (mfp == NULL)
948 	return;
949     hp = mf_get(mfp, (blocknr_T)0, 1);
950     if (hp == NULL)
951     {
952 #ifdef FEAT_CRYPT
953 	// Possibly update the seed in the memfile before there is a block0.
954 	if (what == UB_CRYPT)
955 	    ml_set_mfp_crypt(buf);
956 #endif
957 	return;
958     }
959 
960     b0p = (ZERO_BL *)(hp->bh_data);
961     if (ml_check_b0_id(b0p) == FAIL)
962 	iemsg(_("E304: ml_upd_block0(): Didn't get block 0??"));
963     else
964     {
965 	if (what == UB_FNAME)
966 	    set_b0_fname(b0p, buf);
967 #ifdef FEAT_CRYPT
968 	else if (what == UB_CRYPT)
969 	    ml_set_b0_crypt(buf, b0p);
970 #endif
971 	else // what == UB_SAME_DIR
972 	    set_b0_dir_flag(b0p, buf);
973     }
974     mf_put(mfp, hp, TRUE, FALSE);
975 }
976 
977 /*
978  * Write file name and timestamp into block 0 of a swap file.
979  * Also set buf->b_mtime.
980  * Don't use NameBuff[]!!!
981  */
982     static void
set_b0_fname(ZERO_BL * b0p,buf_T * buf)983 set_b0_fname(ZERO_BL *b0p, buf_T *buf)
984 {
985     stat_T	st;
986 
987     if (buf->b_ffname == NULL)
988 	b0p->b0_fname[0] = NUL;
989     else
990     {
991 #if defined(MSWIN) || defined(AMIGA)
992 	// Systems that cannot translate "~user" back into a path: copy the
993 	// file name unmodified.  Do use slashes instead of backslashes for
994 	// portability.
995 	vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
996 # ifdef BACKSLASH_IN_FILENAME
997 	forward_slash(b0p->b0_fname);
998 # endif
999 #else
1000 	size_t	flen, ulen;
1001 	char_u	uname[B0_UNAME_SIZE];
1002 
1003 	/*
1004 	 * For a file under the home directory of the current user, we try to
1005 	 * replace the home directory path with "~user". This helps when
1006 	 * editing the same file on different machines over a network.
1007 	 * First replace home dir path with "~/" with home_replace().
1008 	 * Then insert the user name to get "~user/".
1009 	 */
1010 	home_replace(NULL, buf->b_ffname, b0p->b0_fname,
1011 						   B0_FNAME_SIZE_CRYPT, TRUE);
1012 	if (b0p->b0_fname[0] == '~')
1013 	{
1014 	    flen = STRLEN(b0p->b0_fname);
1015 	    // If there is no user name or it is too long, don't use "~/"
1016 	    if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
1017 		   || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
1018 		vim_strncpy(b0p->b0_fname, buf->b_ffname,
1019 						     B0_FNAME_SIZE_CRYPT - 1);
1020 	    else
1021 	    {
1022 		mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
1023 		mch_memmove(b0p->b0_fname + 1, uname, ulen);
1024 	    }
1025 	}
1026 #endif
1027 	if (mch_stat((char *)buf->b_ffname, &st) >= 0)
1028 	{
1029 	    long_to_char((long)st.st_mtime, b0p->b0_mtime);
1030 #ifdef CHECK_INODE
1031 	    long_to_char((long)st.st_ino, b0p->b0_ino);
1032 #endif
1033 	    buf_store_time(buf, &st, buf->b_ffname);
1034 	    buf->b_mtime_read = buf->b_mtime;
1035 	    buf->b_mtime_read_ns = buf->b_mtime_ns;
1036 	}
1037 	else
1038 	{
1039 	    long_to_char(0L, b0p->b0_mtime);
1040 #ifdef CHECK_INODE
1041 	    long_to_char(0L, b0p->b0_ino);
1042 #endif
1043 	    buf->b_mtime = 0;
1044 	    buf->b_mtime_ns = 0;
1045 	    buf->b_mtime_read = 0;
1046 	    buf->b_mtime_read_ns = 0;
1047 	    buf->b_orig_size = 0;
1048 	    buf->b_orig_mode = 0;
1049 	}
1050     }
1051 
1052     // Also add the 'fileencoding' if there is room.
1053     add_b0_fenc(b0p, curbuf);
1054 }
1055 
1056 /*
1057  * Update the B0_SAME_DIR flag of the swap file.  It's set if the file and the
1058  * swapfile for "buf" are in the same directory.
1059  * This is fail safe: if we are not sure the directories are equal the flag is
1060  * not set.
1061  */
1062     static void
set_b0_dir_flag(ZERO_BL * b0p,buf_T * buf)1063 set_b0_dir_flag(ZERO_BL *b0p, buf_T *buf)
1064 {
1065     if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1066 	b0p->b0_flags |= B0_SAME_DIR;
1067     else
1068 	b0p->b0_flags &= ~B0_SAME_DIR;
1069 }
1070 
1071 /*
1072  * When there is room, add the 'fileencoding' to block zero.
1073  */
1074     static void
add_b0_fenc(ZERO_BL * b0p,buf_T * buf)1075 add_b0_fenc(
1076     ZERO_BL	*b0p,
1077     buf_T	*buf)
1078 {
1079     int		n;
1080     int		size = B0_FNAME_SIZE_NOCRYPT;
1081 
1082 #ifdef FEAT_CRYPT
1083     // Without encryption use the same offset as in Vim 7.2 to be compatible.
1084     // With encryption it's OK to move elsewhere, the swap file is not
1085     // compatible anyway.
1086     if (*buf->b_p_key != NUL)
1087 	size = B0_FNAME_SIZE_CRYPT;
1088 #endif
1089 
1090     n = (int)STRLEN(buf->b_p_fenc);
1091     if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
1092 	b0p->b0_flags &= ~B0_HAS_FENC;
1093     else
1094     {
1095 	mch_memmove((char *)b0p->b0_fname + size - n,
1096 					    (char *)buf->b_p_fenc, (size_t)n);
1097 	*(b0p->b0_fname + size - n - 1) = NUL;
1098 	b0p->b0_flags |= B0_HAS_FENC;
1099     }
1100 }
1101 
1102 #if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO_UPTIME)
1103 # include <sys/sysinfo.h>
1104 #endif
1105 
1106 #if defined(UNIX) || defined(MSWIN)
1107 /*
1108  * Return TRUE if the process with number "b0p->b0_pid" is still running.
1109  * "swap_fname" is the name of the swap file, if it's from before a reboot then
1110  * the result is FALSE;
1111  */
1112     static int
swapfile_process_running(ZERO_BL * b0p,char_u * swap_fname UNUSED)1113 swapfile_process_running(ZERO_BL *b0p, char_u *swap_fname UNUSED)
1114 {
1115 #if defined(HAVE_SYSINFO) && defined(HAVE_SYSINFO_UPTIME)
1116     stat_T	    st;
1117     struct sysinfo  sinfo;
1118 
1119     // If the system rebooted after when the swap file was written then the
1120     // process can't be running now.
1121     if (mch_stat((char *)swap_fname, &st) != -1
1122 	    && sysinfo(&sinfo) == 0
1123 	    && st.st_mtime < time(NULL) - (
1124 #  ifdef FEAT_EVAL
1125 		override_sysinfo_uptime >= 0 ? override_sysinfo_uptime :
1126 #  endif
1127 		sinfo.uptime))
1128 	return FALSE;
1129 # endif
1130     return mch_process_running(char_to_long(b0p->b0_pid));
1131 }
1132 #endif
1133 
1134 /*
1135  * Try to recover curbuf from the .swp file.
1136  * If "checkext" is TRUE, check the extension and detect whether it is
1137  * a swap file.
1138  */
1139     void
ml_recover(int checkext)1140 ml_recover(int checkext)
1141 {
1142     buf_T	*buf = NULL;
1143     memfile_T	*mfp = NULL;
1144     char_u	*fname;
1145     char_u	*fname_used = NULL;
1146     bhdr_T	*hp = NULL;
1147     ZERO_BL	*b0p;
1148     int		b0_ff;
1149     char_u	*b0_fenc = NULL;
1150 #ifdef FEAT_CRYPT
1151     int		b0_cm = -1;
1152 #endif
1153     PTR_BL	*pp;
1154     DATA_BL	*dp;
1155     infoptr_T	*ip;
1156     blocknr_T	bnum;
1157     int		page_count;
1158     stat_T	org_stat, swp_stat;
1159     int		len;
1160     int		directly;
1161     linenr_T	lnum;
1162     char_u	*p;
1163     int		i;
1164     long	error;
1165     int		cannot_open;
1166     linenr_T	line_count;
1167     int		has_error;
1168     int		idx;
1169     int		top;
1170     int		txt_start;
1171     off_T	size;
1172     int		called_from_main;
1173     int		serious_error = TRUE;
1174     long	mtime;
1175     int		attr;
1176     int		orig_file_status = NOTDONE;
1177 
1178     recoverymode = TRUE;
1179     called_from_main = (curbuf->b_ml.ml_mfp == NULL);
1180     attr = HL_ATTR(HLF_E);
1181 
1182     /*
1183      * If the file name ends in ".s[a-w][a-z]" we assume this is the swap file.
1184      * Otherwise a search is done to find the swap file(s).
1185      */
1186     fname = curbuf->b_fname;
1187     if (fname == NULL)		    // When there is no file name
1188 	fname = (char_u *)"";
1189     len = (int)STRLEN(fname);
1190     if (checkext && len >= 4 &&
1191 #if defined(VMS)
1192 	    STRNICMP(fname + len - 4, "_s", 2)
1193 #else
1194 	    STRNICMP(fname + len - 4, ".s", 2)
1195 #endif
1196 						== 0
1197 		&& vim_strchr((char_u *)"abcdefghijklmnopqrstuvw",
1198 					   TOLOWER_ASC(fname[len - 2])) != NULL
1199 		&& ASCII_ISALPHA(fname[len - 1]))
1200     {
1201 	directly = TRUE;
1202 	fname_used = vim_strsave(fname); // make a copy for mf_open()
1203     }
1204     else
1205     {
1206 	directly = FALSE;
1207 
1208 	// count the number of matching swap files
1209 	len = recover_names(fname, FALSE, 0, NULL);
1210 	if (len == 0)		    // no swap files found
1211 	{
1212 	    semsg(_("E305: No swap file found for %s"), fname);
1213 	    goto theend;
1214 	}
1215 	if (len == 1)		    // one swap file found, use it
1216 	    i = 1;
1217 	else			    // several swap files found, choose
1218 	{
1219 	    // list the names of the swap files
1220 	    (void)recover_names(fname, TRUE, 0, NULL);
1221 	    msg_putchar('\n');
1222 	    msg_puts(_("Enter number of swap file to use (0 to quit): "));
1223 	    i = get_number(FALSE, NULL);
1224 	    if (i < 1 || i > len)
1225 		goto theend;
1226 	}
1227 	// get the swap file name that will be used
1228 	(void)recover_names(fname, FALSE, i, &fname_used);
1229     }
1230     if (fname_used == NULL)
1231 	goto theend;			// out of memory
1232 
1233     // When called from main() still need to initialize storage structure
1234     if (called_from_main && ml_open(curbuf) == FAIL)
1235 	getout(1);
1236 
1237     /*
1238      * Allocate a buffer structure for the swap file that is used for recovery.
1239      * Only the memline and crypt information in it are really used.
1240      */
1241     buf = ALLOC_ONE(buf_T);
1242     if (buf == NULL)
1243 	goto theend;
1244 
1245     /*
1246      * init fields in memline struct
1247      */
1248     buf->b_ml.ml_stack_size = 0;	// no stack yet
1249     buf->b_ml.ml_stack = NULL;		// no stack yet
1250     buf->b_ml.ml_stack_top = 0;		// nothing in the stack
1251     buf->b_ml.ml_line_lnum = 0;		// no cached line
1252     buf->b_ml.ml_locked = NULL;		// no locked block
1253     buf->b_ml.ml_flags = 0;
1254 #ifdef FEAT_CRYPT
1255     buf->b_p_key = empty_option;
1256     buf->b_p_cm = empty_option;
1257 #endif
1258 
1259     /*
1260      * open the memfile from the old swap file
1261      */
1262     p = vim_strsave(fname_used); // save "fname_used" for the message:
1263 				 // mf_open() will consume "fname_used"!
1264     mfp = mf_open(fname_used, O_RDONLY);
1265     fname_used = p;
1266     if (mfp == NULL || mfp->mf_fd < 0)
1267     {
1268 	if (fname_used != NULL)
1269 	    semsg(_("E306: Cannot open %s"), fname_used);
1270 	goto theend;
1271     }
1272     buf->b_ml.ml_mfp = mfp;
1273 #ifdef FEAT_CRYPT
1274     mfp->mf_buffer = buf;
1275 #endif
1276 
1277     /*
1278      * The page size set in mf_open() might be different from the page size
1279      * used in the swap file, we must get it from block 0.  But to read block
1280      * 0 we need a page size.  Use the minimal size for block 0 here, it will
1281      * be set to the real value below.
1282      */
1283     mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1284 
1285     /*
1286      * try to read block 0
1287      */
1288     if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1289     {
1290 	msg_start();
1291 	msg_puts_attr(_("Unable to read block 0 from "), attr | MSG_HIST);
1292 	msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1293 	msg_puts_attr(_("\nMaybe no changes were made or Vim did not update the swap file."),
1294 		attr | MSG_HIST);
1295 	msg_end();
1296 	goto theend;
1297     }
1298     b0p = (ZERO_BL *)(hp->bh_data);
1299     if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1300     {
1301 	msg_start();
1302 	msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1303 	msg_puts_attr(_(" cannot be used with this version of Vim.\n"),
1304 								    MSG_HIST);
1305 	msg_puts_attr(_("Use Vim version 3.0.\n"), MSG_HIST);
1306 	msg_end();
1307 	goto theend;
1308     }
1309     if (ml_check_b0_id(b0p) == FAIL)
1310     {
1311 	semsg(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1312 	goto theend;
1313     }
1314     if (b0_magic_wrong(b0p))
1315     {
1316 	msg_start();
1317 	msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1318 #if defined(MSWIN)
1319 	if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1320 	    msg_puts_attr(_(" cannot be used with this version of Vim.\n"),
1321 							     attr | MSG_HIST);
1322 	else
1323 #endif
1324 	    msg_puts_attr(_(" cannot be used on this computer.\n"),
1325 							     attr | MSG_HIST);
1326 	msg_puts_attr(_("The file was created on "), attr | MSG_HIST);
1327 	// avoid going past the end of a corrupted hostname
1328 	b0p->b0_fname[0] = NUL;
1329 	msg_puts_attr((char *)b0p->b0_hname, attr | MSG_HIST);
1330 	msg_puts_attr(_(",\nor the file has been damaged."), attr | MSG_HIST);
1331 	msg_end();
1332 	goto theend;
1333     }
1334 
1335 #ifdef FEAT_CRYPT
1336     for (i = 0; i < (int)ARRAY_LENGTH(id1_codes); ++i)
1337 	if (id1_codes[i] == b0p->b0_id[1])
1338 	    b0_cm = i;
1339     if (b0_cm > 0)
1340 	mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
1341     crypt_set_cm_option(buf, b0_cm < 0 ? 0 : b0_cm);
1342 #else
1343     if (b0p->b0_id[1] != BLOCK0_ID1)
1344     {
1345 	semsg(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
1346 	goto theend;
1347     }
1348 #endif
1349 
1350     /*
1351      * If we guessed the wrong page size, we have to recalculate the
1352      * highest block number in the file.
1353      */
1354     if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1355     {
1356 	unsigned previous_page_size = mfp->mf_page_size;
1357 
1358 	mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
1359 	if (mfp->mf_page_size < previous_page_size)
1360 	{
1361 	    msg_start();
1362 	    msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1363 	    msg_puts_attr(_(" has been damaged (page size is smaller than minimum value).\n"),
1364 			attr | MSG_HIST);
1365 	    msg_end();
1366 	    goto theend;
1367 	}
1368 	if ((size = vim_lseek(mfp->mf_fd, (off_T)0L, SEEK_END)) <= 0)
1369 	    mfp->mf_blocknr_max = 0;	    // no file or empty file
1370 	else
1371 	    mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1372 	mfp->mf_infile_count = mfp->mf_blocknr_max;
1373 
1374 	// need to reallocate the memory used to store the data
1375 	p = alloc(mfp->mf_page_size);
1376 	if (p == NULL)
1377 	    goto theend;
1378 	mch_memmove(p, hp->bh_data, previous_page_size);
1379 	vim_free(hp->bh_data);
1380 	hp->bh_data = p;
1381 	b0p = (ZERO_BL *)(hp->bh_data);
1382     }
1383 
1384     /*
1385      * If .swp file name given directly, use name from swap file for buffer.
1386      */
1387     if (directly)
1388     {
1389 	expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1390 	if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1391 	    goto theend;
1392     }
1393 
1394     home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
1395     smsg(_("Using swap file \"%s\""), NameBuff);
1396 
1397     if (buf_spname(curbuf) != NULL)
1398 	vim_strncpy(NameBuff, buf_spname(curbuf), MAXPATHL - 1);
1399     else
1400 	home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
1401     smsg(_("Original file \"%s\""), NameBuff);
1402     msg_putchar('\n');
1403 
1404     /*
1405      * check date of swap file and original file
1406      */
1407     mtime = char_to_long(b0p->b0_mtime);
1408     if (curbuf->b_ffname != NULL
1409 	    && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1410 	    && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1411 		    && org_stat.st_mtime > swp_stat.st_mtime)
1412 		|| org_stat.st_mtime != mtime))
1413 	emsg(_("E308: Warning: Original file may have been changed"));
1414     out_flush();
1415 
1416     // Get the 'fileformat' and 'fileencoding' from block zero.
1417     b0_ff = (b0p->b0_flags & B0_FF_MASK);
1418     if (b0p->b0_flags & B0_HAS_FENC)
1419     {
1420 	int fnsize = B0_FNAME_SIZE_NOCRYPT;
1421 
1422 #ifdef FEAT_CRYPT
1423 	// Use the same size as in add_b0_fenc().
1424 	if (b0p->b0_id[1] != BLOCK0_ID1)
1425 	    fnsize = B0_FNAME_SIZE_CRYPT;
1426 #endif
1427 	for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
1428 	    ;
1429 	b0_fenc = vim_strnsave(p, b0p->b0_fname + fnsize - p);
1430     }
1431 
1432     mf_put(mfp, hp, FALSE, FALSE);	// release block 0
1433     hp = NULL;
1434 
1435     /*
1436      * Now that we are sure that the file is going to be recovered, clear the
1437      * contents of the current buffer.
1438      */
1439     while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1440 	ml_delete((linenr_T)1);
1441 
1442     /*
1443      * Try reading the original file to obtain the values of 'fileformat',
1444      * 'fileencoding', etc.  Ignore errors.  The text itself is not used.
1445      * When the file is encrypted the user is asked to enter the key.
1446      */
1447     if (curbuf->b_ffname != NULL)
1448 	orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
1449 			      (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
1450 
1451 #ifdef FEAT_CRYPT
1452     if (b0_cm >= 0)
1453     {
1454 	// Need to ask the user for the crypt key.  If this fails we continue
1455 	// without a key, will probably get garbage text.
1456 	if (*curbuf->b_p_key != NUL)
1457 	{
1458 	    smsg(_("Swap file is encrypted: \"%s\""), fname_used);
1459 	    msg_puts(_("\nIf you entered a new crypt key but did not write the text file,"));
1460 	    msg_puts(_("\nenter the new crypt key."));
1461 	    msg_puts(_("\nIf you wrote the text file after changing the crypt key press enter"));
1462 	    msg_puts(_("\nto use the same key for text file and swap file"));
1463 	}
1464 	else
1465 	    smsg(_(need_key_msg), fname_used);
1466 	buf->b_p_key = crypt_get_key(FALSE, FALSE);
1467 	if (buf->b_p_key == NULL)
1468 	    buf->b_p_key = curbuf->b_p_key;
1469 	else if (*buf->b_p_key == NUL)
1470 	{
1471 	    vim_free(buf->b_p_key);
1472 	    buf->b_p_key = curbuf->b_p_key;
1473 	}
1474 	if (buf->b_p_key == NULL)
1475 	    buf->b_p_key = empty_option;
1476     }
1477 #endif
1478 
1479     // Use the 'fileformat' and 'fileencoding' as stored in the swap file.
1480     if (b0_ff != 0)
1481 	set_fileformat(b0_ff - 1, OPT_LOCAL);
1482     if (b0_fenc != NULL)
1483     {
1484 	set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1485 	vim_free(b0_fenc);
1486     }
1487     unchanged(curbuf, TRUE, TRUE);
1488 
1489     bnum = 1;		// start with block 1
1490     page_count = 1;	// which is 1 page
1491     lnum = 0;		// append after line 0 in curbuf
1492     line_count = 0;
1493     idx = 0;		// start with first index in block 1
1494     error = 0;
1495     buf->b_ml.ml_stack_top = 0;
1496     buf->b_ml.ml_stack = NULL;
1497     buf->b_ml.ml_stack_size = 0;	// no stack yet
1498 
1499     if (curbuf->b_ffname == NULL)
1500 	cannot_open = TRUE;
1501     else
1502 	cannot_open = FALSE;
1503 
1504     serious_error = FALSE;
1505     for ( ; !got_int; line_breakcheck())
1506     {
1507 	if (hp != NULL)
1508 	    mf_put(mfp, hp, FALSE, FALSE);	// release previous block
1509 
1510 	/*
1511 	 * get block
1512 	 */
1513 	if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1514 	{
1515 	    if (bnum == 1)
1516 	    {
1517 		semsg(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1518 		goto theend;
1519 	    }
1520 	    ++error;
1521 	    ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1522 							    (colnr_T)0, TRUE);
1523 	}
1524 	else		// there is a block
1525 	{
1526 	    pp = (PTR_BL *)(hp->bh_data);
1527 	    if (pp->pb_id == PTR_ID)		// it is a pointer block
1528 	    {
1529 		// check line count when using pointer block first time
1530 		if (idx == 0 && line_count != 0)
1531 		{
1532 		    for (i = 0; i < (int)pp->pb_count; ++i)
1533 			line_count -= pp->pb_pointer[i].pe_line_count;
1534 		    if (line_count != 0)
1535 		    {
1536 			++error;
1537 			ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1538 							    (colnr_T)0, TRUE);
1539 		    }
1540 		}
1541 
1542 		if (pp->pb_count == 0)
1543 		{
1544 		    ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1545 							    (colnr_T)0, TRUE);
1546 		    ++error;
1547 		}
1548 		else if (idx < (int)pp->pb_count)	// go a block deeper
1549 		{
1550 		    if (pp->pb_pointer[idx].pe_bnum < 0)
1551 		    {
1552 			/*
1553 			 * Data block with negative block number.
1554 			 * Try to read lines from the original file.
1555 			 * This is slow, but it works.
1556 			 */
1557 			if (!cannot_open)
1558 			{
1559 			    line_count = pp->pb_pointer[idx].pe_line_count;
1560 			    if (readfile(curbuf->b_ffname, NULL, lnum,
1561 					pp->pb_pointer[idx].pe_old_lnum - 1,
1562 					line_count, NULL, 0) != OK)
1563 				cannot_open = TRUE;
1564 			    else
1565 				lnum += line_count;
1566 			}
1567 			if (cannot_open)
1568 			{
1569 			    ++error;
1570 			    ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1571 							    (colnr_T)0, TRUE);
1572 			}
1573 			++idx;	    // get same block again for next index
1574 			continue;
1575 		    }
1576 
1577 		    /*
1578 		     * going one block deeper in the tree
1579 		     */
1580 		    if ((top = ml_add_stack(buf)) < 0)	// new entry in stack
1581 		    {
1582 			++error;
1583 			break;		    // out of memory
1584 		    }
1585 		    ip = &(buf->b_ml.ml_stack[top]);
1586 		    ip->ip_bnum = bnum;
1587 		    ip->ip_index = idx;
1588 
1589 		    bnum = pp->pb_pointer[idx].pe_bnum;
1590 		    line_count = pp->pb_pointer[idx].pe_line_count;
1591 		    page_count = pp->pb_pointer[idx].pe_page_count;
1592 		    idx = 0;
1593 		    continue;
1594 		}
1595 	    }
1596 	    else	    // not a pointer block
1597 	    {
1598 		dp = (DATA_BL *)(hp->bh_data);
1599 		if (dp->db_id != DATA_ID)	// block id wrong
1600 		{
1601 		    if (bnum == 1)
1602 		    {
1603 			semsg(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1604 							       mfp->mf_fname);
1605 			goto theend;
1606 		    }
1607 		    ++error;
1608 		    ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1609 							    (colnr_T)0, TRUE);
1610 		}
1611 		else
1612 		{
1613 		    /*
1614 		     * it is a data block
1615 		     * Append all the lines in this block
1616 		     */
1617 		    has_error = FALSE;
1618 			/*
1619 			 * check length of block
1620 			 * if wrong, use length in pointer block
1621 			 */
1622 		    if (page_count * mfp->mf_page_size != dp->db_txt_end)
1623 		    {
1624 			ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1625 							    (colnr_T)0, TRUE);
1626 			++error;
1627 			has_error = TRUE;
1628 			dp->db_txt_end = page_count * mfp->mf_page_size;
1629 		    }
1630 
1631 			// make sure there is a NUL at the end of the block
1632 		    *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1633 
1634 			/*
1635 			 * check number of lines in block
1636 			 * if wrong, use count in data block
1637 			 */
1638 		    if (line_count != dp->db_line_count)
1639 		    {
1640 			ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1641 							    (colnr_T)0, TRUE);
1642 			++error;
1643 			has_error = TRUE;
1644 		    }
1645 
1646 		    for (i = 0; i < dp->db_line_count; ++i)
1647 		    {
1648 			txt_start = (dp->db_index[i] & DB_INDEX_MASK);
1649 			if (txt_start <= (int)HEADER_SIZE
1650 					  || txt_start >= (int)dp->db_txt_end)
1651 			{
1652 			    p = (char_u *)"???";
1653 			    ++error;
1654 			}
1655 			else
1656 			    p = (char_u *)dp + txt_start;
1657 			ml_append(lnum++, p, (colnr_T)0, TRUE);
1658 		    }
1659 		    if (has_error)
1660 			ml_append(lnum++, (char_u *)_("???END"),
1661 							    (colnr_T)0, TRUE);
1662 		}
1663 	    }
1664 	}
1665 
1666 	if (buf->b_ml.ml_stack_top == 0)	// finished
1667 	    break;
1668 
1669 	/*
1670 	 * go one block up in the tree
1671 	 */
1672 	ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1673 	bnum = ip->ip_bnum;
1674 	idx = ip->ip_index + 1;	    // go to next index
1675 	page_count = 1;
1676     }
1677 
1678     /*
1679      * Compare the buffer contents with the original file.  When they differ
1680      * set the 'modified' flag.
1681      * Lines 1 - lnum are the new contents.
1682      * Lines lnum + 1 to ml_line_count are the original contents.
1683      * Line ml_line_count + 1 in the dummy empty line.
1684      */
1685     if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1686     {
1687 	// Recovering an empty file results in two lines and the first line is
1688 	// empty.  Don't set the modified flag then.
1689 	if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1690 	{
1691 	    changed_internal();
1692 	    ++CHANGEDTICK(curbuf);
1693 	}
1694     }
1695     else
1696     {
1697 	for (idx = 1; idx <= lnum; ++idx)
1698 	{
1699 	    // Need to copy one line, fetching the other one may flush it.
1700 	    p = vim_strsave(ml_get(idx));
1701 	    i = STRCMP(p, ml_get(idx + lnum));
1702 	    vim_free(p);
1703 	    if (i != 0)
1704 	    {
1705 		changed_internal();
1706 		++CHANGEDTICK(curbuf);
1707 		break;
1708 	    }
1709 	}
1710     }
1711 
1712     /*
1713      * Delete the lines from the original file and the dummy line from the
1714      * empty buffer.  These will now be after the last line in the buffer.
1715      */
1716     while (curbuf->b_ml.ml_line_count > lnum
1717 				       && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1718 	ml_delete(curbuf->b_ml.ml_line_count);
1719     curbuf->b_flags |= BF_RECOVERED;
1720     check_cursor();
1721 
1722     recoverymode = FALSE;
1723     if (got_int)
1724 	emsg(_("E311: Recovery Interrupted"));
1725     else if (error)
1726     {
1727 	++no_wait_return;
1728 	msg(">>>>>>>>>>>>>");
1729 	emsg(_("E312: Errors detected while recovering; look for lines starting with ???"));
1730 	--no_wait_return;
1731 	msg(_("See \":help E312\" for more information."));
1732 	msg(">>>>>>>>>>>>>");
1733     }
1734     else
1735     {
1736 	if (curbuf->b_changed)
1737 	{
1738 	    msg(_("Recovery completed. You should check if everything is OK."));
1739 	    msg_puts(_("\n(You might want to write out this file under another name\n"));
1740 	    msg_puts(_("and run diff with the original file to check for changes)"));
1741 	}
1742 	else
1743 	    msg(_("Recovery completed. Buffer contents equals file contents."));
1744 	msg_puts(_("\nYou may want to delete the .swp file now."));
1745 #if defined(UNIX) || defined(MSWIN)
1746 	if (swapfile_process_running(b0p, fname_used))
1747 	{
1748 	    // Warn there could be an active Vim on the same file, the user may
1749 	    // want to kill it.
1750 	    msg_puts(_("\nNote: process STILL RUNNING: "));
1751 	    msg_outnum(char_to_long(b0p->b0_pid));
1752 	}
1753 #endif
1754 	msg_puts("\n\n");
1755 	cmdline_row = msg_row;
1756     }
1757 #ifdef FEAT_CRYPT
1758     if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1759     {
1760 	msg_puts(_("Using crypt key from swap file for the text file.\n"));
1761 	set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1762     }
1763 #endif
1764     redraw_curbuf_later(NOT_VALID);
1765 
1766 theend:
1767     vim_free(fname_used);
1768     recoverymode = FALSE;
1769     if (mfp != NULL)
1770     {
1771 	if (hp != NULL)
1772 	    mf_put(mfp, hp, FALSE, FALSE);
1773 	mf_close(mfp, FALSE);	    // will also vim_free(mfp->mf_fname)
1774     }
1775     if (buf != NULL)
1776     {
1777 #ifdef FEAT_CRYPT
1778 	if (buf->b_p_key != curbuf->b_p_key)
1779 	    free_string_option(buf->b_p_key);
1780 	free_string_option(buf->b_p_cm);
1781 #endif
1782 	vim_free(buf->b_ml.ml_stack);
1783 	vim_free(buf);
1784     }
1785     if (serious_error && called_from_main)
1786 	ml_close(curbuf, TRUE);
1787     else
1788     {
1789 	apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1790 	apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1791     }
1792 }
1793 
1794 /*
1795  * Find the names of swap files in current directory and the directory given
1796  * with the 'directory' option.
1797  *
1798  * Used to:
1799  * - list the swap files for "vim -r"
1800  * - count the number of swap files when recovering
1801  * - list the swap files when recovering
1802  * - find the name of the n'th swap file when recovering
1803  */
1804     int
recover_names(char_u * fname,int list,int nr,char_u ** fname_out)1805 recover_names(
1806     char_u	*fname,		// base for swap file name
1807     int		list,		// when TRUE, list the swap file names
1808     int		nr,		// when non-zero, return nr'th swap file name
1809     char_u	**fname_out)	// result when "nr" > 0
1810 {
1811     int		num_names;
1812     char_u	*(names[6]);
1813     char_u	*tail;
1814     char_u	*p;
1815     int		num_files;
1816     int		file_count = 0;
1817     char_u	**files;
1818     int		i;
1819     char_u	*dirp;
1820     char_u	*dir_name;
1821     char_u	*fname_res = NULL;
1822 #ifdef HAVE_READLINK
1823     char_u	fname_buf[MAXPATHL];
1824 #endif
1825 
1826     if (fname != NULL)
1827     {
1828 #ifdef HAVE_READLINK
1829 	// Expand symlink in the file name, because the swap file is created
1830 	// with the actual file instead of with the symlink.
1831 	if (resolve_symlink(fname, fname_buf) == OK)
1832 	    fname_res = fname_buf;
1833 	else
1834 #endif
1835 	    fname_res = fname;
1836     }
1837 
1838     if (list)
1839     {
1840 	// use msg() to start the scrolling properly
1841 	msg(_("Swap files found:"));
1842 	msg_putchar('\n');
1843     }
1844 
1845     /*
1846      * Do the loop for every directory in 'directory'.
1847      * First allocate some memory to put the directory name in.
1848      */
1849     dir_name = alloc(STRLEN(p_dir) + 1);
1850     dirp = p_dir;
1851     while (dir_name != NULL && *dirp)
1852     {
1853 	/*
1854 	 * Isolate a directory name from *dirp and put it in dir_name (we know
1855 	 * it is large enough, so use 31000 for length).
1856 	 * Advance dirp to next directory name.
1857 	 */
1858 	(void)copy_option_part(&dirp, dir_name, 31000, ",");
1859 
1860 	if (dir_name[0] == '.' && dir_name[1] == NUL)	// check current dir
1861 	{
1862 	    if (fname == NULL)
1863 	    {
1864 #ifdef VMS
1865 		names[0] = vim_strsave((char_u *)"*_sw%");
1866 #else
1867 		names[0] = vim_strsave((char_u *)"*.sw?");
1868 #endif
1869 #if defined(UNIX) || defined(MSWIN)
1870 		// For Unix names starting with a dot are special.  MS-Windows
1871 		// supports this too, on some file systems.
1872 		names[1] = vim_strsave((char_u *)".*.sw?");
1873 		names[2] = vim_strsave((char_u *)".sw?");
1874 		num_names = 3;
1875 #else
1876 # ifdef VMS
1877 		names[1] = vim_strsave((char_u *)".*_sw%");
1878 		num_names = 2;
1879 # else
1880 		num_names = 1;
1881 # endif
1882 #endif
1883 	    }
1884 	    else
1885 		num_names = recov_file_names(names, fname_res, TRUE);
1886 	}
1887 	else			    // check directory dir_name
1888 	{
1889 	    if (fname == NULL)
1890 	    {
1891 #ifdef VMS
1892 		names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1893 #else
1894 		names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
1895 #endif
1896 #if defined(UNIX) || defined(MSWIN)
1897 		// For Unix names starting with a dot are special.  MS-Windows
1898 		// supports this too, on some file systems.
1899 		names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1900 		names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1901 		num_names = 3;
1902 #else
1903 # ifdef VMS
1904 		names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1905 		num_names = 2;
1906 # else
1907 		num_names = 1;
1908 # endif
1909 #endif
1910 	    }
1911 	    else
1912 	    {
1913 #if defined(UNIX) || defined(MSWIN)
1914 		int	len = (int)STRLEN(dir_name);
1915 
1916 		p = dir_name + len;
1917 		if (after_pathsep(dir_name, p) && len > 1 && p[-1] == p[-2])
1918 		{
1919 		    // Ends with '//', Use Full path for swap name
1920 		    tail = make_percent_swname(dir_name, fname_res);
1921 		}
1922 		else
1923 #endif
1924 		{
1925 		    tail = gettail(fname_res);
1926 		    tail = concat_fnames(dir_name, tail, TRUE);
1927 		}
1928 		if (tail == NULL)
1929 		    num_names = 0;
1930 		else
1931 		{
1932 		    num_names = recov_file_names(names, tail, FALSE);
1933 		    vim_free(tail);
1934 		}
1935 	    }
1936 	}
1937 
1938 	// check for out-of-memory
1939 	for (i = 0; i < num_names; ++i)
1940 	{
1941 	    if (names[i] == NULL)
1942 	    {
1943 		for (i = 0; i < num_names; ++i)
1944 		    vim_free(names[i]);
1945 		num_names = 0;
1946 	    }
1947 	}
1948 	if (num_names == 0)
1949 	    num_files = 0;
1950 	else if (expand_wildcards(num_names, names, &num_files, &files,
1951 			    EW_NOTENV|EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1952 	    num_files = 0;
1953 
1954 	/*
1955 	 * When no swap file found, wildcard expansion might have failed (e.g.
1956 	 * not able to execute the shell).
1957 	 * Try finding a swap file by simply adding ".swp" to the file name.
1958 	 */
1959 	if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
1960 	{
1961 	    stat_T	    st;
1962 	    char_u	    *swapname;
1963 
1964 	    swapname = modname(fname_res,
1965 #if defined(VMS)
1966 			       (char_u *)"_swp", FALSE
1967 #else
1968 			       (char_u *)".swp", TRUE
1969 #endif
1970 			      );
1971 	    if (swapname != NULL)
1972 	    {
1973 		if (mch_stat((char *)swapname, &st) != -1)    // It exists!
1974 		{
1975 		    files = ALLOC_ONE(char_u *);
1976 		    if (files != NULL)
1977 		    {
1978 			files[0] = swapname;
1979 			swapname = NULL;
1980 			num_files = 1;
1981 		    }
1982 		}
1983 		vim_free(swapname);
1984 	    }
1985 	}
1986 
1987 	/*
1988 	 * remove swapfile name of the current buffer, it must be ignored
1989 	 */
1990 	if (curbuf->b_ml.ml_mfp != NULL
1991 			       && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1992 	{
1993 	    for (i = 0; i < num_files; ++i)
1994 		// Do not expand wildcards, on windows would try to expand
1995 		// "%tmp%" in "%tmp%file".
1996 		if (fullpathcmp(p, files[i], TRUE, FALSE) & FPC_SAME)
1997 		{
1998 		    // Remove the name from files[i].  Move further entries
1999 		    // down.  When the array becomes empty free it here, since
2000 		    // FreeWild() won't be called below.
2001 		    vim_free(files[i]);
2002 		    if (--num_files == 0)
2003 			vim_free(files);
2004 		    else
2005 			for ( ; i < num_files; ++i)
2006 			    files[i] = files[i + 1];
2007 		}
2008 	}
2009 	if (nr > 0)
2010 	{
2011 	    file_count += num_files;
2012 	    if (nr <= file_count)
2013 	    {
2014 		*fname_out = vim_strsave(
2015 				      files[nr - 1 + num_files - file_count]);
2016 		dirp = (char_u *)"";		    // stop searching
2017 	    }
2018 	}
2019 	else if (list)
2020 	{
2021 	    if (dir_name[0] == '.' && dir_name[1] == NUL)
2022 	    {
2023 		if (fname == NULL)
2024 		    msg_puts(_("   In current directory:\n"));
2025 		else
2026 		    msg_puts(_("   Using specified name:\n"));
2027 	    }
2028 	    else
2029 	    {
2030 		msg_puts(_("   In directory "));
2031 		msg_home_replace(dir_name);
2032 		msg_puts(":\n");
2033 	    }
2034 
2035 	    if (num_files)
2036 	    {
2037 		for (i = 0; i < num_files; ++i)
2038 		{
2039 		    // print the swap file name
2040 		    msg_outnum((long)++file_count);
2041 		    msg_puts(".    ");
2042 		    msg_puts((char *)gettail(files[i]));
2043 		    msg_putchar('\n');
2044 		    (void)swapfile_info(files[i]);
2045 		}
2046 	    }
2047 	    else
2048 		msg_puts(_("      -- none --\n"));
2049 	    out_flush();
2050 	}
2051 	else
2052 	    file_count += num_files;
2053 
2054 	for (i = 0; i < num_names; ++i)
2055 	    vim_free(names[i]);
2056 	if (num_files > 0)
2057 	    FreeWild(num_files, files);
2058     }
2059     vim_free(dir_name);
2060     return file_count;
2061 }
2062 
2063 #if defined(UNIX) || defined(MSWIN) || defined(PROTO)
2064 /*
2065  * Need _very_ long file names.
2066  * Append the full path to name with path separators made into percent
2067  * signs, to "dir". An unnamed buffer is handled as "" (<currentdir>/"")
2068  * The last character in "dir" must be an extra slash or backslash, it is
2069  * removed.
2070  */
2071     char_u *
make_percent_swname(char_u * dir,char_u * name)2072 make_percent_swname(char_u *dir, char_u *name)
2073 {
2074     char_u *d = NULL, *s, *f;
2075 
2076     f = fix_fname(name != NULL ? name : (char_u *)"");
2077     if (f != NULL)
2078     {
2079 	s = alloc(STRLEN(f) + 1);
2080 	if (s != NULL)
2081 	{
2082 	    STRCPY(s, f);
2083 	    for (d = s; *d != NUL; MB_PTR_ADV(d))
2084 		if (vim_ispathsep(*d))
2085 		    *d = '%';
2086 
2087 	    dir[STRLEN(dir) - 1] = NUL;  // remove one trailing slash
2088 	    d = concat_fnames(dir, s, TRUE);
2089 	    vim_free(s);
2090 	}
2091 	vim_free(f);
2092     }
2093     return d;
2094 }
2095 #endif
2096 
2097 #if (defined(UNIX) || defined(VMS) || defined(MSWIN)) \
2098 	&& (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
2099 # define HAVE_PROCESS_STILL_RUNNING
2100 static int process_still_running;
2101 #endif
2102 
2103 #if defined(FEAT_EVAL) || defined(PROTO)
2104 /*
2105  * Return information found in swapfile "fname" in dictionary "d".
2106  * This is used by the swapinfo() function.
2107  */
2108     void
get_b0_dict(char_u * fname,dict_T * d)2109 get_b0_dict(char_u *fname, dict_T *d)
2110 {
2111     int fd;
2112     struct block0 b0;
2113 
2114     if ((fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
2115     {
2116 	if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
2117 	{
2118 	    if (ml_check_b0_id(&b0) == FAIL)
2119 		dict_add_string(d, "error", (char_u *)"Not a swap file");
2120 	    else if (b0_magic_wrong(&b0))
2121 		dict_add_string(d, "error", (char_u *)"Magic number mismatch");
2122 	    else
2123 	    {
2124 		// we have swap information
2125 		dict_add_string_len(d, "version", b0.b0_version, 10);
2126 		dict_add_string_len(d, "user", b0.b0_uname, B0_UNAME_SIZE);
2127 		dict_add_string_len(d, "host", b0.b0_hname, B0_HNAME_SIZE);
2128 		dict_add_string_len(d, "fname", b0.b0_fname, B0_FNAME_SIZE_ORG);
2129 
2130 		dict_add_number(d, "pid", char_to_long(b0.b0_pid));
2131 		dict_add_number(d, "mtime", char_to_long(b0.b0_mtime));
2132 		dict_add_number(d, "dirty", b0.b0_dirty ? 1 : 0);
2133 # ifdef CHECK_INODE
2134 		dict_add_number(d, "inode", char_to_long(b0.b0_ino));
2135 # endif
2136 	    }
2137 	}
2138 	else
2139 	    dict_add_string(d, "error", (char_u *)"Cannot read file");
2140 	close(fd);
2141     }
2142     else
2143 	dict_add_string(d, "error", (char_u *)"Cannot open file");
2144 }
2145 #endif
2146 
2147 /*
2148  * Give information about an existing swap file.
2149  * Returns timestamp (0 when unknown).
2150  */
2151     static time_t
swapfile_info(char_u * fname)2152 swapfile_info(char_u *fname)
2153 {
2154     stat_T	    st;
2155     int		    fd;
2156     struct block0   b0;
2157 #ifdef UNIX
2158     char_u	    uname[B0_UNAME_SIZE];
2159 #endif
2160 
2161     // print the swap file date
2162     if (mch_stat((char *)fname, &st) != -1)
2163     {
2164 #ifdef UNIX
2165 	// print name of owner of the file
2166 	if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2167 	{
2168 	    msg_puts(_("          owned by: "));
2169 	    msg_outtrans(uname);
2170 	    msg_puts(_("   dated: "));
2171 	}
2172 	else
2173 #endif
2174 	    msg_puts(_("             dated: "));
2175 	msg_puts(get_ctime(st.st_mtime, TRUE));
2176     }
2177     else
2178 	st.st_mtime = 0;
2179 
2180     /*
2181      * print the original file name
2182      */
2183     fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2184     if (fd >= 0)
2185     {
2186 	if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
2187 	{
2188 	    if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2189 	    {
2190 		msg_puts(_("         [from Vim version 3.0]"));
2191 	    }
2192 	    else if (ml_check_b0_id(&b0) == FAIL)
2193 	    {
2194 		msg_puts(_("         [does not look like a Vim swap file]"));
2195 	    }
2196 	    else
2197 	    {
2198 		msg_puts(_("         file name: "));
2199 		if (b0.b0_fname[0] == NUL)
2200 		    msg_puts(_("[No Name]"));
2201 		else
2202 		    msg_outtrans(b0.b0_fname);
2203 
2204 		msg_puts(_("\n          modified: "));
2205 		msg_puts(b0.b0_dirty ? _("YES") : _("no"));
2206 
2207 		if (*(b0.b0_uname) != NUL)
2208 		{
2209 		    msg_puts(_("\n         user name: "));
2210 		    msg_outtrans(b0.b0_uname);
2211 		}
2212 
2213 		if (*(b0.b0_hname) != NUL)
2214 		{
2215 		    if (*(b0.b0_uname) != NUL)
2216 			msg_puts(_("   host name: "));
2217 		    else
2218 			msg_puts(_("\n         host name: "));
2219 		    msg_outtrans(b0.b0_hname);
2220 		}
2221 
2222 		if (char_to_long(b0.b0_pid) != 0L)
2223 		{
2224 		    msg_puts(_("\n        process ID: "));
2225 		    msg_outnum(char_to_long(b0.b0_pid));
2226 #if defined(UNIX) || defined(MSWIN)
2227 		    if (swapfile_process_running(&b0, fname))
2228 		    {
2229 			msg_puts(_(" (STILL RUNNING)"));
2230 # ifdef HAVE_PROCESS_STILL_RUNNING
2231 			process_still_running = TRUE;
2232 # endif
2233 		    }
2234 #endif
2235 		}
2236 
2237 		if (b0_magic_wrong(&b0))
2238 		{
2239 #if defined(MSWIN)
2240 		    if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2241 			msg_puts(_("\n         [not usable with this version of Vim]"));
2242 		    else
2243 #endif
2244 			msg_puts(_("\n         [not usable on this computer]"));
2245 		}
2246 	    }
2247 	}
2248 	else
2249 	    msg_puts(_("         [cannot be read]"));
2250 	close(fd);
2251     }
2252     else
2253 	msg_puts(_("         [cannot be opened]"));
2254     msg_putchar('\n');
2255 
2256     return st.st_mtime;
2257 }
2258 
2259 /*
2260  * Return TRUE if the swap file looks OK and there are no changes, thus it can
2261  * be safely deleted.
2262  */
2263     static time_t
swapfile_unchanged(char_u * fname)2264 swapfile_unchanged(char_u *fname)
2265 {
2266     stat_T	    st;
2267     int		    fd;
2268     struct block0   b0;
2269     int		    ret = TRUE;
2270 
2271     // must be able to stat the swap file
2272     if (mch_stat((char *)fname, &st) == -1)
2273 	return FALSE;
2274 
2275     // must be able to read the first block
2276     fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2277     if (fd < 0)
2278 	return FALSE;
2279     if (read_eintr(fd, &b0, sizeof(b0)) != sizeof(b0))
2280     {
2281 	close(fd);
2282 	return FALSE;
2283     }
2284 
2285     // the ID and magic number must be correct
2286     if (ml_check_b0_id(&b0) == FAIL|| b0_magic_wrong(&b0))
2287 	ret = FALSE;
2288 
2289     // must be unchanged
2290     if (b0.b0_dirty)
2291 	ret = FALSE;
2292 
2293 #if defined(UNIX) || defined(MSWIN)
2294     // Host name must be known and must equal the current host name, otherwise
2295     // comparing pid is meaningless.
2296     if (*(b0.b0_hname) == NUL)
2297     {
2298 	ret = FALSE;
2299     }
2300     else
2301     {
2302 	char_u	    hostname[B0_HNAME_SIZE];
2303 
2304 	mch_get_host_name(hostname, B0_HNAME_SIZE);
2305 	hostname[B0_HNAME_SIZE - 1] = NUL;
2306 	b0.b0_hname[B0_HNAME_SIZE - 1] = NUL; // in case of corruption
2307 	if (STRICMP(b0.b0_hname, hostname) != 0)
2308 	    ret = FALSE;
2309     }
2310 
2311     // process must be known and not be running
2312     if (char_to_long(b0.b0_pid) == 0L || swapfile_process_running(&b0, fname))
2313 	ret = FALSE;
2314 #endif
2315 
2316     // We do not check the user, it should be irrelevant for whether the swap
2317     // file is still useful.
2318 
2319     close(fd);
2320     return ret;
2321 }
2322 
2323     static int
recov_file_names(char_u ** names,char_u * path,int prepend_dot)2324 recov_file_names(char_u **names, char_u *path, int prepend_dot)
2325 {
2326     int		num_names;
2327 
2328     /*
2329      * (Win32 and Win64) never short names, but do prepend a dot.
2330      * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2331      * Only use the short name if it is different.
2332      */
2333     char_u	*p;
2334     int		i;
2335 # ifndef MSWIN
2336     int	    shortname = curbuf->b_shortname;
2337 
2338     curbuf->b_shortname = FALSE;
2339 # endif
2340 
2341     num_names = 0;
2342 
2343     /*
2344      * May also add the file name with a dot prepended, for swap file in same
2345      * dir as original file.
2346      */
2347     if (prepend_dot)
2348     {
2349 	names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2350 	if (names[num_names] == NULL)
2351 	    goto end;
2352 	++num_names;
2353     }
2354 
2355     /*
2356      * Form the normal swap file name pattern by appending ".sw?".
2357      */
2358 #ifdef VMS
2359     names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2360 #else
2361     names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
2362 #endif
2363     if (names[num_names] == NULL)
2364 	goto end;
2365     if (num_names >= 1)	    // check if we have the same name twice
2366     {
2367 	p = names[num_names - 1];
2368 	i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2369 	if (i > 0)
2370 	    p += i;	    // file name has been expanded to full path
2371 
2372 	if (STRCMP(p, names[num_names]) != 0)
2373 	    ++num_names;
2374 	else
2375 	    vim_free(names[num_names]);
2376     }
2377     else
2378 	++num_names;
2379 
2380 # ifndef MSWIN
2381     /*
2382      * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2383      */
2384     curbuf->b_shortname = TRUE;
2385 #ifdef VMS
2386     names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2387 #else
2388     names[num_names] = modname(path, (char_u *)".sw?", FALSE);
2389 #endif
2390     if (names[num_names] == NULL)
2391 	goto end;
2392 
2393     /*
2394      * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2395      */
2396     p = names[num_names];
2397     i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2398     if (i > 0)
2399 	p += i;		// file name has been expanded to full path
2400     if (STRCMP(names[num_names - 1], p) == 0)
2401 	vim_free(names[num_names]);
2402     else
2403 	++num_names;
2404 # endif
2405 
2406 end:
2407 # ifndef MSWIN
2408     curbuf->b_shortname = shortname;
2409 # endif
2410 
2411     return num_names;
2412 }
2413 
2414 /*
2415  * sync all memlines
2416  *
2417  * If 'check_file' is TRUE, check if original file exists and was not changed.
2418  * If 'check_char' is TRUE, stop syncing when character becomes available, but
2419  * always sync at least one block.
2420  */
2421     void
ml_sync_all(int check_file,int check_char)2422 ml_sync_all(int check_file, int check_char)
2423 {
2424     buf_T		*buf;
2425     stat_T		st;
2426 
2427     FOR_ALL_BUFFERS(buf)
2428     {
2429 	if (buf->b_ml.ml_mfp == NULL
2430 		|| buf->b_ml.ml_mfp->mf_fname == NULL
2431 		|| buf->b_ml.ml_mfp->mf_fd < 0)
2432 	    continue;			    // no file
2433 
2434 	ml_flush_line(buf);		    // flush buffered line
2435 					    // flush locked block
2436 	(void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2437 	if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2438 						     && buf->b_ffname != NULL)
2439 	{
2440 	    /*
2441 	     * If the original file does not exist anymore or has been changed
2442 	     * call ml_preserve() to get rid of all negative numbered blocks.
2443 	     */
2444 	    if (mch_stat((char *)buf->b_ffname, &st) == -1
2445 		    || st.st_mtime != buf->b_mtime_read
2446 #ifdef ST_MTIM_NSEC
2447 		    || st.ST_MTIM_NSEC != buf->b_mtime_read_ns
2448 #endif
2449 		    || st.st_size != buf->b_orig_size)
2450 	    {
2451 		ml_preserve(buf, FALSE);
2452 		did_check_timestamps = FALSE;
2453 		need_check_timestamps = TRUE;	// give message later
2454 	    }
2455 	}
2456 	if (buf->b_ml.ml_mfp->mf_dirty)
2457 	{
2458 	    (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2459 					| (bufIsChanged(buf) ? MFS_FLUSH : 0));
2460 	    if (check_char && ui_char_avail())	// character available now
2461 		break;
2462 	}
2463     }
2464 }
2465 
2466 /*
2467  * sync one buffer, including negative blocks
2468  *
2469  * after this all the blocks are in the swap file
2470  *
2471  * Used for the :preserve command and when the original file has been
2472  * changed or deleted.
2473  *
2474  * when message is TRUE the success of preserving is reported
2475  */
2476     void
ml_preserve(buf_T * buf,int message)2477 ml_preserve(buf_T *buf, int message)
2478 {
2479     bhdr_T	*hp;
2480     linenr_T	lnum;
2481     memfile_T	*mfp = buf->b_ml.ml_mfp;
2482     int		status;
2483     int		got_int_save = got_int;
2484 
2485     if (mfp == NULL || mfp->mf_fname == NULL)
2486     {
2487 	if (message)
2488 	    emsg(_("E313: Cannot preserve, there is no swap file"));
2489 	return;
2490     }
2491 
2492     // We only want to stop when interrupted here, not when interrupted
2493     // before.
2494     got_int = FALSE;
2495 
2496     ml_flush_line(buf);				    // flush buffered line
2497     (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); // flush locked block
2498     status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2499 
2500     // stack is invalid after mf_sync(.., MFS_ALL)
2501     buf->b_ml.ml_stack_top = 0;
2502 
2503     /*
2504      * Some of the data blocks may have been changed from negative to
2505      * positive block number. In that case the pointer blocks need to be
2506      * updated.
2507      *
2508      * We don't know in which pointer block the references are, so we visit
2509      * all data blocks until there are no more translations to be done (or
2510      * we hit the end of the file, which can only happen in case a write fails,
2511      * e.g. when file system if full).
2512      * ml_find_line() does the work by translating the negative block numbers
2513      * when getting the first line of each data block.
2514      */
2515     if (mf_need_trans(mfp) && !got_int)
2516     {
2517 	lnum = 1;
2518 	while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2519 	{
2520 	    hp = ml_find_line(buf, lnum, ML_FIND);
2521 	    if (hp == NULL)
2522 	    {
2523 		status = FAIL;
2524 		goto theend;
2525 	    }
2526 	    CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2527 	    lnum = buf->b_ml.ml_locked_high + 1;
2528 	}
2529 	(void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);	// flush locked block
2530 	// sync the updated pointer blocks
2531 	if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2532 	    status = FAIL;
2533 	buf->b_ml.ml_stack_top = 0;	    // stack is invalid now
2534     }
2535 theend:
2536     got_int |= got_int_save;
2537 
2538     if (message)
2539     {
2540 	if (status == OK)
2541 	    msg(_("File preserved"));
2542 	else
2543 	    emsg(_("E314: Preserve failed"));
2544     }
2545 }
2546 
2547 /*
2548  * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2549  * until the next call!
2550  *  line1 = ml_get(1);
2551  *  line2 = ml_get(2);	// line1 is now invalid!
2552  * Make a copy of the line if necessary.
2553  */
2554 /*
2555  * Return a pointer to a (read-only copy of a) line.
2556  *
2557  * On failure an error message is given and IObuff is returned (to avoid
2558  * having to check for error everywhere).
2559  */
2560     char_u  *
ml_get(linenr_T lnum)2561 ml_get(linenr_T lnum)
2562 {
2563     return ml_get_buf(curbuf, lnum, FALSE);
2564 }
2565 
2566 /*
2567  * Return pointer to position "pos".
2568  */
2569     char_u *
ml_get_pos(pos_T * pos)2570 ml_get_pos(pos_T *pos)
2571 {
2572     return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2573 }
2574 
2575 /*
2576  * Return pointer to cursor line.
2577  */
2578     char_u *
ml_get_curline(void)2579 ml_get_curline(void)
2580 {
2581     return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2582 }
2583 
2584 /*
2585  * Return pointer to cursor position.
2586  */
2587     char_u *
ml_get_cursor(void)2588 ml_get_cursor(void)
2589 {
2590     return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2591 							curwin->w_cursor.col);
2592 }
2593 
2594 /*
2595  * Return a pointer to a line in a specific buffer
2596  *
2597  * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2598  * changed)
2599  */
2600     char_u  *
ml_get_buf(buf_T * buf,linenr_T lnum,int will_change)2601 ml_get_buf(
2602     buf_T	*buf,
2603     linenr_T	lnum,
2604     int		will_change)		// line will be changed
2605 {
2606     bhdr_T	*hp;
2607     DATA_BL	*dp;
2608     static int	recursive = 0;
2609 
2610     if (lnum > buf->b_ml.ml_line_count)	// invalid line number
2611     {
2612 	if (recursive == 0)
2613 	{
2614 	    // Avoid giving this message for a recursive call, may happen when
2615 	    // the GUI redraws part of the text.
2616 	    ++recursive;
2617 	    siemsg(_("E315: ml_get: invalid lnum: %ld"), lnum);
2618 	    --recursive;
2619 	}
2620 errorret:
2621 	STRCPY(IObuff, "???");
2622 	buf->b_ml.ml_line_len = 4;
2623 	return IObuff;
2624     }
2625     if (lnum <= 0)			// pretend line 0 is line 1
2626 	lnum = 1;
2627 
2628     if (buf->b_ml.ml_mfp == NULL)	// there are no lines
2629     {
2630 	buf->b_ml.ml_line_len = 1;
2631 	return (char_u *)"";
2632     }
2633 
2634     /*
2635      * See if it is the same line as requested last time.
2636      * Otherwise may need to flush last used line.
2637      * Don't use the last used line when 'swapfile' is reset, need to load all
2638      * blocks.
2639      */
2640     if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
2641     {
2642 	unsigned    start, end;
2643 	colnr_T	    len;
2644 	int	    idx;
2645 
2646 	ml_flush_line(buf);
2647 
2648 	/*
2649 	 * Find the data block containing the line.
2650 	 * This also fills the stack with the blocks from the root to the data
2651 	 * block and releases any locked block.
2652 	 */
2653 	if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2654 	{
2655 	    if (recursive == 0)
2656 	    {
2657 		// Avoid giving this message for a recursive call, may happen
2658 		// when the GUI redraws part of the text.
2659 		++recursive;
2660 		get_trans_bufname(buf);
2661 		shorten_dir(NameBuff);
2662 		siemsg(_("E316: ml_get: cannot find line %ld in buffer %d %s"),
2663 						  lnum, buf->b_fnum, NameBuff);
2664 		--recursive;
2665 	    }
2666 	    goto errorret;
2667 	}
2668 
2669 	dp = (DATA_BL *)(hp->bh_data);
2670 
2671 	idx = lnum - buf->b_ml.ml_locked_low;
2672 	start = ((dp->db_index[idx]) & DB_INDEX_MASK);
2673 	// The text ends where the previous line starts.  The first line ends
2674 	// at the end of the block.
2675 	if (idx == 0)
2676 	    end = dp->db_txt_end;
2677 	else
2678 	    end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
2679 	len = end - start;
2680 
2681 	buf->b_ml.ml_line_ptr = (char_u *)dp + start;
2682 	buf->b_ml.ml_line_len = len;
2683 	buf->b_ml.ml_line_lnum = lnum;
2684 	buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2685     }
2686     if (will_change)
2687 	buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2688 
2689     return buf->b_ml.ml_line_ptr;
2690 }
2691 
2692 /*
2693  * Check if a line that was just obtained by a call to ml_get
2694  * is in allocated memory.
2695  */
2696     int
ml_line_alloced(void)2697 ml_line_alloced(void)
2698 {
2699     return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2700 }
2701 
2702 #ifdef FEAT_PROP_POPUP
2703 /*
2704  * Add text properties that continue from the previous line.
2705  */
2706     static void
add_text_props_for_append(buf_T * buf,linenr_T lnum,char_u ** line,int * len,char_u ** tofree)2707 add_text_props_for_append(
2708 	    buf_T	*buf,
2709 	    linenr_T	lnum,
2710 	    char_u	**line,
2711 	    int		*len,
2712 	    char_u	**tofree)
2713 {
2714     int		round;
2715     int		new_prop_count = 0;
2716     int		count;
2717     int		n;
2718     char_u	*props;
2719     int		new_len = 0;  // init for gcc
2720     char_u	*new_line = NULL;
2721     textprop_T	prop;
2722 
2723     // Make two rounds:
2724     // 1. calculate the extra space needed
2725     // 2. allocate the space and fill it
2726     for (round = 1; round <= 2; ++round)
2727     {
2728 	if (round == 2)
2729 	{
2730 	    if (new_prop_count == 0)
2731 		return;  // nothing to do
2732 	    new_len = *len + new_prop_count * sizeof(textprop_T);
2733 	    new_line = alloc(new_len);
2734 	    if (new_line == NULL)
2735 		return;
2736 	    mch_memmove(new_line, *line, *len);
2737 	    new_prop_count = 0;
2738 	}
2739 
2740 	// Get the line above to find any props that continue in the next
2741 	// line.
2742 	count = get_text_props(buf, lnum, &props, FALSE);
2743 	for (n = 0; n < count; ++n)
2744 	{
2745 	    mch_memmove(&prop, props + n * sizeof(textprop_T),
2746 							   sizeof(textprop_T));
2747 	    if (prop.tp_flags & TP_FLAG_CONT_NEXT)
2748 	    {
2749 		if (round == 2)
2750 		{
2751 		    prop.tp_flags |= TP_FLAG_CONT_PREV;
2752 		    prop.tp_col = 1;
2753 		    prop.tp_len = *len;  // not exactly the right length
2754 		    mch_memmove(new_line + *len + new_prop_count
2755 			      * sizeof(textprop_T), &prop, sizeof(textprop_T));
2756 		}
2757 		++new_prop_count;
2758 	    }
2759 	}
2760     }
2761     *line = new_line;
2762     *tofree = new_line;
2763     *len = new_len;
2764 }
2765 #endif
2766 
2767     static int
ml_append_int(buf_T * buf,linenr_T lnum,char_u * line_arg,colnr_T len_arg,int flags)2768 ml_append_int(
2769     buf_T	*buf,
2770     linenr_T	lnum,		// append after this line (can be 0)
2771     char_u	*line_arg,	// text of the new line
2772     colnr_T	len_arg,	// length of line, including NUL, or 0
2773     int		flags)		// ML_APPEND_ flags
2774 {
2775     char_u	*line = line_arg;
2776     colnr_T	len = len_arg;
2777     int		i;
2778     int		line_count;	// number of indexes in current block
2779     int		offset;
2780     int		from, to;
2781     int		space_needed;	// space needed for new line
2782     int		page_size;
2783     int		page_count;
2784     int		db_idx;		// index for lnum in data block
2785     bhdr_T	*hp;
2786     memfile_T	*mfp;
2787     DATA_BL	*dp;
2788     PTR_BL	*pp;
2789     infoptr_T	*ip;
2790 #ifdef FEAT_PROP_POPUP
2791     char_u	*tofree = NULL;
2792 #endif
2793     int		ret = FAIL;
2794 
2795     if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2796 	return FAIL;  // lnum out of range
2797 
2798     if (lowest_marked && lowest_marked > lnum)
2799 	lowest_marked = lnum + 1;
2800 
2801     if (len == 0)
2802 	len = (colnr_T)STRLEN(line) + 1;	// space needed for the text
2803 
2804 #ifdef FEAT_PROP_POPUP
2805     if (curbuf->b_has_textprop && lnum > 0
2806 			     && !(flags & (ML_APPEND_UNDO | ML_APPEND_NOPROP)))
2807 	// Add text properties that continue from the previous line.
2808 	add_text_props_for_append(buf, lnum, &line, &len, &tofree);
2809 #endif
2810 
2811     space_needed = len + INDEX_SIZE;	// space needed for text + index
2812 
2813     mfp = buf->b_ml.ml_mfp;
2814     page_size = mfp->mf_page_size;
2815 
2816 /*
2817  * find the data block containing the previous line
2818  * This also fills the stack with the blocks from the root to the data block
2819  * This also releases any locked block.
2820  */
2821     if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2822 							  ML_INSERT)) == NULL)
2823 	goto theend;
2824 
2825     buf->b_ml.ml_flags &= ~ML_EMPTY;
2826 
2827     if (lnum == 0)		// got line one instead, correct db_idx
2828 	db_idx = -1;		// careful, it is negative!
2829     else
2830 	db_idx = lnum - buf->b_ml.ml_locked_low;
2831 		// get line count before the insertion
2832     line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2833 
2834     dp = (DATA_BL *)(hp->bh_data);
2835 
2836 /*
2837  * If
2838  * - there is not enough room in the current block
2839  * - appending to the last line in the block
2840  * - not appending to the last line in the file
2841  * insert in front of the next block.
2842  */
2843     if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2844 					    && lnum < buf->b_ml.ml_line_count)
2845     {
2846 	/*
2847 	 * Now that the line is not going to be inserted in the block that we
2848 	 * expected, the line count has to be adjusted in the pointer blocks
2849 	 * by using ml_locked_lineadd.
2850 	 */
2851 	--(buf->b_ml.ml_locked_lineadd);
2852 	--(buf->b_ml.ml_locked_high);
2853 	if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2854 	    goto theend;
2855 
2856 	db_idx = -1;		    // careful, it is negative!
2857 		    // get line count before the insertion
2858 	line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2859 	CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2860 
2861 	dp = (DATA_BL *)(hp->bh_data);
2862     }
2863 
2864     ++buf->b_ml.ml_line_count;
2865 
2866     if ((int)dp->db_free >= space_needed)	// enough room in data block
2867     {
2868 	/*
2869 	 * Insert the new line in an existing data block, or in the data block
2870 	 * allocated above.
2871 	 */
2872 	dp->db_txt_start -= len;
2873 	dp->db_free -= space_needed;
2874 	++(dp->db_line_count);
2875 
2876 	/*
2877 	 * move the text of the lines that follow to the front
2878 	 * adjust the indexes of the lines that follow
2879 	 */
2880 	if (line_count > db_idx + 1)	    // if there are following lines
2881 	{
2882 	    /*
2883 	     * Offset is the start of the previous line.
2884 	     * This will become the character just after the new line.
2885 	     */
2886 	    if (db_idx < 0)
2887 		offset = dp->db_txt_end;
2888 	    else
2889 		offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2890 	    mch_memmove((char *)dp + dp->db_txt_start,
2891 					  (char *)dp + dp->db_txt_start + len,
2892 				 (size_t)(offset - (dp->db_txt_start + len)));
2893 	    for (i = line_count - 1; i > db_idx; --i)
2894 		dp->db_index[i + 1] = dp->db_index[i] - len;
2895 	    dp->db_index[db_idx + 1] = offset - len;
2896 	}
2897 	else
2898 	    // add line at the end (which is the start of the text)
2899 	    dp->db_index[db_idx + 1] = dp->db_txt_start;
2900 
2901 	/*
2902 	 * copy the text into the block
2903 	 */
2904 	mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2905 	if (flags & ML_APPEND_MARK)
2906 	    dp->db_index[db_idx + 1] |= DB_MARKED;
2907 
2908 	/*
2909 	 * Mark the block dirty.
2910 	 */
2911 	buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2912 	if (!(flags & ML_APPEND_NEW))
2913 	    buf->b_ml.ml_flags |= ML_LOCKED_POS;
2914     }
2915     else	    // not enough space in data block
2916     {
2917 	long	    line_count_left, line_count_right;
2918 	int	    page_count_left, page_count_right;
2919 	bhdr_T	    *hp_left;
2920 	bhdr_T	    *hp_right;
2921 	bhdr_T	    *hp_new;
2922 	int	    lines_moved;
2923 	int	    data_moved = 0;	    // init to shut up gcc
2924 	int	    total_moved = 0;	    // init to shut up gcc
2925 	DATA_BL	    *dp_right, *dp_left;
2926 	int	    stack_idx;
2927 	int	    in_left;
2928 	int	    lineadd;
2929 	blocknr_T   bnum_left, bnum_right;
2930 	linenr_T    lnum_left, lnum_right;
2931 	int	    pb_idx;
2932 	PTR_BL	    *pp_new;
2933 
2934 	/*
2935 	 * There is not enough room, we have to create a new data block and
2936 	 * copy some lines into it.
2937 	 * Then we have to insert an entry in the pointer block.
2938 	 * If this pointer block also is full, we go up another block, and so
2939 	 * on, up to the root if necessary.
2940 	 * The line counts in the pointer blocks have already been adjusted by
2941 	 * ml_find_line().
2942 	 *
2943 	 * We are going to allocate a new data block. Depending on the
2944 	 * situation it will be put to the left or right of the existing
2945 	 * block.  If possible we put the new line in the left block and move
2946 	 * the lines after it to the right block. Otherwise the new line is
2947 	 * also put in the right block. This method is more efficient when
2948 	 * inserting a lot of lines at one place.
2949 	 */
2950 	if (db_idx < 0)		// left block is new, right block is existing
2951 	{
2952 	    lines_moved = 0;
2953 	    in_left = TRUE;
2954 	    // space_needed does not change
2955 	}
2956 	else			// left block is existing, right block is new
2957 	{
2958 	    lines_moved = line_count - db_idx - 1;
2959 	    if (lines_moved == 0)
2960 		in_left = FALSE;	// put new line in right block
2961 					// space_needed does not change
2962 	    else
2963 	    {
2964 		data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2965 							    dp->db_txt_start;
2966 		total_moved = data_moved + lines_moved * INDEX_SIZE;
2967 		if ((int)dp->db_free + total_moved >= space_needed)
2968 		{
2969 		    in_left = TRUE;	// put new line in left block
2970 		    space_needed = total_moved;
2971 		}
2972 		else
2973 		{
2974 		    in_left = FALSE;	    // put new line in right block
2975 		    space_needed += total_moved;
2976 		}
2977 	    }
2978 	}
2979 
2980 	page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2981 	if ((hp_new = ml_new_data(mfp, flags & ML_APPEND_NEW, page_count))
2982 								       == NULL)
2983 	{
2984 			// correct line counts in pointer blocks
2985 	    --(buf->b_ml.ml_locked_lineadd);
2986 	    --(buf->b_ml.ml_locked_high);
2987 	    goto theend;
2988 	}
2989 	if (db_idx < 0)		// left block is new
2990 	{
2991 	    hp_left = hp_new;
2992 	    hp_right = hp;
2993 	    line_count_left = 0;
2994 	    line_count_right = line_count;
2995 	}
2996 	else			// right block is new
2997 	{
2998 	    hp_left = hp;
2999 	    hp_right = hp_new;
3000 	    line_count_left = line_count;
3001 	    line_count_right = 0;
3002 	}
3003 	dp_right = (DATA_BL *)(hp_right->bh_data);
3004 	dp_left = (DATA_BL *)(hp_left->bh_data);
3005 	bnum_left = hp_left->bh_bnum;
3006 	bnum_right = hp_right->bh_bnum;
3007 	page_count_left = hp_left->bh_page_count;
3008 	page_count_right = hp_right->bh_page_count;
3009 
3010 	/*
3011 	 * May move the new line into the right/new block.
3012 	 */
3013 	if (!in_left)
3014 	{
3015 	    dp_right->db_txt_start -= len;
3016 	    dp_right->db_free -= len + INDEX_SIZE;
3017 	    dp_right->db_index[0] = dp_right->db_txt_start;
3018 	    if (flags & ML_APPEND_MARK)
3019 		dp_right->db_index[0] |= DB_MARKED;
3020 
3021 	    mch_memmove((char *)dp_right + dp_right->db_txt_start,
3022 							   line, (size_t)len);
3023 	    ++line_count_right;
3024 	}
3025 	/*
3026 	 * may move lines from the left/old block to the right/new one.
3027 	 */
3028 	if (lines_moved)
3029 	{
3030 	    /*
3031 	     */
3032 	    dp_right->db_txt_start -= data_moved;
3033 	    dp_right->db_free -= total_moved;
3034 	    mch_memmove((char *)dp_right + dp_right->db_txt_start,
3035 			(char *)dp_left + dp_left->db_txt_start,
3036 			(size_t)data_moved);
3037 	    offset = dp_right->db_txt_start - dp_left->db_txt_start;
3038 	    dp_left->db_txt_start += data_moved;
3039 	    dp_left->db_free += total_moved;
3040 
3041 	    /*
3042 	     * update indexes in the new block
3043 	     */
3044 	    for (to = line_count_right, from = db_idx + 1;
3045 					 from < line_count_left; ++from, ++to)
3046 		dp_right->db_index[to] = dp->db_index[from] + offset;
3047 	    line_count_right += lines_moved;
3048 	    line_count_left -= lines_moved;
3049 	}
3050 
3051 	/*
3052 	 * May move the new line into the left (old or new) block.
3053 	 */
3054 	if (in_left)
3055 	{
3056 	    dp_left->db_txt_start -= len;
3057 	    dp_left->db_free -= len + INDEX_SIZE;
3058 	    dp_left->db_index[line_count_left] = dp_left->db_txt_start;
3059 	    if (flags & ML_APPEND_MARK)
3060 		dp_left->db_index[line_count_left] |= DB_MARKED;
3061 	    mch_memmove((char *)dp_left + dp_left->db_txt_start,
3062 							   line, (size_t)len);
3063 	    ++line_count_left;
3064 	}
3065 
3066 	if (db_idx < 0)		// left block is new
3067 	{
3068 	    lnum_left = lnum + 1;
3069 	    lnum_right = 0;
3070 	}
3071 	else			// right block is new
3072 	{
3073 	    lnum_left = 0;
3074 	    if (in_left)
3075 		lnum_right = lnum + 2;
3076 	    else
3077 		lnum_right = lnum + 1;
3078 	}
3079 	dp_left->db_line_count = line_count_left;
3080 	dp_right->db_line_count = line_count_right;
3081 
3082 	/*
3083 	 * release the two data blocks
3084 	 * The new one (hp_new) already has a correct blocknumber.
3085 	 * The old one (hp, in ml_locked) gets a positive blocknumber if
3086 	 * we changed it and we are not editing a new file.
3087 	 */
3088 	if (lines_moved || in_left)
3089 	    buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3090 	if (!(flags & ML_APPEND_NEW) && db_idx >= 0 && in_left)
3091 	    buf->b_ml.ml_flags |= ML_LOCKED_POS;
3092 	mf_put(mfp, hp_new, TRUE, FALSE);
3093 
3094 	/*
3095 	 * flush the old data block
3096 	 * set ml_locked_lineadd to 0, because the updating of the
3097 	 * pointer blocks is done below
3098 	 */
3099 	lineadd = buf->b_ml.ml_locked_lineadd;
3100 	buf->b_ml.ml_locked_lineadd = 0;
3101 	ml_find_line(buf, (linenr_T)0, ML_FLUSH);   // flush data block
3102 
3103 	/*
3104 	 * update pointer blocks for the new data block
3105 	 */
3106 	for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3107 								  --stack_idx)
3108 	{
3109 	    ip = &(buf->b_ml.ml_stack[stack_idx]);
3110 	    pb_idx = ip->ip_index;
3111 	    if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3112 		goto theend;
3113 	    pp = (PTR_BL *)(hp->bh_data);   // must be pointer block
3114 	    if (pp->pb_id != PTR_ID)
3115 	    {
3116 		iemsg(_("E317: pointer block id wrong 3"));
3117 		mf_put(mfp, hp, FALSE, FALSE);
3118 		goto theend;
3119 	    }
3120 	    /*
3121 	     * TODO: If the pointer block is full and we are adding at the end
3122 	     * try to insert in front of the next block
3123 	     */
3124 	    // block not full, add one entry
3125 	    if (pp->pb_count < pp->pb_count_max)
3126 	    {
3127 		if (pb_idx + 1 < (int)pp->pb_count)
3128 		    mch_memmove(&pp->pb_pointer[pb_idx + 2],
3129 				&pp->pb_pointer[pb_idx + 1],
3130 			(size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
3131 		++pp->pb_count;
3132 		pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3133 		pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3134 		pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3135 		pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
3136 		pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
3137 		pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
3138 
3139 		if (lnum_left != 0)
3140 		    pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3141 		if (lnum_right != 0)
3142 		    pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
3143 
3144 		mf_put(mfp, hp, TRUE, FALSE);
3145 		buf->b_ml.ml_stack_top = stack_idx + 1;	    // truncate stack
3146 
3147 		if (lineadd)
3148 		{
3149 		    --(buf->b_ml.ml_stack_top);
3150 		    // fix line count for rest of blocks in the stack
3151 		    ml_lineadd(buf, lineadd);
3152 							// fix stack itself
3153 		    buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
3154 								      lineadd;
3155 		    ++(buf->b_ml.ml_stack_top);
3156 		}
3157 
3158 		/*
3159 		 * We are finished, break the loop here.
3160 		 */
3161 		break;
3162 	    }
3163 	    else			// pointer block full
3164 	    {
3165 		/*
3166 		 * split the pointer block
3167 		 * allocate a new pointer block
3168 		 * move some of the pointer into the new block
3169 		 * prepare for updating the parent block
3170 		 */
3171 		for (;;)	// do this twice when splitting block 1
3172 		{
3173 		    hp_new = ml_new_ptr(mfp);
3174 		    if (hp_new == NULL)	    // TODO: try to fix tree
3175 			goto theend;
3176 		    pp_new = (PTR_BL *)(hp_new->bh_data);
3177 
3178 		    if (hp->bh_bnum != 1)
3179 			break;
3180 
3181 		    /*
3182 		     * if block 1 becomes full the tree is given an extra level
3183 		     * The pointers from block 1 are moved into the new block.
3184 		     * block 1 is updated to point to the new block
3185 		     * then continue to split the new block
3186 		     */
3187 		    mch_memmove(pp_new, pp, (size_t)page_size);
3188 		    pp->pb_count = 1;
3189 		    pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
3190 		    pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
3191 		    pp->pb_pointer[0].pe_old_lnum = 1;
3192 		    pp->pb_pointer[0].pe_page_count = 1;
3193 		    mf_put(mfp, hp, TRUE, FALSE);   // release block 1
3194 		    hp = hp_new;		// new block is to be split
3195 		    pp = pp_new;
3196 		    CHECK(stack_idx != 0, _("stack_idx should be 0"));
3197 		    ip->ip_index = 0;
3198 		    ++stack_idx;	// do block 1 again later
3199 		}
3200 		/*
3201 		 * move the pointers after the current one to the new block
3202 		 * If there are none, the new entry will be in the new block.
3203 		 */
3204 		total_moved = pp->pb_count - pb_idx - 1;
3205 		if (total_moved)
3206 		{
3207 		    mch_memmove(&pp_new->pb_pointer[0],
3208 				&pp->pb_pointer[pb_idx + 1],
3209 				(size_t)(total_moved) * sizeof(PTR_EN));
3210 		    pp_new->pb_count = total_moved;
3211 		    pp->pb_count -= total_moved - 1;
3212 		    pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
3213 		    pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
3214 		    pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
3215 		    if (lnum_right)
3216 			pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
3217 		}
3218 		else
3219 		{
3220 		    pp_new->pb_count = 1;
3221 		    pp_new->pb_pointer[0].pe_bnum = bnum_right;
3222 		    pp_new->pb_pointer[0].pe_line_count = line_count_right;
3223 		    pp_new->pb_pointer[0].pe_page_count = page_count_right;
3224 		    pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
3225 		}
3226 		pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3227 		pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3228 		pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3229 		if (lnum_left)
3230 		    pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3231 		lnum_left = 0;
3232 		lnum_right = 0;
3233 
3234 		/*
3235 		 * recompute line counts
3236 		 */
3237 		line_count_right = 0;
3238 		for (i = 0; i < (int)pp_new->pb_count; ++i)
3239 		    line_count_right += pp_new->pb_pointer[i].pe_line_count;
3240 		line_count_left = 0;
3241 		for (i = 0; i < (int)pp->pb_count; ++i)
3242 		    line_count_left += pp->pb_pointer[i].pe_line_count;
3243 
3244 		bnum_left = hp->bh_bnum;
3245 		bnum_right = hp_new->bh_bnum;
3246 		page_count_left = 1;
3247 		page_count_right = 1;
3248 		mf_put(mfp, hp, TRUE, FALSE);
3249 		mf_put(mfp, hp_new, TRUE, FALSE);
3250 	    }
3251 	}
3252 
3253 	/*
3254 	 * Safety check: fallen out of for loop?
3255 	 */
3256 	if (stack_idx < 0)
3257 	{
3258 	    iemsg(_("E318: Updated too many blocks?"));
3259 	    buf->b_ml.ml_stack_top = 0;	// invalidate stack
3260 	}
3261     }
3262 
3263 #ifdef FEAT_BYTEOFF
3264 # ifdef FEAT_PROP_POPUP
3265     if (curbuf->b_has_textprop)
3266 	// only use the space needed for the text, ignore properties
3267 	len = (colnr_T)STRLEN(line) + 1;
3268 # endif
3269     // The line was inserted below 'lnum'
3270     ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3271 #endif
3272 
3273 #ifdef FEAT_NETBEANS_INTG
3274     if (netbeans_active())
3275     {
3276 	if (STRLEN(line) > 0)
3277 	    netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
3278 	netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
3279 							   (char_u *)"\n", 1);
3280     }
3281 #endif
3282 #ifdef FEAT_JOB_CHANNEL
3283     if (buf->b_write_to_channel)
3284 	channel_write_new_lines(buf);
3285 #endif
3286     ret = OK;
3287 
3288 theend:
3289 #ifdef FEAT_PROP_POPUP
3290     vim_free(tofree);
3291 #endif
3292     return ret;
3293 }
3294 
3295 /*
3296  * Flush any pending change and call ml_append_int()
3297  */
3298     static int
ml_append_flush(buf_T * buf,linenr_T lnum,char_u * line,colnr_T len,int flags)3299 ml_append_flush(
3300     buf_T	*buf,
3301     linenr_T	lnum,		// append after this line (can be 0)
3302     char_u	*line,		// text of the new line
3303     colnr_T	len,		// length of line, including NUL, or 0
3304     int		flags)		// ML_APPEND_ flags
3305 {
3306     if (lnum > buf->b_ml.ml_line_count)
3307 	return FAIL;  // lnum out of range
3308 
3309     if (buf->b_ml.ml_line_lnum != 0)
3310 	// This may also invoke ml_append_int().
3311 	ml_flush_line(buf);
3312 
3313 #ifdef FEAT_EVAL
3314     // When inserting above recorded changes: flush the changes before changing
3315     // the text.  Then flush the cached line, it may become invalid.
3316     may_invoke_listeners(buf, lnum + 1, lnum + 1, 1);
3317     if (buf->b_ml.ml_line_lnum != 0)
3318 	ml_flush_line(buf);
3319 #endif
3320 
3321     return ml_append_int(buf, lnum, line, len, flags);
3322 }
3323 
3324 /*
3325  * Append a line after lnum (may be 0 to insert a line in front of the file).
3326  * "line" does not need to be allocated, but can't be another line in a
3327  * buffer, unlocking may make it invalid.
3328  *
3329  * "newfile": TRUE when starting to edit a new file, meaning that pe_old_lnum
3330  *		will be set for recovery
3331  * Check: The caller of this function should probably also call
3332  * appended_lines().
3333  *
3334  * return FAIL for failure, OK otherwise
3335  */
3336     int
ml_append(linenr_T lnum,char_u * line,colnr_T len,int newfile)3337 ml_append(
3338     linenr_T	lnum,		// append after this line (can be 0)
3339     char_u	*line,		// text of the new line
3340     colnr_T	len,		// length of new line, including NUL, or 0
3341     int		newfile)	// flag, see above
3342 {
3343     return ml_append_flags(lnum, line, len, newfile ? ML_APPEND_NEW : 0);
3344 }
3345 
3346     int
ml_append_flags(linenr_T lnum,char_u * line,colnr_T len,int flags)3347 ml_append_flags(
3348     linenr_T	lnum,		// append after this line (can be 0)
3349     char_u	*line,		// text of the new line
3350     colnr_T	len,		// length of new line, including NUL, or 0
3351     int		flags)		// ML_APPEND_ values
3352 {
3353     // When starting up, we might still need to create the memfile
3354     if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
3355 	return FAIL;
3356     return ml_append_flush(curbuf, lnum, line, len, flags);
3357 }
3358 
3359 
3360 #if defined(FEAT_SPELL) || defined(FEAT_QUICKFIX) || defined(PROTO)
3361 /*
3362  * Like ml_append() but for an arbitrary buffer.  The buffer must already have
3363  * a memline.
3364  */
3365     int
ml_append_buf(buf_T * buf,linenr_T lnum,char_u * line,colnr_T len,int newfile)3366 ml_append_buf(
3367     buf_T	*buf,
3368     linenr_T	lnum,		// append after this line (can be 0)
3369     char_u	*line,		// text of the new line
3370     colnr_T	len,		// length of new line, including NUL, or 0
3371     int		newfile)	// flag, see above
3372 {
3373     if (buf->b_ml.ml_mfp == NULL)
3374 	return FAIL;
3375     return ml_append_flush(buf, lnum, line, len, newfile ? ML_APPEND_NEW : 0);
3376 }
3377 #endif
3378 
3379 /*
3380  * Replace line "lnum", with buffering, in current buffer.
3381  *
3382  * If "copy" is TRUE, make a copy of the line, otherwise the line has been
3383  * copied to allocated memory already.
3384  * If "copy" is FALSE the "line" may be freed to add text properties!
3385  * Do not use it after calling ml_replace().
3386  *
3387  * Check: The caller of this function should probably also call
3388  * changed_lines(), unless update_screen(NOT_VALID) is used.
3389  *
3390  * return FAIL for failure, OK otherwise
3391  */
3392     int
ml_replace(linenr_T lnum,char_u * line,int copy)3393 ml_replace(linenr_T lnum, char_u *line, int copy)
3394 {
3395     colnr_T len = -1;
3396 
3397     if (line != NULL)
3398 	len = (colnr_T)STRLEN(line);
3399     return ml_replace_len(lnum, line, len, FALSE, copy);
3400 }
3401 
3402 /*
3403  * Replace a line for the current buffer.  Like ml_replace() with:
3404  * "len_arg" is the length of the text, excluding NUL.
3405  * If "has_props" is TRUE then "line_arg" includes the text properties and
3406  * "len_arg" includes the NUL of the text.
3407  */
3408     int
ml_replace_len(linenr_T lnum,char_u * line_arg,colnr_T len_arg,int has_props,int copy)3409 ml_replace_len(
3410 	linenr_T    lnum,
3411 	char_u	    *line_arg,
3412 	colnr_T	    len_arg,
3413 	int	    has_props,
3414 	int	    copy)
3415 {
3416     char_u *line = line_arg;
3417     colnr_T len = len_arg;
3418 
3419     if (line == NULL)		// just checking...
3420 	return FAIL;
3421 
3422     // When starting up, we might still need to create the memfile
3423     if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
3424 	return FAIL;
3425 
3426     if (!has_props)
3427 	++len;  // include the NUL after the text
3428     if (copy)
3429     {
3430 	// copy the line to allocated memory
3431 #ifdef FEAT_PROP_POPUP
3432 	if (has_props)
3433 	    line = vim_memsave(line, len);
3434 	else
3435 #endif
3436 	    line = vim_strnsave(line, len - 1);
3437 	if (line == NULL)
3438 	    return FAIL;
3439     }
3440 
3441 #ifdef FEAT_NETBEANS_INTG
3442     if (netbeans_active())
3443     {
3444 	netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
3445 	netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
3446     }
3447 #endif
3448     if (curbuf->b_ml.ml_line_lnum != lnum)
3449     {
3450 	// another line is buffered, flush it
3451 	ml_flush_line(curbuf);
3452 	curbuf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
3453 
3454 #ifdef FEAT_PROP_POPUP
3455 	if (curbuf->b_has_textprop && !has_props)
3456 	    // Need to fetch the old line to copy over any text properties.
3457 	    ml_get_buf(curbuf, lnum, TRUE);
3458 #endif
3459     }
3460 
3461 #ifdef FEAT_PROP_POPUP
3462     if (curbuf->b_has_textprop && !has_props)
3463     {
3464 	size_t	oldtextlen = STRLEN(curbuf->b_ml.ml_line_ptr) + 1;
3465 
3466 	if (oldtextlen < (size_t)curbuf->b_ml.ml_line_len)
3467 	{
3468 	    char_u *newline;
3469 	    size_t textproplen = curbuf->b_ml.ml_line_len - oldtextlen;
3470 
3471 	    // Need to copy over text properties, stored after the text.
3472 	    newline = alloc(len + (int)textproplen);
3473 	    if (newline != NULL)
3474 	    {
3475 		mch_memmove(newline, line, len);
3476 		mch_memmove(newline + len, curbuf->b_ml.ml_line_ptr
3477 						    + oldtextlen, textproplen);
3478 		vim_free(line);
3479 		line = newline;
3480 		len += (colnr_T)textproplen;
3481 	    }
3482 	}
3483     }
3484 #endif
3485 
3486     if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY)	// same line allocated
3487 	vim_free(curbuf->b_ml.ml_line_ptr);	// free it
3488 
3489     curbuf->b_ml.ml_line_ptr = line;
3490     curbuf->b_ml.ml_line_len = len;
3491     curbuf->b_ml.ml_line_lnum = lnum;
3492     curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3493 
3494     return OK;
3495 }
3496 
3497 #ifdef FEAT_PROP_POPUP
3498 /*
3499  * Adjust text properties in line "lnum" for a deleted line.
3500  * When "above" is true this is the line above the deleted line.
3501  * "del_props" are the properties of the deleted line.
3502  */
3503     static void
adjust_text_props_for_delete(buf_T * buf,linenr_T lnum,char_u * del_props,int del_props_len,int above)3504 adjust_text_props_for_delete(
3505 	buf_T	    *buf,
3506 	linenr_T    lnum,
3507 	char_u	    *del_props,
3508 	int	    del_props_len,
3509 	int	    above)
3510 {
3511     int		did_get_line = FALSE;
3512     int		done_del;
3513     int		done_this;
3514     textprop_T	prop_del;
3515     bhdr_T	*hp;
3516     DATA_BL	*dp;
3517     int		idx;
3518     int		line_start;
3519     long	line_size;
3520     int		this_props_len;
3521     char_u	*text;
3522     size_t	textlen;
3523     int		found;
3524 
3525     for (done_del = 0; done_del < del_props_len; done_del += sizeof(textprop_T))
3526     {
3527 	mch_memmove(&prop_del, del_props + done_del, sizeof(textprop_T));
3528 	if ((above && (prop_del.tp_flags & TP_FLAG_CONT_PREV)
3529 		    && !(prop_del.tp_flags & TP_FLAG_CONT_NEXT))
3530 		|| (!above && (prop_del.tp_flags & TP_FLAG_CONT_NEXT)
3531 		    && !(prop_del.tp_flags & TP_FLAG_CONT_PREV)))
3532 	{
3533 	    if (!did_get_line)
3534 	    {
3535 		did_get_line = TRUE;
3536 		if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
3537 		    return;
3538 
3539 		dp = (DATA_BL *)(hp->bh_data);
3540 		idx = lnum - buf->b_ml.ml_locked_low;
3541 		line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3542 		if (idx == 0)		// first line in block, text at the end
3543 		    line_size = dp->db_txt_end - line_start;
3544 		else
3545 		    line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK)
3546 								  - line_start;
3547 		text = (char_u *)dp + line_start;
3548 		textlen = STRLEN(text) + 1;
3549 		if ((long)textlen >= line_size)
3550 		{
3551 		    if (above)
3552 			internal_error("no text property above deleted line");
3553 		    else
3554 			internal_error("no text property below deleted line");
3555 		    return;
3556 		}
3557 		this_props_len = line_size - (int)textlen;
3558 	    }
3559 
3560 	    found = FALSE;
3561 	    for (done_this = 0; done_this < this_props_len;
3562 					       done_this += sizeof(textprop_T))
3563 	    {
3564 		int	    flag = above ? TP_FLAG_CONT_NEXT
3565 							   : TP_FLAG_CONT_PREV;
3566 		textprop_T  prop_this;
3567 
3568 		mch_memmove(&prop_this, text + textlen + done_del,
3569 							   sizeof(textprop_T));
3570 		if ((prop_this.tp_flags & flag)
3571 			&& prop_del.tp_id == prop_this.tp_id
3572 			&& prop_del.tp_type == prop_this.tp_type)
3573 		{
3574 		    found = TRUE;
3575 		    prop_this.tp_flags &= ~flag;
3576 		    mch_memmove(text + textlen + done_del, &prop_this,
3577 							   sizeof(textprop_T));
3578 		    break;
3579 		}
3580 	    }
3581 	    if (!found)
3582 	    {
3583 		if (above)
3584 		    internal_error("text property above deleted line not found");
3585 		else
3586 		    internal_error("text property below deleted line not found");
3587 	    }
3588 
3589 	    buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3590 	}
3591     }
3592 }
3593 #endif
3594 
3595 /*
3596  * Delete line "lnum" in the current buffer.
3597  * When "flags" has ML_DEL_MESSAGE may give a "No lines in buffer" message.
3598  * When "flags" has ML_DEL_UNDO this is called from undo.
3599  *
3600  * return FAIL for failure, OK otherwise
3601  */
3602     static int
ml_delete_int(buf_T * buf,linenr_T lnum,int flags)3603 ml_delete_int(buf_T *buf, linenr_T lnum, int flags)
3604 {
3605     bhdr_T	*hp;
3606     memfile_T	*mfp;
3607     DATA_BL	*dp;
3608     PTR_BL	*pp;
3609     infoptr_T	*ip;
3610     int		count;	    // number of entries in block
3611     int		idx;
3612     int		stack_idx;
3613     int		text_start;
3614     int		line_start;
3615     long	line_size;
3616     int		i;
3617     int		ret = FAIL;
3618 #ifdef FEAT_PROP_POPUP
3619     char_u	*textprop_save = NULL;
3620     int		textprop_save_len = 0;
3621 #endif
3622 
3623     if (lowest_marked && lowest_marked > lnum)
3624 	lowest_marked--;
3625 
3626 /*
3627  * If the file becomes empty the last line is replaced by an empty line.
3628  */
3629     if (buf->b_ml.ml_line_count == 1)	    // file becomes empty
3630     {
3631 	if ((flags & ML_DEL_MESSAGE)
3632 #ifdef FEAT_NETBEANS_INTG
3633 		&& !netbeansSuppressNoLines
3634 #endif
3635 	   )
3636 	    set_keep_msg((char_u *)_(no_lines_msg), 0);
3637 
3638 	// FEAT_BYTEOFF already handled in there, don't worry 'bout it below
3639 	i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3640 	buf->b_ml.ml_flags |= ML_EMPTY;
3641 
3642 	return i;
3643     }
3644 
3645 /*
3646  * Find the data block containing the line.
3647  * This also fills the stack with the blocks from the root to the data block.
3648  * This also releases any locked block..
3649  */
3650     mfp = buf->b_ml.ml_mfp;
3651     if (mfp == NULL)
3652 	return FAIL;
3653 
3654     if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3655 	return FAIL;
3656 
3657     dp = (DATA_BL *)(hp->bh_data);
3658     // compute line count before the delete
3659     count = (long)(buf->b_ml.ml_locked_high)
3660 					- (long)(buf->b_ml.ml_locked_low) + 2;
3661     idx = lnum - buf->b_ml.ml_locked_low;
3662 
3663     --buf->b_ml.ml_line_count;
3664 
3665     line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3666     if (idx == 0)		// first line in block, text at the end
3667 	line_size = dp->db_txt_end - line_start;
3668     else
3669 	line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3670 
3671 #ifdef FEAT_NETBEANS_INTG
3672     if (netbeans_active())
3673 	netbeans_removed(buf, lnum, 0, (long)line_size);
3674 #endif
3675 #ifdef FEAT_PROP_POPUP
3676     // If there are text properties, make a copy, so that we can update
3677     // properties in preceding and following lines.
3678     if (buf->b_has_textprop && !(flags & (ML_DEL_UNDO | ML_DEL_NOPROP)))
3679     {
3680 	size_t	textlen = STRLEN((char_u *)dp + line_start) + 1;
3681 
3682 	if ((long)textlen < line_size)
3683 	{
3684 	    textprop_save_len = line_size - (int)textlen;
3685 	    textprop_save = vim_memsave((char_u *)dp + line_start + textlen,
3686 							  textprop_save_len);
3687 	}
3688     }
3689 #endif
3690 
3691 /*
3692  * special case: If there is only one line in the data block it becomes empty.
3693  * Then we have to remove the entry, pointing to this data block, from the
3694  * pointer block. If this pointer block also becomes empty, we go up another
3695  * block, and so on, up to the root if necessary.
3696  * The line counts in the pointer blocks have already been adjusted by
3697  * ml_find_line().
3698  */
3699     if (count == 1)
3700     {
3701 	mf_free(mfp, hp);	// free the data block
3702 	buf->b_ml.ml_locked = NULL;
3703 
3704 	for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3705 								  --stack_idx)
3706 	{
3707 	    buf->b_ml.ml_stack_top = 0;	    // stack is invalid when failing
3708 	    ip = &(buf->b_ml.ml_stack[stack_idx]);
3709 	    idx = ip->ip_index;
3710 	    if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3711 		goto theend;
3712 	    pp = (PTR_BL *)(hp->bh_data);   // must be pointer block
3713 	    if (pp->pb_id != PTR_ID)
3714 	    {
3715 		iemsg(_("E317: pointer block id wrong 4"));
3716 		mf_put(mfp, hp, FALSE, FALSE);
3717 		goto theend;
3718 	    }
3719 	    count = --(pp->pb_count);
3720 	    if (count == 0)	    // the pointer block becomes empty!
3721 		mf_free(mfp, hp);
3722 	    else
3723 	    {
3724 		if (count != idx)	// move entries after the deleted one
3725 		    mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3726 				      (size_t)(count - idx) * sizeof(PTR_EN));
3727 		mf_put(mfp, hp, TRUE, FALSE);
3728 
3729 		buf->b_ml.ml_stack_top = stack_idx;	// truncate stack
3730 		// fix line count for rest of blocks in the stack
3731 		if (buf->b_ml.ml_locked_lineadd != 0)
3732 		{
3733 		    ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3734 		    buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
3735 						  buf->b_ml.ml_locked_lineadd;
3736 		}
3737 		++(buf->b_ml.ml_stack_top);
3738 
3739 		break;
3740 	    }
3741 	}
3742 	CHECK(stack_idx < 0, _("deleted block 1?"));
3743     }
3744     else
3745     {
3746 	/*
3747 	 * delete the text by moving the next lines forwards
3748 	 */
3749 	text_start = dp->db_txt_start;
3750 	mch_memmove((char *)dp + text_start + line_size,
3751 		  (char *)dp + text_start, (size_t)(line_start - text_start));
3752 
3753 	/*
3754 	 * delete the index by moving the next indexes backwards
3755 	 * Adjust the indexes for the text movement.
3756 	 */
3757 	for (i = idx; i < count - 1; ++i)
3758 	    dp->db_index[i] = dp->db_index[i + 1] + line_size;
3759 
3760 	dp->db_free += line_size + INDEX_SIZE;
3761 	dp->db_txt_start += line_size;
3762 	--(dp->db_line_count);
3763 
3764 	/*
3765 	 * mark the block dirty and make sure it is in the file (for recovery)
3766 	 */
3767 	buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3768     }
3769 
3770 #ifdef FEAT_BYTEOFF
3771     ml_updatechunk(buf, lnum, line_size
3772 # ifdef FEAT_PROP_POPUP
3773 					- textprop_save_len
3774 # endif
3775 							    , ML_CHNK_DELLINE);
3776 #endif
3777     ret = OK;
3778 
3779 theend:
3780 #ifdef FEAT_PROP_POPUP
3781     if (textprop_save != NULL)
3782     {
3783 	// Adjust text properties in the line above and below.
3784 	if (lnum > 1)
3785 	    adjust_text_props_for_delete(buf, lnum - 1, textprop_save,
3786 						      textprop_save_len, TRUE);
3787 	if (lnum <= buf->b_ml.ml_line_count)
3788 	    adjust_text_props_for_delete(buf, lnum, textprop_save,
3789 						     textprop_save_len, FALSE);
3790     }
3791     vim_free(textprop_save);
3792 #endif
3793     return ret;
3794 }
3795 
3796 /*
3797  * Delete line "lnum" in the current buffer.
3798  * When "message" is TRUE may give a "No lines in buffer" message.
3799  *
3800  * Check: The caller of this function should probably also call
3801  * deleted_lines() after this.
3802  *
3803  * return FAIL for failure, OK otherwise
3804  */
3805     int
ml_delete(linenr_T lnum)3806 ml_delete(linenr_T lnum)
3807 {
3808     return ml_delete_flags(lnum, 0);
3809 }
3810 
3811 /*
3812  * Like ml_delete() but using flags (see ml_delete_int()).
3813  */
3814     int
ml_delete_flags(linenr_T lnum,int flags)3815 ml_delete_flags(linenr_T lnum, int flags)
3816 {
3817     ml_flush_line(curbuf);
3818     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3819 	return FAIL;
3820 
3821 #ifdef FEAT_EVAL
3822     // When inserting above recorded changes: flush the changes before changing
3823     // the text.
3824     may_invoke_listeners(curbuf, lnum, lnum + 1, -1);
3825 #endif
3826 
3827     return ml_delete_int(curbuf, lnum, flags);
3828 }
3829 
3830 /*
3831  * set the DB_MARKED flag for line 'lnum'
3832  */
3833     void
ml_setmarked(linenr_T lnum)3834 ml_setmarked(linenr_T lnum)
3835 {
3836     bhdr_T    *hp;
3837     DATA_BL *dp;
3838 				    // invalid line number
3839     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3840 					       || curbuf->b_ml.ml_mfp == NULL)
3841 	return;			    // give error message?
3842 
3843     if (lowest_marked == 0 || lowest_marked > lnum)
3844 	lowest_marked = lnum;
3845 
3846     /*
3847      * find the data block containing the line
3848      * This also fills the stack with the blocks from the root to the data block
3849      * This also releases any locked block.
3850      */
3851     if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3852 	return;		    // give error message?
3853 
3854     dp = (DATA_BL *)(hp->bh_data);
3855     dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3856     curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3857 }
3858 
3859 /*
3860  * find the first line with its DB_MARKED flag set
3861  */
3862     linenr_T
ml_firstmarked(void)3863 ml_firstmarked(void)
3864 {
3865     bhdr_T	*hp;
3866     DATA_BL	*dp;
3867     linenr_T	lnum;
3868     int		i;
3869 
3870     if (curbuf->b_ml.ml_mfp == NULL)
3871 	return (linenr_T) 0;
3872 
3873     /*
3874      * The search starts with lowest_marked line. This is the last line where
3875      * a mark was found, adjusted by inserting/deleting lines.
3876      */
3877     for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3878     {
3879 	/*
3880 	 * Find the data block containing the line.
3881 	 * This also fills the stack with the blocks from the root to the data
3882 	 * block This also releases any locked block.
3883 	 */
3884 	if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3885 	    return (linenr_T)0;		    // give error message?
3886 
3887 	dp = (DATA_BL *)(hp->bh_data);
3888 
3889 	for (i = lnum - curbuf->b_ml.ml_locked_low;
3890 			    lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3891 	    if ((dp->db_index[i]) & DB_MARKED)
3892 	    {
3893 		(dp->db_index[i]) &= DB_INDEX_MASK;
3894 		curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3895 		lowest_marked = lnum + 1;
3896 		return lnum;
3897 	    }
3898     }
3899 
3900     return (linenr_T) 0;
3901 }
3902 
3903 /*
3904  * clear all DB_MARKED flags
3905  */
3906     void
ml_clearmarked(void)3907 ml_clearmarked(void)
3908 {
3909     bhdr_T	*hp;
3910     DATA_BL	*dp;
3911     linenr_T	lnum;
3912     int		i;
3913 
3914     if (curbuf->b_ml.ml_mfp == NULL)	    // nothing to do
3915 	return;
3916 
3917     /*
3918      * The search starts with line lowest_marked.
3919      */
3920     for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3921     {
3922 	/*
3923 	 * Find the data block containing the line.
3924 	 * This also fills the stack with the blocks from the root to the data
3925 	 * block and releases any locked block.
3926 	 */
3927 	if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3928 	    return;		// give error message?
3929 
3930 	dp = (DATA_BL *)(hp->bh_data);
3931 
3932 	for (i = lnum - curbuf->b_ml.ml_locked_low;
3933 			    lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3934 	    if ((dp->db_index[i]) & DB_MARKED)
3935 	    {
3936 		(dp->db_index[i]) &= DB_INDEX_MASK;
3937 		curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3938 	    }
3939     }
3940 
3941     lowest_marked = 0;
3942 }
3943 
3944 /*
3945  * flush ml_line if necessary
3946  */
3947     static void
ml_flush_line(buf_T * buf)3948 ml_flush_line(buf_T *buf)
3949 {
3950     bhdr_T	*hp;
3951     DATA_BL	*dp;
3952     linenr_T	lnum;
3953     char_u	*new_line;
3954     char_u	*old_line;
3955     colnr_T	new_len;
3956     int		old_len;
3957     int		extra;
3958     int		idx;
3959     int		start;
3960     int		count;
3961     int		i;
3962     static int  entered = FALSE;
3963 
3964     if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3965 	return;		// nothing to do
3966 
3967     if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3968     {
3969 	// This code doesn't work recursively, but Netbeans may call back here
3970 	// when obtaining the cursor position.
3971 	if (entered)
3972 	    return;
3973 	entered = TRUE;
3974 
3975 	lnum = buf->b_ml.ml_line_lnum;
3976 	new_line = buf->b_ml.ml_line_ptr;
3977 
3978 	hp = ml_find_line(buf, lnum, ML_FIND);
3979 	if (hp == NULL)
3980 	    siemsg(_("E320: Cannot find line %ld"), lnum);
3981 	else
3982 	{
3983 	    dp = (DATA_BL *)(hp->bh_data);
3984 	    idx = lnum - buf->b_ml.ml_locked_low;
3985 	    start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3986 	    old_line = (char_u *)dp + start;
3987 	    if (idx == 0)	// line is last in block
3988 		old_len = dp->db_txt_end - start;
3989 	    else		// text of previous line follows
3990 		old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3991 	    new_len = buf->b_ml.ml_line_len;
3992 	    extra = new_len - old_len;	    // negative if lines gets smaller
3993 
3994 	    /*
3995 	     * if new line fits in data block, replace directly
3996 	     */
3997 	    if ((int)dp->db_free >= extra)
3998 	    {
3999 #if defined(FEAT_BYTEOFF) && defined(FEAT_PROP_POPUP)
4000 		int old_prop_len = 0;
4001 #endif
4002 		// if the length changes and there are following lines
4003 		count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
4004 		if (extra != 0 && idx < count - 1)
4005 		{
4006 		    // move text of following lines
4007 		    mch_memmove((char *)dp + dp->db_txt_start - extra,
4008 				(char *)dp + dp->db_txt_start,
4009 				(size_t)(start - dp->db_txt_start));
4010 
4011 		    // adjust pointers of this and following lines
4012 		    for (i = idx + 1; i < count; ++i)
4013 			dp->db_index[i] -= extra;
4014 		}
4015 		dp->db_index[idx] -= extra;
4016 
4017 		// adjust free space
4018 		dp->db_free -= extra;
4019 		dp->db_txt_start -= extra;
4020 #if defined(FEAT_BYTEOFF) && defined(FEAT_PROP_POPUP)
4021 		if (buf->b_has_textprop)
4022 		    old_prop_len = old_len - (int)STRLEN(new_line) - 1;
4023 #endif
4024 
4025 		// copy new line into the data block
4026 		mch_memmove(old_line - extra, new_line, (size_t)new_len);
4027 		buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
4028 #if defined(FEAT_BYTEOFF) && defined(FEAT_PROP_POPUP)
4029 		// The else case is already covered by the insert and delete
4030 		if (buf->b_has_textprop)
4031 		{
4032 		    // Do not count the size of any text properties.
4033 		    extra += old_prop_len;
4034 		    extra -= new_len - (int)STRLEN(new_line) - 1;
4035 		}
4036 		if (extra != 0)
4037 		    ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
4038 #endif
4039 	    }
4040 	    else
4041 	    {
4042 		/*
4043 		 * Cannot do it in one data block: Delete and append.
4044 		 * Append first, because ml_delete_int() cannot delete the
4045 		 * last line in a buffer, which causes trouble for a buffer
4046 		 * that has only one line.
4047 		 * Don't forget to copy the mark!
4048 		 */
4049 		// How about handling errors???
4050 		(void)ml_append_int(buf, lnum, new_line, new_len,
4051 			 ((dp->db_index[idx] & DB_MARKED) ? ML_APPEND_MARK : 0)
4052 #ifdef FEAT_PROP_POPUP
4053 			     | ML_APPEND_NOPROP
4054 #endif
4055 			 );
4056 		(void)ml_delete_int(buf, lnum, ML_DEL_NOPROP);
4057 	    }
4058 	}
4059 	vim_free(new_line);
4060 
4061 	entered = FALSE;
4062     }
4063 
4064     buf->b_ml.ml_line_lnum = 0;
4065 }
4066 
4067 /*
4068  * create a new, empty, data block
4069  */
4070     static bhdr_T *
ml_new_data(memfile_T * mfp,int negative,int page_count)4071 ml_new_data(memfile_T *mfp, int negative, int page_count)
4072 {
4073     bhdr_T	*hp;
4074     DATA_BL	*dp;
4075 
4076     if ((hp = mf_new(mfp, negative, page_count)) == NULL)
4077 	return NULL;
4078 
4079     dp = (DATA_BL *)(hp->bh_data);
4080     dp->db_id = DATA_ID;
4081     dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
4082     dp->db_free = dp->db_txt_start - HEADER_SIZE;
4083     dp->db_line_count = 0;
4084 
4085     return hp;
4086 }
4087 
4088 /*
4089  * create a new, empty, pointer block
4090  */
4091     static bhdr_T *
ml_new_ptr(memfile_T * mfp)4092 ml_new_ptr(memfile_T *mfp)
4093 {
4094     bhdr_T	*hp;
4095     PTR_BL	*pp;
4096 
4097     if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
4098 	return NULL;
4099 
4100     pp = (PTR_BL *)(hp->bh_data);
4101     pp->pb_id = PTR_ID;
4102     pp->pb_count = 0;
4103     pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
4104 							/ sizeof(PTR_EN) + 1);
4105 
4106     return hp;
4107 }
4108 
4109 /*
4110  * Lookup line 'lnum' in a memline.
4111  *
4112  *   action: if ML_DELETE or ML_INSERT the line count is updated while searching
4113  *	     if ML_FLUSH only flush a locked block
4114  *	     if ML_FIND just find the line
4115  *
4116  * If the block was found it is locked and put in ml_locked.
4117  * The stack is updated to lead to the locked block. The ip_high field in
4118  * the stack is updated to reflect the last line in the block AFTER the
4119  * insert or delete, also if the pointer block has not been updated yet. But
4120  * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
4121  *
4122  * return: NULL for failure, pointer to block header otherwise
4123  */
4124     static bhdr_T *
ml_find_line(buf_T * buf,linenr_T lnum,int action)4125 ml_find_line(buf_T *buf, linenr_T lnum, int action)
4126 {
4127     DATA_BL	*dp;
4128     PTR_BL	*pp;
4129     infoptr_T	*ip;
4130     bhdr_T	*hp;
4131     memfile_T	*mfp;
4132     linenr_T	t;
4133     blocknr_T	bnum, bnum2;
4134     int		dirty;
4135     linenr_T	low, high;
4136     int		top;
4137     int		page_count;
4138     int		idx;
4139 
4140     mfp = buf->b_ml.ml_mfp;
4141 
4142     /*
4143      * If there is a locked block check if the wanted line is in it.
4144      * If not, flush and release the locked block.
4145      * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
4146      * Don't do this for ML_FLUSH, because we want to flush the locked block.
4147      * Don't do this when 'swapfile' is reset, we want to load all the blocks.
4148      */
4149     if (buf->b_ml.ml_locked)
4150     {
4151 	if (ML_SIMPLE(action)
4152 		&& buf->b_ml.ml_locked_low <= lnum
4153 		&& buf->b_ml.ml_locked_high >= lnum
4154 		&& !mf_dont_release)
4155 	{
4156 	    // remember to update pointer blocks and stack later
4157 	    if (action == ML_INSERT)
4158 	    {
4159 		++(buf->b_ml.ml_locked_lineadd);
4160 		++(buf->b_ml.ml_locked_high);
4161 	    }
4162 	    else if (action == ML_DELETE)
4163 	    {
4164 		--(buf->b_ml.ml_locked_lineadd);
4165 		--(buf->b_ml.ml_locked_high);
4166 	    }
4167 	    return (buf->b_ml.ml_locked);
4168 	}
4169 
4170 	mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
4171 					    buf->b_ml.ml_flags & ML_LOCKED_POS);
4172 	buf->b_ml.ml_locked = NULL;
4173 
4174 	/*
4175 	 * If lines have been added or deleted in the locked block, need to
4176 	 * update the line count in pointer blocks.
4177 	 */
4178 	if (buf->b_ml.ml_locked_lineadd != 0)
4179 	    ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
4180     }
4181 
4182     if (action == ML_FLUSH)	    // nothing else to do
4183 	return NULL;
4184 
4185     bnum = 1;			    // start at the root of the tree
4186     page_count = 1;
4187     low = 1;
4188     high = buf->b_ml.ml_line_count;
4189 
4190     if (action == ML_FIND)	// first try stack entries
4191     {
4192 	for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
4193 	{
4194 	    ip = &(buf->b_ml.ml_stack[top]);
4195 	    if (ip->ip_low <= lnum && ip->ip_high >= lnum)
4196 	    {
4197 		bnum = ip->ip_bnum;
4198 		low = ip->ip_low;
4199 		high = ip->ip_high;
4200 		buf->b_ml.ml_stack_top = top;	// truncate stack at prev entry
4201 		break;
4202 	    }
4203 	}
4204 	if (top < 0)
4205 	    buf->b_ml.ml_stack_top = 0;		// not found, start at the root
4206     }
4207     else	// ML_DELETE or ML_INSERT
4208 	buf->b_ml.ml_stack_top = 0;	// start at the root
4209 
4210 /*
4211  * search downwards in the tree until a data block is found
4212  */
4213     for (;;)
4214     {
4215 	if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
4216 	    goto error_noblock;
4217 
4218 	/*
4219 	 * update high for insert/delete
4220 	 */
4221 	if (action == ML_INSERT)
4222 	    ++high;
4223 	else if (action == ML_DELETE)
4224 	    --high;
4225 
4226 	dp = (DATA_BL *)(hp->bh_data);
4227 	if (dp->db_id == DATA_ID)	// data block
4228 	{
4229 	    buf->b_ml.ml_locked = hp;
4230 	    buf->b_ml.ml_locked_low = low;
4231 	    buf->b_ml.ml_locked_high = high;
4232 	    buf->b_ml.ml_locked_lineadd = 0;
4233 	    buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
4234 	    return hp;
4235 	}
4236 
4237 	pp = (PTR_BL *)(dp);		// must be pointer block
4238 	if (pp->pb_id != PTR_ID)
4239 	{
4240 	    iemsg(_("E317: pointer block id wrong"));
4241 	    goto error_block;
4242 	}
4243 
4244 	if ((top = ml_add_stack(buf)) < 0)	// add new entry to stack
4245 	    goto error_block;
4246 	ip = &(buf->b_ml.ml_stack[top]);
4247 	ip->ip_bnum = bnum;
4248 	ip->ip_low = low;
4249 	ip->ip_high = high;
4250 	ip->ip_index = -1;		// index not known yet
4251 
4252 	dirty = FALSE;
4253 	for (idx = 0; idx < (int)pp->pb_count; ++idx)
4254 	{
4255 	    t = pp->pb_pointer[idx].pe_line_count;
4256 	    CHECK(t == 0, _("pe_line_count is zero"));
4257 	    if ((low += t) > lnum)
4258 	    {
4259 		ip->ip_index = idx;
4260 		bnum = pp->pb_pointer[idx].pe_bnum;
4261 		page_count = pp->pb_pointer[idx].pe_page_count;
4262 		high = low - 1;
4263 		low -= t;
4264 
4265 		/*
4266 		 * a negative block number may have been changed
4267 		 */
4268 		if (bnum < 0)
4269 		{
4270 		    bnum2 = mf_trans_del(mfp, bnum);
4271 		    if (bnum != bnum2)
4272 		    {
4273 			bnum = bnum2;
4274 			pp->pb_pointer[idx].pe_bnum = bnum;
4275 			dirty = TRUE;
4276 		    }
4277 		}
4278 
4279 		break;
4280 	    }
4281 	}
4282 	if (idx >= (int)pp->pb_count)	    // past the end: something wrong!
4283 	{
4284 	    if (lnum > buf->b_ml.ml_line_count)
4285 		siemsg(_("E322: line number out of range: %ld past the end"),
4286 					      lnum - buf->b_ml.ml_line_count);
4287 
4288 	    else
4289 		siemsg(_("E323: line count wrong in block %ld"), bnum);
4290 	    goto error_block;
4291 	}
4292 	if (action == ML_DELETE)
4293 	{
4294 	    pp->pb_pointer[idx].pe_line_count--;
4295 	    dirty = TRUE;
4296 	}
4297 	else if (action == ML_INSERT)
4298 	{
4299 	    pp->pb_pointer[idx].pe_line_count++;
4300 	    dirty = TRUE;
4301 	}
4302 	mf_put(mfp, hp, dirty, FALSE);
4303     }
4304 
4305 error_block:
4306     mf_put(mfp, hp, FALSE, FALSE);
4307 error_noblock:
4308     /*
4309      * If action is ML_DELETE or ML_INSERT we have to correct the tree for
4310      * the incremented/decremented line counts, because there won't be a line
4311      * inserted/deleted after all.
4312      */
4313     if (action == ML_DELETE)
4314 	ml_lineadd(buf, 1);
4315     else if (action == ML_INSERT)
4316 	ml_lineadd(buf, -1);
4317     buf->b_ml.ml_stack_top = 0;
4318     return NULL;
4319 }
4320 
4321 /*
4322  * add an entry to the info pointer stack
4323  *
4324  * return -1 for failure, number of the new entry otherwise
4325  */
4326     static int
ml_add_stack(buf_T * buf)4327 ml_add_stack(buf_T *buf)
4328 {
4329     int		top;
4330     infoptr_T	*newstack;
4331 
4332     top = buf->b_ml.ml_stack_top;
4333 
4334     // may have to increase the stack size
4335     if (top == buf->b_ml.ml_stack_size)
4336     {
4337 	CHECK(top > 0, _("Stack size increases")); // more than 5 levels???
4338 
4339 	newstack = ALLOC_MULT(infoptr_T, buf->b_ml.ml_stack_size + STACK_INCR);
4340 	if (newstack == NULL)
4341 	    return -1;
4342 	if (top > 0)
4343 	    mch_memmove(newstack, buf->b_ml.ml_stack,
4344 					     (size_t)top * sizeof(infoptr_T));
4345 	vim_free(buf->b_ml.ml_stack);
4346 	buf->b_ml.ml_stack = newstack;
4347 	buf->b_ml.ml_stack_size += STACK_INCR;
4348     }
4349 
4350     buf->b_ml.ml_stack_top++;
4351     return top;
4352 }
4353 
4354 /*
4355  * Update the pointer blocks on the stack for inserted/deleted lines.
4356  * The stack itself is also updated.
4357  *
4358  * When a insert/delete line action fails, the line is not inserted/deleted,
4359  * but the pointer blocks have already been updated. That is fixed here by
4360  * walking through the stack.
4361  *
4362  * Count is the number of lines added, negative if lines have been deleted.
4363  */
4364     static void
ml_lineadd(buf_T * buf,int count)4365 ml_lineadd(buf_T *buf, int count)
4366 {
4367     int		idx;
4368     infoptr_T	*ip;
4369     PTR_BL	*pp;
4370     memfile_T	*mfp = buf->b_ml.ml_mfp;
4371     bhdr_T	*hp;
4372 
4373     for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
4374     {
4375 	ip = &(buf->b_ml.ml_stack[idx]);
4376 	if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
4377 	    break;
4378 	pp = (PTR_BL *)(hp->bh_data);	// must be pointer block
4379 	if (pp->pb_id != PTR_ID)
4380 	{
4381 	    mf_put(mfp, hp, FALSE, FALSE);
4382 	    iemsg(_("E317: pointer block id wrong 2"));
4383 	    break;
4384 	}
4385 	pp->pb_pointer[ip->ip_index].pe_line_count += count;
4386 	ip->ip_high += count;
4387 	mf_put(mfp, hp, TRUE, FALSE);
4388     }
4389 }
4390 
4391 #if defined(HAVE_READLINK) || defined(PROTO)
4392 /*
4393  * Resolve a symlink in the last component of a file name.
4394  * Note that f_resolve() does it for every part of the path, we don't do that
4395  * here.
4396  * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
4397  * Otherwise returns FAIL.
4398  */
4399     int
resolve_symlink(char_u * fname,char_u * buf)4400 resolve_symlink(char_u *fname, char_u *buf)
4401 {
4402     char_u	tmp[MAXPATHL];
4403     int		ret;
4404     int		depth = 0;
4405 
4406     if (fname == NULL)
4407 	return FAIL;
4408 
4409     // Put the result so far in tmp[], starting with the original name.
4410     vim_strncpy(tmp, fname, MAXPATHL - 1);
4411 
4412     for (;;)
4413     {
4414 	// Limit symlink depth to 100, catch recursive loops.
4415 	if (++depth == 100)
4416 	{
4417 	    semsg(_("E773: Symlink loop for \"%s\""), fname);
4418 	    return FAIL;
4419 	}
4420 
4421 	ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
4422 	if (ret <= 0)
4423 	{
4424 	    if (errno == EINVAL || errno == ENOENT)
4425 	    {
4426 		// Found non-symlink or not existing file, stop here.
4427 		// When at the first level use the unmodified name, skip the
4428 		// call to vim_FullName().
4429 		if (depth == 1)
4430 		    return FAIL;
4431 
4432 		// Use the resolved name in tmp[].
4433 		break;
4434 	    }
4435 
4436 	    // There must be some error reading links, use original name.
4437 	    return FAIL;
4438 	}
4439 	buf[ret] = NUL;
4440 
4441 	/*
4442 	 * Check whether the symlink is relative or absolute.
4443 	 * If it's relative, build a new path based on the directory
4444 	 * portion of the filename (if any) and the path the symlink
4445 	 * points to.
4446 	 */
4447 	if (mch_isFullName(buf))
4448 	    STRCPY(tmp, buf);
4449 	else
4450 	{
4451 	    char_u *tail;
4452 
4453 	    tail = gettail(tmp);
4454 	    if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
4455 		return FAIL;
4456 	    STRCPY(tail, buf);
4457 	}
4458     }
4459 
4460     /*
4461      * Try to resolve the full name of the file so that the swapfile name will
4462      * be consistent even when opening a relative symlink from different
4463      * working directories.
4464      */
4465     return vim_FullName(tmp, buf, MAXPATHL, TRUE);
4466 }
4467 #endif
4468 
4469 /*
4470  * Make swap file name out of the file name and a directory name.
4471  * Returns pointer to allocated memory or NULL.
4472  */
4473     char_u *
makeswapname(char_u * fname,char_u * ffname UNUSED,buf_T * buf,char_u * dir_name)4474 makeswapname(
4475     char_u	*fname,
4476     char_u	*ffname UNUSED,
4477     buf_T	*buf,
4478     char_u	*dir_name)
4479 {
4480     char_u	*r, *s;
4481     char_u	*fname_res = fname;
4482 #ifdef HAVE_READLINK
4483     char_u	fname_buf[MAXPATHL];
4484 
4485     // Expand symlink in the file name, so that we put the swap file with the
4486     // actual file instead of with the symlink.
4487     if (resolve_symlink(fname, fname_buf) == OK)
4488 	fname_res = fname_buf;
4489 #endif
4490 
4491 #if defined(UNIX) || defined(MSWIN)  // Need _very_ long file names
4492     int		len = (int)STRLEN(dir_name);
4493 
4494     s = dir_name + len;
4495     if (after_pathsep(dir_name, s) && len > 1 && s[-1] == s[-2])
4496     {			       // Ends with '//', Use Full path
4497 	r = NULL;
4498 	if ((s = make_percent_swname(dir_name, fname_res)) != NULL)
4499 	{
4500 	    r = modname(s, (char_u *)".swp", FALSE);
4501 	    vim_free(s);
4502 	}
4503 	return r;
4504     }
4505 #endif
4506 
4507     r = buf_modname(
4508 	    (buf->b_p_sn || buf->b_shortname),
4509 	    fname_res,
4510 	    (char_u *)
4511 #if defined(VMS)
4512 	    "_swp",
4513 #else
4514 	    ".swp",
4515 #endif
4516 	    // Prepend a '.' to the swap file name for the current directory.
4517 	    dir_name[0] == '.' && dir_name[1] == NUL);
4518     if (r == NULL)	    // out of memory
4519 	return NULL;
4520 
4521     s = get_file_in_dir(r, dir_name);
4522     vim_free(r);
4523     return s;
4524 }
4525 
4526 /*
4527  * Get file name to use for swap file or backup file.
4528  * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
4529  * option "dname".
4530  * - If "dname" is ".", return "fname" (swap file in dir of file).
4531  * - If "dname" starts with "./", insert "dname" in "fname" (swap file
4532  *   relative to dir of file).
4533  * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
4534  *   dir).
4535  *
4536  * The return value is an allocated string and can be NULL.
4537  */
4538     char_u *
get_file_in_dir(char_u * fname,char_u * dname)4539 get_file_in_dir(
4540     char_u  *fname,
4541     char_u  *dname)	// don't use "dirname", it is a global for Alpha
4542 {
4543     char_u	*t;
4544     char_u	*tail;
4545     char_u	*retval;
4546     int		save_char;
4547 
4548     tail = gettail(fname);
4549 
4550     if (dname[0] == '.' && dname[1] == NUL)
4551 	retval = vim_strsave(fname);
4552     else if (dname[0] == '.' && vim_ispathsep(dname[1]))
4553     {
4554 	if (tail == fname)	    // no path before file name
4555 	    retval = concat_fnames(dname + 2, tail, TRUE);
4556 	else
4557 	{
4558 	    save_char = *tail;
4559 	    *tail = NUL;
4560 	    t = concat_fnames(fname, dname + 2, TRUE);
4561 	    *tail = save_char;
4562 	    if (t == NULL)	    // out of memory
4563 		retval = NULL;
4564 	    else
4565 	    {
4566 		retval = concat_fnames(t, tail, TRUE);
4567 		vim_free(t);
4568 	    }
4569 	}
4570     }
4571     else
4572 	retval = concat_fnames(dname, tail, TRUE);
4573 
4574 #ifdef MSWIN
4575     if (retval != NULL)
4576 	for (t = gettail(retval); *t != NUL; MB_PTR_ADV(t))
4577 	    if (*t == ':')
4578 		*t = '%';
4579 #endif
4580 
4581     return retval;
4582 }
4583 
4584 /*
4585  * Print the ATTENTION message: info about an existing swap file.
4586  */
4587     static void
attention_message(buf_T * buf,char_u * fname)4588 attention_message(
4589     buf_T   *buf,	// buffer being edited
4590     char_u  *fname)	// swap file name
4591 {
4592     stat_T	st;
4593     time_t	swap_mtime;
4594 
4595     ++no_wait_return;
4596     (void)emsg(_("E325: ATTENTION"));
4597     msg_puts(_("\nFound a swap file by the name \""));
4598     msg_home_replace(fname);
4599     msg_puts("\"\n");
4600     swap_mtime = swapfile_info(fname);
4601     msg_puts(_("While opening file \""));
4602     msg_outtrans(buf->b_fname);
4603     msg_puts("\"\n");
4604     if (mch_stat((char *)buf->b_fname, &st) == -1)
4605     {
4606 	msg_puts(_("      CANNOT BE FOUND"));
4607     }
4608     else
4609     {
4610 	msg_puts(_("             dated: "));
4611 	msg_puts(get_ctime(st.st_mtime, TRUE));
4612 	if (swap_mtime != 0 && st.st_mtime > swap_mtime)
4613 	    msg_puts(_("      NEWER than swap file!\n"));
4614     }
4615     // Some of these messages are long to allow translation to
4616     // other languages.
4617     msg_puts(_("\n(1) Another program may be editing the same file.  If this is the case,\n    be careful not to end up with two different instances of the same\n    file when making changes.  Quit, or continue with caution.\n"));
4618     msg_puts(_("(2) An edit session for this file crashed.\n"));
4619     msg_puts(_("    If this is the case, use \":recover\" or \"vim -r "));
4620     msg_outtrans(buf->b_fname);
4621     msg_puts(_("\"\n    to recover the changes (see \":help recovery\").\n"));
4622     msg_puts(_("    If you did this already, delete the swap file \""));
4623     msg_outtrans(fname);
4624     msg_puts(_("\"\n    to avoid this message.\n"));
4625     cmdline_row = msg_row;
4626     --no_wait_return;
4627 }
4628 
4629 #if defined(FEAT_EVAL)
4630 /*
4631  * Trigger the SwapExists autocommands.
4632  * Returns a value for equivalent to do_dialog() (see below):
4633  * 0: still need to ask for a choice
4634  * 1: open read-only
4635  * 2: edit anyway
4636  * 3: recover
4637  * 4: delete it
4638  * 5: quit
4639  * 6: abort
4640  */
4641     static int
do_swapexists(buf_T * buf,char_u * fname)4642 do_swapexists(buf_T *buf, char_u *fname)
4643 {
4644     set_vim_var_string(VV_SWAPNAME, fname, -1);
4645     set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4646 
4647     // Trigger SwapExists autocommands with <afile> set to the file being
4648     // edited.  Disallow changing directory here.
4649     ++allbuf_lock;
4650     apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
4651     --allbuf_lock;
4652 
4653     set_vim_var_string(VV_SWAPNAME, NULL, -1);
4654 
4655     switch (*get_vim_var_str(VV_SWAPCHOICE))
4656     {
4657 	case 'o': return 1;
4658 	case 'e': return 2;
4659 	case 'r': return 3;
4660 	case 'd': return 4;
4661 	case 'q': return 5;
4662 	case 'a': return 6;
4663     }
4664 
4665     return 0;
4666 }
4667 #endif
4668 
4669 /*
4670  * Find out what name to use for the swap file for buffer 'buf'.
4671  *
4672  * Several names are tried to find one that does not exist
4673  * Returns the name in allocated memory or NULL.
4674  * When out of memory "dirp" is set to NULL.
4675  *
4676  * Note: If BASENAMELEN is not correct, you will get error messages for
4677  *	 not being able to open the swap or undo file
4678  * Note: May trigger SwapExists autocmd, pointers may change!
4679  */
4680     static char_u *
findswapname(buf_T * buf,char_u ** dirp,char_u * old_fname)4681 findswapname(
4682     buf_T	*buf,
4683     char_u	**dirp,		// pointer to list of directories
4684     char_u	*old_fname)	// don't give warning for this file name
4685 {
4686     char_u	*fname;
4687     int		n;
4688     char_u	*dir_name;
4689 #ifdef AMIGA
4690     BPTR	fh;
4691 #endif
4692     int		r;
4693     char_u	*buf_fname = buf->b_fname;
4694 
4695 #if !defined(UNIX)
4696 # define CREATE_DUMMY_FILE
4697     FILE	*dummyfd = NULL;
4698 
4699 # ifdef MSWIN
4700     if (buf_fname != NULL && !mch_isFullName(buf_fname)
4701 				       && vim_strchr(gettail(buf_fname), ':'))
4702     {
4703 	char_u *t;
4704 
4705 	buf_fname = vim_strsave(buf_fname);
4706 	if (buf_fname == NULL)
4707 	    buf_fname = buf->b_fname;
4708 	else
4709 	    for (t = gettail(buf_fname); *t != NUL; MB_PTR_ADV(t))
4710 		if (*t == ':')
4711 		    *t = '%';
4712     }
4713 # endif
4714 
4715     /*
4716      * If we start editing a new file, e.g. "test.doc", which resides on an
4717      * MSDOS compatible filesystem, it is possible that the file
4718      * "test.doc.swp" which we create will be exactly the same file. To avoid
4719      * this problem we temporarily create "test.doc".  Don't do this when the
4720      * check below for a 8.3 file name is used.
4721      */
4722     if (!(buf->b_p_sn || buf->b_shortname) && buf_fname != NULL
4723 					     && mch_getperm(buf_fname) < 0)
4724 	dummyfd = mch_fopen((char *)buf_fname, "w");
4725 #endif
4726 
4727     /*
4728      * Isolate a directory name from *dirp and put it in dir_name.
4729      * First allocate some memory to put the directory name in.
4730      */
4731     dir_name = alloc(STRLEN(*dirp) + 1);
4732     if (dir_name == NULL)
4733 	*dirp = NULL;
4734     else
4735 	(void)copy_option_part(dirp, dir_name, 31000, ",");
4736 
4737     /*
4738      * we try different names until we find one that does not exist yet
4739      */
4740     if (dir_name == NULL)	    // out of memory
4741 	fname = NULL;
4742     else
4743 	fname = makeswapname(buf_fname, buf->b_ffname, buf, dir_name);
4744 
4745     for (;;)
4746     {
4747 	if (fname == NULL)	// must be out of memory
4748 	    break;
4749 	if ((n = (int)STRLEN(fname)) == 0)	// safety check
4750 	{
4751 	    VIM_CLEAR(fname);
4752 	    break;
4753 	}
4754 #if defined(UNIX)
4755 /*
4756  * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4757  * file names. If this is the first try and the swap file name does not fit in
4758  * 8.3, detect if this is the case, set shortname and try again.
4759  */
4760 	if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4761 					&& !(buf->b_p_sn || buf->b_shortname))
4762 	{
4763 	    char_u	    *tail;
4764 	    char_u	    *fname2;
4765 	    stat_T	    s1, s2;
4766 	    int		    f1, f2;
4767 	    int		    created1 = FALSE, created2 = FALSE;
4768 	    int		    same = FALSE;
4769 
4770 	    /*
4771 	     * Check if swapfile name does not fit in 8.3:
4772 	     * It either contains two dots, is longer than 8 chars, or starts
4773 	     * with a dot.
4774 	     */
4775 	    tail = gettail(buf_fname);
4776 	    if (       vim_strchr(tail, '.') != NULL
4777 		    || STRLEN(tail) > (size_t)8
4778 		    || *gettail(fname) == '.')
4779 	    {
4780 		fname2 = alloc(n + 2);
4781 		if (fname2 != NULL)
4782 		{
4783 		    STRCPY(fname2, fname);
4784 		    // if fname == "xx.xx.swp",	    fname2 = "xx.xx.swx"
4785 		    // if fname == ".xx.swp",	    fname2 = ".xx.swpx"
4786 		    // if fname == "123456789.swp", fname2 = "12345678x.swp"
4787 		    if (vim_strchr(tail, '.') != NULL)
4788 			fname2[n - 1] = 'x';
4789 		    else if (*gettail(fname) == '.')
4790 		    {
4791 			fname2[n] = 'x';
4792 			fname2[n + 1] = NUL;
4793 		    }
4794 		    else
4795 			fname2[n - 5] += 1;
4796 		    /*
4797 		     * may need to create the files to be able to use mch_stat()
4798 		     */
4799 		    f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4800 		    if (f1 < 0)
4801 		    {
4802 			f1 = mch_open_rw((char *)fname,
4803 					       O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4804 			created1 = TRUE;
4805 		    }
4806 		    if (f1 >= 0)
4807 		    {
4808 			f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4809 			if (f2 < 0)
4810 			{
4811 			    f2 = mch_open_rw((char *)fname2,
4812 					       O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4813 			    created2 = TRUE;
4814 			}
4815 			if (f2 >= 0)
4816 			{
4817 			    /*
4818 			     * Both files exist now. If mch_stat() returns the
4819 			     * same device and inode they are the same file.
4820 			     */
4821 			    if (mch_fstat(f1, &s1) != -1
4822 				    && mch_fstat(f2, &s2) != -1
4823 				    && s1.st_dev == s2.st_dev
4824 				    && s1.st_ino == s2.st_ino)
4825 				same = TRUE;
4826 			    close(f2);
4827 			    if (created2)
4828 				mch_remove(fname2);
4829 			}
4830 			close(f1);
4831 			if (created1)
4832 			    mch_remove(fname);
4833 		    }
4834 		    vim_free(fname2);
4835 		    if (same)
4836 		    {
4837 			buf->b_shortname = TRUE;
4838 			vim_free(fname);
4839 			fname = makeswapname(buf_fname, buf->b_ffname,
4840 							       buf, dir_name);
4841 			continue;	// try again with b_shortname set
4842 		    }
4843 		}
4844 	    }
4845 	}
4846 #endif
4847 	/*
4848 	 * check if the swapfile already exists
4849 	 */
4850 	if (mch_getperm(fname) < 0)	// it does not exist
4851 	{
4852 #ifdef HAVE_LSTAT
4853 	    stat_T	sb;
4854 
4855 	    /*
4856 	     * Extra security check: When a swap file is a symbolic link, this
4857 	     * is most likely a symlink attack.
4858 	     */
4859 	    if (mch_lstat((char *)fname, &sb) < 0)
4860 #else
4861 # ifdef AMIGA
4862 	    fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4863 	    /*
4864 	     * on the Amiga mch_getperm() will return -1 when the file exists
4865 	     * but is being used by another program. This happens if you edit
4866 	     * a file twice.
4867 	     */
4868 	    if (fh != (BPTR)NULL)	// can open file, OK
4869 	    {
4870 		Close(fh);
4871 		mch_remove(fname);
4872 		break;
4873 	    }
4874 	    if (IoErr() != ERROR_OBJECT_IN_USE
4875 					    && IoErr() != ERROR_OBJECT_EXISTS)
4876 # endif
4877 #endif
4878 		break;
4879 	}
4880 
4881 	/*
4882 	 * A file name equal to old_fname is OK to use.
4883 	 */
4884 	if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4885 	    break;
4886 
4887 	/*
4888 	 * get here when file already exists
4889 	 */
4890 	if (fname[n - 2] == 'w' && fname[n - 1] == 'p')	// first try
4891 	{
4892 	    /*
4893 	     * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4894 	     * and file.doc are the same file. To guess if this problem is
4895 	     * present try if file.doc.swx exists. If it does, we set
4896 	     * buf->b_shortname and try file_doc.swp (dots replaced by
4897 	     * underscores for this file), and try again. If it doesn't we
4898 	     * assume that "file.doc.swp" already exists.
4899 	     */
4900 	    if (!(buf->b_p_sn || buf->b_shortname))	// not tried yet
4901 	    {
4902 		fname[n - 1] = 'x';
4903 		r = mch_getperm(fname);		// try "file.swx"
4904 		fname[n - 1] = 'p';
4905 		if (r >= 0)		    // "file.swx" seems to exist
4906 		{
4907 		    buf->b_shortname = TRUE;
4908 		    vim_free(fname);
4909 		    fname = makeswapname(buf_fname, buf->b_ffname,
4910 							       buf, dir_name);
4911 		    continue;	    // try again with '.' replaced with '_'
4912 		}
4913 	    }
4914 	    /*
4915 	     * If we get here the ".swp" file really exists.
4916 	     * Give an error message, unless recovering, no file name, we are
4917 	     * viewing a help file or when the path of the file is different
4918 	     * (happens when all .swp files are in one directory).
4919 	     */
4920 	    if (!recoverymode && buf_fname != NULL
4921 				&& !buf->b_help
4922 				&& !(buf->b_flags & (BF_DUMMY | BF_NO_SEA)))
4923 	    {
4924 		int		fd;
4925 		struct block0	b0;
4926 		int		differ = FALSE;
4927 
4928 		/*
4929 		 * Try to read block 0 from the swap file to get the original
4930 		 * file name (and inode number).
4931 		 */
4932 		fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4933 		if (fd >= 0)
4934 		{
4935 		    if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
4936 		    {
4937 			/*
4938 			 * If the swapfile has the same directory as the
4939 			 * buffer don't compare the directory names, they can
4940 			 * have a different mountpoint.
4941 			 */
4942 			if (b0.b0_flags & B0_SAME_DIR)
4943 			{
4944 			    if (fnamecmp(gettail(buf->b_ffname),
4945 						   gettail(b0.b0_fname)) != 0
4946 				    || !same_directory(fname, buf->b_ffname))
4947 			    {
4948 #ifdef CHECK_INODE
4949 				// Symlinks may point to the same file even
4950 				// when the name differs, need to check the
4951 				// inode too.
4952 				expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4953 				if (fnamecmp_ino(buf->b_ffname, NameBuff,
4954 						     char_to_long(b0.b0_ino)))
4955 #endif
4956 				    differ = TRUE;
4957 			    }
4958 			}
4959 			else
4960 			{
4961 			    /*
4962 			     * The name in the swap file may be
4963 			     * "~user/path/file".  Expand it first.
4964 			     */
4965 			    expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4966 #ifdef CHECK_INODE
4967 			    if (fnamecmp_ino(buf->b_ffname, NameBuff,
4968 						     char_to_long(b0.b0_ino)))
4969 				differ = TRUE;
4970 #else
4971 			    if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4972 				differ = TRUE;
4973 #endif
4974 			}
4975 		    }
4976 		    close(fd);
4977 		}
4978 
4979 		// give the ATTENTION message when there is an old swap file
4980 		// for the current file, and the buffer was not recovered.
4981 		if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4982 			&& vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4983 		{
4984 		    int		choice = 0;
4985 		    stat_T	st;
4986 #ifdef CREATE_DUMMY_FILE
4987 		    int		did_use_dummy = FALSE;
4988 
4989 		    // Avoid getting a warning for the file being created
4990 		    // outside of Vim, it was created at the start of this
4991 		    // function.  Delete the file now, because Vim might exit
4992 		    // here if the window is closed.
4993 		    if (dummyfd != NULL)
4994 		    {
4995 			fclose(dummyfd);
4996 			dummyfd = NULL;
4997 			mch_remove(buf_fname);
4998 			did_use_dummy = TRUE;
4999 		    }
5000 #endif
5001 
5002 #ifdef HAVE_PROCESS_STILL_RUNNING
5003 		    process_still_running = FALSE;
5004 #endif
5005 		    // It's safe to delete the swap file if all these are true:
5006 		    // - the edited file exists
5007 		    // - the swap file has no changes and looks OK
5008 		    if (mch_stat((char *)buf->b_fname, &st) == 0
5009 						  && swapfile_unchanged(fname))
5010 		    {
5011 			choice = 4;
5012 			if (p_verbose > 0)
5013 			    verb_msg(_("Found a swap file that is not useful, deleting it"));
5014 		    }
5015 
5016 #if defined(FEAT_EVAL)
5017 		    /*
5018 		     * If there is an SwapExists autocommand and we can handle
5019 		     * the response, trigger it.  It may return 0 to ask the
5020 		     * user anyway.
5021 		     */
5022 		    if (choice == 0
5023 			    && swap_exists_action != SEA_NONE
5024 			    && has_autocmd(EVENT_SWAPEXISTS, buf_fname, buf))
5025 			choice = do_swapexists(buf, fname);
5026 
5027 		    if (choice == 0)
5028 #endif
5029 		    {
5030 #ifdef FEAT_GUI
5031 			// If we are supposed to start the GUI but it wasn't
5032 			// completely started yet, start it now.  This makes
5033 			// the messages displayed in the Vim window when
5034 			// loading a session from the .gvimrc file.
5035 			if (gui.starting && !gui.in_use)
5036 			    gui_start(NULL);
5037 #endif
5038 			// Show info about the existing swap file.
5039 			attention_message(buf, fname);
5040 
5041 			// We don't want a 'q' typed at the more-prompt
5042 			// interrupt loading a file.
5043 			got_int = FALSE;
5044 
5045 			// If vimrc has "simalt ~x" we don't want it to
5046 			// interfere with the prompt here.
5047 			flush_buffers(FLUSH_TYPEAHEAD);
5048 		    }
5049 
5050 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
5051 		    if (swap_exists_action != SEA_NONE && choice == 0)
5052 		    {
5053 			char_u	*name;
5054 
5055 			name = alloc(STRLEN(fname)
5056 				+ STRLEN(_("Swap file \""))
5057 				+ STRLEN(_("\" already exists!")) + 5);
5058 			if (name != NULL)
5059 			{
5060 			    STRCPY(name, _("Swap file \""));
5061 			    home_replace(NULL, fname, name + STRLEN(name),
5062 								  1000, TRUE);
5063 			    STRCAT(name, _("\" already exists!"));
5064 			}
5065 			choice = do_dialog(VIM_WARNING,
5066 				    (char_u *)_("VIM - ATTENTION"),
5067 				    name == NULL
5068 					?  (char_u *)_("Swap file already exists!")
5069 					: name,
5070 # ifdef HAVE_PROCESS_STILL_RUNNING
5071 				    process_still_running
5072 					? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
5073 # endif
5074 					(char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL, FALSE);
5075 
5076 # ifdef HAVE_PROCESS_STILL_RUNNING
5077 			if (process_still_running && choice >= 4)
5078 			    choice++;	// Skip missing "Delete it" button
5079 # endif
5080 			vim_free(name);
5081 
5082 			// pretend screen didn't scroll, need redraw anyway
5083 			msg_scrolled = 0;
5084 			redraw_all_later(NOT_VALID);
5085 		    }
5086 #endif
5087 
5088 		    if (choice > 0)
5089 		    {
5090 			switch (choice)
5091 			{
5092 			    case 1:
5093 				buf->b_p_ro = TRUE;
5094 				break;
5095 			    case 2:
5096 				break;
5097 			    case 3:
5098 				swap_exists_action = SEA_RECOVER;
5099 				break;
5100 			    case 4:
5101 				mch_remove(fname);
5102 				break;
5103 			    case 5:
5104 				swap_exists_action = SEA_QUIT;
5105 				break;
5106 			    case 6:
5107 				swap_exists_action = SEA_QUIT;
5108 				got_int = TRUE;
5109 				break;
5110 			}
5111 
5112 			// If the file was deleted this fname can be used.
5113 			if (mch_getperm(fname) < 0)
5114 			    break;
5115 		    }
5116 		    else
5117 		    {
5118 			msg_puts("\n");
5119 			if (msg_silent == 0)
5120 			    // call wait_return() later
5121 			    need_wait_return = TRUE;
5122 		    }
5123 
5124 #ifdef CREATE_DUMMY_FILE
5125 		    // Going to try another name, need the dummy file again.
5126 		    if (did_use_dummy)
5127 			dummyfd = mch_fopen((char *)buf_fname, "w");
5128 #endif
5129 		}
5130 	    }
5131 	}
5132 
5133 	/*
5134 	 * Change the ".swp" extension to find another file that can be used.
5135 	 * First decrement the last char: ".swo", ".swn", etc.
5136 	 * If that still isn't enough decrement the last but one char: ".svz"
5137 	 * Can happen when editing many "No Name" buffers.
5138 	 */
5139 	if (fname[n - 1] == 'a')	// ".s?a"
5140 	{
5141 	    if (fname[n - 2] == 'a')    // ".saa": tried enough, give up
5142 	    {
5143 		emsg(_("E326: Too many swap files found"));
5144 		VIM_CLEAR(fname);
5145 		break;
5146 	    }
5147 	    --fname[n - 2];		// ".svz", ".suz", etc.
5148 	    fname[n - 1] = 'z' + 1;
5149 	}
5150 	--fname[n - 1];			// ".swo", ".swn", etc.
5151     }
5152 
5153     vim_free(dir_name);
5154 #ifdef CREATE_DUMMY_FILE
5155     if (dummyfd != NULL)	// file has been created temporarily
5156     {
5157 	fclose(dummyfd);
5158 	mch_remove(buf_fname);
5159     }
5160 #endif
5161 #ifdef MSWIN
5162     if (buf_fname != buf->b_fname)
5163 	vim_free(buf_fname);
5164 #endif
5165     return fname;
5166 }
5167 
5168     static int
b0_magic_wrong(ZERO_BL * b0p)5169 b0_magic_wrong(ZERO_BL *b0p)
5170 {
5171     return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
5172 	    || b0p->b0_magic_int != (int)B0_MAGIC_INT
5173 	    || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
5174 	    || b0p->b0_magic_char != B0_MAGIC_CHAR);
5175 }
5176 
5177 #ifdef CHECK_INODE
5178 /*
5179  * Compare current file name with file name from swap file.
5180  * Try to use inode numbers when possible.
5181  * Return non-zero when files are different.
5182  *
5183  * When comparing file names a few things have to be taken into consideration:
5184  * - When working over a network the full path of a file depends on the host.
5185  *   We check the inode number if possible.  It is not 100% reliable though,
5186  *   because the device number cannot be used over a network.
5187  * - When a file does not exist yet (editing a new file) there is no inode
5188  *   number.
5189  * - The file name in a swap file may not be valid on the current host.  The
5190  *   "~user" form is used whenever possible to avoid this.
5191  *
5192  * This is getting complicated, let's make a table:
5193  *
5194  *		ino_c  ino_s  fname_c  fname_s	differ =
5195  *
5196  * both files exist -> compare inode numbers:
5197  *		!= 0   != 0	X	 X	ino_c != ino_s
5198  *
5199  * inode number(s) unknown, file names available -> compare file names
5200  *		== 0	X	OK	 OK	fname_c != fname_s
5201  *		 X     == 0	OK	 OK	fname_c != fname_s
5202  *
5203  * current file doesn't exist, file for swap file exist, file name(s) not
5204  * available -> probably different
5205  *		== 0   != 0    FAIL	 X	TRUE
5206  *		== 0   != 0	X	FAIL	TRUE
5207  *
5208  * current file exists, inode for swap unknown, file name(s) not
5209  * available -> probably different
5210  *		!= 0   == 0    FAIL	 X	TRUE
5211  *		!= 0   == 0	X	FAIL	TRUE
5212  *
5213  * current file doesn't exist, inode for swap unknown, one file name not
5214  * available -> probably different
5215  *		== 0   == 0    FAIL	 OK	TRUE
5216  *		== 0   == 0	OK	FAIL	TRUE
5217  *
5218  * current file doesn't exist, inode for swap unknown, both file names not
5219  * available -> compare file names
5220  *		== 0   == 0    FAIL	FAIL	fname_c != fname_s
5221  *
5222  * Note that when the ino_t is 64 bits, only the last 32 will be used.  This
5223  * can't be changed without making the block 0 incompatible with 32 bit
5224  * versions.
5225  */
5226 
5227     static int
fnamecmp_ino(char_u * fname_c,char_u * fname_s,long ino_block0)5228 fnamecmp_ino(
5229     char_u	*fname_c,	    // current file name
5230     char_u	*fname_s,	    // file name from swap file
5231     long	ino_block0)
5232 {
5233     stat_T	st;
5234     ino_t	ino_c = 0;	    // ino of current file
5235     ino_t	ino_s;		    // ino of file from swap file
5236     char_u	buf_c[MAXPATHL];    // full path of fname_c
5237     char_u	buf_s[MAXPATHL];    // full path of fname_s
5238     int		retval_c;	    // flag: buf_c valid
5239     int		retval_s;	    // flag: buf_s valid
5240 
5241     if (mch_stat((char *)fname_c, &st) == 0)
5242 	ino_c = (ino_t)st.st_ino;
5243 
5244     /*
5245      * First we try to get the inode from the file name, because the inode in
5246      * the swap file may be outdated.  If that fails (e.g. this path is not
5247      * valid on this machine), use the inode from block 0.
5248      */
5249     if (mch_stat((char *)fname_s, &st) == 0)
5250 	ino_s = (ino_t)st.st_ino;
5251     else
5252 	ino_s = (ino_t)ino_block0;
5253 
5254     if (ino_c && ino_s)
5255 	return (ino_c != ino_s);
5256 
5257     /*
5258      * One of the inode numbers is unknown, try a forced vim_FullName() and
5259      * compare the file names.
5260      */
5261     retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
5262     retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
5263     if (retval_c == OK && retval_s == OK)
5264 	return STRCMP(buf_c, buf_s) != 0;
5265 
5266     /*
5267      * Can't compare inodes or file names, guess that the files are different,
5268      * unless both appear not to exist at all, then compare with the file name
5269      * in the swap file.
5270      */
5271     if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
5272 	return STRCMP(fname_c, fname_s) != 0;
5273     return TRUE;
5274 }
5275 #endif // CHECK_INODE
5276 
5277 /*
5278  * Move a long integer into a four byte character array.
5279  * Used for machine independency in block zero.
5280  */
5281     static void
long_to_char(long n,char_u * s)5282 long_to_char(long n, char_u *s)
5283 {
5284     s[0] = (char_u)(n & 0xff);
5285     n = (unsigned)n >> 8;
5286     s[1] = (char_u)(n & 0xff);
5287     n = (unsigned)n >> 8;
5288     s[2] = (char_u)(n & 0xff);
5289     n = (unsigned)n >> 8;
5290     s[3] = (char_u)(n & 0xff);
5291 }
5292 
5293     static long
char_to_long(char_u * s)5294 char_to_long(char_u *s)
5295 {
5296     long    retval;
5297 
5298     retval = s[3];
5299     retval <<= 8;
5300     retval |= s[2];
5301     retval <<= 8;
5302     retval |= s[1];
5303     retval <<= 8;
5304     retval |= s[0];
5305 
5306     return retval;
5307 }
5308 
5309 /*
5310  * Set the flags in the first block of the swap file:
5311  * - file is modified or not: buf->b_changed
5312  * - 'fileformat'
5313  * - 'fileencoding'
5314  */
5315     void
ml_setflags(buf_T * buf)5316 ml_setflags(buf_T *buf)
5317 {
5318     bhdr_T	*hp;
5319     ZERO_BL	*b0p;
5320 
5321     if (!buf->b_ml.ml_mfp)
5322 	return;
5323     for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
5324     {
5325 	if (hp->bh_bnum == 0)
5326 	{
5327 	    b0p = (ZERO_BL *)(hp->bh_data);
5328 	    b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
5329 	    b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
5330 						  | (get_fileformat(buf) + 1);
5331 	    add_b0_fenc(b0p, buf);
5332 	    hp->bh_flags |= BH_DIRTY;
5333 	    mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
5334 	    break;
5335 	}
5336     }
5337 }
5338 
5339 #if defined(FEAT_CRYPT) || defined(PROTO)
5340 /*
5341  * If "data" points to a data block encrypt the text in it and return a copy
5342  * in allocated memory.  Return NULL when out of memory.
5343  * Otherwise return "data".
5344  */
5345     char_u *
ml_encrypt_data(memfile_T * mfp,char_u * data,off_T offset,unsigned size)5346 ml_encrypt_data(
5347     memfile_T	*mfp,
5348     char_u	*data,
5349     off_T	offset,
5350     unsigned	size)
5351 {
5352     DATA_BL	*dp = (DATA_BL *)data;
5353     char_u	*head_end;
5354     char_u	*text_start;
5355     char_u	*new_data;
5356     int		text_len;
5357     cryptstate_T *state;
5358 
5359     if (dp->db_id != DATA_ID)
5360 	return data;
5361 
5362     state = ml_crypt_prepare(mfp, offset, FALSE);
5363     if (state == NULL)
5364 	return data;
5365 
5366     new_data = alloc(size);
5367     if (new_data == NULL)
5368 	return NULL;
5369     head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
5370     text_start = (char_u *)dp + dp->db_txt_start;
5371     text_len = size - dp->db_txt_start;
5372 
5373     // Copy the header and the text.
5374     mch_memmove(new_data, dp, head_end - (char_u *)dp);
5375 
5376     // Encrypt the text.
5377     crypt_encode(state, text_start, text_len, new_data + dp->db_txt_start,
5378 									FALSE);
5379     crypt_free_state(state);
5380 
5381     // Clear the gap.
5382     if (head_end < text_start)
5383 	vim_memset(new_data + (head_end - data), 0, text_start - head_end);
5384 
5385     return new_data;
5386 }
5387 
5388 /*
5389  * Decrypt the text in "data" if it points to an encrypted data block.
5390  */
5391     void
ml_decrypt_data(memfile_T * mfp,char_u * data,off_T offset,unsigned size)5392 ml_decrypt_data(
5393     memfile_T	*mfp,
5394     char_u	*data,
5395     off_T	offset,
5396     unsigned	size)
5397 {
5398     DATA_BL	*dp = (DATA_BL *)data;
5399     char_u	*head_end;
5400     char_u	*text_start;
5401     int		text_len;
5402     cryptstate_T *state;
5403 
5404     if (dp->db_id == DATA_ID)
5405     {
5406 	head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
5407 	text_start = (char_u *)dp + dp->db_txt_start;
5408 	text_len = dp->db_txt_end - dp->db_txt_start;
5409 
5410 	if (head_end > text_start || dp->db_txt_start > size
5411 						     || dp->db_txt_end > size)
5412 	    return;  // data was messed up
5413 
5414 	state = ml_crypt_prepare(mfp, offset, TRUE);
5415 	if (state != NULL)
5416 	{
5417 	    // Decrypt the text in place.
5418 	    crypt_decode_inplace(state, text_start, text_len, FALSE);
5419 	    crypt_free_state(state);
5420 	}
5421     }
5422 }
5423 
5424 /*
5425  * Prepare for encryption/decryption, using the key, seed and offset.
5426  * Return an allocated cryptstate_T *.
5427  */
5428     static cryptstate_T *
ml_crypt_prepare(memfile_T * mfp,off_T offset,int reading)5429 ml_crypt_prepare(memfile_T *mfp, off_T offset, int reading)
5430 {
5431     buf_T	*buf = mfp->mf_buffer;
5432     char_u	salt[50];
5433     int		method_nr;
5434     char_u	*key;
5435     char_u	*seed;
5436 
5437     if (reading && mfp->mf_old_key != NULL)
5438     {
5439 	// Reading back blocks with the previous key/method/seed.
5440 	method_nr = mfp->mf_old_cm;
5441 	key = mfp->mf_old_key;
5442 	seed = mfp->mf_old_seed;
5443     }
5444     else
5445     {
5446 	method_nr = crypt_get_method_nr(buf);
5447 	key = buf->b_p_key;
5448 	seed = mfp->mf_seed;
5449     }
5450     if (*key == NUL)
5451 	return NULL;
5452 
5453     if (method_nr == CRYPT_M_ZIP)
5454     {
5455 	// For PKzip: Append the offset to the key, so that we use a different
5456 	// key for every block.
5457 	vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
5458 	return crypt_create(method_nr, salt, NULL, 0, NULL, 0);
5459     }
5460 
5461     // Using blowfish or better: add salt and seed. We use the byte offset
5462     // of the block for the salt.
5463     vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
5464     return crypt_create(method_nr, key, salt, (int)STRLEN(salt),
5465 							seed, MF_SEED_LEN);
5466 }
5467 
5468 #endif
5469 
5470 
5471 #if defined(FEAT_BYTEOFF) || defined(PROTO)
5472 
5473 #define MLCS_MAXL 800	// max no of lines in chunk
5474 #define MLCS_MINL 400   // should be half of MLCS_MAXL
5475 
5476 /*
5477  * Keep information for finding byte offset of a line, updtype may be one of:
5478  * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
5479  *	   Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
5480  * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
5481  * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
5482  */
5483     static void
ml_updatechunk(buf_T * buf,linenr_T line,long len,int updtype)5484 ml_updatechunk(
5485     buf_T	*buf,
5486     linenr_T	line,
5487     long	len,
5488     int		updtype)
5489 {
5490     static buf_T	*ml_upd_lastbuf = NULL;
5491     static linenr_T	ml_upd_lastline;
5492     static linenr_T	ml_upd_lastcurline;
5493     static int		ml_upd_lastcurix;
5494 
5495     linenr_T		curline = ml_upd_lastcurline;
5496     int			curix = ml_upd_lastcurix;
5497     long		size;
5498     chunksize_T		*curchnk;
5499     int			rest;
5500     bhdr_T		*hp;
5501     DATA_BL		*dp;
5502 
5503     if (buf->b_ml.ml_usedchunks == -1 || len == 0)
5504 	return;
5505     if (buf->b_ml.ml_chunksize == NULL)
5506     {
5507 	buf->b_ml.ml_chunksize = ALLOC_MULT(chunksize_T, 100);
5508 	if (buf->b_ml.ml_chunksize == NULL)
5509 	{
5510 	    buf->b_ml.ml_usedchunks = -1;
5511 	    return;
5512 	}
5513 	buf->b_ml.ml_numchunks = 100;
5514 	buf->b_ml.ml_usedchunks = 1;
5515 	buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
5516 	buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
5517     }
5518 
5519     if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
5520     {
5521 	/*
5522 	 * First line in empty buffer from ml_flush_line() -- reset
5523 	 */
5524 	buf->b_ml.ml_usedchunks = 1;
5525 	buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
5526 	buf->b_ml.ml_chunksize[0].mlcs_totalsize = (long)buf->b_ml.ml_line_len;
5527 	return;
5528     }
5529 
5530     /*
5531      * Find chunk that our line belongs to, curline will be at start of the
5532      * chunk.
5533      */
5534     if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
5535 	    || updtype != ML_CHNK_ADDLINE)
5536     {
5537 	for (curline = 1, curix = 0;
5538 	     curix < buf->b_ml.ml_usedchunks - 1
5539 	     && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5540 	     curix++)
5541 	    curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5542     }
5543     else if (curix < buf->b_ml.ml_usedchunks - 1
5544 	      && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
5545     {
5546 	// Adjust cached curix & curline
5547 	curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5548 	curix++;
5549     }
5550     curchnk = buf->b_ml.ml_chunksize + curix;
5551 
5552     if (updtype == ML_CHNK_DELLINE)
5553 	len = -len;
5554     curchnk->mlcs_totalsize += len;
5555     if (updtype == ML_CHNK_ADDLINE)
5556     {
5557 	curchnk->mlcs_numlines++;
5558 
5559 	// May resize here so we don't have to do it in both cases below
5560 	if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
5561 	{
5562 	    chunksize_T *t_chunksize = buf->b_ml.ml_chunksize;
5563 
5564 	    buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
5565 	    buf->b_ml.ml_chunksize = vim_realloc(buf->b_ml.ml_chunksize,
5566 			    sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5567 	    if (buf->b_ml.ml_chunksize == NULL)
5568 	    {
5569 		// Hmmmm, Give up on offset for this buffer
5570 		vim_free(t_chunksize);
5571 		buf->b_ml.ml_usedchunks = -1;
5572 		return;
5573 	    }
5574 	}
5575 
5576 	if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5577 	{
5578 	    int	    count;	    // number of entries in block
5579 	    int	    idx;
5580 	    int	    end_idx;
5581 	    int	    text_end;
5582 	    int	    linecnt;
5583 
5584 	    mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5585 			buf->b_ml.ml_chunksize + curix,
5586 			(buf->b_ml.ml_usedchunks - curix) *
5587 			sizeof(chunksize_T));
5588 	    // Compute length of first half of lines in the split chunk
5589 	    size = 0;
5590 	    linecnt = 0;
5591 	    while (curline < buf->b_ml.ml_line_count
5592 			&& linecnt < MLCS_MINL)
5593 	    {
5594 		if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5595 		{
5596 		    buf->b_ml.ml_usedchunks = -1;
5597 		    return;
5598 		}
5599 		dp = (DATA_BL *)(hp->bh_data);
5600 		count = (long)(buf->b_ml.ml_locked_high) -
5601 			(long)(buf->b_ml.ml_locked_low) + 1;
5602 		idx = curline - buf->b_ml.ml_locked_low;
5603 		curline = buf->b_ml.ml_locked_high + 1;
5604 
5605 		// compute index of last line to use in this MEMLINE
5606 		rest = count - idx;
5607 		if (linecnt + rest > MLCS_MINL)
5608 		{
5609 		    end_idx = idx + MLCS_MINL - linecnt - 1;
5610 		    linecnt = MLCS_MINL;
5611 		}
5612 		else
5613 		{
5614 		    end_idx = count - 1;
5615 		    linecnt += rest;
5616 		}
5617 #ifdef FEAT_PROP_POPUP
5618 		if (buf->b_has_textprop)
5619 		{
5620 		    int i;
5621 
5622 		    // We cannot use the text pointers to get the text length,
5623 		    // the text prop info would also be counted.  Go over the
5624 		    // lines.
5625 		    for (i = end_idx; i < idx; ++i)
5626 			size += (int)STRLEN((char_u *)dp + (dp->db_index[i] & DB_INDEX_MASK)) + 1;
5627 		}
5628 		else
5629 #endif
5630 		{
5631 		    if (idx == 0) // first line in block, text at the end
5632 			text_end = dp->db_txt_end;
5633 		    else
5634 			text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5635 		    size += text_end - ((dp->db_index[end_idx]) & DB_INDEX_MASK);
5636 		}
5637 	    }
5638 	    buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5639 	    buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5640 	    buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5641 	    buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5642 	    buf->b_ml.ml_usedchunks++;
5643 	    ml_upd_lastbuf = NULL;   // Force recalc of curix & curline
5644 	    return;
5645 	}
5646 	else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5647 		     && curix == buf->b_ml.ml_usedchunks - 1
5648 		     && buf->b_ml.ml_line_count - line <= 1)
5649 	{
5650 	    /*
5651 	     * We are in the last chunk and it is cheap to create a new one
5652 	     * after this. Do it now to avoid the loop above later on
5653 	     */
5654 	    curchnk = buf->b_ml.ml_chunksize + curix + 1;
5655 	    buf->b_ml.ml_usedchunks++;
5656 	    if (line == buf->b_ml.ml_line_count)
5657 	    {
5658 		curchnk->mlcs_numlines = 0;
5659 		curchnk->mlcs_totalsize = 0;
5660 	    }
5661 	    else
5662 	    {
5663 		/*
5664 		 * Line is just prior to last, move count for last
5665 		 * This is the common case  when loading a new file
5666 		 */
5667 		hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5668 		if (hp == NULL)
5669 		{
5670 		    buf->b_ml.ml_usedchunks = -1;
5671 		    return;
5672 		}
5673 		dp = (DATA_BL *)(hp->bh_data);
5674 		if (dp->db_line_count == 1)
5675 		    rest = dp->db_txt_end - dp->db_txt_start;
5676 		else
5677 		    rest =
5678 			((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5679 			- dp->db_txt_start;
5680 		curchnk->mlcs_totalsize = rest;
5681 		curchnk->mlcs_numlines = 1;
5682 		curchnk[-1].mlcs_totalsize -= rest;
5683 		curchnk[-1].mlcs_numlines -= 1;
5684 	    }
5685 	}
5686     }
5687     else if (updtype == ML_CHNK_DELLINE)
5688     {
5689 	curchnk->mlcs_numlines--;
5690 	ml_upd_lastbuf = NULL;   // Force recalc of curix & curline
5691 	if (curix < (buf->b_ml.ml_usedchunks - 1)
5692 		&& (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5693 		   <= MLCS_MINL)
5694 	{
5695 	    curix++;
5696 	    curchnk = buf->b_ml.ml_chunksize + curix;
5697 	}
5698 	else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5699 	{
5700 	    buf->b_ml.ml_usedchunks--;
5701 	    mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5702 			buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5703 	    return;
5704 	}
5705 	else if (curix == 0 || (curchnk->mlcs_numlines > 10
5706 		    && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5707 		       > MLCS_MINL))
5708 	{
5709 	    return;
5710 	}
5711 
5712 	// Collapse chunks
5713 	curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5714 	curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5715 	buf->b_ml.ml_usedchunks--;
5716 	if (curix < buf->b_ml.ml_usedchunks)
5717 	{
5718 	    mch_memmove(buf->b_ml.ml_chunksize + curix,
5719 			buf->b_ml.ml_chunksize + curix + 1,
5720 			(buf->b_ml.ml_usedchunks - curix) *
5721 			sizeof(chunksize_T));
5722 	}
5723 	return;
5724     }
5725     ml_upd_lastbuf = buf;
5726     ml_upd_lastline = line;
5727     ml_upd_lastcurline = curline;
5728     ml_upd_lastcurix = curix;
5729 }
5730 
5731 /*
5732  * Find offset for line or line with offset.
5733  * Find line with offset if "lnum" is 0; return remaining offset in offp
5734  * Find offset of line if "lnum" > 0
5735  * return -1 if information is not available
5736  */
5737     long
ml_find_line_or_offset(buf_T * buf,linenr_T lnum,long * offp)5738 ml_find_line_or_offset(buf_T *buf, linenr_T lnum, long *offp)
5739 {
5740     linenr_T	curline;
5741     int		curix;
5742     long	size;
5743     bhdr_T	*hp;
5744     DATA_BL	*dp;
5745     int		count;		// number of entries in block
5746     int		idx;
5747     int		start_idx;
5748     int		text_end;
5749     long	offset;
5750     int		len;
5751     int		ffdos = (get_fileformat(buf) == EOL_DOS);
5752     int		extra = 0;
5753 
5754     // take care of cached line first
5755     ml_flush_line(curbuf);
5756 
5757     if (buf->b_ml.ml_usedchunks == -1
5758 	    || buf->b_ml.ml_chunksize == NULL
5759 	    || lnum < 0)
5760 	return -1;
5761 
5762     if (offp == NULL)
5763 	offset = 0;
5764     else
5765 	offset = *offp;
5766     if (lnum == 0 && offset <= 0)
5767 	return 1;   // Not a "find offset" and offset 0 _must_ be in line 1
5768     /*
5769      * Find the last chunk before the one containing our line. Last chunk is
5770      * special because it will never qualify.
5771      */
5772     curline = 1;
5773     curix = size = 0;
5774     while (curix < buf->b_ml.ml_usedchunks - 1
5775 	    && ((lnum != 0
5776 	     && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
5777 		|| (offset != 0
5778 	       && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5779 		      + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5780     {
5781 	curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5782 	size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5783 	if (offset && ffdos)
5784 	    size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5785 	curix++;
5786     }
5787 
5788     while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
5789     {
5790 #ifdef FEAT_PROP_POPUP
5791 	size_t textprop_total = 0;
5792 #endif
5793 
5794 	if (curline > buf->b_ml.ml_line_count
5795 		|| (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5796 	    return -1;
5797 	dp = (DATA_BL *)(hp->bh_data);
5798 	count = (long)(buf->b_ml.ml_locked_high) -
5799 		(long)(buf->b_ml.ml_locked_low) + 1;
5800 	start_idx = idx = curline - buf->b_ml.ml_locked_low;
5801 	if (idx == 0)  // first line in block, text at the end
5802 	    text_end = dp->db_txt_end;
5803 	else
5804 	    text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5805 	// Compute index of last line to use in this MEMLINE
5806 	if (lnum != 0)
5807 	{
5808 	    if (curline + (count - idx) >= lnum)
5809 		idx += lnum - curline - 1;
5810 	    else
5811 		idx = count - 1;
5812 	}
5813 	else
5814 	{
5815 	    extra = 0;
5816 	    for (;;)
5817 	    {
5818 #ifdef FEAT_PROP_POPUP
5819 		size_t textprop_size = 0;
5820 
5821 		if (buf->b_has_textprop)
5822 		{
5823 		    char_u *l1, *l2;
5824 
5825 		    // compensate for the extra bytes taken by textprops
5826 		    l1 = (char_u *)dp + ((dp->db_index[idx]) & DB_INDEX_MASK);
5827 		    l2 = (char_u *)dp + (idx == 0 ? dp->db_txt_end
5828 				  : ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5829 		    textprop_size = (l2 - l1) - (STRLEN(l1) + 1);
5830 		}
5831 #endif
5832 		if (!(offset >= size
5833 			+ text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5834 #ifdef FEAT_PROP_POPUP
5835 			- (long)(textprop_total + textprop_size)
5836 #endif
5837 			+ ffdos))
5838 		    break;
5839 
5840 		if (ffdos)
5841 		    size++;
5842 #ifdef FEAT_PROP_POPUP
5843 		textprop_total += textprop_size;
5844 #endif
5845 		if (idx == count - 1)
5846 		{
5847 		    extra = 1;
5848 		    break;
5849 		}
5850 		idx++;
5851 	    }
5852 	}
5853 #ifdef FEAT_PROP_POPUP
5854 	if (buf->b_has_textprop && lnum != 0)
5855 	{
5856 	    int i;
5857 
5858 	    // cannot use the db_index pointer, need to get the actual text
5859 	    // lengths.
5860 	    len = 0;
5861 	    for (i = start_idx; i <= idx; ++i)
5862 	    {
5863 		char_u *p = (char_u *)dp + ((dp->db_index[i]) & DB_INDEX_MASK);
5864 		len += (int)STRLEN(p) + 1;
5865 	    }
5866 	}
5867 	else
5868 #endif
5869 	    len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK)
5870 #ifdef FEAT_PROP_POPUP
5871 				- (long)textprop_total
5872 #endif
5873 				;
5874 	size += len;
5875 	if (offset != 0 && size >= offset)
5876 	{
5877 	    if (size + ffdos == offset)
5878 		*offp = 0;
5879 	    else if (idx == start_idx)
5880 		*offp = offset - size + len;
5881 	    else
5882 		*offp = offset - size + len
5883 		     - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK))
5884 #ifdef FEAT_PROP_POPUP
5885 		     + (long)textprop_total
5886 #endif
5887 		     ;
5888 	    curline += idx - start_idx + extra;
5889 	    if (curline > buf->b_ml.ml_line_count)
5890 		return -1;	// exactly one byte beyond the end
5891 	    return curline;
5892 	}
5893 	curline = buf->b_ml.ml_locked_high + 1;
5894     }
5895 
5896     if (lnum != 0)
5897     {
5898 	// Count extra CR characters.
5899 	if (ffdos)
5900 	    size += lnum - 1;
5901 
5902 	// Don't count the last line break if 'noeol' and ('bin' or
5903 	// 'nofixeol').
5904 	if ((!buf->b_p_fixeol || buf->b_p_bin) && !buf->b_p_eol
5905 					   && lnum > buf->b_ml.ml_line_count)
5906 	    size -= ffdos + 1;
5907     }
5908 
5909     return size;
5910 }
5911 
5912 /*
5913  * Goto byte in buffer with offset 'cnt'.
5914  */
5915     void
goto_byte(long cnt)5916 goto_byte(long cnt)
5917 {
5918     long	boff = cnt;
5919     linenr_T	lnum;
5920 
5921     ml_flush_line(curbuf);	// cached line may be dirty
5922     setpcmark();
5923     if (boff)
5924 	--boff;
5925     lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5926     if (lnum < 1)	// past the end
5927     {
5928 	curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5929 	curwin->w_curswant = MAXCOL;
5930 	coladvance((colnr_T)MAXCOL);
5931     }
5932     else
5933     {
5934 	curwin->w_cursor.lnum = lnum;
5935 	curwin->w_cursor.col = (colnr_T)boff;
5936 	curwin->w_cursor.coladd = 0;
5937 	curwin->w_set_curswant = TRUE;
5938     }
5939     check_cursor();
5940 
5941     // Make sure the cursor is on the first byte of a multi-byte char.
5942     if (has_mbyte)
5943 	mb_adjust_cursor();
5944 }
5945 #endif
5946