xref: /vim-8.2.3635/src/ops.c (revision 94688b8a)
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 /*
11  * ops.c: implementation of various operators: op_shift, op_delete, op_tilde,
12  *	  op_change, op_yank, do_put, do_join
13  */
14 
15 #include "vim.h"
16 
17 /*
18  * Number of registers.
19  *	0 = unnamed register, for normal yanks and puts
20  *   1..9 = registers '1' to '9', for deletes
21  * 10..35 = registers 'a' to 'z'
22  *     36 = delete register '-'
23  *     37 = Selection register '*'. Only if FEAT_CLIPBOARD defined
24  *     38 = Clipboard register '+'. Only if FEAT_CLIPBOARD and FEAT_X11 defined
25  */
26 /*
27  * Symbolic names for some registers.
28  */
29 #define DELETION_REGISTER	36
30 #ifdef FEAT_CLIPBOARD
31 # define STAR_REGISTER		37
32 #  ifdef FEAT_X11
33 #   define PLUS_REGISTER	38
34 #  else
35 #   define PLUS_REGISTER	STAR_REGISTER	    /* there is only one */
36 #  endif
37 #endif
38 #ifdef FEAT_DND
39 # define TILDE_REGISTER		(PLUS_REGISTER + 1)
40 #endif
41 
42 #ifdef FEAT_CLIPBOARD
43 # ifdef FEAT_DND
44 #  define NUM_REGISTERS		(TILDE_REGISTER + 1)
45 # else
46 #  define NUM_REGISTERS		(PLUS_REGISTER + 1)
47 # endif
48 #else
49 # define NUM_REGISTERS		37
50 #endif
51 
52 /*
53  * Each yank register has an array of pointers to lines.
54  */
55 typedef struct
56 {
57     char_u	**y_array;	/* pointer to array of line pointers */
58     linenr_T	y_size;		/* number of lines in y_array */
59     char_u	y_type;		/* MLINE, MCHAR or MBLOCK */
60     colnr_T	y_width;	/* only set if y_type == MBLOCK */
61 #ifdef FEAT_VIMINFO
62     time_t	y_time_set;
63 #endif
64 } yankreg_T;
65 
66 static yankreg_T	y_regs[NUM_REGISTERS];
67 
68 static yankreg_T	*y_current;	    /* ptr to current yankreg */
69 static int		y_append;	    /* TRUE when appending */
70 static yankreg_T	*y_previous = NULL; /* ptr to last written yankreg */
71 
72 /*
73  * structure used by block_prep, op_delete and op_yank for blockwise operators
74  * also op_change, op_shift, op_insert, op_replace - AKelly
75  */
76 struct block_def
77 {
78     int		startspaces;	/* 'extra' cols before first char */
79     int		endspaces;	/* 'extra' cols after last char */
80     int		textlen;	/* chars in block */
81     char_u	*textstart;	/* pointer to 1st char (partially) in block */
82     colnr_T	textcol;	/* index of chars (partially) in block */
83     colnr_T	start_vcol;	/* start col of 1st char wholly inside block */
84     colnr_T	end_vcol;	/* start col of 1st char wholly after block */
85     int		is_short;	/* TRUE if line is too short to fit in block */
86     int		is_MAX;		/* TRUE if curswant==MAXCOL when starting */
87     int		is_oneChar;	/* TRUE if block within one character */
88     int		pre_whitesp;	/* screen cols of ws before block */
89     int		pre_whitesp_c;	/* chars of ws before block */
90     colnr_T	end_char_vcols;	/* number of vcols of post-block char */
91     colnr_T	start_char_vcols; /* number of vcols of pre-block char */
92 };
93 
94 static void shift_block(oparg_T *oap, int amount);
95 static int	stuff_yank(int, char_u *);
96 static void	put_reedit_in_typebuf(int silent);
97 static int	put_in_typebuf(char_u *s, int esc, int colon,
98 								 int silent);
99 static void	stuffescaped(char_u *arg, int literally);
100 static void	mb_adjust_opend(oparg_T *oap);
101 static void	free_yank_all(void);
102 static int	yank_copy_line(struct block_def *bd, long y_idx);
103 #ifdef FEAT_CLIPBOARD
104 static void	copy_yank_reg(yankreg_T *reg);
105 static void	may_set_selection(void);
106 #endif
107 static void	dis_msg(char_u *p, int skip_esc);
108 static void	block_prep(oparg_T *oap, struct block_def *, linenr_T, int);
109 static int	do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1);
110 #if defined(FEAT_CLIPBOARD) || defined(FEAT_EVAL)
111 static void	str_to_reg(yankreg_T *y_ptr, int yank_type, char_u *str, long len, long blocklen, int str_list);
112 #endif
113 static int	ends_in_white(linenr_T lnum);
114 #ifdef FEAT_COMMENTS
115 static int	fmt_check_par(linenr_T, int *, char_u **, int do_comments);
116 #else
117 static int	fmt_check_par(linenr_T);
118 #endif
119 
120 // Flags for third item in "opchars".
121 #define OPF_LINES  1	// operator always works on lines
122 #define OPF_CHANGE 2	// operator changes text
123 
124 /*
125  * The names of operators.
126  * IMPORTANT: Index must correspond with defines in vim.h!!!
127  * The third field holds OPF_ flags.
128  */
129 static char opchars[][3] =
130 {
131     {NUL, NUL, 0},			// OP_NOP
132     {'d', NUL, OPF_CHANGE},		// OP_DELETE
133     {'y', NUL, 0},			// OP_YANK
134     {'c', NUL, OPF_CHANGE},		// OP_CHANGE
135     {'<', NUL, OPF_LINES | OPF_CHANGE},	// OP_LSHIFT
136     {'>', NUL, OPF_LINES | OPF_CHANGE},	// OP_RSHIFT
137     {'!', NUL, OPF_LINES | OPF_CHANGE},	// OP_FILTER
138     {'g', '~', OPF_CHANGE},		// OP_TILDE
139     {'=', NUL, OPF_LINES | OPF_CHANGE},	// OP_INDENT
140     {'g', 'q', OPF_LINES | OPF_CHANGE},	// OP_FORMAT
141     {':', NUL, OPF_LINES},		// OP_COLON
142     {'g', 'U', OPF_CHANGE},		// OP_UPPER
143     {'g', 'u', OPF_CHANGE},		// OP_LOWER
144     {'J', NUL, OPF_LINES | OPF_CHANGE},	// DO_JOIN
145     {'g', 'J', OPF_LINES | OPF_CHANGE},	// DO_JOIN_NS
146     {'g', '?', OPF_CHANGE},		// OP_ROT13
147     {'r', NUL, OPF_CHANGE},		// OP_REPLACE
148     {'I', NUL, OPF_CHANGE},		// OP_INSERT
149     {'A', NUL, OPF_CHANGE},		// OP_APPEND
150     {'z', 'f', OPF_LINES},		// OP_FOLD
151     {'z', 'o', OPF_LINES},		// OP_FOLDOPEN
152     {'z', 'O', OPF_LINES},		// OP_FOLDOPENREC
153     {'z', 'c', OPF_LINES},		// OP_FOLDCLOSE
154     {'z', 'C', OPF_LINES},		// OP_FOLDCLOSEREC
155     {'z', 'd', OPF_LINES},		// OP_FOLDDEL
156     {'z', 'D', OPF_LINES},		// OP_FOLDDELREC
157     {'g', 'w', OPF_LINES | OPF_CHANGE},	// OP_FORMAT2
158     {'g', '@', OPF_CHANGE},		// OP_FUNCTION
159     {Ctrl_A, NUL, OPF_CHANGE},		// OP_NR_ADD
160     {Ctrl_X, NUL, OPF_CHANGE},		// OP_NR_SUB
161 };
162 
163 /*
164  * Translate a command name into an operator type.
165  * Must only be called with a valid operator name!
166  */
167     int
168 get_op_type(int char1, int char2)
169 {
170     int		i;
171 
172     if (char1 == 'r')		/* ignore second character */
173 	return OP_REPLACE;
174     if (char1 == '~')		/* when tilde is an operator */
175 	return OP_TILDE;
176     if (char1 == 'g' && char2 == Ctrl_A)	/* add */
177 	return OP_NR_ADD;
178     if (char1 == 'g' && char2 == Ctrl_X)	/* subtract */
179 	return OP_NR_SUB;
180     for (i = 0; ; ++i)
181     {
182 	if (opchars[i][0] == char1 && opchars[i][1] == char2)
183 	    break;
184 	if (i == (int)(sizeof(opchars) / sizeof(char [3]) - 1))
185 	{
186 	    internal_error("get_op_type()");
187 	    break;
188 	}
189     }
190     return i;
191 }
192 
193 /*
194  * Return TRUE if operator "op" always works on whole lines.
195  */
196     int
197 op_on_lines(int op)
198 {
199     return opchars[op][2] & OPF_LINES;
200 }
201 
202 #if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
203 /*
204  * Return TRUE if operator "op" changes text.
205  */
206     int
207 op_is_change(int op)
208 {
209     return opchars[op][2] & OPF_CHANGE;
210 }
211 #endif
212 
213 /*
214  * Get first operator command character.
215  * Returns 'g' or 'z' if there is another command character.
216  */
217     int
218 get_op_char(int optype)
219 {
220     return opchars[optype][0];
221 }
222 
223 /*
224  * Get second operator command character.
225  */
226     int
227 get_extra_op_char(int optype)
228 {
229     return opchars[optype][1];
230 }
231 
232 /*
233  * op_shift - handle a shift operation
234  */
235     void
236 op_shift(oparg_T *oap, int curs_top, int amount)
237 {
238     long	    i;
239     int		    first_char;
240     int		    block_col = 0;
241 
242     if (u_save((linenr_T)(oap->start.lnum - 1),
243 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
244 	return;
245 
246     if (oap->block_mode)
247 	block_col = curwin->w_cursor.col;
248 
249     for (i = oap->line_count; --i >= 0; )
250     {
251 	first_char = *ml_get_curline();
252 	if (first_char == NUL)				/* empty line */
253 	    curwin->w_cursor.col = 0;
254 	else if (oap->block_mode)
255 	    shift_block(oap, amount);
256 	else
257 	    /* Move the line right if it doesn't start with '#', 'smartindent'
258 	     * isn't set or 'cindent' isn't set or '#' isn't in 'cino'. */
259 #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
260 	    if (first_char != '#' || !preprocs_left())
261 #endif
262 	{
263 	    shift_line(oap->op_type == OP_LSHIFT, p_sr, amount, FALSE);
264 	}
265 	++curwin->w_cursor.lnum;
266     }
267 
268     changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
269     if (oap->block_mode)
270     {
271 	curwin->w_cursor.lnum = oap->start.lnum;
272 	curwin->w_cursor.col = block_col;
273     }
274     else if (curs_top)	    /* put cursor on first line, for ">>" */
275     {
276 	curwin->w_cursor.lnum = oap->start.lnum;
277 	beginline(BL_SOL | BL_FIX);   /* shift_line() may have set cursor.col */
278     }
279     else
280 	--curwin->w_cursor.lnum;	/* put cursor on last line, for ":>" */
281 
282 #ifdef FEAT_FOLDING
283     /* The cursor line is not in a closed fold */
284     foldOpenCursor();
285 #endif
286 
287 
288     if (oap->line_count > p_report)
289     {
290 	char	    *op;
291 	char	    *msg_line_single;
292 	char	    *msg_line_plural;
293 
294 	if (oap->op_type == OP_RSHIFT)
295 	    op = ">";
296 	else
297 	    op = "<";
298 	msg_line_single = NGETTEXT("%ld line %sed %d time",
299 					     "%ld line %sed %d times", amount);
300 	msg_line_plural = NGETTEXT("%ld lines %sed %d time",
301 					    "%ld lines %sed %d times", amount);
302 	vim_snprintf((char *)IObuff, IOSIZE,
303 		NGETTEXT(msg_line_single, msg_line_plural, oap->line_count),
304 		oap->line_count, op, amount);
305 	msg((char *)IObuff);
306     }
307 
308     /*
309      * Set "'[" and "']" marks.
310      */
311     curbuf->b_op_start = oap->start;
312     curbuf->b_op_end.lnum = oap->end.lnum;
313     curbuf->b_op_end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
314     if (curbuf->b_op_end.col > 0)
315 	--curbuf->b_op_end.col;
316 }
317 
318 /*
319  * Shift the current line one shiftwidth left (if left != 0) or right
320  * leaves cursor on first blank in the line.
321  */
322     void
323 shift_line(
324     int	left,
325     int	round,
326     int	amount,
327     int call_changed_bytes)	/* call changed_bytes() */
328 {
329     int		count;
330     int		i, j;
331     int		p_sw = (int)get_sw_value_indent(curbuf);
332 
333     count = get_indent();	/* get current indent */
334 
335     if (round)			/* round off indent */
336     {
337 	i = count / p_sw;	/* number of p_sw rounded down */
338 	j = count % p_sw;	/* extra spaces */
339 	if (j && left)		/* first remove extra spaces */
340 	    --amount;
341 	if (left)
342 	{
343 	    i -= amount;
344 	    if (i < 0)
345 		i = 0;
346 	}
347 	else
348 	    i += amount;
349 	count = i * p_sw;
350     }
351     else		/* original vi indent */
352     {
353 	if (left)
354 	{
355 	    count -= p_sw * amount;
356 	    if (count < 0)
357 		count = 0;
358 	}
359 	else
360 	    count += p_sw * amount;
361     }
362 
363     /* Set new indent */
364     if (State & VREPLACE_FLAG)
365 	change_indent(INDENT_SET, count, FALSE, NUL, call_changed_bytes);
366     else
367 	(void)set_indent(count, call_changed_bytes ? SIN_CHANGED : 0);
368 }
369 
370 /*
371  * Shift one line of the current block one shiftwidth right or left.
372  * Leaves cursor on first character in block.
373  */
374     static void
375 shift_block(oparg_T *oap, int amount)
376 {
377     int			left = (oap->op_type == OP_LSHIFT);
378     int			oldstate = State;
379     int			total;
380     char_u		*newp, *oldp;
381     int			oldcol = curwin->w_cursor.col;
382     int			p_sw = (int)get_sw_value_indent(curbuf);
383 #ifdef FEAT_VARTABS
384     int			*p_vts = curbuf->b_p_vts_array;
385 #endif
386     int			p_ts = (int)curbuf->b_p_ts;
387     struct block_def	bd;
388     int			incr;
389     colnr_T		ws_vcol;
390     int			i = 0, j = 0;
391     int			len;
392 #ifdef FEAT_RIGHTLEFT
393     int			old_p_ri = p_ri;
394 
395     p_ri = 0;			/* don't want revins in indent */
396 #endif
397 
398     State = INSERT;		/* don't want REPLACE for State */
399     block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE);
400     if (bd.is_short)
401 	return;
402 
403     /* total is number of screen columns to be inserted/removed */
404     total = (int)((unsigned)amount * (unsigned)p_sw);
405     if ((total / p_sw) != amount)
406 	return; /* multiplication overflow */
407 
408     oldp = ml_get_curline();
409 
410     if (!left)
411     {
412 	/*
413 	 *  1. Get start vcol
414 	 *  2. Total ws vcols
415 	 *  3. Divvy into TABs & spp
416 	 *  4. Construct new string
417 	 */
418 	total += bd.pre_whitesp; /* all virtual WS upto & incl a split TAB */
419 	ws_vcol = bd.start_vcol - bd.pre_whitesp;
420 	if (bd.startspaces)
421 	{
422 	    if (has_mbyte)
423 	    {
424 		if ((*mb_ptr2len)(bd.textstart) == 1)
425 		    ++bd.textstart;
426 		else
427 		{
428 		    ws_vcol = 0;
429 		    bd.startspaces = 0;
430 		}
431 	    }
432 	    else
433 		++bd.textstart;
434 	}
435 	for ( ; VIM_ISWHITE(*bd.textstart); )
436 	{
437 	    /* TODO: is passing bd.textstart for start of the line OK? */
438 	    incr = lbr_chartabsize_adv(bd.textstart, &bd.textstart,
439 						    (colnr_T)(bd.start_vcol));
440 	    total += incr;
441 	    bd.start_vcol += incr;
442 	}
443 	/* OK, now total=all the VWS reqd, and textstart points at the 1st
444 	 * non-ws char in the block. */
445 #ifdef FEAT_VARTABS
446 	if (!curbuf->b_p_et)
447 	    tabstop_fromto(ws_vcol, ws_vcol + total, p_ts, p_vts, &i, &j);
448 	else
449 	    j = total;
450 #else
451 	if (!curbuf->b_p_et)
452 	    i = ((ws_vcol % p_ts) + total) / p_ts; /* number of tabs */
453 	if (i)
454 	    j = ((ws_vcol % p_ts) + total) % p_ts; /* number of spp */
455 	else
456 	    j = total;
457 #endif
458 	/* if we're splitting a TAB, allow for it */
459 	bd.textcol -= bd.pre_whitesp_c - (bd.startspaces != 0);
460 	len = (int)STRLEN(bd.textstart) + 1;
461 	newp = alloc_check((unsigned)(bd.textcol + i + j + len));
462 	if (newp == NULL)
463 	    return;
464 	vim_memset(newp, NUL, (size_t)(bd.textcol + i + j + len));
465 	mch_memmove(newp, oldp, (size_t)bd.textcol);
466 	vim_memset(newp + bd.textcol, TAB, (size_t)i);
467 	vim_memset(newp + bd.textcol + i, ' ', (size_t)j);
468 	/* the end */
469 	mch_memmove(newp + bd.textcol + i + j, bd.textstart, (size_t)len);
470     }
471     else /* left */
472     {
473 	colnr_T	    destination_col;	/* column to which text in block will
474 					   be shifted */
475 	char_u	    *verbatim_copy_end;	/* end of the part of the line which is
476 					   copied verbatim */
477 	colnr_T	    verbatim_copy_width;/* the (displayed) width of this part
478 					   of line */
479 	unsigned    fill;		/* nr of spaces that replace a TAB */
480 	unsigned    new_line_len;	/* the length of the line after the
481 					   block shift */
482 	size_t	    block_space_width;
483 	size_t	    shift_amount;
484 	char_u	    *non_white = bd.textstart;
485 	colnr_T	    non_white_col;
486 
487 	/*
488 	 * Firstly, let's find the first non-whitespace character that is
489 	 * displayed after the block's start column and the character's column
490 	 * number. Also, let's calculate the width of all the whitespace
491 	 * characters that are displayed in the block and precede the searched
492 	 * non-whitespace character.
493 	 */
494 
495 	/* If "bd.startspaces" is set, "bd.textstart" points to the character,
496 	 * the part of which is displayed at the block's beginning. Let's start
497 	 * searching from the next character. */
498 	if (bd.startspaces)
499 	    MB_PTR_ADV(non_white);
500 
501 	/* The character's column is in "bd.start_vcol".  */
502 	non_white_col = bd.start_vcol;
503 
504 	while (VIM_ISWHITE(*non_white))
505 	{
506 	    incr = lbr_chartabsize_adv(bd.textstart, &non_white, non_white_col);
507 	    non_white_col += incr;
508 	}
509 
510 	block_space_width = non_white_col - oap->start_vcol;
511 	/* We will shift by "total" or "block_space_width", whichever is less.
512 	 */
513 	shift_amount = (block_space_width < (size_t)total
514 					 ? block_space_width : (size_t)total);
515 
516 	/* The column to which we will shift the text.  */
517 	destination_col = (colnr_T)(non_white_col - shift_amount);
518 
519 	/* Now let's find out how much of the beginning of the line we can
520 	 * reuse without modification.  */
521 	verbatim_copy_end = bd.textstart;
522 	verbatim_copy_width = bd.start_vcol;
523 
524 	/* If "bd.startspaces" is set, "bd.textstart" points to the character
525 	 * preceding the block. We have to subtract its width to obtain its
526 	 * column number.  */
527 	if (bd.startspaces)
528 	    verbatim_copy_width -= bd.start_char_vcols;
529 	while (verbatim_copy_width < destination_col)
530 	{
531 	    char_u *line = verbatim_copy_end;
532 
533 	    /* TODO: is passing verbatim_copy_end for start of the line OK? */
534 	    incr = lbr_chartabsize(line, verbatim_copy_end,
535 							 verbatim_copy_width);
536 	    if (verbatim_copy_width + incr > destination_col)
537 		break;
538 	    verbatim_copy_width += incr;
539 	    MB_PTR_ADV(verbatim_copy_end);
540 	}
541 
542 	/* If "destination_col" is different from the width of the initial
543 	 * part of the line that will be copied, it means we encountered a tab
544 	 * character, which we will have to partly replace with spaces.  */
545 	fill = destination_col - verbatim_copy_width;
546 
547 	/* The replacement line will consist of:
548 	 * - the beginning of the original line up to "verbatim_copy_end",
549 	 * - "fill" number of spaces,
550 	 * - the rest of the line, pointed to by non_white.  */
551 	new_line_len = (unsigned)(verbatim_copy_end - oldp)
552 		       + fill
553 		       + (unsigned)STRLEN(non_white) + 1;
554 
555 	newp = alloc_check(new_line_len);
556 	if (newp == NULL)
557 	    return;
558 	mch_memmove(newp, oldp, (size_t)(verbatim_copy_end - oldp));
559 	vim_memset(newp + (verbatim_copy_end - oldp), ' ', (size_t)fill);
560 	STRMOVE(newp + (verbatim_copy_end - oldp) + fill, non_white);
561     }
562     /* replace the line */
563     ml_replace(curwin->w_cursor.lnum, newp, FALSE);
564     changed_bytes(curwin->w_cursor.lnum, (colnr_T)bd.textcol);
565     State = oldstate;
566     curwin->w_cursor.col = oldcol;
567 #ifdef FEAT_RIGHTLEFT
568     p_ri = old_p_ri;
569 #endif
570 }
571 
572 /*
573  * Insert string "s" (b_insert ? before : after) block :AKelly
574  * Caller must prepare for undo.
575  */
576     static void
577 block_insert(
578     oparg_T		*oap,
579     char_u		*s,
580     int			b_insert,
581     struct block_def	*bdp)
582 {
583     int		p_ts;
584     int		count = 0;	/* extra spaces to replace a cut TAB */
585     int		spaces = 0;	/* non-zero if cutting a TAB */
586     colnr_T	offset;		/* pointer along new line */
587     unsigned	s_len;		/* STRLEN(s) */
588     char_u	*newp, *oldp;	/* new, old lines */
589     linenr_T	lnum;		/* loop var */
590     int		oldstate = State;
591 
592     State = INSERT;		/* don't want REPLACE for State */
593     s_len = (unsigned)STRLEN(s);
594 
595     for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)
596     {
597 	block_prep(oap, bdp, lnum, TRUE);
598 	if (bdp->is_short && b_insert)
599 	    continue;	/* OP_INSERT, line ends before block start */
600 
601 	oldp = ml_get(lnum);
602 
603 	if (b_insert)
604 	{
605 	    p_ts = bdp->start_char_vcols;
606 	    spaces = bdp->startspaces;
607 	    if (spaces != 0)
608 		count = p_ts - 1; /* we're cutting a TAB */
609 	    offset = bdp->textcol;
610 	}
611 	else /* append */
612 	{
613 	    p_ts = bdp->end_char_vcols;
614 	    if (!bdp->is_short) /* spaces = padding after block */
615 	    {
616 		spaces = (bdp->endspaces ? p_ts - bdp->endspaces : 0);
617 		if (spaces != 0)
618 		    count = p_ts - 1; /* we're cutting a TAB */
619 		offset = bdp->textcol + bdp->textlen - (spaces != 0);
620 	    }
621 	    else /* spaces = padding to block edge */
622 	    {
623 		/* if $ used, just append to EOL (ie spaces==0) */
624 		if (!bdp->is_MAX)
625 		    spaces = (oap->end_vcol - bdp->end_vcol) + 1;
626 		count = spaces;
627 		offset = bdp->textcol + bdp->textlen;
628 	    }
629 	}
630 
631 	if (has_mbyte && spaces > 0)
632 	{
633 	    int off;
634 
635 	    /* Avoid starting halfway a multi-byte character. */
636 	    if (b_insert)
637 	    {
638 		off = (*mb_head_off)(oldp, oldp + offset + spaces);
639 	    }
640 	    else
641 	    {
642 		off = (*mb_off_next)(oldp, oldp + offset);
643 		offset += off;
644 	    }
645 	    spaces -= off;
646 	    count -= off;
647 	}
648 
649 	newp = alloc_check((unsigned)(STRLEN(oldp)) + s_len + count + 1);
650 	if (newp == NULL)
651 	    continue;
652 
653 	/* copy up to shifted part */
654 	mch_memmove(newp, oldp, (size_t)(offset));
655 	oldp += offset;
656 
657 	/* insert pre-padding */
658 	vim_memset(newp + offset, ' ', (size_t)spaces);
659 
660 	/* copy the new text */
661 	mch_memmove(newp + offset + spaces, s, (size_t)s_len);
662 	offset += s_len;
663 
664 	if (spaces && !bdp->is_short)
665 	{
666 	    /* insert post-padding */
667 	    vim_memset(newp + offset + spaces, ' ', (size_t)(p_ts - spaces));
668 	    /* We're splitting a TAB, don't copy it. */
669 	    oldp++;
670 	    /* We allowed for that TAB, remember this now */
671 	    count++;
672 	}
673 
674 	if (spaces > 0)
675 	    offset += count;
676 	STRMOVE(newp + offset, oldp);
677 
678 	ml_replace(lnum, newp, FALSE);
679 
680 	if (lnum == oap->end.lnum)
681 	{
682 	    /* Set "']" mark to the end of the block instead of the end of
683 	     * the insert in the first line.  */
684 	    curbuf->b_op_end.lnum = oap->end.lnum;
685 	    curbuf->b_op_end.col = offset;
686 	}
687     } /* for all lnum */
688 
689     changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
690 
691     State = oldstate;
692 }
693 
694 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
695 /*
696  * op_reindent - handle reindenting a block of lines.
697  */
698     void
699 op_reindent(oparg_T *oap, int (*how)(void))
700 {
701     long	i;
702     char_u	*l;
703     int		amount;
704     linenr_T	first_changed = 0;
705     linenr_T	last_changed = 0;
706     linenr_T	start_lnum = curwin->w_cursor.lnum;
707 
708     /* Don't even try when 'modifiable' is off. */
709     if (!curbuf->b_p_ma)
710     {
711 	emsg(_(e_modifiable));
712 	return;
713     }
714 
715     for (i = oap->line_count; --i >= 0 && !got_int; )
716     {
717 	/* it's a slow thing to do, so give feedback so there's no worry that
718 	 * the computer's just hung. */
719 
720 	if (i > 1
721 		&& (i % 50 == 0 || i == oap->line_count - 1)
722 		&& oap->line_count > p_report)
723 	    smsg(_("%ld lines to indent... "), i);
724 
725 	/*
726 	 * Be vi-compatible: For lisp indenting the first line is not
727 	 * indented, unless there is only one line.
728 	 */
729 #ifdef FEAT_LISP
730 	if (i != oap->line_count - 1 || oap->line_count == 1
731 						    || how != get_lisp_indent)
732 #endif
733 	{
734 	    l = skipwhite(ml_get_curline());
735 	    if (*l == NUL)		    /* empty or blank line */
736 		amount = 0;
737 	    else
738 		amount = how();		    /* get the indent for this line */
739 
740 	    if (amount >= 0 && set_indent(amount, SIN_UNDO))
741 	    {
742 		/* did change the indent, call changed_lines() later */
743 		if (first_changed == 0)
744 		    first_changed = curwin->w_cursor.lnum;
745 		last_changed = curwin->w_cursor.lnum;
746 	    }
747 	}
748 	++curwin->w_cursor.lnum;
749 	curwin->w_cursor.col = 0;  /* make sure it's valid */
750     }
751 
752     /* put cursor on first non-blank of indented line */
753     curwin->w_cursor.lnum = start_lnum;
754     beginline(BL_SOL | BL_FIX);
755 
756     /* Mark changed lines so that they will be redrawn.  When Visual
757      * highlighting was present, need to continue until the last line.  When
758      * there is no change still need to remove the Visual highlighting. */
759     if (last_changed != 0)
760 	changed_lines(first_changed, 0,
761 		oap->is_VIsual ? start_lnum + oap->line_count :
762 		last_changed + 1, 0L);
763     else if (oap->is_VIsual)
764 	redraw_curbuf_later(INVERTED);
765 
766     if (oap->line_count > p_report)
767     {
768 	i = oap->line_count - (i + 1);
769 	smsg(NGETTEXT("%ld line indented ",
770 						 "%ld lines indented ", i), i);
771     }
772     /* set '[ and '] marks */
773     curbuf->b_op_start = oap->start;
774     curbuf->b_op_end = oap->end;
775 }
776 #endif /* defined(FEAT_LISP) || defined(FEAT_CINDENT) */
777 
778 #if defined(FEAT_EVAL) || defined(PROTO)
779 /*
780  * Keep the last expression line here, for repeating.
781  */
782 static char_u	*expr_line = NULL;
783 
784 /*
785  * Get an expression for the "\"=expr1" or "CTRL-R =expr1"
786  * Returns '=' when OK, NUL otherwise.
787  */
788     int
789 get_expr_register(void)
790 {
791     char_u	*new_line;
792 
793     new_line = getcmdline('=', 0L, 0);
794     if (new_line == NULL)
795 	return NUL;
796     if (*new_line == NUL)	/* use previous line */
797 	vim_free(new_line);
798     else
799 	set_expr_line(new_line);
800     return '=';
801 }
802 
803 /*
804  * Set the expression for the '=' register.
805  * Argument must be an allocated string.
806  */
807     void
808 set_expr_line(char_u *new_line)
809 {
810     vim_free(expr_line);
811     expr_line = new_line;
812 }
813 
814 /*
815  * Get the result of the '=' register expression.
816  * Returns a pointer to allocated memory, or NULL for failure.
817  */
818     char_u *
819 get_expr_line(void)
820 {
821     char_u	*expr_copy;
822     char_u	*rv;
823     static int	nested = 0;
824 
825     if (expr_line == NULL)
826 	return NULL;
827 
828     /* Make a copy of the expression, because evaluating it may cause it to be
829      * changed. */
830     expr_copy = vim_strsave(expr_line);
831     if (expr_copy == NULL)
832 	return NULL;
833 
834     /* When we are invoked recursively limit the evaluation to 10 levels.
835      * Then return the string as-is. */
836     if (nested >= 10)
837 	return expr_copy;
838 
839     ++nested;
840     rv = eval_to_string(expr_copy, NULL, TRUE);
841     --nested;
842     vim_free(expr_copy);
843     return rv;
844 }
845 
846 /*
847  * Get the '=' register expression itself, without evaluating it.
848  */
849     char_u *
850 get_expr_line_src(void)
851 {
852     if (expr_line == NULL)
853 	return NULL;
854     return vim_strsave(expr_line);
855 }
856 #endif /* FEAT_EVAL */
857 
858 /*
859  * Check if 'regname' is a valid name of a yank register.
860  * Note: There is no check for 0 (default register), caller should do this
861  */
862     int
863 valid_yank_reg(
864     int	    regname,
865     int	    writing)	    /* if TRUE check for writable registers */
866 {
867     if (       (regname > 0 && ASCII_ISALNUM(regname))
868 	    || (!writing && vim_strchr((char_u *)
869 #ifdef FEAT_EVAL
870 				    "/.%:="
871 #else
872 				    "/.%:"
873 #endif
874 					, regname) != NULL)
875 	    || regname == '#'
876 	    || regname == '"'
877 	    || regname == '-'
878 	    || regname == '_'
879 #ifdef FEAT_CLIPBOARD
880 	    || regname == '*'
881 	    || regname == '+'
882 #endif
883 #ifdef FEAT_DND
884 	    || (!writing && regname == '~')
885 #endif
886 							)
887 	return TRUE;
888     return FALSE;
889 }
890 
891 /*
892  * Set y_current and y_append, according to the value of "regname".
893  * Cannot handle the '_' register.
894  * Must only be called with a valid register name!
895  *
896  * If regname is 0 and writing, use register 0
897  * If regname is 0 and reading, use previous register
898  *
899  * Return TRUE when the register should be inserted literally (selection or
900  * clipboard).
901  */
902     int
903 get_yank_register(int regname, int writing)
904 {
905     int	    i;
906     int	    ret = FALSE;
907 
908     y_append = FALSE;
909     if ((regname == 0 || regname == '"') && !writing && y_previous != NULL)
910     {
911 	y_current = y_previous;
912 	return ret;
913     }
914     i = regname;
915     if (VIM_ISDIGIT(i))
916 	i -= '0';
917     else if (ASCII_ISLOWER(i))
918 	i = CharOrdLow(i) + 10;
919     else if (ASCII_ISUPPER(i))
920     {
921 	i = CharOrdUp(i) + 10;
922 	y_append = TRUE;
923     }
924     else if (regname == '-')
925 	i = DELETION_REGISTER;
926 #ifdef FEAT_CLIPBOARD
927     /* When selection is not available, use register 0 instead of '*' */
928     else if (clip_star.available && regname == '*')
929     {
930 	i = STAR_REGISTER;
931 	ret = TRUE;
932     }
933     /* When clipboard is not available, use register 0 instead of '+' */
934     else if (clip_plus.available && regname == '+')
935     {
936 	i = PLUS_REGISTER;
937 	ret = TRUE;
938     }
939 #endif
940 #ifdef FEAT_DND
941     else if (!writing && regname == '~')
942 	i = TILDE_REGISTER;
943 #endif
944     else		/* not 0-9, a-z, A-Z or '-': use register 0 */
945 	i = 0;
946     y_current = &(y_regs[i]);
947     if (writing)	/* remember the register we write into for do_put() */
948 	y_previous = y_current;
949     return ret;
950 }
951 
952 #if defined(FEAT_CLIPBOARD) || defined(PROTO)
953 /*
954  * When "regname" is a clipboard register, obtain the selection.  If it's not
955  * available return zero, otherwise return "regname".
956  */
957     int
958 may_get_selection(int regname)
959 {
960     if (regname == '*')
961     {
962 	if (!clip_star.available)
963 	    regname = 0;
964 	else
965 	    clip_get_selection(&clip_star);
966     }
967     else if (regname == '+')
968     {
969 	if (!clip_plus.available)
970 	    regname = 0;
971 	else
972 	    clip_get_selection(&clip_plus);
973     }
974     return regname;
975 }
976 #endif
977 
978 /*
979  * Obtain the contents of a "normal" register. The register is made empty.
980  * The returned pointer has allocated memory, use put_register() later.
981  */
982     void *
983 get_register(
984     int		name,
985     int		copy)	/* make a copy, if FALSE make register empty. */
986 {
987     yankreg_T	*reg;
988     int		i;
989 
990 #ifdef FEAT_CLIPBOARD
991     /* When Visual area changed, may have to update selection.  Obtain the
992      * selection too. */
993     if (name == '*' && clip_star.available)
994     {
995 	if (clip_isautosel_star())
996 	    clip_update_selection(&clip_star);
997 	may_get_selection(name);
998     }
999     if (name == '+' && clip_plus.available)
1000     {
1001 	if (clip_isautosel_plus())
1002 	    clip_update_selection(&clip_plus);
1003 	may_get_selection(name);
1004     }
1005 #endif
1006 
1007     get_yank_register(name, 0);
1008     reg = (yankreg_T *)alloc((unsigned)sizeof(yankreg_T));
1009     if (reg != NULL)
1010     {
1011 	*reg = *y_current;
1012 	if (copy)
1013 	{
1014 	    /* If we run out of memory some or all of the lines are empty. */
1015 	    if (reg->y_size == 0)
1016 		reg->y_array = NULL;
1017 	    else
1018 		reg->y_array = (char_u **)alloc((unsigned)(sizeof(char_u *)
1019 							      * reg->y_size));
1020 	    if (reg->y_array != NULL)
1021 	    {
1022 		for (i = 0; i < reg->y_size; ++i)
1023 		    reg->y_array[i] = vim_strsave(y_current->y_array[i]);
1024 	    }
1025 	}
1026 	else
1027 	    y_current->y_array = NULL;
1028     }
1029     return (void *)reg;
1030 }
1031 
1032 /*
1033  * Put "reg" into register "name".  Free any previous contents and "reg".
1034  */
1035     void
1036 put_register(int name, void *reg)
1037 {
1038     get_yank_register(name, 0);
1039     free_yank_all();
1040     *y_current = *(yankreg_T *)reg;
1041     vim_free(reg);
1042 
1043 #ifdef FEAT_CLIPBOARD
1044     /* Send text written to clipboard register to the clipboard. */
1045     may_set_selection();
1046 #endif
1047 }
1048 
1049 #if (defined(FEAT_CLIPBOARD) && defined(FEAT_X11) && defined(USE_SYSTEM)) \
1050 	|| defined(PROTO)
1051     void
1052 free_register(void *reg)
1053 {
1054     yankreg_T tmp;
1055 
1056     tmp = *y_current;
1057     *y_current = *(yankreg_T *)reg;
1058     free_yank_all();
1059     vim_free(reg);
1060     *y_current = tmp;
1061 }
1062 #endif
1063 
1064 #if defined(FEAT_MOUSE) || defined(PROTO)
1065 /*
1066  * return TRUE if the current yank register has type MLINE
1067  */
1068     int
1069 yank_register_mline(int regname)
1070 {
1071     if (regname != 0 && !valid_yank_reg(regname, FALSE))
1072 	return FALSE;
1073     if (regname == '_')		/* black hole is always empty */
1074 	return FALSE;
1075     get_yank_register(regname, FALSE);
1076     return (y_current->y_type == MLINE);
1077 }
1078 #endif
1079 
1080 /*
1081  * Start or stop recording into a yank register.
1082  *
1083  * Return FAIL for failure, OK otherwise.
1084  */
1085     int
1086 do_record(int c)
1087 {
1088     char_u	    *p;
1089     static int	    regname;
1090     yankreg_T	    *old_y_previous, *old_y_current;
1091     int		    retval;
1092 
1093     if (reg_recording == 0)	    /* start recording */
1094     {
1095 	/* registers 0-9, a-z and " are allowed */
1096 	if (c < 0 || (!ASCII_ISALNUM(c) && c != '"'))
1097 	    retval = FAIL;
1098 	else
1099 	{
1100 	    reg_recording = c;
1101 	    showmode();
1102 	    regname = c;
1103 	    retval = OK;
1104 	}
1105     }
1106     else			    /* stop recording */
1107     {
1108 	/*
1109 	 * Get the recorded key hits.  K_SPECIAL and CSI will be escaped, this
1110 	 * needs to be removed again to put it in a register.  exec_reg then
1111 	 * adds the escaping back later.
1112 	 */
1113 	reg_recording = 0;
1114 	msg("");
1115 	p = get_recorded();
1116 	if (p == NULL)
1117 	    retval = FAIL;
1118 	else
1119 	{
1120 	    /* Remove escaping for CSI and K_SPECIAL in multi-byte chars. */
1121 	    vim_unescape_csi(p);
1122 
1123 	    /*
1124 	     * We don't want to change the default register here, so save and
1125 	     * restore the current register name.
1126 	     */
1127 	    old_y_previous = y_previous;
1128 	    old_y_current = y_current;
1129 
1130 	    retval = stuff_yank(regname, p);
1131 
1132 	    y_previous = old_y_previous;
1133 	    y_current = old_y_current;
1134 	}
1135     }
1136     return retval;
1137 }
1138 
1139 /*
1140  * Stuff string "p" into yank register "regname" as a single line (append if
1141  * uppercase).	"p" must have been alloced.
1142  *
1143  * return FAIL for failure, OK otherwise
1144  */
1145     static int
1146 stuff_yank(int regname, char_u *p)
1147 {
1148     char_u	*lp;
1149     char_u	**pp;
1150 
1151     /* check for read-only register */
1152     if (regname != 0 && !valid_yank_reg(regname, TRUE))
1153     {
1154 	vim_free(p);
1155 	return FAIL;
1156     }
1157     if (regname == '_')		    /* black hole: don't do anything */
1158     {
1159 	vim_free(p);
1160 	return OK;
1161     }
1162     get_yank_register(regname, TRUE);
1163     if (y_append && y_current->y_array != NULL)
1164     {
1165 	pp = &(y_current->y_array[y_current->y_size - 1]);
1166 	lp = lalloc((long_u)(STRLEN(*pp) + STRLEN(p) + 1), TRUE);
1167 	if (lp == NULL)
1168 	{
1169 	    vim_free(p);
1170 	    return FAIL;
1171 	}
1172 	STRCPY(lp, *pp);
1173 	STRCAT(lp, p);
1174 	vim_free(p);
1175 	vim_free(*pp);
1176 	*pp = lp;
1177     }
1178     else
1179     {
1180 	free_yank_all();
1181 	if ((y_current->y_array =
1182 			(char_u **)alloc((unsigned)sizeof(char_u *))) == NULL)
1183 	{
1184 	    vim_free(p);
1185 	    return FAIL;
1186 	}
1187 	y_current->y_array[0] = p;
1188 	y_current->y_size = 1;
1189 	y_current->y_type = MCHAR;  /* used to be MLINE, why? */
1190 #ifdef FEAT_VIMINFO
1191 	y_current->y_time_set = vim_time();
1192 #endif
1193     }
1194     return OK;
1195 }
1196 
1197 static int execreg_lastc = NUL;
1198 
1199 /*
1200  * Execute a yank register: copy it into the stuff buffer.
1201  *
1202  * Return FAIL for failure, OK otherwise.
1203  */
1204     int
1205 do_execreg(
1206     int	    regname,
1207     int	    colon,		/* insert ':' before each line */
1208     int	    addcr,		/* always add '\n' to end of line */
1209     int	    silent)		/* set "silent" flag in typeahead buffer */
1210 {
1211     long	i;
1212     char_u	*p;
1213     int		retval = OK;
1214     int		remap;
1215 
1216     if (regname == '@')			/* repeat previous one */
1217     {
1218 	if (execreg_lastc == NUL)
1219 	{
1220 	    emsg(_("E748: No previously used register"));
1221 	    return FAIL;
1222 	}
1223 	regname = execreg_lastc;
1224     }
1225 					/* check for valid regname */
1226     if (regname == '%' || regname == '#' || !valid_yank_reg(regname, FALSE))
1227     {
1228 	emsg_invreg(regname);
1229 	return FAIL;
1230     }
1231     execreg_lastc = regname;
1232 
1233 #ifdef FEAT_CLIPBOARD
1234     regname = may_get_selection(regname);
1235 #endif
1236 
1237     if (regname == '_')			/* black hole: don't stuff anything */
1238 	return OK;
1239 
1240 #ifdef FEAT_CMDHIST
1241     if (regname == ':')			/* use last command line */
1242     {
1243 	if (last_cmdline == NULL)
1244 	{
1245 	    emsg(_(e_nolastcmd));
1246 	    return FAIL;
1247 	}
1248 	VIM_CLEAR(new_last_cmdline); /* don't keep the cmdline containing @: */
1249 	/* Escape all control characters with a CTRL-V */
1250 	p = vim_strsave_escaped_ext(last_cmdline,
1251 		(char_u *)"\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037", Ctrl_V, FALSE);
1252 	if (p != NULL)
1253 	{
1254 	    /* When in Visual mode "'<,'>" will be prepended to the command.
1255 	     * Remove it when it's already there. */
1256 	    if (VIsual_active && STRNCMP(p, "'<,'>", 5) == 0)
1257 		retval = put_in_typebuf(p + 5, TRUE, TRUE, silent);
1258 	    else
1259 		retval = put_in_typebuf(p, TRUE, TRUE, silent);
1260 	}
1261 	vim_free(p);
1262     }
1263 #endif
1264 #ifdef FEAT_EVAL
1265     else if (regname == '=')
1266     {
1267 	p = get_expr_line();
1268 	if (p == NULL)
1269 	    return FAIL;
1270 	retval = put_in_typebuf(p, TRUE, colon, silent);
1271 	vim_free(p);
1272     }
1273 #endif
1274     else if (regname == '.')		/* use last inserted text */
1275     {
1276 	p = get_last_insert_save();
1277 	if (p == NULL)
1278 	{
1279 	    emsg(_(e_noinstext));
1280 	    return FAIL;
1281 	}
1282 	retval = put_in_typebuf(p, FALSE, colon, silent);
1283 	vim_free(p);
1284     }
1285     else
1286     {
1287 	get_yank_register(regname, FALSE);
1288 	if (y_current->y_array == NULL)
1289 	    return FAIL;
1290 
1291 	/* Disallow remaping for ":@r". */
1292 	remap = colon ? REMAP_NONE : REMAP_YES;
1293 
1294 	/*
1295 	 * Insert lines into typeahead buffer, from last one to first one.
1296 	 */
1297 	put_reedit_in_typebuf(silent);
1298 	for (i = y_current->y_size; --i >= 0; )
1299 	{
1300 	    char_u *escaped;
1301 
1302 	    /* insert NL between lines and after last line if type is MLINE */
1303 	    if (y_current->y_type == MLINE || i < y_current->y_size - 1
1304 								     || addcr)
1305 	    {
1306 		if (ins_typebuf((char_u *)"\n", remap, 0, TRUE, silent) == FAIL)
1307 		    return FAIL;
1308 	    }
1309 	    escaped = vim_strsave_escape_csi(y_current->y_array[i]);
1310 	    if (escaped == NULL)
1311 		return FAIL;
1312 	    retval = ins_typebuf(escaped, remap, 0, TRUE, silent);
1313 	    vim_free(escaped);
1314 	    if (retval == FAIL)
1315 		return FAIL;
1316 	    if (colon && ins_typebuf((char_u *)":", remap, 0, TRUE, silent)
1317 								      == FAIL)
1318 		return FAIL;
1319 	}
1320 	reg_executing = regname == 0 ? '"' : regname; // disable "q" command
1321     }
1322     return retval;
1323 }
1324 
1325 /*
1326  * If "restart_edit" is not zero, put it in the typeahead buffer, so that it's
1327  * used only after other typeahead has been processed.
1328  */
1329     static void
1330 put_reedit_in_typebuf(int silent)
1331 {
1332     char_u	buf[3];
1333 
1334     if (restart_edit != NUL)
1335     {
1336 	if (restart_edit == 'V')
1337 	{
1338 	    buf[0] = 'g';
1339 	    buf[1] = 'R';
1340 	    buf[2] = NUL;
1341 	}
1342 	else
1343 	{
1344 	    buf[0] = restart_edit == 'I' ? 'i' : restart_edit;
1345 	    buf[1] = NUL;
1346 	}
1347 	if (ins_typebuf(buf, REMAP_NONE, 0, TRUE, silent) == OK)
1348 	    restart_edit = NUL;
1349     }
1350 }
1351 
1352 /*
1353  * Insert register contents "s" into the typeahead buffer, so that it will be
1354  * executed again.
1355  * When "esc" is TRUE it is to be taken literally: Escape CSI characters and
1356  * no remapping.
1357  */
1358     static int
1359 put_in_typebuf(
1360     char_u	*s,
1361     int		esc,
1362     int		colon,	    /* add ':' before the line */
1363     int		silent)
1364 {
1365     int		retval = OK;
1366 
1367     put_reedit_in_typebuf(silent);
1368     if (colon)
1369 	retval = ins_typebuf((char_u *)"\n", REMAP_NONE, 0, TRUE, silent);
1370     if (retval == OK)
1371     {
1372 	char_u	*p;
1373 
1374 	if (esc)
1375 	    p = vim_strsave_escape_csi(s);
1376 	else
1377 	    p = s;
1378 	if (p == NULL)
1379 	    retval = FAIL;
1380 	else
1381 	    retval = ins_typebuf(p, esc ? REMAP_NONE : REMAP_YES,
1382 							     0, TRUE, silent);
1383 	if (esc)
1384 	    vim_free(p);
1385     }
1386     if (colon && retval == OK)
1387 	retval = ins_typebuf((char_u *)":", REMAP_NONE, 0, TRUE, silent);
1388     return retval;
1389 }
1390 
1391 /*
1392  * Insert a yank register: copy it into the Read buffer.
1393  * Used by CTRL-R command and middle mouse button in insert mode.
1394  *
1395  * return FAIL for failure, OK otherwise
1396  */
1397     int
1398 insert_reg(
1399     int		regname,
1400     int		literally_arg)	/* insert literally, not as if typed */
1401 {
1402     long	i;
1403     int		retval = OK;
1404     char_u	*arg;
1405     int		allocated;
1406     int		literally = literally_arg;
1407 
1408     /*
1409      * It is possible to get into an endless loop by having CTRL-R a in
1410      * register a and then, in insert mode, doing CTRL-R a.
1411      * If you hit CTRL-C, the loop will be broken here.
1412      */
1413     ui_breakcheck();
1414     if (got_int)
1415 	return FAIL;
1416 
1417     /* check for valid regname */
1418     if (regname != NUL && !valid_yank_reg(regname, FALSE))
1419 	return FAIL;
1420 
1421 #ifdef FEAT_CLIPBOARD
1422     regname = may_get_selection(regname);
1423 #endif
1424 
1425     if (regname == '.')			/* insert last inserted text */
1426 	retval = stuff_inserted(NUL, 1L, TRUE);
1427     else if (get_spec_reg(regname, &arg, &allocated, TRUE))
1428     {
1429 	if (arg == NULL)
1430 	    return FAIL;
1431 	stuffescaped(arg, literally);
1432 	if (allocated)
1433 	    vim_free(arg);
1434     }
1435     else				/* name or number register */
1436     {
1437 	if (get_yank_register(regname, FALSE))
1438 	    literally = TRUE;
1439 	if (y_current->y_array == NULL)
1440 	    retval = FAIL;
1441 	else
1442 	{
1443 	    for (i = 0; i < y_current->y_size; ++i)
1444 	    {
1445 		stuffescaped(y_current->y_array[i], literally);
1446 		/*
1447 		 * Insert a newline between lines and after last line if
1448 		 * y_type is MLINE.
1449 		 */
1450 		if (y_current->y_type == MLINE || i < y_current->y_size - 1)
1451 		    stuffcharReadbuff('\n');
1452 	    }
1453 	}
1454     }
1455 
1456     return retval;
1457 }
1458 
1459 /*
1460  * Stuff a string into the typeahead buffer, such that edit() will insert it
1461  * literally ("literally" TRUE) or interpret is as typed characters.
1462  */
1463     static void
1464 stuffescaped(char_u *arg, int literally)
1465 {
1466     int		c;
1467     char_u	*start;
1468 
1469     while (*arg != NUL)
1470     {
1471 	/* Stuff a sequence of normal ASCII characters, that's fast.  Also
1472 	 * stuff K_SPECIAL to get the effect of a special key when "literally"
1473 	 * is TRUE. */
1474 	start = arg;
1475 	while ((*arg >= ' '
1476 #ifndef EBCDIC
1477 		    && *arg < DEL /* EBCDIC: chars above space are normal */
1478 #endif
1479 		    )
1480 		|| (*arg == K_SPECIAL && !literally))
1481 	    ++arg;
1482 	if (arg > start)
1483 	    stuffReadbuffLen(start, (long)(arg - start));
1484 
1485 	/* stuff a single special character */
1486 	if (*arg != NUL)
1487 	{
1488 	    if (has_mbyte)
1489 		c = mb_cptr2char_adv(&arg);
1490 	    else
1491 		c = *arg++;
1492 	    if (literally && ((c < ' ' && c != TAB) || c == DEL))
1493 		stuffcharReadbuff(Ctrl_V);
1494 	    stuffcharReadbuff(c);
1495 	}
1496     }
1497 }
1498 
1499 /*
1500  * If "regname" is a special register, return TRUE and store a pointer to its
1501  * value in "argp".
1502  */
1503     int
1504 get_spec_reg(
1505     int		regname,
1506     char_u	**argp,
1507     int		*allocated,	/* return: TRUE when value was allocated */
1508     int		errmsg)		/* give error message when failing */
1509 {
1510     int		cnt;
1511 
1512     *argp = NULL;
1513     *allocated = FALSE;
1514     switch (regname)
1515     {
1516 	case '%':		/* file name */
1517 	    if (errmsg)
1518 		check_fname();	/* will give emsg if not set */
1519 	    *argp = curbuf->b_fname;
1520 	    return TRUE;
1521 
1522 	case '#':		/* alternate file name */
1523 	    *argp = getaltfname(errmsg);	/* may give emsg if not set */
1524 	    return TRUE;
1525 
1526 #ifdef FEAT_EVAL
1527 	case '=':		/* result of expression */
1528 	    *argp = get_expr_line();
1529 	    *allocated = TRUE;
1530 	    return TRUE;
1531 #endif
1532 
1533 	case ':':		/* last command line */
1534 	    if (last_cmdline == NULL && errmsg)
1535 		emsg(_(e_nolastcmd));
1536 	    *argp = last_cmdline;
1537 	    return TRUE;
1538 
1539 	case '/':		/* last search-pattern */
1540 	    if (last_search_pat() == NULL && errmsg)
1541 		emsg(_(e_noprevre));
1542 	    *argp = last_search_pat();
1543 	    return TRUE;
1544 
1545 	case '.':		/* last inserted text */
1546 	    *argp = get_last_insert_save();
1547 	    *allocated = TRUE;
1548 	    if (*argp == NULL && errmsg)
1549 		emsg(_(e_noinstext));
1550 	    return TRUE;
1551 
1552 #ifdef FEAT_SEARCHPATH
1553 	case Ctrl_F:		/* Filename under cursor */
1554 	case Ctrl_P:		/* Path under cursor, expand via "path" */
1555 	    if (!errmsg)
1556 		return FALSE;
1557 	    *argp = file_name_at_cursor(FNAME_MESS | FNAME_HYP
1558 			    | (regname == Ctrl_P ? FNAME_EXP : 0), 1L, NULL);
1559 	    *allocated = TRUE;
1560 	    return TRUE;
1561 #endif
1562 
1563 	case Ctrl_W:		/* word under cursor */
1564 	case Ctrl_A:		/* WORD (mnemonic All) under cursor */
1565 	    if (!errmsg)
1566 		return FALSE;
1567 	    cnt = find_ident_under_cursor(argp, regname == Ctrl_W
1568 				   ?  (FIND_IDENT|FIND_STRING) : FIND_STRING);
1569 	    *argp = cnt ? vim_strnsave(*argp, cnt) : NULL;
1570 	    *allocated = TRUE;
1571 	    return TRUE;
1572 
1573 	case Ctrl_L:		/* Line under cursor */
1574 	    if (!errmsg)
1575 		return FALSE;
1576 
1577 	    *argp = ml_get_buf(curwin->w_buffer,
1578 			curwin->w_cursor.lnum, FALSE);
1579 	    return TRUE;
1580 
1581 	case '_':		/* black hole: always empty */
1582 	    *argp = (char_u *)"";
1583 	    return TRUE;
1584     }
1585 
1586     return FALSE;
1587 }
1588 
1589 /*
1590  * Paste a yank register into the command line.
1591  * Only for non-special registers.
1592  * Used by CTRL-R command in command-line mode
1593  * insert_reg() can't be used here, because special characters from the
1594  * register contents will be interpreted as commands.
1595  *
1596  * return FAIL for failure, OK otherwise
1597  */
1598     int
1599 cmdline_paste_reg(
1600     int regname,
1601     int literally_arg,	/* Insert text literally instead of "as typed" */
1602     int remcr)		/* don't add CR characters */
1603 {
1604     long	i;
1605     int		literally = literally_arg;
1606 
1607     if (get_yank_register(regname, FALSE))
1608 	literally = TRUE;
1609     if (y_current->y_array == NULL)
1610 	return FAIL;
1611 
1612     for (i = 0; i < y_current->y_size; ++i)
1613     {
1614 	cmdline_paste_str(y_current->y_array[i], literally);
1615 
1616 	/* Insert ^M between lines and after last line if type is MLINE.
1617 	 * Don't do this when "remcr" is TRUE. */
1618 	if ((y_current->y_type == MLINE || i < y_current->y_size - 1) && !remcr)
1619 	    cmdline_paste_str((char_u *)"\r", literally);
1620 
1621 	/* Check for CTRL-C, in case someone tries to paste a few thousand
1622 	 * lines and gets bored. */
1623 	ui_breakcheck();
1624 	if (got_int)
1625 	    return FAIL;
1626     }
1627     return OK;
1628 }
1629 
1630 #if defined(FEAT_CLIPBOARD) || defined(PROTO)
1631 /*
1632  * Adjust the register name pointed to with "rp" for the clipboard being
1633  * used always and the clipboard being available.
1634  */
1635     void
1636 adjust_clip_reg(int *rp)
1637 {
1638     /* If no reg. specified, and "unnamed" or "unnamedplus" is in 'clipboard',
1639      * use '*' or '+' reg, respectively. "unnamedplus" prevails. */
1640     if (*rp == 0 && (clip_unnamed != 0 || clip_unnamed_saved != 0))
1641     {
1642 	if (clip_unnamed != 0)
1643 	    *rp = ((clip_unnamed & CLIP_UNNAMED_PLUS) && clip_plus.available)
1644 								  ? '+' : '*';
1645 	else
1646 	    *rp = ((clip_unnamed_saved & CLIP_UNNAMED_PLUS) && clip_plus.available)
1647 								  ? '+' : '*';
1648     }
1649     if (!clip_star.available && *rp == '*')
1650 	*rp = 0;
1651     if (!clip_plus.available && *rp == '+')
1652 	*rp = 0;
1653 }
1654 #endif
1655 
1656 /*
1657  * Shift the delete registers: "9 is cleared, "8 becomes "9, etc.
1658  */
1659     void
1660 shift_delete_registers()
1661 {
1662     int		n;
1663 
1664     y_current = &y_regs[9];
1665     free_yank_all();			/* free register nine */
1666     for (n = 9; n > 1; --n)
1667 	y_regs[n] = y_regs[n - 1];
1668     y_current = &y_regs[1];
1669     if (!y_append)
1670 	y_previous = y_current;
1671     y_regs[1].y_array = NULL;		/* set register one to empty */
1672 }
1673 
1674 #if defined(FEAT_EVAL)
1675     static void
1676 yank_do_autocmd(oparg_T *oap, yankreg_T *reg)
1677 {
1678     static int	recursive = FALSE;
1679     dict_T	*v_event;
1680     list_T	*list;
1681     int		n;
1682     char_u	buf[NUMBUFLEN + 2];
1683     long	reglen = 0;
1684 
1685     if (recursive)
1686 	return;
1687 
1688     v_event = get_vim_var_dict(VV_EVENT);
1689 
1690     list = list_alloc();
1691     if (list == NULL)
1692 	return;
1693     for (n = 0; n < reg->y_size; n++)
1694 	list_append_string(list, reg->y_array[n], -1);
1695     list->lv_lock = VAR_FIXED;
1696     dict_add_list(v_event, "regcontents", list);
1697 
1698     buf[0] = (char_u)oap->regname;
1699     buf[1] = NUL;
1700     dict_add_string(v_event, "regname", buf);
1701 
1702     buf[0] = get_op_char(oap->op_type);
1703     buf[1] = get_extra_op_char(oap->op_type);
1704     buf[2] = NUL;
1705     dict_add_string(v_event, "operator", buf);
1706 
1707     buf[0] = NUL;
1708     buf[1] = NUL;
1709     switch (get_reg_type(oap->regname, &reglen))
1710     {
1711 	case MLINE: buf[0] = 'V'; break;
1712 	case MCHAR: buf[0] = 'v'; break;
1713 	case MBLOCK:
1714 		vim_snprintf((char *)buf, sizeof(buf), "%c%ld", Ctrl_V,
1715 			     reglen + 1);
1716 		break;
1717     }
1718     dict_add_string(v_event, "regtype", buf);
1719 
1720     /* Lock the dictionary and its keys */
1721     dict_set_items_ro(v_event);
1722 
1723     recursive = TRUE;
1724     textlock++;
1725     apply_autocmds(EVENT_TEXTYANKPOST, NULL, NULL, FALSE, curbuf);
1726     textlock--;
1727     recursive = FALSE;
1728 
1729     /* Empty the dictionary, v:event is still valid */
1730     dict_free_contents(v_event);
1731     hash_init(&v_event->dv_hashtab);
1732 }
1733 #endif
1734 
1735 /*
1736  * Handle a delete operation.
1737  *
1738  * Return FAIL if undo failed, OK otherwise.
1739  */
1740     int
1741 op_delete(oparg_T *oap)
1742 {
1743     int			n;
1744     linenr_T		lnum;
1745     char_u		*ptr;
1746     char_u		*newp, *oldp;
1747     struct block_def	bd;
1748     linenr_T		old_lcount = curbuf->b_ml.ml_line_count;
1749     int			did_yank = FALSE;
1750     int			orig_regname = oap->regname;
1751 
1752     if (curbuf->b_ml.ml_flags & ML_EMPTY)	    /* nothing to do */
1753 	return OK;
1754 
1755     /* Nothing to delete, return here.	Do prepare undo, for op_change(). */
1756     if (oap->empty)
1757 	return u_save_cursor();
1758 
1759     if (!curbuf->b_p_ma)
1760     {
1761 	emsg(_(e_modifiable));
1762 	return FAIL;
1763     }
1764 
1765 #ifdef FEAT_CLIPBOARD
1766     adjust_clip_reg(&oap->regname);
1767 #endif
1768 
1769     if (has_mbyte)
1770 	mb_adjust_opend(oap);
1771 
1772     /*
1773      * Imitate the strange Vi behaviour: If the delete spans more than one
1774      * line and motion_type == MCHAR and the result is a blank line, make the
1775      * delete linewise.  Don't do this for the change command or Visual mode.
1776      */
1777     if (       oap->motion_type == MCHAR
1778 	    && !oap->is_VIsual
1779 	    && !oap->block_mode
1780 	    && oap->line_count > 1
1781 	    && oap->motion_force == NUL
1782 	    && oap->op_type == OP_DELETE)
1783     {
1784 	ptr = ml_get(oap->end.lnum) + oap->end.col;
1785 	if (*ptr != NUL)
1786 	    ptr += oap->inclusive;
1787 	ptr = skipwhite(ptr);
1788 	if (*ptr == NUL && inindent(0))
1789 	    oap->motion_type = MLINE;
1790     }
1791 
1792     /*
1793      * Check for trying to delete (e.g. "D") in an empty line.
1794      * Note: For the change operator it is ok.
1795      */
1796     if (       oap->motion_type == MCHAR
1797 	    && oap->line_count == 1
1798 	    && oap->op_type == OP_DELETE
1799 	    && *ml_get(oap->start.lnum) == NUL)
1800     {
1801 	/*
1802 	 * It's an error to operate on an empty region, when 'E' included in
1803 	 * 'cpoptions' (Vi compatible).
1804 	 */
1805 	if (virtual_op)
1806 	    /* Virtual editing: Nothing gets deleted, but we set the '[ and ']
1807 	     * marks as if it happened. */
1808 	    goto setmarks;
1809 	if (vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL)
1810 	    beep_flush();
1811 	return OK;
1812     }
1813 
1814     /*
1815      * Do a yank of whatever we're about to delete.
1816      * If a yank register was specified, put the deleted text into that
1817      * register.  For the black hole register '_' don't yank anything.
1818      */
1819     if (oap->regname != '_')
1820     {
1821 	if (oap->regname != 0)
1822 	{
1823 	    /* check for read-only register */
1824 	    if (!valid_yank_reg(oap->regname, TRUE))
1825 	    {
1826 		beep_flush();
1827 		return OK;
1828 	    }
1829 	    get_yank_register(oap->regname, TRUE); /* yank into specif'd reg. */
1830 	    if (op_yank(oap, TRUE, FALSE) == OK)   /* yank without message */
1831 		did_yank = TRUE;
1832 	}
1833 
1834 	/*
1835 	 * Put deleted text into register 1 and shift number registers if the
1836 	 * delete contains a line break, or when a regname has been specified.
1837 	 * Use the register name from before adjust_clip_reg() may have
1838 	 * changed it.
1839 	 */
1840 	if (orig_regname != 0 || oap->motion_type == MLINE
1841 				   || oap->line_count > 1 || oap->use_reg_one)
1842 	{
1843 	    shift_delete_registers();
1844 	    if (op_yank(oap, TRUE, FALSE) == OK)
1845 		did_yank = TRUE;
1846 	}
1847 
1848 	/* Yank into small delete register when no named register specified
1849 	 * and the delete is within one line. */
1850 	if ((
1851 #ifdef FEAT_CLIPBOARD
1852 	    ((clip_unnamed & CLIP_UNNAMED) && oap->regname == '*') ||
1853 	    ((clip_unnamed & CLIP_UNNAMED_PLUS) && oap->regname == '+') ||
1854 #endif
1855 	    oap->regname == 0) && oap->motion_type != MLINE
1856 						      && oap->line_count == 1)
1857 	{
1858 	    oap->regname = '-';
1859 	    get_yank_register(oap->regname, TRUE);
1860 	    if (op_yank(oap, TRUE, FALSE) == OK)
1861 		did_yank = TRUE;
1862 	    oap->regname = 0;
1863 	}
1864 
1865 	/*
1866 	 * If there's too much stuff to fit in the yank register, then get a
1867 	 * confirmation before doing the delete. This is crude, but simple.
1868 	 * And it avoids doing a delete of something we can't put back if we
1869 	 * want.
1870 	 */
1871 	if (!did_yank)
1872 	{
1873 	    int msg_silent_save = msg_silent;
1874 
1875 	    msg_silent = 0;	/* must display the prompt */
1876 	    n = ask_yesno((char_u *)_("cannot yank; delete anyway"), TRUE);
1877 	    msg_silent = msg_silent_save;
1878 	    if (n != 'y')
1879 	    {
1880 		emsg(_(e_abort));
1881 		return FAIL;
1882 	    }
1883 	}
1884 
1885 #if defined(FEAT_EVAL)
1886 	if (did_yank && has_textyankpost())
1887 	    yank_do_autocmd(oap, y_current);
1888 #endif
1889     }
1890 
1891     /*
1892      * block mode delete
1893      */
1894     if (oap->block_mode)
1895     {
1896 	if (u_save((linenr_T)(oap->start.lnum - 1),
1897 			       (linenr_T)(oap->end.lnum + 1)) == FAIL)
1898 	    return FAIL;
1899 
1900 	for (lnum = curwin->w_cursor.lnum; lnum <= oap->end.lnum; ++lnum)
1901 	{
1902 	    block_prep(oap, &bd, lnum, TRUE);
1903 	    if (bd.textlen == 0)	/* nothing to delete */
1904 		continue;
1905 
1906 	    /* Adjust cursor position for tab replaced by spaces and 'lbr'. */
1907 	    if (lnum == curwin->w_cursor.lnum)
1908 	    {
1909 		curwin->w_cursor.col = bd.textcol + bd.startspaces;
1910 		curwin->w_cursor.coladd = 0;
1911 	    }
1912 
1913 	    /* n == number of chars deleted
1914 	     * If we delete a TAB, it may be replaced by several characters.
1915 	     * Thus the number of characters may increase!
1916 	     */
1917 	    n = bd.textlen - bd.startspaces - bd.endspaces;
1918 	    oldp = ml_get(lnum);
1919 	    newp = alloc_check((unsigned)STRLEN(oldp) + 1 - n);
1920 	    if (newp == NULL)
1921 		continue;
1922 	    /* copy up to deleted part */
1923 	    mch_memmove(newp, oldp, (size_t)bd.textcol);
1924 	    /* insert spaces */
1925 	    vim_memset(newp + bd.textcol, ' ',
1926 				     (size_t)(bd.startspaces + bd.endspaces));
1927 	    /* copy the part after the deleted part */
1928 	    oldp += bd.textcol + bd.textlen;
1929 	    STRMOVE(newp + bd.textcol + bd.startspaces + bd.endspaces, oldp);
1930 	    /* replace the line */
1931 	    ml_replace(lnum, newp, FALSE);
1932 	}
1933 
1934 	check_cursor_col();
1935 	changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1936 						       oap->end.lnum + 1, 0L);
1937 	oap->line_count = 0;	    /* no lines deleted */
1938     }
1939     else if (oap->motion_type == MLINE)
1940     {
1941 	if (oap->op_type == OP_CHANGE)
1942 	{
1943 	    /* Delete the lines except the first one.  Temporarily move the
1944 	     * cursor to the next line.  Save the current line number, if the
1945 	     * last line is deleted it may be changed.
1946 	     */
1947 	    if (oap->line_count > 1)
1948 	    {
1949 		lnum = curwin->w_cursor.lnum;
1950 		++curwin->w_cursor.lnum;
1951 		del_lines((long)(oap->line_count - 1), TRUE);
1952 		curwin->w_cursor.lnum = lnum;
1953 	    }
1954 	    if (u_save_cursor() == FAIL)
1955 		return FAIL;
1956 	    if (curbuf->b_p_ai)		    /* don't delete indent */
1957 	    {
1958 		beginline(BL_WHITE);	    /* cursor on first non-white */
1959 		did_ai = TRUE;		    /* delete the indent when ESC hit */
1960 		ai_col = curwin->w_cursor.col;
1961 	    }
1962 	    else
1963 		beginline(0);		    /* cursor in column 0 */
1964 	    truncate_line(FALSE);   /* delete the rest of the line */
1965 				    /* leave cursor past last char in line */
1966 	    if (oap->line_count > 1)
1967 		u_clearline();	    /* "U" command not possible after "2cc" */
1968 	}
1969 	else
1970 	{
1971 	    del_lines(oap->line_count, TRUE);
1972 	    beginline(BL_WHITE | BL_FIX);
1973 	    u_clearline();	/* "U" command not possible after "dd" */
1974 	}
1975     }
1976     else
1977     {
1978 	if (virtual_op)
1979 	{
1980 	    int		endcol = 0;
1981 
1982 	    /* For virtualedit: break the tabs that are partly included. */
1983 	    if (gchar_pos(&oap->start) == '\t')
1984 	    {
1985 		if (u_save_cursor() == FAIL)	/* save first line for undo */
1986 		    return FAIL;
1987 		if (oap->line_count == 1)
1988 		    endcol = getviscol2(oap->end.col, oap->end.coladd);
1989 		coladvance_force(getviscol2(oap->start.col, oap->start.coladd));
1990 		oap->start = curwin->w_cursor;
1991 		if (oap->line_count == 1)
1992 		{
1993 		    coladvance(endcol);
1994 		    oap->end.col = curwin->w_cursor.col;
1995 		    oap->end.coladd = curwin->w_cursor.coladd;
1996 		    curwin->w_cursor = oap->start;
1997 		}
1998 	    }
1999 
2000 	    /* Break a tab only when it's included in the area. */
2001 	    if (gchar_pos(&oap->end) == '\t'
2002 				     && (int)oap->end.coladd < oap->inclusive)
2003 	    {
2004 		/* save last line for undo */
2005 		if (u_save((linenr_T)(oap->end.lnum - 1),
2006 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
2007 		    return FAIL;
2008 		curwin->w_cursor = oap->end;
2009 		coladvance_force(getviscol2(oap->end.col, oap->end.coladd));
2010 		oap->end = curwin->w_cursor;
2011 		curwin->w_cursor = oap->start;
2012 	    }
2013 	}
2014 
2015 	if (oap->line_count == 1)	/* delete characters within one line */
2016 	{
2017 	    if (u_save_cursor() == FAIL)	/* save line for undo */
2018 		return FAIL;
2019 
2020 	    /* if 'cpoptions' contains '$', display '$' at end of change */
2021 	    if (       vim_strchr(p_cpo, CPO_DOLLAR) != NULL
2022 		    && oap->op_type == OP_CHANGE
2023 		    && oap->end.lnum == curwin->w_cursor.lnum
2024 		    && !oap->is_VIsual)
2025 		display_dollar(oap->end.col - !oap->inclusive);
2026 
2027 	    n = oap->end.col - oap->start.col + 1 - !oap->inclusive;
2028 
2029 	    if (virtual_op)
2030 	    {
2031 		/* fix up things for virtualedit-delete:
2032 		 * break the tabs which are going to get in our way
2033 		 */
2034 		char_u		*curline = ml_get_curline();
2035 		int		len = (int)STRLEN(curline);
2036 
2037 		if (oap->end.coladd != 0
2038 			&& (int)oap->end.col >= len - 1
2039 			&& !(oap->start.coladd && (int)oap->end.col >= len - 1))
2040 		    n++;
2041 		/* Delete at least one char (e.g, when on a control char). */
2042 		if (n == 0 && oap->start.coladd != oap->end.coladd)
2043 		    n = 1;
2044 
2045 		/* When deleted a char in the line, reset coladd. */
2046 		if (gchar_cursor() != NUL)
2047 		    curwin->w_cursor.coladd = 0;
2048 	    }
2049 	    (void)del_bytes((long)n, !virtual_op,
2050 			    oap->op_type == OP_DELETE && !oap->is_VIsual);
2051 	}
2052 	else				/* delete characters between lines */
2053 	{
2054 	    pos_T   curpos;
2055 
2056 	    /* save deleted and changed lines for undo */
2057 	    if (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
2058 		 (linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL)
2059 		return FAIL;
2060 
2061 	    truncate_line(TRUE);	/* delete from cursor to end of line */
2062 
2063 	    curpos = curwin->w_cursor;	/* remember curwin->w_cursor */
2064 	    ++curwin->w_cursor.lnum;
2065 	    del_lines((long)(oap->line_count - 2), FALSE);
2066 
2067 	    /* delete from start of line until op_end */
2068 	    n = (oap->end.col + 1 - !oap->inclusive);
2069 	    curwin->w_cursor.col = 0;
2070 	    (void)del_bytes((long)n, !virtual_op,
2071 			    oap->op_type == OP_DELETE && !oap->is_VIsual);
2072 	    curwin->w_cursor = curpos;	/* restore curwin->w_cursor */
2073 	    (void)do_join(2, FALSE, FALSE, FALSE, FALSE);
2074 	}
2075     }
2076 
2077     msgmore(curbuf->b_ml.ml_line_count - old_lcount);
2078 
2079 setmarks:
2080     if (oap->block_mode)
2081     {
2082 	curbuf->b_op_end.lnum = oap->end.lnum;
2083 	curbuf->b_op_end.col = oap->start.col;
2084     }
2085     else
2086 	curbuf->b_op_end = oap->start;
2087     curbuf->b_op_start = oap->start;
2088 
2089     return OK;
2090 }
2091 
2092 /*
2093  * Adjust end of operating area for ending on a multi-byte character.
2094  * Used for deletion.
2095  */
2096     static void
2097 mb_adjust_opend(oparg_T *oap)
2098 {
2099     char_u	*p;
2100 
2101     if (oap->inclusive)
2102     {
2103 	p = ml_get(oap->end.lnum);
2104 	oap->end.col += mb_tail_off(p, p + oap->end.col);
2105     }
2106 }
2107 
2108 /*
2109  * Replace the character under the cursor with "c".
2110  * This takes care of multi-byte characters.
2111  */
2112     static void
2113 replace_character(int c)
2114 {
2115     int n = State;
2116 
2117     State = REPLACE;
2118     ins_char(c);
2119     State = n;
2120     /* Backup to the replaced character. */
2121     dec_cursor();
2122 }
2123 
2124 /*
2125  * Replace a whole area with one character.
2126  */
2127     int
2128 op_replace(oparg_T *oap, int c)
2129 {
2130     int			n, numc;
2131     int			num_chars;
2132     char_u		*newp, *oldp;
2133     size_t		oldlen;
2134     struct block_def	bd;
2135     char_u		*after_p = NULL;
2136     int			had_ctrl_v_cr = FALSE;
2137 
2138     if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty)
2139 	return OK;	    /* nothing to do */
2140 
2141     if (c == REPLACE_CR_NCHAR)
2142     {
2143 	had_ctrl_v_cr = TRUE;
2144 	c = CAR;
2145     }
2146     else if (c == REPLACE_NL_NCHAR)
2147     {
2148 	had_ctrl_v_cr = TRUE;
2149 	c = NL;
2150     }
2151 
2152     if (has_mbyte)
2153 	mb_adjust_opend(oap);
2154 
2155     if (u_save((linenr_T)(oap->start.lnum - 1),
2156 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
2157 	return FAIL;
2158 
2159     /*
2160      * block mode replace
2161      */
2162     if (oap->block_mode)
2163     {
2164 	bd.is_MAX = (curwin->w_curswant == MAXCOL);
2165 	for ( ; curwin->w_cursor.lnum <= oap->end.lnum; ++curwin->w_cursor.lnum)
2166 	{
2167 	    curwin->w_cursor.col = 0;  /* make sure cursor position is valid */
2168 	    block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE);
2169 	    if (bd.textlen == 0 && (!virtual_op || bd.is_MAX))
2170 		continue;	    /* nothing to replace */
2171 
2172 	    /* n == number of extra chars required
2173 	     * If we split a TAB, it may be replaced by several characters.
2174 	     * Thus the number of characters may increase!
2175 	     */
2176 	    /* If the range starts in virtual space, count the initial
2177 	     * coladd offset as part of "startspaces" */
2178 	    if (virtual_op && bd.is_short && *bd.textstart == NUL)
2179 	    {
2180 		pos_T vpos;
2181 
2182 		vpos.lnum = curwin->w_cursor.lnum;
2183 		getvpos(&vpos, oap->start_vcol);
2184 		bd.startspaces += vpos.coladd;
2185 		n = bd.startspaces;
2186 	    }
2187 	    else
2188 		/* allow for pre spaces */
2189 		n = (bd.startspaces ? bd.start_char_vcols - 1 : 0);
2190 
2191 	    /* allow for post spp */
2192 	    n += (bd.endspaces
2193 		    && !bd.is_oneChar
2194 		    && bd.end_char_vcols > 0) ? bd.end_char_vcols - 1 : 0;
2195 	    /* Figure out how many characters to replace. */
2196 	    numc = oap->end_vcol - oap->start_vcol + 1;
2197 	    if (bd.is_short && (!virtual_op || bd.is_MAX))
2198 		numc -= (oap->end_vcol - bd.end_vcol) + 1;
2199 
2200 	    /* A double-wide character can be replaced only up to half the
2201 	     * times. */
2202 	    if ((*mb_char2cells)(c) > 1)
2203 	    {
2204 		if ((numc & 1) && !bd.is_short)
2205 		{
2206 		    ++bd.endspaces;
2207 		    ++n;
2208 		}
2209 		numc = numc / 2;
2210 	    }
2211 
2212 	    /* Compute bytes needed, move character count to num_chars. */
2213 	    num_chars = numc;
2214 	    numc *= (*mb_char2len)(c);
2215 	    /* oldlen includes textlen, so don't double count */
2216 	    n += numc - bd.textlen;
2217 
2218 	    oldp = ml_get_curline();
2219 	    oldlen = STRLEN(oldp);
2220 	    newp = alloc_check((unsigned)oldlen + 1 + n);
2221 	    if (newp == NULL)
2222 		continue;
2223 	    vim_memset(newp, NUL, (size_t)(oldlen + 1 + n));
2224 	    /* copy up to deleted part */
2225 	    mch_memmove(newp, oldp, (size_t)bd.textcol);
2226 	    oldp += bd.textcol + bd.textlen;
2227 	    /* insert pre-spaces */
2228 	    vim_memset(newp + bd.textcol, ' ', (size_t)bd.startspaces);
2229 	    /* insert replacement chars CHECK FOR ALLOCATED SPACE */
2230 	    /* REPLACE_CR_NCHAR/REPLACE_NL_NCHAR is used for entering CR
2231 	     * literally. */
2232 	    if (had_ctrl_v_cr || (c != '\r' && c != '\n'))
2233 	    {
2234 		if (has_mbyte)
2235 		{
2236 		    n = (int)STRLEN(newp);
2237 		    while (--num_chars >= 0)
2238 			n += (*mb_char2bytes)(c, newp + n);
2239 		}
2240 		else
2241 		    vim_memset(newp + STRLEN(newp), c, (size_t)numc);
2242 		if (!bd.is_short)
2243 		{
2244 		    /* insert post-spaces */
2245 		    vim_memset(newp + STRLEN(newp), ' ', (size_t)bd.endspaces);
2246 		    /* copy the part after the changed part */
2247 		    STRMOVE(newp + STRLEN(newp), oldp);
2248 		}
2249 	    }
2250 	    else
2251 	    {
2252 		/* Replacing with \r or \n means splitting the line. */
2253 		after_p = alloc_check(
2254 				   (unsigned)(oldlen + 1 + n - STRLEN(newp)));
2255 		if (after_p != NULL)
2256 		    STRMOVE(after_p, oldp);
2257 	    }
2258 	    /* replace the line */
2259 	    ml_replace(curwin->w_cursor.lnum, newp, FALSE);
2260 	    if (after_p != NULL)
2261 	    {
2262 		ml_append(curwin->w_cursor.lnum++, after_p, 0, FALSE);
2263 		appended_lines_mark(curwin->w_cursor.lnum, 1L);
2264 		oap->end.lnum++;
2265 		vim_free(after_p);
2266 	    }
2267 	}
2268     }
2269     else
2270     {
2271 	/*
2272 	 * MCHAR and MLINE motion replace.
2273 	 */
2274 	if (oap->motion_type == MLINE)
2275 	{
2276 	    oap->start.col = 0;
2277 	    curwin->w_cursor.col = 0;
2278 	    oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
2279 	    if (oap->end.col)
2280 		--oap->end.col;
2281 	}
2282 	else if (!oap->inclusive)
2283 	    dec(&(oap->end));
2284 
2285 	while (LTOREQ_POS(curwin->w_cursor, oap->end))
2286 	{
2287 	    n = gchar_cursor();
2288 	    if (n != NUL)
2289 	    {
2290 		if ((*mb_char2len)(c) > 1 || (*mb_char2len)(n) > 1)
2291 		{
2292 		    /* This is slow, but it handles replacing a single-byte
2293 		     * with a multi-byte and the other way around. */
2294 		    if (curwin->w_cursor.lnum == oap->end.lnum)
2295 			oap->end.col += (*mb_char2len)(c) - (*mb_char2len)(n);
2296 		    replace_character(c);
2297 		}
2298 		else
2299 		{
2300 		    if (n == TAB)
2301 		    {
2302 			int end_vcol = 0;
2303 
2304 			if (curwin->w_cursor.lnum == oap->end.lnum)
2305 			{
2306 			    /* oap->end has to be recalculated when
2307 			     * the tab breaks */
2308 			    end_vcol = getviscol2(oap->end.col,
2309 							     oap->end.coladd);
2310 			}
2311 			coladvance_force(getviscol());
2312 			if (curwin->w_cursor.lnum == oap->end.lnum)
2313 			    getvpos(&oap->end, end_vcol);
2314 		    }
2315 		    PBYTE(curwin->w_cursor, c);
2316 		}
2317 	    }
2318 	    else if (virtual_op && curwin->w_cursor.lnum == oap->end.lnum)
2319 	    {
2320 		int virtcols = oap->end.coladd;
2321 
2322 		if (curwin->w_cursor.lnum == oap->start.lnum
2323 			&& oap->start.col == oap->end.col && oap->start.coladd)
2324 		    virtcols -= oap->start.coladd;
2325 
2326 		/* oap->end has been trimmed so it's effectively inclusive;
2327 		 * as a result an extra +1 must be counted so we don't
2328 		 * trample the NUL byte. */
2329 		coladvance_force(getviscol2(oap->end.col, oap->end.coladd) + 1);
2330 		curwin->w_cursor.col -= (virtcols + 1);
2331 		for (; virtcols >= 0; virtcols--)
2332 		{
2333                    if ((*mb_char2len)(c) > 1)
2334 		       replace_character(c);
2335                    else
2336 			PBYTE(curwin->w_cursor, c);
2337 		   if (inc(&curwin->w_cursor) == -1)
2338 		       break;
2339 		}
2340 	    }
2341 
2342 	    /* Advance to next character, stop at the end of the file. */
2343 	    if (inc_cursor() == -1)
2344 		break;
2345 	}
2346     }
2347 
2348     curwin->w_cursor = oap->start;
2349     check_cursor();
2350     changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L);
2351 
2352     /* Set "'[" and "']" marks. */
2353     curbuf->b_op_start = oap->start;
2354     curbuf->b_op_end = oap->end;
2355 
2356     return OK;
2357 }
2358 
2359 static int swapchars(int op_type, pos_T *pos, int length);
2360 
2361 /*
2362  * Handle the (non-standard vi) tilde operator.  Also for "gu", "gU" and "g?".
2363  */
2364     void
2365 op_tilde(oparg_T *oap)
2366 {
2367     pos_T		pos;
2368     struct block_def	bd;
2369     int			did_change = FALSE;
2370 
2371     if (u_save((linenr_T)(oap->start.lnum - 1),
2372 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
2373 	return;
2374 
2375     pos = oap->start;
2376     if (oap->block_mode)		    /* Visual block mode */
2377     {
2378 	for (; pos.lnum <= oap->end.lnum; ++pos.lnum)
2379 	{
2380 	    int one_change;
2381 
2382 	    block_prep(oap, &bd, pos.lnum, FALSE);
2383 	    pos.col = bd.textcol;
2384 	    one_change = swapchars(oap->op_type, &pos, bd.textlen);
2385 	    did_change |= one_change;
2386 
2387 #ifdef FEAT_NETBEANS_INTG
2388 	    if (netbeans_active() && one_change)
2389 	    {
2390 		char_u *ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
2391 
2392 		netbeans_removed(curbuf, pos.lnum, bd.textcol,
2393 							    (long)bd.textlen);
2394 		netbeans_inserted(curbuf, pos.lnum, bd.textcol,
2395 						&ptr[bd.textcol], bd.textlen);
2396 	    }
2397 #endif
2398 	}
2399 	if (did_change)
2400 	    changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
2401     }
2402     else				    /* not block mode */
2403     {
2404 	if (oap->motion_type == MLINE)
2405 	{
2406 	    oap->start.col = 0;
2407 	    pos.col = 0;
2408 	    oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
2409 	    if (oap->end.col)
2410 		--oap->end.col;
2411 	}
2412 	else if (!oap->inclusive)
2413 	    dec(&(oap->end));
2414 
2415 	if (pos.lnum == oap->end.lnum)
2416 	    did_change = swapchars(oap->op_type, &pos,
2417 						  oap->end.col - pos.col + 1);
2418 	else
2419 	    for (;;)
2420 	    {
2421 		did_change |= swapchars(oap->op_type, &pos,
2422 				pos.lnum == oap->end.lnum ? oap->end.col + 1:
2423 					   (int)STRLEN(ml_get_pos(&pos)));
2424 		if (LTOREQ_POS(oap->end, pos) || inc(&pos) == -1)
2425 		    break;
2426 	    }
2427 	if (did_change)
2428 	{
2429 	    changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1,
2430 									  0L);
2431 #ifdef FEAT_NETBEANS_INTG
2432 	    if (netbeans_active() && did_change)
2433 	    {
2434 		char_u *ptr;
2435 		int count;
2436 
2437 		pos = oap->start;
2438 		while (pos.lnum < oap->end.lnum)
2439 		{
2440 		    ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
2441 		    count = (int)STRLEN(ptr) - pos.col;
2442 		    netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
2443 		    netbeans_inserted(curbuf, pos.lnum, pos.col,
2444 							&ptr[pos.col], count);
2445 		    pos.col = 0;
2446 		    pos.lnum++;
2447 		}
2448 		ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
2449 		count = oap->end.col - pos.col + 1;
2450 		netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
2451 		netbeans_inserted(curbuf, pos.lnum, pos.col,
2452 							&ptr[pos.col], count);
2453 	    }
2454 #endif
2455 	}
2456     }
2457 
2458     if (!did_change && oap->is_VIsual)
2459 	/* No change: need to remove the Visual selection */
2460 	redraw_curbuf_later(INVERTED);
2461 
2462     /*
2463      * Set '[ and '] marks.
2464      */
2465     curbuf->b_op_start = oap->start;
2466     curbuf->b_op_end = oap->end;
2467 
2468     if (oap->line_count > p_report)
2469 	smsg(NGETTEXT("%ld line changed", "%ld lines changed",
2470 					    oap->line_count), oap->line_count);
2471 }
2472 
2473 /*
2474  * Invoke swapchar() on "length" bytes at position "pos".
2475  * "pos" is advanced to just after the changed characters.
2476  * "length" is rounded up to include the whole last multi-byte character.
2477  * Also works correctly when the number of bytes changes.
2478  * Returns TRUE if some character was changed.
2479  */
2480     static int
2481 swapchars(int op_type, pos_T *pos, int length)
2482 {
2483     int todo;
2484     int	did_change = 0;
2485 
2486     for (todo = length; todo > 0; --todo)
2487     {
2488 	if (has_mbyte)
2489 	{
2490 	    int len = (*mb_ptr2len)(ml_get_pos(pos));
2491 
2492 	    /* we're counting bytes, not characters */
2493 	    if (len > 0)
2494 		todo -= len - 1;
2495 	}
2496 	did_change |= swapchar(op_type, pos);
2497 	if (inc(pos) == -1)    /* at end of file */
2498 	    break;
2499     }
2500     return did_change;
2501 }
2502 
2503 /*
2504  * If op_type == OP_UPPER: make uppercase,
2505  * if op_type == OP_LOWER: make lowercase,
2506  * if op_type == OP_ROT13: do rot13 encoding,
2507  * else swap case of character at 'pos'
2508  * returns TRUE when something actually changed.
2509  */
2510     int
2511 swapchar(int op_type, pos_T *pos)
2512 {
2513     int	    c;
2514     int	    nc;
2515 
2516     c = gchar_pos(pos);
2517 
2518     /* Only do rot13 encoding for ASCII characters. */
2519     if (c >= 0x80 && op_type == OP_ROT13)
2520 	return FALSE;
2521 
2522     if (op_type == OP_UPPER && c == 0xdf
2523 		      && (enc_latin1like || STRCMP(p_enc, "iso-8859-2") == 0))
2524     {
2525 	pos_T   sp = curwin->w_cursor;
2526 
2527 	/* Special handling of German sharp s: change to "SS". */
2528 	curwin->w_cursor = *pos;
2529 	del_char(FALSE);
2530 	ins_char('S');
2531 	ins_char('S');
2532 	curwin->w_cursor = sp;
2533 	inc(pos);
2534     }
2535 
2536     if (enc_dbcs != 0 && c >= 0x100)	/* No lower/uppercase letter */
2537 	return FALSE;
2538     nc = c;
2539     if (MB_ISLOWER(c))
2540     {
2541 	if (op_type == OP_ROT13)
2542 	    nc = ROT13(c, 'a');
2543 	else if (op_type != OP_LOWER)
2544 	    nc = MB_TOUPPER(c);
2545     }
2546     else if (MB_ISUPPER(c))
2547     {
2548 	if (op_type == OP_ROT13)
2549 	    nc = ROT13(c, 'A');
2550 	else if (op_type != OP_UPPER)
2551 	    nc = MB_TOLOWER(c);
2552     }
2553     if (nc != c)
2554     {
2555 	if (enc_utf8 && (c >= 0x80 || nc >= 0x80))
2556 	{
2557 	    pos_T   sp = curwin->w_cursor;
2558 
2559 	    curwin->w_cursor = *pos;
2560 	    /* don't use del_char(), it also removes composing chars */
2561 	    del_bytes(utf_ptr2len(ml_get_cursor()), FALSE, FALSE);
2562 	    ins_char(nc);
2563 	    curwin->w_cursor = sp;
2564 	}
2565 	else
2566 	    PBYTE(*pos, nc);
2567 	return TRUE;
2568     }
2569     return FALSE;
2570 }
2571 
2572 /*
2573  * op_insert - Insert and append operators for Visual mode.
2574  */
2575     void
2576 op_insert(oparg_T *oap, long count1)
2577 {
2578     long		ins_len, pre_textlen = 0;
2579     char_u		*firstline, *ins_text;
2580     colnr_T		ind_pre = 0, ind_post;
2581     struct block_def	bd;
2582     int			i;
2583     pos_T		t1;
2584 
2585     /* edit() changes this - record it for OP_APPEND */
2586     bd.is_MAX = (curwin->w_curswant == MAXCOL);
2587 
2588     /* vis block is still marked. Get rid of it now. */
2589     curwin->w_cursor.lnum = oap->start.lnum;
2590     update_screen(INVERTED);
2591 
2592     if (oap->block_mode)
2593     {
2594 	/* When 'virtualedit' is used, need to insert the extra spaces before
2595 	 * doing block_prep().  When only "block" is used, virtual edit is
2596 	 * already disabled, but still need it when calling
2597 	 * coladvance_force(). */
2598 	if (curwin->w_cursor.coladd > 0)
2599 	{
2600 	    int		old_ve_flags = ve_flags;
2601 
2602 	    ve_flags = VE_ALL;
2603 	    if (u_save_cursor() == FAIL)
2604 		return;
2605 	    coladvance_force(oap->op_type == OP_APPEND
2606 					   ? oap->end_vcol + 1 : getviscol());
2607 	    if (oap->op_type == OP_APPEND)
2608 		--curwin->w_cursor.col;
2609 	    ve_flags = old_ve_flags;
2610 	}
2611 	/* Get the info about the block before entering the text */
2612 	block_prep(oap, &bd, oap->start.lnum, TRUE);
2613 	/* Get indent information */
2614 	ind_pre = (colnr_T)getwhitecols_curline();
2615 	firstline = ml_get(oap->start.lnum) + bd.textcol;
2616 
2617 	if (oap->op_type == OP_APPEND)
2618 	    firstline += bd.textlen;
2619 	pre_textlen = (long)STRLEN(firstline);
2620     }
2621 
2622     if (oap->op_type == OP_APPEND)
2623     {
2624 	if (oap->block_mode && curwin->w_cursor.coladd == 0)
2625 	{
2626 	    /* Move the cursor to the character right of the block. */
2627 	    curwin->w_set_curswant = TRUE;
2628 	    while (*ml_get_cursor() != NUL
2629 		    && (curwin->w_cursor.col < bd.textcol + bd.textlen))
2630 		++curwin->w_cursor.col;
2631 	    if (bd.is_short && !bd.is_MAX)
2632 	    {
2633 		/* First line was too short, make it longer and adjust the
2634 		 * values in "bd". */
2635 		if (u_save_cursor() == FAIL)
2636 		    return;
2637 		for (i = 0; i < bd.endspaces; ++i)
2638 		    ins_char(' ');
2639 		bd.textlen += bd.endspaces;
2640 	    }
2641 	}
2642 	else
2643 	{
2644 	    curwin->w_cursor = oap->end;
2645 	    check_cursor_col();
2646 
2647 	    /* Works just like an 'i'nsert on the next character. */
2648 	    if (!LINEEMPTY(curwin->w_cursor.lnum)
2649 		    && oap->start_vcol != oap->end_vcol)
2650 		inc_cursor();
2651 	}
2652     }
2653 
2654     t1 = oap->start;
2655     (void)edit(NUL, FALSE, (linenr_T)count1);
2656 
2657     /* When a tab was inserted, and the characters in front of the tab
2658      * have been converted to a tab as well, the column of the cursor
2659      * might have actually been reduced, so need to adjust here. */
2660     if (t1.lnum == curbuf->b_op_start_orig.lnum
2661 	    && LT_POS(curbuf->b_op_start_orig, t1))
2662 	oap->start = curbuf->b_op_start_orig;
2663 
2664     /* If user has moved off this line, we don't know what to do, so do
2665      * nothing.
2666      * Also don't repeat the insert when Insert mode ended with CTRL-C. */
2667     if (curwin->w_cursor.lnum != oap->start.lnum || got_int)
2668 	return;
2669 
2670     if (oap->block_mode)
2671     {
2672 	struct block_def	bd2;
2673 	int			did_indent = FALSE;
2674 	size_t			len;
2675 	int			add;
2676 
2677 	/* If indent kicked in, the firstline might have changed
2678 	 * but only do that, if the indent actually increased. */
2679 	ind_post = (colnr_T)getwhitecols_curline();
2680 	if (curbuf->b_op_start.col > ind_pre && ind_post > ind_pre)
2681 	{
2682 	    bd.textcol += ind_post - ind_pre;
2683 	    bd.start_vcol += ind_post - ind_pre;
2684 	    did_indent = TRUE;
2685 	}
2686 
2687 	/* The user may have moved the cursor before inserting something, try
2688 	 * to adjust the block for that.  But only do it, if the difference
2689 	 * does not come from indent kicking in. */
2690 	if (oap->start.lnum == curbuf->b_op_start_orig.lnum
2691 						  && !bd.is_MAX && !did_indent)
2692 	{
2693 	    if (oap->op_type == OP_INSERT
2694 		    && oap->start.col + oap->start.coladd
2695 			!= curbuf->b_op_start_orig.col
2696 					      + curbuf->b_op_start_orig.coladd)
2697 	    {
2698 		int t = getviscol2(curbuf->b_op_start_orig.col,
2699 					      curbuf->b_op_start_orig.coladd);
2700 		oap->start.col = curbuf->b_op_start_orig.col;
2701 		pre_textlen -= t - oap->start_vcol;
2702 		oap->start_vcol = t;
2703 	    }
2704 	    else if (oap->op_type == OP_APPEND
2705 		      && oap->end.col + oap->end.coladd
2706 			>= curbuf->b_op_start_orig.col
2707 					      + curbuf->b_op_start_orig.coladd)
2708 	    {
2709 		int t = getviscol2(curbuf->b_op_start_orig.col,
2710 					      curbuf->b_op_start_orig.coladd);
2711 		oap->start.col = curbuf->b_op_start_orig.col;
2712 		/* reset pre_textlen to the value of OP_INSERT */
2713 		pre_textlen += bd.textlen;
2714 		pre_textlen -= t - oap->start_vcol;
2715 		oap->start_vcol = t;
2716 		oap->op_type = OP_INSERT;
2717 	    }
2718 	}
2719 
2720 	/*
2721 	 * Spaces and tabs in the indent may have changed to other spaces and
2722 	 * tabs.  Get the starting column again and correct the length.
2723 	 * Don't do this when "$" used, end-of-line will have changed.
2724 	 */
2725 	block_prep(oap, &bd2, oap->start.lnum, TRUE);
2726 	if (!bd.is_MAX || bd2.textlen < bd.textlen)
2727 	{
2728 	    if (oap->op_type == OP_APPEND)
2729 	    {
2730 		pre_textlen += bd2.textlen - bd.textlen;
2731 		if (bd2.endspaces)
2732 		    --bd2.textlen;
2733 	    }
2734 	    bd.textcol = bd2.textcol;
2735 	    bd.textlen = bd2.textlen;
2736 	}
2737 
2738 	/*
2739 	 * Subsequent calls to ml_get() flush the firstline data - take a
2740 	 * copy of the required string.
2741 	 */
2742 	firstline = ml_get(oap->start.lnum);
2743 	len = STRLEN(firstline);
2744 	add = bd.textcol;
2745 	if (oap->op_type == OP_APPEND)
2746 	    add += bd.textlen;
2747 	if ((size_t)add > len)
2748 	    firstline += len;  // short line, point to the NUL
2749 	else
2750 	    firstline += add;
2751 	if (pre_textlen >= 0
2752 		     && (ins_len = (long)STRLEN(firstline) - pre_textlen) > 0)
2753 	{
2754 	    ins_text = vim_strnsave(firstline, (int)ins_len);
2755 	    if (ins_text != NULL)
2756 	    {
2757 		/* block handled here */
2758 		if (u_save(oap->start.lnum,
2759 					 (linenr_T)(oap->end.lnum + 1)) == OK)
2760 		    block_insert(oap, ins_text, (oap->op_type == OP_INSERT),
2761 									 &bd);
2762 
2763 		curwin->w_cursor.col = oap->start.col;
2764 		check_cursor();
2765 		vim_free(ins_text);
2766 	    }
2767 	}
2768     }
2769 }
2770 
2771 /*
2772  * op_change - handle a change operation
2773  *
2774  * return TRUE if edit() returns because of a CTRL-O command
2775  */
2776     int
2777 op_change(oparg_T *oap)
2778 {
2779     colnr_T		l;
2780     int			retval;
2781     long		offset;
2782     linenr_T		linenr;
2783     long		ins_len;
2784     long		pre_textlen = 0;
2785     long		pre_indent = 0;
2786     char_u		*firstline;
2787     char_u		*ins_text, *newp, *oldp;
2788     struct block_def	bd;
2789 
2790     l = oap->start.col;
2791     if (oap->motion_type == MLINE)
2792     {
2793 	l = 0;
2794 #ifdef FEAT_SMARTINDENT
2795 	if (!p_paste && curbuf->b_p_si
2796 # ifdef FEAT_CINDENT
2797 		&& !curbuf->b_p_cin
2798 # endif
2799 		)
2800 	    can_si = TRUE;	/* It's like opening a new line, do si */
2801 #endif
2802     }
2803 
2804     /* First delete the text in the region.  In an empty buffer only need to
2805      * save for undo */
2806     if (curbuf->b_ml.ml_flags & ML_EMPTY)
2807     {
2808 	if (u_save_cursor() == FAIL)
2809 	    return FALSE;
2810     }
2811     else if (op_delete(oap) == FAIL)
2812 	return FALSE;
2813 
2814     if ((l > curwin->w_cursor.col) && !LINEEMPTY(curwin->w_cursor.lnum)
2815 							 && !virtual_op)
2816 	inc_cursor();
2817 
2818     /* check for still on same line (<CR> in inserted text meaningless) */
2819     /* skip blank lines too */
2820     if (oap->block_mode)
2821     {
2822 	/* Add spaces before getting the current line length. */
2823 	if (virtual_op && (curwin->w_cursor.coladd > 0
2824 						    || gchar_cursor() == NUL))
2825 	    coladvance_force(getviscol());
2826 	firstline = ml_get(oap->start.lnum);
2827 	pre_textlen = (long)STRLEN(firstline);
2828 	pre_indent = (long)getwhitecols(firstline);
2829 	bd.textcol = curwin->w_cursor.col;
2830     }
2831 
2832 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
2833     if (oap->motion_type == MLINE)
2834 	fix_indent();
2835 #endif
2836 
2837     retval = edit(NUL, FALSE, (linenr_T)1);
2838 
2839     /*
2840      * In Visual block mode, handle copying the new text to all lines of the
2841      * block.
2842      * Don't repeat the insert when Insert mode ended with CTRL-C.
2843      */
2844     if (oap->block_mode && oap->start.lnum != oap->end.lnum && !got_int)
2845     {
2846 	/* Auto-indenting may have changed the indent.  If the cursor was past
2847 	 * the indent, exclude that indent change from the inserted text. */
2848 	firstline = ml_get(oap->start.lnum);
2849 	if (bd.textcol > (colnr_T)pre_indent)
2850 	{
2851 	    long new_indent = (long)getwhitecols(firstline);
2852 
2853 	    pre_textlen += new_indent - pre_indent;
2854 	    bd.textcol += new_indent - pre_indent;
2855 	}
2856 
2857 	ins_len = (long)STRLEN(firstline) - pre_textlen;
2858 	if (ins_len > 0)
2859 	{
2860 	    /* Subsequent calls to ml_get() flush the firstline data - take a
2861 	     * copy of the inserted text.  */
2862 	    if ((ins_text = alloc_check((unsigned)(ins_len + 1))) != NULL)
2863 	    {
2864 		vim_strncpy(ins_text, firstline + bd.textcol, (size_t)ins_len);
2865 		for (linenr = oap->start.lnum + 1; linenr <= oap->end.lnum;
2866 								     linenr++)
2867 		{
2868 		    block_prep(oap, &bd, linenr, TRUE);
2869 		    if (!bd.is_short || virtual_op)
2870 		    {
2871 			pos_T vpos;
2872 
2873 			/* If the block starts in virtual space, count the
2874 			 * initial coladd offset as part of "startspaces" */
2875 			if (bd.is_short)
2876 			{
2877 			    vpos.lnum = linenr;
2878 			    (void)getvpos(&vpos, oap->start_vcol);
2879 			}
2880 			else
2881 			    vpos.coladd = 0;
2882 			oldp = ml_get(linenr);
2883 			newp = alloc_check((unsigned)(STRLEN(oldp)
2884 						 + vpos.coladd + ins_len + 1));
2885 			if (newp == NULL)
2886 			    continue;
2887 			/* copy up to block start */
2888 			mch_memmove(newp, oldp, (size_t)bd.textcol);
2889 			offset = bd.textcol;
2890 			vim_memset(newp + offset, ' ', (size_t)vpos.coladd);
2891 			offset += vpos.coladd;
2892 			mch_memmove(newp + offset, ins_text, (size_t)ins_len);
2893 			offset += ins_len;
2894 			oldp += bd.textcol;
2895 			STRMOVE(newp + offset, oldp);
2896 			ml_replace(linenr, newp, FALSE);
2897 		    }
2898 		}
2899 		check_cursor();
2900 
2901 		changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
2902 	    }
2903 	    vim_free(ins_text);
2904 	}
2905     }
2906 
2907     return retval;
2908 }
2909 
2910 /*
2911  * set all the yank registers to empty (called from main())
2912  */
2913     void
2914 init_yank(void)
2915 {
2916     int		i;
2917 
2918     for (i = 0; i < NUM_REGISTERS; ++i)
2919 	y_regs[i].y_array = NULL;
2920 }
2921 
2922 #if defined(EXITFREE) || defined(PROTO)
2923     void
2924 clear_registers(void)
2925 {
2926     int		i;
2927 
2928     for (i = 0; i < NUM_REGISTERS; ++i)
2929     {
2930 	y_current = &y_regs[i];
2931 	if (y_current->y_array != NULL)
2932 	    free_yank_all();
2933     }
2934 }
2935 #endif
2936 
2937 /*
2938  * Free "n" lines from the current yank register.
2939  * Called for normal freeing and in case of error.
2940  */
2941     static void
2942 free_yank(long n)
2943 {
2944     if (y_current->y_array != NULL)
2945     {
2946 	long	    i;
2947 
2948 	for (i = n; --i >= 0; )
2949 	{
2950 #ifdef AMIGA	    /* only for very slow machines */
2951 	    if ((i & 1023) == 1023)  /* this may take a while */
2952 	    {
2953 		/*
2954 		 * This message should never cause a hit-return message.
2955 		 * Overwrite this message with any next message.
2956 		 */
2957 		++no_wait_return;
2958 		smsg(_("freeing %ld lines"), i + 1);
2959 		--no_wait_return;
2960 		msg_didout = FALSE;
2961 		msg_col = 0;
2962 	    }
2963 #endif
2964 	    vim_free(y_current->y_array[i]);
2965 	}
2966 	VIM_CLEAR(y_current->y_array);
2967 #ifdef AMIGA
2968 	if (n >= 1000)
2969 	    msg("");
2970 #endif
2971     }
2972 }
2973 
2974     static void
2975 free_yank_all(void)
2976 {
2977     free_yank(y_current->y_size);
2978 }
2979 
2980 /*
2981  * Yank the text between "oap->start" and "oap->end" into a yank register.
2982  * If we are to append (uppercase register), we first yank into a new yank
2983  * register and then concatenate the old and the new one (so we keep the old
2984  * one in case of out-of-memory).
2985  *
2986  * Return FAIL for failure, OK otherwise.
2987  */
2988     int
2989 op_yank(oparg_T *oap, int deleting, int mess)
2990 {
2991     long		y_idx;		/* index in y_array[] */
2992     yankreg_T		*curr;		/* copy of y_current */
2993     yankreg_T		newreg;		/* new yank register when appending */
2994     char_u		**new_ptr;
2995     linenr_T		lnum;		/* current line number */
2996     long		j;
2997     int			yanktype = oap->motion_type;
2998     long		yanklines = oap->line_count;
2999     linenr_T		yankendlnum = oap->end.lnum;
3000     char_u		*p;
3001     char_u		*pnew;
3002     struct block_def	bd;
3003 #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3004     int			did_star = FALSE;
3005 #endif
3006 
3007 				    /* check for read-only register */
3008     if (oap->regname != 0 && !valid_yank_reg(oap->regname, TRUE))
3009     {
3010 	beep_flush();
3011 	return FAIL;
3012     }
3013     if (oap->regname == '_')	    /* black hole: nothing to do */
3014 	return OK;
3015 
3016 #ifdef FEAT_CLIPBOARD
3017     if (!clip_star.available && oap->regname == '*')
3018 	oap->regname = 0;
3019     else if (!clip_plus.available && oap->regname == '+')
3020 	oap->regname = 0;
3021 #endif
3022 
3023     if (!deleting)		    /* op_delete() already set y_current */
3024 	get_yank_register(oap->regname, TRUE);
3025 
3026     curr = y_current;
3027 				    /* append to existing contents */
3028     if (y_append && y_current->y_array != NULL)
3029 	y_current = &newreg;
3030     else
3031 	free_yank_all();	    /* free previously yanked lines */
3032 
3033     /*
3034      * If the cursor was in column 1 before and after the movement, and the
3035      * operator is not inclusive, the yank is always linewise.
3036      */
3037     if (       oap->motion_type == MCHAR
3038 	    && oap->start.col == 0
3039 	    && !oap->inclusive
3040 	    && (!oap->is_VIsual || *p_sel == 'o')
3041 	    && !oap->block_mode
3042 	    && oap->end.col == 0
3043 	    && yanklines > 1)
3044     {
3045 	yanktype = MLINE;
3046 	--yankendlnum;
3047 	--yanklines;
3048     }
3049 
3050     y_current->y_size = yanklines;
3051     y_current->y_type = yanktype;   /* set the yank register type */
3052     y_current->y_width = 0;
3053     y_current->y_array = (char_u **)lalloc_clear((long_u)(sizeof(char_u *) *
3054 							    yanklines), TRUE);
3055     if (y_current->y_array == NULL)
3056     {
3057 	y_current = curr;
3058 	return FAIL;
3059     }
3060 #ifdef FEAT_VIMINFO
3061     y_current->y_time_set = vim_time();
3062 #endif
3063 
3064     y_idx = 0;
3065     lnum = oap->start.lnum;
3066 
3067     if (oap->block_mode)
3068     {
3069 	/* Visual block mode */
3070 	y_current->y_type = MBLOCK;	    /* set the yank register type */
3071 	y_current->y_width = oap->end_vcol - oap->start_vcol;
3072 
3073 	if (curwin->w_curswant == MAXCOL && y_current->y_width > 0)
3074 	    y_current->y_width--;
3075     }
3076 
3077     for ( ; lnum <= yankendlnum; lnum++, y_idx++)
3078     {
3079 	switch (y_current->y_type)
3080 	{
3081 	    case MBLOCK:
3082 		block_prep(oap, &bd, lnum, FALSE);
3083 		if (yank_copy_line(&bd, y_idx) == FAIL)
3084 		    goto fail;
3085 		break;
3086 
3087 	    case MLINE:
3088 		if ((y_current->y_array[y_idx] =
3089 			    vim_strsave(ml_get(lnum))) == NULL)
3090 		    goto fail;
3091 		break;
3092 
3093 	    case MCHAR:
3094 		{
3095 		    colnr_T startcol = 0, endcol = MAXCOL;
3096 		    int is_oneChar = FALSE;
3097 		    colnr_T cs, ce;
3098 
3099 		    p = ml_get(lnum);
3100 		    bd.startspaces = 0;
3101 		    bd.endspaces = 0;
3102 
3103 		    if (lnum == oap->start.lnum)
3104 		    {
3105 			startcol = oap->start.col;
3106 			if (virtual_op)
3107 			{
3108 			    getvcol(curwin, &oap->start, &cs, NULL, &ce);
3109 			    if (ce != cs && oap->start.coladd > 0)
3110 			    {
3111 				/* Part of a tab selected -- but don't
3112 				 * double-count it. */
3113 				bd.startspaces = (ce - cs + 1)
3114 							  - oap->start.coladd;
3115 				startcol++;
3116 			    }
3117 			}
3118 		    }
3119 
3120 		    if (lnum == oap->end.lnum)
3121 		    {
3122 			endcol = oap->end.col;
3123 			if (virtual_op)
3124 			{
3125 			    getvcol(curwin, &oap->end, &cs, NULL, &ce);
3126 			    if (p[endcol] == NUL || (cs + oap->end.coladd < ce
3127 					/* Don't add space for double-wide
3128 					 * char; endcol will be on last byte
3129 					 * of multi-byte char. */
3130 					&& (*mb_head_off)(p, p + endcol) == 0))
3131 			    {
3132 				if (oap->start.lnum == oap->end.lnum
3133 					    && oap->start.col == oap->end.col)
3134 				{
3135 				    /* Special case: inside a single char */
3136 				    is_oneChar = TRUE;
3137 				    bd.startspaces = oap->end.coladd
3138 					 - oap->start.coladd + oap->inclusive;
3139 				    endcol = startcol;
3140 				}
3141 				else
3142 				{
3143 				    bd.endspaces = oap->end.coladd
3144 							     + oap->inclusive;
3145 				    endcol -= oap->inclusive;
3146 				}
3147 			    }
3148 			}
3149 		    }
3150 		    if (endcol == MAXCOL)
3151 			endcol = (colnr_T)STRLEN(p);
3152 		    if (startcol > endcol || is_oneChar)
3153 			bd.textlen = 0;
3154 		    else
3155 		    {
3156 			bd.textlen = endcol - startcol + oap->inclusive;
3157 		    }
3158 		    bd.textstart = p + startcol;
3159 		    if (yank_copy_line(&bd, y_idx) == FAIL)
3160 			goto fail;
3161 		    break;
3162 		}
3163 		/* NOTREACHED */
3164 	}
3165     }
3166 
3167     if (curr != y_current)	/* append the new block to the old block */
3168     {
3169 	new_ptr = (char_u **)lalloc((long_u)(sizeof(char_u *) *
3170 				   (curr->y_size + y_current->y_size)), TRUE);
3171 	if (new_ptr == NULL)
3172 	    goto fail;
3173 	for (j = 0; j < curr->y_size; ++j)
3174 	    new_ptr[j] = curr->y_array[j];
3175 	vim_free(curr->y_array);
3176 	curr->y_array = new_ptr;
3177 #ifdef FEAT_VIMINFO
3178 	curr->y_time_set = vim_time();
3179 #endif
3180 
3181 	if (yanktype == MLINE)	/* MLINE overrides MCHAR and MBLOCK */
3182 	    curr->y_type = MLINE;
3183 
3184 	/* Concatenate the last line of the old block with the first line of
3185 	 * the new block, unless being Vi compatible. */
3186 	if (curr->y_type == MCHAR && vim_strchr(p_cpo, CPO_REGAPPEND) == NULL)
3187 	{
3188 	    pnew = lalloc((long_u)(STRLEN(curr->y_array[curr->y_size - 1])
3189 			      + STRLEN(y_current->y_array[0]) + 1), TRUE);
3190 	    if (pnew == NULL)
3191 	    {
3192 		y_idx = y_current->y_size - 1;
3193 		goto fail;
3194 	    }
3195 	    STRCPY(pnew, curr->y_array[--j]);
3196 	    STRCAT(pnew, y_current->y_array[0]);
3197 	    vim_free(curr->y_array[j]);
3198 	    vim_free(y_current->y_array[0]);
3199 	    curr->y_array[j++] = pnew;
3200 	    y_idx = 1;
3201 	}
3202 	else
3203 	    y_idx = 0;
3204 	while (y_idx < y_current->y_size)
3205 	    curr->y_array[j++] = y_current->y_array[y_idx++];
3206 	curr->y_size = j;
3207 	vim_free(y_current->y_array);
3208 	y_current = curr;
3209     }
3210     if (curwin->w_p_rnu)
3211 	redraw_later(SOME_VALID);	/* cursor moved to start */
3212     if (mess)			/* Display message about yank? */
3213     {
3214 	if (yanktype == MCHAR
3215 		&& !oap->block_mode
3216 		&& yanklines == 1)
3217 	    yanklines = 0;
3218 	/* Some versions of Vi use ">=" here, some don't...  */
3219 	if (yanklines > p_report)
3220 	{
3221 	    char namebuf[100];
3222 
3223 	    if (oap->regname == NUL)
3224 		*namebuf = NUL;
3225 	    else
3226 		vim_snprintf(namebuf, sizeof(namebuf),
3227 						_(" into \"%c"), oap->regname);
3228 
3229 	    /* redisplay now, so message is not deleted */
3230 	    update_topline_redraw();
3231 	    if (oap->block_mode)
3232 	    {
3233 		smsg(NGETTEXT("block of %ld line yanked%s",
3234 				     "block of %ld lines yanked%s", yanklines),
3235 			yanklines, namebuf);
3236 	    }
3237 	    else
3238 	    {
3239 		smsg(NGETTEXT("%ld line yanked%s",
3240 					      "%ld lines yanked%s", yanklines),
3241 			yanklines, namebuf);
3242 	    }
3243 	}
3244     }
3245 
3246     /*
3247      * Set "'[" and "']" marks.
3248      */
3249     curbuf->b_op_start = oap->start;
3250     curbuf->b_op_end = oap->end;
3251     if (yanktype == MLINE && !oap->block_mode)
3252     {
3253 	curbuf->b_op_start.col = 0;
3254 	curbuf->b_op_end.col = MAXCOL;
3255     }
3256 
3257 #ifdef FEAT_CLIPBOARD
3258     /*
3259      * If we were yanking to the '*' register, send result to clipboard.
3260      * If no register was specified, and "unnamed" in 'clipboard', make a copy
3261      * to the '*' register.
3262      */
3263     if (clip_star.available
3264 	    && (curr == &(y_regs[STAR_REGISTER])
3265 		|| (!deleting && oap->regname == 0
3266 		   && ((clip_unnamed | clip_unnamed_saved) & CLIP_UNNAMED))))
3267     {
3268 	if (curr != &(y_regs[STAR_REGISTER]))
3269 	    /* Copy the text from register 0 to the clipboard register. */
3270 	    copy_yank_reg(&(y_regs[STAR_REGISTER]));
3271 
3272 	clip_own_selection(&clip_star);
3273 	clip_gen_set_selection(&clip_star);
3274 # ifdef FEAT_X11
3275 	did_star = TRUE;
3276 # endif
3277     }
3278 
3279 # ifdef FEAT_X11
3280     /*
3281      * If we were yanking to the '+' register, send result to selection.
3282      * Also copy to the '*' register, in case auto-select is off.
3283      */
3284     if (clip_plus.available
3285 	    && (curr == &(y_regs[PLUS_REGISTER])
3286 		|| (!deleting && oap->regname == 0
3287 		  && ((clip_unnamed | clip_unnamed_saved) &
3288 		      CLIP_UNNAMED_PLUS))))
3289     {
3290 	if (curr != &(y_regs[PLUS_REGISTER]))
3291 	    /* Copy the text from register 0 to the clipboard register. */
3292 	    copy_yank_reg(&(y_regs[PLUS_REGISTER]));
3293 
3294 	clip_own_selection(&clip_plus);
3295 	clip_gen_set_selection(&clip_plus);
3296 	if (!clip_isautosel_star() && !clip_isautosel_plus()
3297 		&& !did_star && curr == &(y_regs[PLUS_REGISTER]))
3298 	{
3299 	    copy_yank_reg(&(y_regs[STAR_REGISTER]));
3300 	    clip_own_selection(&clip_star);
3301 	    clip_gen_set_selection(&clip_star);
3302 	}
3303     }
3304 # endif
3305 #endif
3306 
3307 #if defined(FEAT_EVAL)
3308     if (!deleting && has_textyankpost())
3309 	yank_do_autocmd(oap, y_current);
3310 #endif
3311 
3312     return OK;
3313 
3314 fail:		/* free the allocated lines */
3315     free_yank(y_idx + 1);
3316     y_current = curr;
3317     return FAIL;
3318 }
3319 
3320     static int
3321 yank_copy_line(struct block_def *bd, long y_idx)
3322 {
3323     char_u	*pnew;
3324 
3325     if ((pnew = alloc(bd->startspaces + bd->endspaces + bd->textlen + 1))
3326 								      == NULL)
3327 	return FAIL;
3328     y_current->y_array[y_idx] = pnew;
3329     vim_memset(pnew, ' ', (size_t)bd->startspaces);
3330     pnew += bd->startspaces;
3331     mch_memmove(pnew, bd->textstart, (size_t)bd->textlen);
3332     pnew += bd->textlen;
3333     vim_memset(pnew, ' ', (size_t)bd->endspaces);
3334     pnew += bd->endspaces;
3335     *pnew = NUL;
3336     return OK;
3337 }
3338 
3339 #ifdef FEAT_CLIPBOARD
3340 /*
3341  * Make a copy of the y_current register to register "reg".
3342  */
3343     static void
3344 copy_yank_reg(yankreg_T *reg)
3345 {
3346     yankreg_T	*curr = y_current;
3347     long	j;
3348 
3349     y_current = reg;
3350     free_yank_all();
3351     *y_current = *curr;
3352     y_current->y_array = (char_u **)lalloc_clear(
3353 			(long_u)(sizeof(char_u *) * y_current->y_size), TRUE);
3354     if (y_current->y_array == NULL)
3355 	y_current->y_size = 0;
3356     else
3357 	for (j = 0; j < y_current->y_size; ++j)
3358 	    if ((y_current->y_array[j] = vim_strsave(curr->y_array[j])) == NULL)
3359 	    {
3360 		free_yank(j);
3361 		y_current->y_size = 0;
3362 		break;
3363 	    }
3364     y_current = curr;
3365 }
3366 #endif
3367 
3368 /*
3369  * Put contents of register "regname" into the text.
3370  * Caller must check "regname" to be valid!
3371  * "flags": PUT_FIXINDENT	make indent look nice
3372  *	    PUT_CURSEND		leave cursor after end of new text
3373  *	    PUT_LINE		force linewise put (":put")
3374  */
3375     void
3376 do_put(
3377     int		regname,
3378     int		dir,		/* BACKWARD for 'P', FORWARD for 'p' */
3379     long	count,
3380     int		flags)
3381 {
3382     char_u	*ptr;
3383     char_u	*newp, *oldp;
3384     int		yanklen;
3385     int		totlen = 0;		/* init for gcc */
3386     linenr_T	lnum;
3387     colnr_T	col;
3388     long	i;			/* index in y_array[] */
3389     int		y_type;
3390     long	y_size;
3391     int		oldlen;
3392     long	y_width = 0;
3393     colnr_T	vcol;
3394     int		delcount;
3395     int		incr = 0;
3396     long	j;
3397     struct block_def bd;
3398     char_u	**y_array = NULL;
3399     long	nr_lines = 0;
3400     pos_T	new_cursor;
3401     int		indent;
3402     int		orig_indent = 0;	/* init for gcc */
3403     int		indent_diff = 0;	/* init for gcc */
3404     int		first_indent = TRUE;
3405     int		lendiff = 0;
3406     pos_T	old_pos;
3407     char_u	*insert_string = NULL;
3408     int		allocated = FALSE;
3409     long	cnt;
3410 
3411 #ifdef FEAT_CLIPBOARD
3412     /* Adjust register name for "unnamed" in 'clipboard'. */
3413     adjust_clip_reg(&regname);
3414     (void)may_get_selection(regname);
3415 #endif
3416 
3417     if (flags & PUT_FIXINDENT)
3418 	orig_indent = get_indent();
3419 
3420     curbuf->b_op_start = curwin->w_cursor;	/* default for '[ mark */
3421     curbuf->b_op_end = curwin->w_cursor;	/* default for '] mark */
3422 
3423     /*
3424      * Using inserted text works differently, because the register includes
3425      * special characters (newlines, etc.).
3426      */
3427     if (regname == '.')
3428     {
3429 	if (VIsual_active)
3430 	    stuffcharReadbuff(VIsual_mode);
3431 	(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :
3432 				    (count == -1 ? 'O' : 'i')), count, FALSE);
3433 	/* Putting the text is done later, so can't really move the cursor to
3434 	 * the next character.  Use "l" to simulate it. */
3435 	if ((flags & PUT_CURSEND) && gchar_cursor() != NUL)
3436 	    stuffcharReadbuff('l');
3437 	return;
3438     }
3439 
3440     /*
3441      * For special registers '%' (file name), '#' (alternate file name) and
3442      * ':' (last command line), etc. we have to create a fake yank register.
3443      */
3444     if (get_spec_reg(regname, &insert_string, &allocated, TRUE))
3445     {
3446 	if (insert_string == NULL)
3447 	    return;
3448     }
3449 
3450     /* Autocommands may be executed when saving lines for undo.  This might
3451      * make "y_array" invalid, so we start undo now to avoid that. */
3452     if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL)
3453 	goto end;
3454 
3455     if (insert_string != NULL)
3456     {
3457 	y_type = MCHAR;
3458 #ifdef FEAT_EVAL
3459 	if (regname == '=')
3460 	{
3461 	    /* For the = register we need to split the string at NL
3462 	     * characters.
3463 	     * Loop twice: count the number of lines and save them. */
3464 	    for (;;)
3465 	    {
3466 		y_size = 0;
3467 		ptr = insert_string;
3468 		while (ptr != NULL)
3469 		{
3470 		    if (y_array != NULL)
3471 			y_array[y_size] = ptr;
3472 		    ++y_size;
3473 		    ptr = vim_strchr(ptr, '\n');
3474 		    if (ptr != NULL)
3475 		    {
3476 			if (y_array != NULL)
3477 			    *ptr = NUL;
3478 			++ptr;
3479 			/* A trailing '\n' makes the register linewise. */
3480 			if (*ptr == NUL)
3481 			{
3482 			    y_type = MLINE;
3483 			    break;
3484 			}
3485 		    }
3486 		}
3487 		if (y_array != NULL)
3488 		    break;
3489 		y_array = (char_u **)alloc((unsigned)
3490 						 (y_size * sizeof(char_u *)));
3491 		if (y_array == NULL)
3492 		    goto end;
3493 	    }
3494 	}
3495 	else
3496 #endif
3497 	{
3498 	    y_size = 1;		/* use fake one-line yank register */
3499 	    y_array = &insert_string;
3500 	}
3501     }
3502     else
3503     {
3504 	get_yank_register(regname, FALSE);
3505 
3506 	y_type = y_current->y_type;
3507 	y_width = y_current->y_width;
3508 	y_size = y_current->y_size;
3509 	y_array = y_current->y_array;
3510     }
3511 
3512     if (y_type == MLINE)
3513     {
3514 	if (flags & PUT_LINE_SPLIT)
3515 	{
3516 	    char_u *p;
3517 
3518 	    /* "p" or "P" in Visual mode: split the lines to put the text in
3519 	     * between. */
3520 	    if (u_save_cursor() == FAIL)
3521 		goto end;
3522 	    p = ml_get_cursor();
3523 	    if (dir == FORWARD && *p != NUL)
3524 		MB_PTR_ADV(p);
3525 	    ptr = vim_strsave(p);
3526 	    if (ptr == NULL)
3527 		goto end;
3528 	    ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);
3529 	    vim_free(ptr);
3530 
3531 	    oldp = ml_get_curline();
3532 	    p = oldp + curwin->w_cursor.col;
3533 	    if (dir == FORWARD && *p != NUL)
3534 		MB_PTR_ADV(p);
3535 	    ptr = vim_strnsave(oldp, p - oldp);
3536 	    if (ptr == NULL)
3537 		goto end;
3538 	    ml_replace(curwin->w_cursor.lnum, ptr, FALSE);
3539 	    ++nr_lines;
3540 	    dir = FORWARD;
3541 	}
3542 	if (flags & PUT_LINE_FORWARD)
3543 	{
3544 	    /* Must be "p" for a Visual block, put lines below the block. */
3545 	    curwin->w_cursor = curbuf->b_visual.vi_end;
3546 	    dir = FORWARD;
3547 	}
3548 	curbuf->b_op_start = curwin->w_cursor;	/* default for '[ mark */
3549 	curbuf->b_op_end = curwin->w_cursor;	/* default for '] mark */
3550     }
3551 
3552     if (flags & PUT_LINE)	/* :put command or "p" in Visual line mode. */
3553 	y_type = MLINE;
3554 
3555     if (y_size == 0 || y_array == NULL)
3556     {
3557 	semsg(_("E353: Nothing in register %s"),
3558 		  regname == 0 ? (char_u *)"\"" : transchar(regname));
3559 	goto end;
3560     }
3561 
3562     if (y_type == MBLOCK)
3563     {
3564 	lnum = curwin->w_cursor.lnum + y_size + 1;
3565 	if (lnum > curbuf->b_ml.ml_line_count)
3566 	    lnum = curbuf->b_ml.ml_line_count + 1;
3567 	if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)
3568 	    goto end;
3569     }
3570     else if (y_type == MLINE)
3571     {
3572 	lnum = curwin->w_cursor.lnum;
3573 #ifdef FEAT_FOLDING
3574 	/* Correct line number for closed fold.  Don't move the cursor yet,
3575 	 * u_save() uses it. */
3576 	if (dir == BACKWARD)
3577 	    (void)hasFolding(lnum, &lnum, NULL);
3578 	else
3579 	    (void)hasFolding(lnum, NULL, &lnum);
3580 #endif
3581 	if (dir == FORWARD)
3582 	    ++lnum;
3583 	/* In an empty buffer the empty line is going to be replaced, include
3584 	 * it in the saved lines. */
3585 	if ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL)
3586 	    goto end;
3587 #ifdef FEAT_FOLDING
3588 	if (dir == FORWARD)
3589 	    curwin->w_cursor.lnum = lnum - 1;
3590 	else
3591 	    curwin->w_cursor.lnum = lnum;
3592 	curbuf->b_op_start = curwin->w_cursor;	/* for mark_adjust() */
3593 #endif
3594     }
3595     else if (u_save_cursor() == FAIL)
3596 	goto end;
3597 
3598     yanklen = (int)STRLEN(y_array[0]);
3599 
3600     if (ve_flags == VE_ALL && y_type == MCHAR)
3601     {
3602 	if (gchar_cursor() == TAB)
3603 	{
3604 	    /* Don't need to insert spaces when "p" on the last position of a
3605 	     * tab or "P" on the first position. */
3606 #ifdef FEAT_VARTABS
3607 	    int viscol = getviscol();
3608 	    if (dir == FORWARD
3609 		    ? tabstop_padding(viscol, curbuf->b_p_ts,
3610 						    curbuf->b_p_vts_array) != 1
3611 		    : curwin->w_cursor.coladd > 0)
3612 		coladvance_force(viscol);
3613 #else
3614 	    if (dir == FORWARD
3615 		    ? (int)curwin->w_cursor.coladd < curbuf->b_p_ts - 1
3616 						: curwin->w_cursor.coladd > 0)
3617 		coladvance_force(getviscol());
3618 #endif
3619 	    else
3620 		curwin->w_cursor.coladd = 0;
3621 	}
3622 	else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)
3623 	    coladvance_force(getviscol() + (dir == FORWARD));
3624     }
3625 
3626     lnum = curwin->w_cursor.lnum;
3627     col = curwin->w_cursor.col;
3628 
3629     /*
3630      * Block mode
3631      */
3632     if (y_type == MBLOCK)
3633     {
3634 	int	c = gchar_cursor();
3635 	colnr_T	endcol2 = 0;
3636 
3637 	if (dir == FORWARD && c != NUL)
3638 	{
3639 	    if (ve_flags == VE_ALL)
3640 		getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
3641 	    else
3642 		getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
3643 
3644 	    if (has_mbyte)
3645 		/* move to start of next multi-byte character */
3646 		curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
3647 	    else
3648 	    if (c != TAB || ve_flags != VE_ALL)
3649 		++curwin->w_cursor.col;
3650 	    ++col;
3651 	}
3652 	else
3653 	    getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
3654 
3655 	col += curwin->w_cursor.coladd;
3656 	if (ve_flags == VE_ALL
3657 		&& (curwin->w_cursor.coladd > 0
3658 		    || endcol2 == curwin->w_cursor.col))
3659 	{
3660 	    if (dir == FORWARD && c == NUL)
3661 		++col;
3662 	    if (dir != FORWARD && c != NUL)
3663 		++curwin->w_cursor.col;
3664 	    if (c == TAB)
3665 	    {
3666 		if (dir == BACKWARD && curwin->w_cursor.col)
3667 		    curwin->w_cursor.col--;
3668 		if (dir == FORWARD && col - 1 == endcol2)
3669 		    curwin->w_cursor.col++;
3670 	    }
3671 	}
3672 	curwin->w_cursor.coladd = 0;
3673 	bd.textcol = 0;
3674 	for (i = 0; i < y_size; ++i)
3675 	{
3676 	    int spaces;
3677 	    char shortline;
3678 
3679 	    bd.startspaces = 0;
3680 	    bd.endspaces = 0;
3681 	    vcol = 0;
3682 	    delcount = 0;
3683 
3684 	    /* add a new line */
3685 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
3686 	    {
3687 		if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"",
3688 						   (colnr_T)1, FALSE) == FAIL)
3689 		    break;
3690 		++nr_lines;
3691 	    }
3692 	    /* get the old line and advance to the position to insert at */
3693 	    oldp = ml_get_curline();
3694 	    oldlen = (int)STRLEN(oldp);
3695 	    for (ptr = oldp; vcol < col && *ptr; )
3696 	    {
3697 		/* Count a tab for what it's worth (if list mode not on) */
3698 		incr = lbr_chartabsize_adv(oldp, &ptr, (colnr_T)vcol);
3699 		vcol += incr;
3700 	    }
3701 	    bd.textcol = (colnr_T)(ptr - oldp);
3702 
3703 	    shortline = (vcol < col) || (vcol == col && !*ptr) ;
3704 
3705 	    if (vcol < col) /* line too short, padd with spaces */
3706 		bd.startspaces = col - vcol;
3707 	    else if (vcol > col)
3708 	    {
3709 		bd.endspaces = vcol - col;
3710 		bd.startspaces = incr - bd.endspaces;
3711 		--bd.textcol;
3712 		delcount = 1;
3713 		if (has_mbyte)
3714 		    bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);
3715 		if (oldp[bd.textcol] != TAB)
3716 		{
3717 		    /* Only a Tab can be split into spaces.  Other
3718 		     * characters will have to be moved to after the
3719 		     * block, causing misalignment. */
3720 		    delcount = 0;
3721 		    bd.endspaces = 0;
3722 		}
3723 	    }
3724 
3725 	    yanklen = (int)STRLEN(y_array[i]);
3726 
3727 	    /* calculate number of spaces required to fill right side of block*/
3728 	    spaces = y_width + 1;
3729 	    for (j = 0; j < yanklen; j++)
3730 		spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);
3731 	    if (spaces < 0)
3732 		spaces = 0;
3733 
3734 	    /* insert the new text */
3735 	    totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;
3736 	    newp = alloc_check((unsigned)totlen + oldlen + 1);
3737 	    if (newp == NULL)
3738 		break;
3739 	    /* copy part up to cursor to new line */
3740 	    ptr = newp;
3741 	    mch_memmove(ptr, oldp, (size_t)bd.textcol);
3742 	    ptr += bd.textcol;
3743 	    /* may insert some spaces before the new text */
3744 	    vim_memset(ptr, ' ', (size_t)bd.startspaces);
3745 	    ptr += bd.startspaces;
3746 	    /* insert the new text */
3747 	    for (j = 0; j < count; ++j)
3748 	    {
3749 		mch_memmove(ptr, y_array[i], (size_t)yanklen);
3750 		ptr += yanklen;
3751 
3752 		/* insert block's trailing spaces only if there's text behind */
3753 		if ((j < count - 1 || !shortline) && spaces)
3754 		{
3755 		    vim_memset(ptr, ' ', (size_t)spaces);
3756 		    ptr += spaces;
3757 		}
3758 	    }
3759 	    /* may insert some spaces after the new text */
3760 	    vim_memset(ptr, ' ', (size_t)bd.endspaces);
3761 	    ptr += bd.endspaces;
3762 	    /* move the text after the cursor to the end of the line. */
3763 	    mch_memmove(ptr, oldp + bd.textcol + delcount,
3764 				(size_t)(oldlen - bd.textcol - delcount + 1));
3765 	    ml_replace(curwin->w_cursor.lnum, newp, FALSE);
3766 
3767 	    ++curwin->w_cursor.lnum;
3768 	    if (i == 0)
3769 		curwin->w_cursor.col += bd.startspaces;
3770 	}
3771 
3772 	changed_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);
3773 
3774 	/* Set '[ mark. */
3775 	curbuf->b_op_start = curwin->w_cursor;
3776 	curbuf->b_op_start.lnum = lnum;
3777 
3778 	/* adjust '] mark */
3779 	curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
3780 	curbuf->b_op_end.col = bd.textcol + totlen - 1;
3781 	curbuf->b_op_end.coladd = 0;
3782 	if (flags & PUT_CURSEND)
3783 	{
3784 	    colnr_T len;
3785 
3786 	    curwin->w_cursor = curbuf->b_op_end;
3787 	    curwin->w_cursor.col++;
3788 
3789 	    /* in Insert mode we might be after the NUL, correct for that */
3790 	    len = (colnr_T)STRLEN(ml_get_curline());
3791 	    if (curwin->w_cursor.col > len)
3792 		curwin->w_cursor.col = len;
3793 	}
3794 	else
3795 	    curwin->w_cursor.lnum = lnum;
3796     }
3797     else
3798     {
3799 	/*
3800 	 * Character or Line mode
3801 	 */
3802 	if (y_type == MCHAR)
3803 	{
3804 	    /* if type is MCHAR, FORWARD is the same as BACKWARD on the next
3805 	     * char */
3806 	    if (dir == FORWARD && gchar_cursor() != NUL)
3807 	    {
3808 		if (has_mbyte)
3809 		{
3810 		    int bytelen = (*mb_ptr2len)(ml_get_cursor());
3811 
3812 		    /* put it on the next of the multi-byte character. */
3813 		    col += bytelen;
3814 		    if (yanklen)
3815 		    {
3816 			curwin->w_cursor.col += bytelen;
3817 			curbuf->b_op_end.col += bytelen;
3818 		    }
3819 		}
3820 		else
3821 		{
3822 		    ++col;
3823 		    if (yanklen)
3824 		    {
3825 			++curwin->w_cursor.col;
3826 			++curbuf->b_op_end.col;
3827 		    }
3828 		}
3829 	    }
3830 	    curbuf->b_op_start = curwin->w_cursor;
3831 	}
3832 	/*
3833 	 * Line mode: BACKWARD is the same as FORWARD on the previous line
3834 	 */
3835 	else if (dir == BACKWARD)
3836 	    --lnum;
3837 	new_cursor = curwin->w_cursor;
3838 
3839 	/*
3840 	 * simple case: insert into current line
3841 	 */
3842 	if (y_type == MCHAR && y_size == 1)
3843 	{
3844 	    linenr_T end_lnum = 0; /* init for gcc */
3845 
3846 	    if (VIsual_active)
3847 	    {
3848 		end_lnum = curbuf->b_visual.vi_end.lnum;
3849 		if (end_lnum < curbuf->b_visual.vi_start.lnum)
3850 		    end_lnum = curbuf->b_visual.vi_start.lnum;
3851 	    }
3852 
3853 	    do {
3854 		totlen = count * yanklen;
3855 		if (totlen > 0)
3856 		{
3857 		    oldp = ml_get(lnum);
3858 		    if (VIsual_active && col > (int)STRLEN(oldp))
3859 		    {
3860 			lnum++;
3861 			continue;
3862 		    }
3863 		    newp = alloc_check((unsigned)(STRLEN(oldp) + totlen + 1));
3864 		    if (newp == NULL)
3865 			goto end;	/* alloc() gave an error message */
3866 		    mch_memmove(newp, oldp, (size_t)col);
3867 		    ptr = newp + col;
3868 		    for (i = 0; i < count; ++i)
3869 		    {
3870 			mch_memmove(ptr, y_array[0], (size_t)yanklen);
3871 			ptr += yanklen;
3872 		    }
3873 		    STRMOVE(ptr, oldp + col);
3874 		    ml_replace(lnum, newp, FALSE);
3875 		    /* Place cursor on last putted char. */
3876 		    if (lnum == curwin->w_cursor.lnum)
3877 		    {
3878 			/* make sure curwin->w_virtcol is updated */
3879 			changed_cline_bef_curs();
3880 			curwin->w_cursor.col += (colnr_T)(totlen - 1);
3881 		    }
3882 		}
3883 		if (VIsual_active)
3884 		    lnum++;
3885 	    } while (VIsual_active && lnum <= end_lnum);
3886 
3887 	    if (VIsual_active) /* reset lnum to the last visual line */
3888 		lnum--;
3889 
3890 	    curbuf->b_op_end = curwin->w_cursor;
3891 	    /* For "CTRL-O p" in Insert mode, put cursor after last char */
3892 	    if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))
3893 		++curwin->w_cursor.col;
3894 	    changed_bytes(lnum, col);
3895 	}
3896 	else
3897 	{
3898 	    /*
3899 	     * Insert at least one line.  When y_type is MCHAR, break the first
3900 	     * line in two.
3901 	     */
3902 	    for (cnt = 1; cnt <= count; ++cnt)
3903 	    {
3904 		i = 0;
3905 		if (y_type == MCHAR)
3906 		{
3907 		    /*
3908 		     * Split the current line in two at the insert position.
3909 		     * First insert y_array[size - 1] in front of second line.
3910 		     * Then append y_array[0] to first line.
3911 		     */
3912 		    lnum = new_cursor.lnum;
3913 		    ptr = ml_get(lnum) + col;
3914 		    totlen = (int)STRLEN(y_array[y_size - 1]);
3915 		    newp = alloc_check((unsigned)(STRLEN(ptr) + totlen + 1));
3916 		    if (newp == NULL)
3917 			goto error;
3918 		    STRCPY(newp, y_array[y_size - 1]);
3919 		    STRCAT(newp, ptr);
3920 		    /* insert second line */
3921 		    ml_append(lnum, newp, (colnr_T)0, FALSE);
3922 		    vim_free(newp);
3923 
3924 		    oldp = ml_get(lnum);
3925 		    newp = alloc_check((unsigned)(col + yanklen + 1));
3926 		    if (newp == NULL)
3927 			goto error;
3928 					    /* copy first part of line */
3929 		    mch_memmove(newp, oldp, (size_t)col);
3930 					    /* append to first line */
3931 		    mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));
3932 		    ml_replace(lnum, newp, FALSE);
3933 
3934 		    curwin->w_cursor.lnum = lnum;
3935 		    i = 1;
3936 		}
3937 
3938 		for (; i < y_size; ++i)
3939 		{
3940 		    if ((y_type != MCHAR || i < y_size - 1)
3941 			    && ml_append(lnum, y_array[i], (colnr_T)0, FALSE)
3942 								      == FAIL)
3943 			    goto error;
3944 		    lnum++;
3945 		    ++nr_lines;
3946 		    if (flags & PUT_FIXINDENT)
3947 		    {
3948 			old_pos = curwin->w_cursor;
3949 			curwin->w_cursor.lnum = lnum;
3950 			ptr = ml_get(lnum);
3951 			if (cnt == count && i == y_size - 1)
3952 			    lendiff = (int)STRLEN(ptr);
3953 #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
3954 			if (*ptr == '#' && preprocs_left())
3955 			    indent = 0;     /* Leave # lines at start */
3956 			else
3957 #endif
3958 			     if (*ptr == NUL)
3959 			    indent = 0;     /* Ignore empty lines */
3960 			else if (first_indent)
3961 			{
3962 			    indent_diff = orig_indent - get_indent();
3963 			    indent = orig_indent;
3964 			    first_indent = FALSE;
3965 			}
3966 			else if ((indent = get_indent() + indent_diff) < 0)
3967 			    indent = 0;
3968 			(void)set_indent(indent, 0);
3969 			curwin->w_cursor = old_pos;
3970 			/* remember how many chars were removed */
3971 			if (cnt == count && i == y_size - 1)
3972 			    lendiff -= (int)STRLEN(ml_get(lnum));
3973 		    }
3974 		}
3975 	    }
3976 
3977 error:
3978 	    /* Adjust marks. */
3979 	    if (y_type == MLINE)
3980 	    {
3981 		curbuf->b_op_start.col = 0;
3982 		if (dir == FORWARD)
3983 		    curbuf->b_op_start.lnum++;
3984 	    }
3985 	    /* Skip mark_adjust when adding lines after the last one, there
3986 	     * can't be marks there. But still needed in diff mode. */
3987 	    if (curbuf->b_op_start.lnum + (y_type == MCHAR) - 1 + nr_lines
3988 						 < curbuf->b_ml.ml_line_count
3989 #ifdef FEAT_DIFF
3990 						 || curwin->w_p_diff
3991 #endif
3992 						 )
3993 		mark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),
3994 					     (linenr_T)MAXLNUM, nr_lines, 0L);
3995 
3996 	    /* note changed text for displaying and folding */
3997 	    if (y_type == MCHAR)
3998 		changed_lines(curwin->w_cursor.lnum, col,
3999 					 curwin->w_cursor.lnum + 1, nr_lines);
4000 	    else
4001 		changed_lines(curbuf->b_op_start.lnum, 0,
4002 					   curbuf->b_op_start.lnum, nr_lines);
4003 
4004 	    /* put '] mark at last inserted character */
4005 	    curbuf->b_op_end.lnum = lnum;
4006 	    /* correct length for change in indent */
4007 	    col = (colnr_T)STRLEN(y_array[y_size - 1]) - lendiff;
4008 	    if (col > 1)
4009 		curbuf->b_op_end.col = col - 1;
4010 	    else
4011 		curbuf->b_op_end.col = 0;
4012 
4013 	    if (flags & PUT_CURSLINE)
4014 	    {
4015 		/* ":put": put cursor on last inserted line */
4016 		curwin->w_cursor.lnum = lnum;
4017 		beginline(BL_WHITE | BL_FIX);
4018 	    }
4019 	    else if (flags & PUT_CURSEND)
4020 	    {
4021 		/* put cursor after inserted text */
4022 		if (y_type == MLINE)
4023 		{
4024 		    if (lnum >= curbuf->b_ml.ml_line_count)
4025 			curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4026 		    else
4027 			curwin->w_cursor.lnum = lnum + 1;
4028 		    curwin->w_cursor.col = 0;
4029 		}
4030 		else
4031 		{
4032 		    curwin->w_cursor.lnum = lnum;
4033 		    curwin->w_cursor.col = col;
4034 		}
4035 	    }
4036 	    else if (y_type == MLINE)
4037 	    {
4038 		/* put cursor on first non-blank in first inserted line */
4039 		curwin->w_cursor.col = 0;
4040 		if (dir == FORWARD)
4041 		    ++curwin->w_cursor.lnum;
4042 		beginline(BL_WHITE | BL_FIX);
4043 	    }
4044 	    else	/* put cursor on first inserted character */
4045 		curwin->w_cursor = new_cursor;
4046 	}
4047     }
4048 
4049     msgmore(nr_lines);
4050     curwin->w_set_curswant = TRUE;
4051 
4052 end:
4053     if (allocated)
4054 	vim_free(insert_string);
4055     if (regname == '=')
4056 	vim_free(y_array);
4057 
4058     VIsual_active = FALSE;
4059 
4060     /* If the cursor is past the end of the line put it at the end. */
4061     adjust_cursor_eol();
4062 }
4063 
4064 /*
4065  * When the cursor is on the NUL past the end of the line and it should not be
4066  * there move it left.
4067  */
4068     void
4069 adjust_cursor_eol(void)
4070 {
4071     if (curwin->w_cursor.col > 0
4072 	    && gchar_cursor() == NUL
4073 	    && (ve_flags & VE_ONEMORE) == 0
4074 	    && !(restart_edit || (State & INSERT)))
4075     {
4076 	/* Put the cursor on the last character in the line. */
4077 	dec_cursor();
4078 
4079 	if (ve_flags == VE_ALL)
4080 	{
4081 	    colnr_T	    scol, ecol;
4082 
4083 	    /* Coladd is set to the width of the last character. */
4084 	    getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
4085 	    curwin->w_cursor.coladd = ecol - scol + 1;
4086 	}
4087     }
4088 }
4089 
4090 #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) || defined(PROTO)
4091 /*
4092  * Return TRUE if lines starting with '#' should be left aligned.
4093  */
4094     int
4095 preprocs_left(void)
4096 {
4097     return
4098 # ifdef FEAT_SMARTINDENT
4099 #  ifdef FEAT_CINDENT
4100 	(curbuf->b_p_si && !curbuf->b_p_cin) ||
4101 #  else
4102 	curbuf->b_p_si
4103 #  endif
4104 # endif
4105 # ifdef FEAT_CINDENT
4106 	(curbuf->b_p_cin && in_cinkeys('#', ' ', TRUE)
4107 					   && curbuf->b_ind_hash_comment == 0)
4108 # endif
4109 	;
4110 }
4111 #endif
4112 
4113 /*
4114  * Return the character name of the register with the given number.
4115  */
4116     int
4117 get_register_name(int num)
4118 {
4119     if (num == -1)
4120 	return '"';
4121     else if (num < 10)
4122 	return num + '0';
4123     else if (num == DELETION_REGISTER)
4124 	return '-';
4125 #ifdef FEAT_CLIPBOARD
4126     else if (num == STAR_REGISTER)
4127 	return '*';
4128     else if (num == PLUS_REGISTER)
4129 	return '+';
4130 #endif
4131     else
4132     {
4133 #ifdef EBCDIC
4134 	int i;
4135 
4136 	/* EBCDIC is really braindead ... */
4137 	i = 'a' + (num - 10);
4138 	if (i > 'i')
4139 	    i += 7;
4140 	if (i > 'r')
4141 	    i += 8;
4142 	return i;
4143 #else
4144 	return num + 'a' - 10;
4145 #endif
4146     }
4147 }
4148 
4149 /*
4150  * ":dis" and ":registers": Display the contents of the yank registers.
4151  */
4152     void
4153 ex_display(exarg_T *eap)
4154 {
4155     int		i, n;
4156     long	j;
4157     char_u	*p;
4158     yankreg_T	*yb;
4159     int		name;
4160     int		attr;
4161     char_u	*arg = eap->arg;
4162     int		clen;
4163 
4164     if (arg != NULL && *arg == NUL)
4165 	arg = NULL;
4166     attr = HL_ATTR(HLF_8);
4167 
4168     /* Highlight title */
4169     msg_puts_title(_("\n--- Registers ---"));
4170     for (i = -1; i < NUM_REGISTERS && !got_int; ++i)
4171     {
4172 	name = get_register_name(i);
4173 	if (arg != NULL && vim_strchr(arg, name) == NULL
4174 #ifdef ONE_CLIPBOARD
4175 	    /* Star register and plus register contain the same thing. */
4176 		&& (name != '*' || vim_strchr(arg, '+') == NULL)
4177 #endif
4178 		)
4179 	    continue;	    /* did not ask for this register */
4180 
4181 #ifdef FEAT_CLIPBOARD
4182 	/* Adjust register name for "unnamed" in 'clipboard'.
4183 	 * When it's a clipboard register, fill it with the current contents
4184 	 * of the clipboard.  */
4185 	adjust_clip_reg(&name);
4186 	(void)may_get_selection(name);
4187 #endif
4188 
4189 	if (i == -1)
4190 	{
4191 	    if (y_previous != NULL)
4192 		yb = y_previous;
4193 	    else
4194 		yb = &(y_regs[0]);
4195 	}
4196 	else
4197 	    yb = &(y_regs[i]);
4198 
4199 #ifdef FEAT_EVAL
4200 	if (name == MB_TOLOWER(redir_reg)
4201 		|| (redir_reg == '"' && yb == y_previous))
4202 	    continue;	    /* do not list register being written to, the
4203 			     * pointer can be freed */
4204 #endif
4205 
4206 	if (yb->y_array != NULL)
4207 	{
4208 	    msg_putchar('\n');
4209 	    msg_putchar('"');
4210 	    msg_putchar(name);
4211 	    msg_puts("   ");
4212 
4213 	    n = (int)Columns - 6;
4214 	    for (j = 0; j < yb->y_size && n > 1; ++j)
4215 	    {
4216 		if (j)
4217 		{
4218 		    msg_puts_attr("^J", attr);
4219 		    n -= 2;
4220 		}
4221 		for (p = yb->y_array[j]; *p && (n -= ptr2cells(p)) >= 0; ++p)
4222 		{
4223 		    clen = (*mb_ptr2len)(p);
4224 		    msg_outtrans_len(p, clen);
4225 		    p += clen - 1;
4226 		}
4227 	    }
4228 	    if (n > 1 && yb->y_type == MLINE)
4229 		msg_puts_attr("^J", attr);
4230 	    out_flush();		    /* show one line at a time */
4231 	}
4232 	ui_breakcheck();
4233     }
4234 
4235     /*
4236      * display last inserted text
4237      */
4238     if ((p = get_last_insert()) != NULL
4239 		 && (arg == NULL || vim_strchr(arg, '.') != NULL) && !got_int)
4240     {
4241 	msg_puts("\n\".   ");
4242 	dis_msg(p, TRUE);
4243     }
4244 
4245     /*
4246      * display last command line
4247      */
4248     if (last_cmdline != NULL && (arg == NULL || vim_strchr(arg, ':') != NULL)
4249 								  && !got_int)
4250     {
4251 	msg_puts("\n\":   ");
4252 	dis_msg(last_cmdline, FALSE);
4253     }
4254 
4255     /*
4256      * display current file name
4257      */
4258     if (curbuf->b_fname != NULL
4259 	    && (arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int)
4260     {
4261 	msg_puts("\n\"%   ");
4262 	dis_msg(curbuf->b_fname, FALSE);
4263     }
4264 
4265     /*
4266      * display alternate file name
4267      */
4268     if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int)
4269     {
4270 	char_u	    *fname;
4271 	linenr_T    dummy;
4272 
4273 	if (buflist_name_nr(0, &fname, &dummy) != FAIL)
4274 	{
4275 	    msg_puts("\n\"#   ");
4276 	    dis_msg(fname, FALSE);
4277 	}
4278     }
4279 
4280     /*
4281      * display last search pattern
4282      */
4283     if (last_search_pat() != NULL
4284 		 && (arg == NULL || vim_strchr(arg, '/') != NULL) && !got_int)
4285     {
4286 	msg_puts("\n\"/   ");
4287 	dis_msg(last_search_pat(), FALSE);
4288     }
4289 
4290 #ifdef FEAT_EVAL
4291     /*
4292      * display last used expression
4293      */
4294     if (expr_line != NULL && (arg == NULL || vim_strchr(arg, '=') != NULL)
4295 								  && !got_int)
4296     {
4297 	msg_puts("\n\"=   ");
4298 	dis_msg(expr_line, FALSE);
4299     }
4300 #endif
4301 }
4302 
4303 /*
4304  * display a string for do_dis()
4305  * truncate at end of screen line
4306  */
4307     static void
4308 dis_msg(
4309     char_u	*p,
4310     int		skip_esc)	    /* if TRUE, ignore trailing ESC */
4311 {
4312     int		n;
4313     int		l;
4314 
4315     n = (int)Columns - 6;
4316     while (*p != NUL
4317 	    && !(*p == ESC && skip_esc && *(p + 1) == NUL)
4318 	    && (n -= ptr2cells(p)) >= 0)
4319     {
4320 	if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
4321 	{
4322 	    msg_outtrans_len(p, l);
4323 	    p += l;
4324 	}
4325 	else
4326 	    msg_outtrans_len(p++, 1);
4327     }
4328     ui_breakcheck();
4329 }
4330 
4331 #if defined(FEAT_COMMENTS) || defined(PROTO)
4332 /*
4333  * If "process" is TRUE and the line begins with a comment leader (possibly
4334  * after some white space), return a pointer to the text after it. Put a boolean
4335  * value indicating whether the line ends with an unclosed comment in
4336  * "is_comment".
4337  * line - line to be processed,
4338  * process - if FALSE, will only check whether the line ends with an unclosed
4339  *	     comment,
4340  * include_space - whether to also skip space following the comment leader,
4341  * is_comment - will indicate whether the current line ends with an unclosed
4342  *		comment.
4343  */
4344     char_u *
4345 skip_comment(
4346     char_u   *line,
4347     int      process,
4348     int	     include_space,
4349     int      *is_comment)
4350 {
4351     char_u *comment_flags = NULL;
4352     int    lead_len;
4353     int    leader_offset = get_last_leader_offset(line, &comment_flags);
4354 
4355     *is_comment = FALSE;
4356     if (leader_offset != -1)
4357     {
4358 	/* Let's check whether the line ends with an unclosed comment.
4359 	 * If the last comment leader has COM_END in flags, there's no comment.
4360 	 */
4361 	while (*comment_flags)
4362 	{
4363 	    if (*comment_flags == COM_END
4364 		    || *comment_flags == ':')
4365 		break;
4366 	    ++comment_flags;
4367 	}
4368 	if (*comment_flags != COM_END)
4369 	    *is_comment = TRUE;
4370     }
4371 
4372     if (process == FALSE)
4373 	return line;
4374 
4375     lead_len = get_leader_len(line, &comment_flags, FALSE, include_space);
4376 
4377     if (lead_len == 0)
4378 	return line;
4379 
4380     /* Find:
4381      * - COM_END,
4382      * - colon,
4383      * whichever comes first.
4384      */
4385     while (*comment_flags)
4386     {
4387 	if (*comment_flags == COM_END
4388 		|| *comment_flags == ':')
4389 	{
4390 	    break;
4391 	}
4392 	++comment_flags;
4393     }
4394 
4395     /* If we found a colon, it means that we are not processing a line
4396      * starting with a closing part of a three-part comment. That's good,
4397      * because we don't want to remove those as this would be annoying.
4398      */
4399     if (*comment_flags == ':' || *comment_flags == NUL)
4400 	line += lead_len;
4401 
4402     return line;
4403 }
4404 #endif
4405 
4406 /*
4407  * Join 'count' lines (minimal 2) at cursor position.
4408  * When "save_undo" is TRUE save lines for undo first.
4409  * Set "use_formatoptions" to FALSE when e.g. processing backspace and comment
4410  * leaders should not be removed.
4411  * When setmark is TRUE, sets the '[ and '] mark, else, the caller is expected
4412  * to set those marks.
4413  *
4414  * return FAIL for failure, OK otherwise
4415  */
4416     int
4417 do_join(
4418     long    count,
4419     int	    insert_space,
4420     int	    save_undo,
4421     int	    use_formatoptions UNUSED,
4422     int	    setmark)
4423 {
4424     char_u	*curr = NULL;
4425     char_u      *curr_start = NULL;
4426     char_u	*cend;
4427     char_u	*newp;
4428     char_u	*spaces;	/* number of spaces inserted before a line */
4429     int		endcurr1 = NUL;
4430     int		endcurr2 = NUL;
4431     int		currsize = 0;	/* size of the current line */
4432     int		sumsize = 0;	/* size of the long new line */
4433     linenr_T	t;
4434     colnr_T	col = 0;
4435     int		ret = OK;
4436 #if defined(FEAT_COMMENTS) || defined(PROTO)
4437     int		*comments = NULL;
4438     int		remove_comments = (use_formatoptions == TRUE)
4439 				  && has_format_option(FO_REMOVE_COMS);
4440     int		prev_was_comment;
4441 #endif
4442 
4443 
4444     if (save_undo && u_save((linenr_T)(curwin->w_cursor.lnum - 1),
4445 			    (linenr_T)(curwin->w_cursor.lnum + count)) == FAIL)
4446 	return FAIL;
4447 
4448     /* Allocate an array to store the number of spaces inserted before each
4449      * line.  We will use it to pre-compute the length of the new line and the
4450      * proper placement of each original line in the new one. */
4451     spaces = lalloc_clear((long_u)count, TRUE);
4452     if (spaces == NULL)
4453 	return FAIL;
4454 #if defined(FEAT_COMMENTS) || defined(PROTO)
4455     if (remove_comments)
4456     {
4457 	comments = (int *)lalloc_clear((long_u)count * sizeof(int), TRUE);
4458 	if (comments == NULL)
4459 	{
4460 	    vim_free(spaces);
4461 	    return FAIL;
4462 	}
4463     }
4464 #endif
4465 
4466     /*
4467      * Don't move anything, just compute the final line length
4468      * and setup the array of space strings lengths
4469      */
4470     for (t = 0; t < count; ++t)
4471     {
4472 	curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t));
4473 	if (t == 0 && setmark)
4474 	{
4475 	    /* Set the '[ mark. */
4476 	    curwin->w_buffer->b_op_start.lnum = curwin->w_cursor.lnum;
4477 	    curwin->w_buffer->b_op_start.col  = (colnr_T)STRLEN(curr);
4478 	}
4479 #if defined(FEAT_COMMENTS) || defined(PROTO)
4480 	if (remove_comments)
4481 	{
4482 	    /* We don't want to remove the comment leader if the
4483 	     * previous line is not a comment. */
4484 	    if (t > 0 && prev_was_comment)
4485 	    {
4486 
4487 		char_u *new_curr = skip_comment(curr, TRUE, insert_space,
4488 							   &prev_was_comment);
4489 		comments[t] = (int)(new_curr - curr);
4490 		curr = new_curr;
4491 	    }
4492 	    else
4493 		curr = skip_comment(curr, FALSE, insert_space,
4494 							   &prev_was_comment);
4495 	}
4496 #endif
4497 
4498 	if (insert_space && t > 0)
4499 	{
4500 	    curr = skipwhite(curr);
4501 	    if (*curr != ')' && currsize != 0 && endcurr1 != TAB
4502 		    && (!has_format_option(FO_MBYTE_JOIN)
4503 			|| (mb_ptr2char(curr) < 0x100 && endcurr1 < 0x100))
4504 		    && (!has_format_option(FO_MBYTE_JOIN2)
4505 			|| mb_ptr2char(curr) < 0x100 || endcurr1 < 0x100)
4506 	       )
4507 	    {
4508 		/* don't add a space if the line is ending in a space */
4509 		if (endcurr1 == ' ')
4510 		    endcurr1 = endcurr2;
4511 		else
4512 		    ++spaces[t];
4513 		/* extra space when 'joinspaces' set and line ends in '.' */
4514 		if (       p_js
4515 			&& (endcurr1 == '.'
4516 			    || (vim_strchr(p_cpo, CPO_JOINSP) == NULL
4517 				&& (endcurr1 == '?' || endcurr1 == '!'))))
4518 		    ++spaces[t];
4519 	    }
4520 	}
4521 	currsize = (int)STRLEN(curr);
4522 	sumsize += currsize + spaces[t];
4523 	endcurr1 = endcurr2 = NUL;
4524 	if (insert_space && currsize > 0)
4525 	{
4526 	    if (has_mbyte)
4527 	    {
4528 		cend = curr + currsize;
4529 		MB_PTR_BACK(curr, cend);
4530 		endcurr1 = (*mb_ptr2char)(cend);
4531 		if (cend > curr)
4532 		{
4533 		    MB_PTR_BACK(curr, cend);
4534 		    endcurr2 = (*mb_ptr2char)(cend);
4535 		}
4536 	    }
4537 	    else
4538 	    {
4539 		endcurr1 = *(curr + currsize - 1);
4540 		if (currsize > 1)
4541 		    endcurr2 = *(curr + currsize - 2);
4542 	    }
4543 	}
4544 	line_breakcheck();
4545 	if (got_int)
4546 	{
4547 	    ret = FAIL;
4548 	    goto theend;
4549 	}
4550     }
4551 
4552     /* store the column position before last line */
4553     col = sumsize - currsize - spaces[count - 1];
4554 
4555     /* allocate the space for the new line */
4556     newp = alloc_check((unsigned)(sumsize + 1));
4557     cend = newp + sumsize;
4558     *cend = 0;
4559 
4560     /*
4561      * Move affected lines to the new long one.
4562      *
4563      * Move marks from each deleted line to the joined line, adjusting the
4564      * column.  This is not Vi compatible, but Vi deletes the marks, thus that
4565      * should not really be a problem.
4566      */
4567     for (t = count - 1; ; --t)
4568     {
4569 	int spaces_removed;
4570 
4571 	cend -= currsize;
4572 	mch_memmove(cend, curr, (size_t)currsize);
4573 	if (spaces[t] > 0)
4574 	{
4575 	    cend -= spaces[t];
4576 	    vim_memset(cend, ' ', (size_t)(spaces[t]));
4577 	}
4578 
4579 	// If deleting more spaces than adding, the cursor moves no more than
4580 	// what is added if it is inside these spaces.
4581 	spaces_removed = (curr - curr_start) - spaces[t];
4582 
4583 	mark_col_adjust(curwin->w_cursor.lnum + t, (colnr_T)0, (linenr_T)-t,
4584 			 (long)(cend - newp - spaces_removed), spaces_removed);
4585 	if (t == 0)
4586 	    break;
4587 	curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1));
4588 #if defined(FEAT_COMMENTS) || defined(PROTO)
4589 	if (remove_comments)
4590 	    curr += comments[t - 1];
4591 #endif
4592 	if (insert_space && t > 1)
4593 	    curr = skipwhite(curr);
4594 	currsize = (int)STRLEN(curr);
4595     }
4596     ml_replace(curwin->w_cursor.lnum, newp, FALSE);
4597 
4598     if (setmark)
4599     {
4600 	/* Set the '] mark. */
4601 	curwin->w_buffer->b_op_end.lnum = curwin->w_cursor.lnum;
4602 	curwin->w_buffer->b_op_end.col  = (colnr_T)STRLEN(newp);
4603     }
4604 
4605     /* Only report the change in the first line here, del_lines() will report
4606      * the deleted line. */
4607     changed_lines(curwin->w_cursor.lnum, currsize,
4608 					       curwin->w_cursor.lnum + 1, 0L);
4609 
4610     /*
4611      * Delete following lines. To do this we move the cursor there
4612      * briefly, and then move it back. After del_lines() the cursor may
4613      * have moved up (last line deleted), so the current lnum is kept in t.
4614      */
4615     t = curwin->w_cursor.lnum;
4616     ++curwin->w_cursor.lnum;
4617     del_lines(count - 1, FALSE);
4618     curwin->w_cursor.lnum = t;
4619 
4620     /*
4621      * Set the cursor column:
4622      * Vi compatible: use the column of the first join
4623      * vim:	      use the column of the last join
4624      */
4625     curwin->w_cursor.col =
4626 		    (vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col);
4627     check_cursor_col();
4628 
4629     curwin->w_cursor.coladd = 0;
4630     curwin->w_set_curswant = TRUE;
4631 
4632 theend:
4633     vim_free(spaces);
4634 #if defined(FEAT_COMMENTS) || defined(PROTO)
4635     if (remove_comments)
4636 	vim_free(comments);
4637 #endif
4638     return ret;
4639 }
4640 
4641 #ifdef FEAT_COMMENTS
4642 /*
4643  * Return TRUE if the two comment leaders given are the same.  "lnum" is
4644  * the first line.  White-space is ignored.  Note that the whole of
4645  * 'leader1' must match 'leader2_len' characters from 'leader2' -- webb
4646  */
4647     static int
4648 same_leader(
4649     linenr_T lnum,
4650     int	    leader1_len,
4651     char_u  *leader1_flags,
4652     int	    leader2_len,
4653     char_u  *leader2_flags)
4654 {
4655     int	    idx1 = 0, idx2 = 0;
4656     char_u  *p;
4657     char_u  *line1;
4658     char_u  *line2;
4659 
4660     if (leader1_len == 0)
4661 	return (leader2_len == 0);
4662 
4663     /*
4664      * If first leader has 'f' flag, the lines can be joined only if the
4665      * second line does not have a leader.
4666      * If first leader has 'e' flag, the lines can never be joined.
4667      * If fist leader has 's' flag, the lines can only be joined if there is
4668      * some text after it and the second line has the 'm' flag.
4669      */
4670     if (leader1_flags != NULL)
4671     {
4672 	for (p = leader1_flags; *p && *p != ':'; ++p)
4673 	{
4674 	    if (*p == COM_FIRST)
4675 		return (leader2_len == 0);
4676 	    if (*p == COM_END)
4677 		return FALSE;
4678 	    if (*p == COM_START)
4679 	    {
4680 		if (*(ml_get(lnum) + leader1_len) == NUL)
4681 		    return FALSE;
4682 		if (leader2_flags == NULL || leader2_len == 0)
4683 		    return FALSE;
4684 		for (p = leader2_flags; *p && *p != ':'; ++p)
4685 		    if (*p == COM_MIDDLE)
4686 			return TRUE;
4687 		return FALSE;
4688 	    }
4689 	}
4690     }
4691 
4692     /*
4693      * Get current line and next line, compare the leaders.
4694      * The first line has to be saved, only one line can be locked at a time.
4695      */
4696     line1 = vim_strsave(ml_get(lnum));
4697     if (line1 != NULL)
4698     {
4699 	for (idx1 = 0; VIM_ISWHITE(line1[idx1]); ++idx1)
4700 	    ;
4701 	line2 = ml_get(lnum + 1);
4702 	for (idx2 = 0; idx2 < leader2_len; ++idx2)
4703 	{
4704 	    if (!VIM_ISWHITE(line2[idx2]))
4705 	    {
4706 		if (line1[idx1++] != line2[idx2])
4707 		    break;
4708 	    }
4709 	    else
4710 		while (VIM_ISWHITE(line1[idx1]))
4711 		    ++idx1;
4712 	}
4713 	vim_free(line1);
4714     }
4715     return (idx2 == leader2_len && idx1 == leader1_len);
4716 }
4717 #endif
4718 
4719 /*
4720  * Implementation of the format operator 'gq'.
4721  */
4722     void
4723 op_format(
4724     oparg_T	*oap,
4725     int		keep_cursor)		/* keep cursor on same text char */
4726 {
4727     long	old_line_count = curbuf->b_ml.ml_line_count;
4728 
4729     /* Place the cursor where the "gq" or "gw" command was given, so that "u"
4730      * can put it back there. */
4731     curwin->w_cursor = oap->cursor_start;
4732 
4733     if (u_save((linenr_T)(oap->start.lnum - 1),
4734 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
4735 	return;
4736     curwin->w_cursor = oap->start;
4737 
4738     if (oap->is_VIsual)
4739 	/* When there is no change: need to remove the Visual selection */
4740 	redraw_curbuf_later(INVERTED);
4741 
4742     /* Set '[ mark at the start of the formatted area */
4743     curbuf->b_op_start = oap->start;
4744 
4745     /* For "gw" remember the cursor position and put it back below (adjusted
4746      * for joined and split lines). */
4747     if (keep_cursor)
4748 	saved_cursor = oap->cursor_start;
4749 
4750     format_lines(oap->line_count, keep_cursor);
4751 
4752     /*
4753      * Leave the cursor at the first non-blank of the last formatted line.
4754      * If the cursor was moved one line back (e.g. with "Q}") go to the next
4755      * line, so "." will do the next lines.
4756      */
4757     if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
4758 	++curwin->w_cursor.lnum;
4759     beginline(BL_WHITE | BL_FIX);
4760     old_line_count = curbuf->b_ml.ml_line_count - old_line_count;
4761     msgmore(old_line_count);
4762 
4763     /* put '] mark on the end of the formatted area */
4764     curbuf->b_op_end = curwin->w_cursor;
4765 
4766     if (keep_cursor)
4767     {
4768 	curwin->w_cursor = saved_cursor;
4769 	saved_cursor.lnum = 0;
4770     }
4771 
4772     if (oap->is_VIsual)
4773     {
4774 	win_T	*wp;
4775 
4776 	FOR_ALL_WINDOWS(wp)
4777 	{
4778 	    if (wp->w_old_cursor_lnum != 0)
4779 	    {
4780 		/* When lines have been inserted or deleted, adjust the end of
4781 		 * the Visual area to be redrawn. */
4782 		if (wp->w_old_cursor_lnum > wp->w_old_visual_lnum)
4783 		    wp->w_old_cursor_lnum += old_line_count;
4784 		else
4785 		    wp->w_old_visual_lnum += old_line_count;
4786 	    }
4787 	}
4788     }
4789 }
4790 
4791 #if defined(FEAT_EVAL) || defined(PROTO)
4792 /*
4793  * Implementation of the format operator 'gq' for when using 'formatexpr'.
4794  */
4795     void
4796 op_formatexpr(oparg_T *oap)
4797 {
4798     if (oap->is_VIsual)
4799 	/* When there is no change: need to remove the Visual selection */
4800 	redraw_curbuf_later(INVERTED);
4801 
4802     if (fex_format(oap->start.lnum, oap->line_count, NUL) != 0)
4803 	/* As documented: when 'formatexpr' returns non-zero fall back to
4804 	 * internal formatting. */
4805 	op_format(oap, FALSE);
4806 }
4807 
4808     int
4809 fex_format(
4810     linenr_T	lnum,
4811     long	count,
4812     int		c)	/* character to be inserted */
4813 {
4814     int		use_sandbox = was_set_insecurely((char_u *)"formatexpr",
4815 								   OPT_LOCAL);
4816     int		r;
4817     char_u	*fex;
4818 
4819     /*
4820      * Set v:lnum to the first line number and v:count to the number of lines.
4821      * Set v:char to the character to be inserted (can be NUL).
4822      */
4823     set_vim_var_nr(VV_LNUM, lnum);
4824     set_vim_var_nr(VV_COUNT, count);
4825     set_vim_var_char(c);
4826 
4827     /* Make a copy, the option could be changed while calling it. */
4828     fex = vim_strsave(curbuf->b_p_fex);
4829     if (fex == NULL)
4830 	return 0;
4831 
4832     /*
4833      * Evaluate the function.
4834      */
4835     if (use_sandbox)
4836 	++sandbox;
4837     r = (int)eval_to_number(fex);
4838     if (use_sandbox)
4839 	--sandbox;
4840 
4841     set_vim_var_string(VV_CHAR, NULL, -1);
4842     vim_free(fex);
4843 
4844     return r;
4845 }
4846 #endif
4847 
4848 /*
4849  * Format "line_count" lines, starting at the cursor position.
4850  * When "line_count" is negative, format until the end of the paragraph.
4851  * Lines after the cursor line are saved for undo, caller must have saved the
4852  * first line.
4853  */
4854     void
4855 format_lines(
4856     linenr_T	line_count,
4857     int		avoid_fex)		/* don't use 'formatexpr' */
4858 {
4859     int		max_len;
4860     int		is_not_par;		/* current line not part of parag. */
4861     int		next_is_not_par;	/* next line not part of paragraph */
4862     int		is_end_par;		/* at end of paragraph */
4863     int		prev_is_end_par = FALSE;/* prev. line not part of parag. */
4864     int		next_is_start_par = FALSE;
4865 #ifdef FEAT_COMMENTS
4866     int		leader_len = 0;		/* leader len of current line */
4867     int		next_leader_len;	/* leader len of next line */
4868     char_u	*leader_flags = NULL;	/* flags for leader of current line */
4869     char_u	*next_leader_flags;	/* flags for leader of next line */
4870     int		do_comments;		/* format comments */
4871     int		do_comments_list = 0;	/* format comments with 'n' or '2' */
4872 #endif
4873     int		advance = TRUE;
4874     int		second_indent = -1;	/* indent for second line (comment
4875 					 * aware) */
4876     int		do_second_indent;
4877     int		do_number_indent;
4878     int		do_trail_white;
4879     int		first_par_line = TRUE;
4880     int		smd_save;
4881     long	count;
4882     int		need_set_indent = TRUE;	/* set indent of next paragraph */
4883     int		force_format = FALSE;
4884     int		old_State = State;
4885 
4886     /* length of a line to force formatting: 3 * 'tw' */
4887     max_len = comp_textwidth(TRUE) * 3;
4888 
4889     /* check for 'q', '2' and '1' in 'formatoptions' */
4890 #ifdef FEAT_COMMENTS
4891     do_comments = has_format_option(FO_Q_COMS);
4892 #endif
4893     do_second_indent = has_format_option(FO_Q_SECOND);
4894     do_number_indent = has_format_option(FO_Q_NUMBER);
4895     do_trail_white = has_format_option(FO_WHITE_PAR);
4896 
4897     /*
4898      * Get info about the previous and current line.
4899      */
4900     if (curwin->w_cursor.lnum > 1)
4901 	is_not_par = fmt_check_par(curwin->w_cursor.lnum - 1
4902 #ifdef FEAT_COMMENTS
4903 				, &leader_len, &leader_flags, do_comments
4904 #endif
4905 				);
4906     else
4907 	is_not_par = TRUE;
4908     next_is_not_par = fmt_check_par(curwin->w_cursor.lnum
4909 #ifdef FEAT_COMMENTS
4910 			   , &next_leader_len, &next_leader_flags, do_comments
4911 #endif
4912 				);
4913     is_end_par = (is_not_par || next_is_not_par);
4914     if (!is_end_par && do_trail_white)
4915 	is_end_par = !ends_in_white(curwin->w_cursor.lnum - 1);
4916 
4917     curwin->w_cursor.lnum--;
4918     for (count = line_count; count != 0 && !got_int; --count)
4919     {
4920 	/*
4921 	 * Advance to next paragraph.
4922 	 */
4923 	if (advance)
4924 	{
4925 	    curwin->w_cursor.lnum++;
4926 	    prev_is_end_par = is_end_par;
4927 	    is_not_par = next_is_not_par;
4928 #ifdef FEAT_COMMENTS
4929 	    leader_len = next_leader_len;
4930 	    leader_flags = next_leader_flags;
4931 #endif
4932 	}
4933 
4934 	/*
4935 	 * The last line to be formatted.
4936 	 */
4937 	if (count == 1 || curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
4938 	{
4939 	    next_is_not_par = TRUE;
4940 #ifdef FEAT_COMMENTS
4941 	    next_leader_len = 0;
4942 	    next_leader_flags = NULL;
4943 #endif
4944 	}
4945 	else
4946 	{
4947 	    next_is_not_par = fmt_check_par(curwin->w_cursor.lnum + 1
4948 #ifdef FEAT_COMMENTS
4949 			   , &next_leader_len, &next_leader_flags, do_comments
4950 #endif
4951 					);
4952 	    if (do_number_indent)
4953 		next_is_start_par =
4954 			   (get_number_indent(curwin->w_cursor.lnum + 1) > 0);
4955 	}
4956 	advance = TRUE;
4957 	is_end_par = (is_not_par || next_is_not_par || next_is_start_par);
4958 	if (!is_end_par && do_trail_white)
4959 	    is_end_par = !ends_in_white(curwin->w_cursor.lnum);
4960 
4961 	/*
4962 	 * Skip lines that are not in a paragraph.
4963 	 */
4964 	if (is_not_par)
4965 	{
4966 	    if (line_count < 0)
4967 		break;
4968 	}
4969 	else
4970 	{
4971 	    /*
4972 	     * For the first line of a paragraph, check indent of second line.
4973 	     * Don't do this for comments and empty lines.
4974 	     */
4975 	    if (first_par_line
4976 		    && (do_second_indent || do_number_indent)
4977 		    && prev_is_end_par
4978 		    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
4979 	    {
4980 		if (do_second_indent && !LINEEMPTY(curwin->w_cursor.lnum + 1))
4981 		{
4982 #ifdef FEAT_COMMENTS
4983 		    if (leader_len == 0 && next_leader_len == 0)
4984 		    {
4985 			/* no comment found */
4986 #endif
4987 			second_indent =
4988 				   get_indent_lnum(curwin->w_cursor.lnum + 1);
4989 #ifdef FEAT_COMMENTS
4990 		    }
4991 		    else
4992 		    {
4993 			second_indent = next_leader_len;
4994 			do_comments_list = 1;
4995 		    }
4996 #endif
4997 		}
4998 		else if (do_number_indent)
4999 		{
5000 #ifdef FEAT_COMMENTS
5001 		    if (leader_len == 0 && next_leader_len == 0)
5002 		    {
5003 			/* no comment found */
5004 #endif
5005 			second_indent =
5006 				     get_number_indent(curwin->w_cursor.lnum);
5007 #ifdef FEAT_COMMENTS
5008 		    }
5009 		    else
5010 		    {
5011 			/* get_number_indent() is now "comment aware"... */
5012 			second_indent =
5013 				     get_number_indent(curwin->w_cursor.lnum);
5014 			do_comments_list = 1;
5015 		    }
5016 #endif
5017 		}
5018 	    }
5019 
5020 	    /*
5021 	     * When the comment leader changes, it's the end of the paragraph.
5022 	     */
5023 	    if (curwin->w_cursor.lnum >= curbuf->b_ml.ml_line_count
5024 #ifdef FEAT_COMMENTS
5025 		    || !same_leader(curwin->w_cursor.lnum,
5026 					leader_len, leader_flags,
5027 					  next_leader_len, next_leader_flags)
5028 #endif
5029 		    )
5030 		is_end_par = TRUE;
5031 
5032 	    /*
5033 	     * If we have got to the end of a paragraph, or the line is
5034 	     * getting long, format it.
5035 	     */
5036 	    if (is_end_par || force_format)
5037 	    {
5038 		if (need_set_indent)
5039 		    /* replace indent in first line with minimal number of
5040 		     * tabs and spaces, according to current options */
5041 		    (void)set_indent(get_indent(), SIN_CHANGED);
5042 
5043 		/* put cursor on last non-space */
5044 		State = NORMAL;	/* don't go past end-of-line */
5045 		coladvance((colnr_T)MAXCOL);
5046 		while (curwin->w_cursor.col && vim_isspace(gchar_cursor()))
5047 		    dec_cursor();
5048 
5049 		/* do the formatting, without 'showmode' */
5050 		State = INSERT;	/* for open_line() */
5051 		smd_save = p_smd;
5052 		p_smd = FALSE;
5053 		insertchar(NUL, INSCHAR_FORMAT
5054 #ifdef FEAT_COMMENTS
5055 			+ (do_comments ? INSCHAR_DO_COM : 0)
5056 			+ (do_comments && do_comments_list
5057 						       ? INSCHAR_COM_LIST : 0)
5058 #endif
5059 			+ (avoid_fex ? INSCHAR_NO_FEX : 0), second_indent);
5060 		State = old_State;
5061 		p_smd = smd_save;
5062 		second_indent = -1;
5063 		/* at end of par.: need to set indent of next par. */
5064 		need_set_indent = is_end_par;
5065 		if (is_end_par)
5066 		{
5067 		    /* When called with a negative line count, break at the
5068 		     * end of the paragraph. */
5069 		    if (line_count < 0)
5070 			break;
5071 		    first_par_line = TRUE;
5072 		}
5073 		force_format = FALSE;
5074 	    }
5075 
5076 	    /*
5077 	     * When still in same paragraph, join the lines together.  But
5078 	     * first delete the leader from the second line.
5079 	     */
5080 	    if (!is_end_par)
5081 	    {
5082 		advance = FALSE;
5083 		curwin->w_cursor.lnum++;
5084 		curwin->w_cursor.col = 0;
5085 		if (line_count < 0 && u_save_cursor() == FAIL)
5086 		    break;
5087 #ifdef FEAT_COMMENTS
5088 		if (next_leader_len > 0)
5089 		{
5090 		    (void)del_bytes((long)next_leader_len, FALSE, FALSE);
5091 		    mark_col_adjust(curwin->w_cursor.lnum, (colnr_T)0, 0L,
5092 						      (long)-next_leader_len, 0);
5093 		} else
5094 #endif
5095 		    if (second_indent > 0)  /* the "leader" for FO_Q_SECOND */
5096 		{
5097 		    int indent = getwhitecols_curline();
5098 
5099 		    if (indent > 0)
5100 		    {
5101 			(void)del_bytes(indent, FALSE, FALSE);
5102 			mark_col_adjust(curwin->w_cursor.lnum,
5103 					       (colnr_T)0, 0L, (long)-indent, 0);
5104 		    }
5105 		}
5106 		curwin->w_cursor.lnum--;
5107 		if (do_join(2, TRUE, FALSE, FALSE, FALSE) == FAIL)
5108 		{
5109 		    beep_flush();
5110 		    break;
5111 		}
5112 		first_par_line = FALSE;
5113 		/* If the line is getting long, format it next time */
5114 		if (STRLEN(ml_get_curline()) > (size_t)max_len)
5115 		    force_format = TRUE;
5116 		else
5117 		    force_format = FALSE;
5118 	    }
5119 	}
5120 	line_breakcheck();
5121     }
5122 }
5123 
5124 /*
5125  * Return TRUE if line "lnum" ends in a white character.
5126  */
5127     static int
5128 ends_in_white(linenr_T lnum)
5129 {
5130     char_u	*s = ml_get(lnum);
5131     size_t	l;
5132 
5133     if (*s == NUL)
5134 	return FALSE;
5135     /* Don't use STRLEN() inside VIM_ISWHITE(), SAS/C complains: "macro
5136      * invocation may call function multiple times". */
5137     l = STRLEN(s) - 1;
5138     return VIM_ISWHITE(s[l]);
5139 }
5140 
5141 /*
5142  * Blank lines, and lines containing only the comment leader, are left
5143  * untouched by the formatting.  The function returns TRUE in this
5144  * case.  It also returns TRUE when a line starts with the end of a comment
5145  * ('e' in comment flags), so that this line is skipped, and not joined to the
5146  * previous line.  A new paragraph starts after a blank line, or when the
5147  * comment leader changes -- webb.
5148  */
5149 #ifdef FEAT_COMMENTS
5150     static int
5151 fmt_check_par(
5152     linenr_T	lnum,
5153     int		*leader_len,
5154     char_u	**leader_flags,
5155     int		do_comments)
5156 {
5157     char_u	*flags = NULL;	    /* init for GCC */
5158     char_u	*ptr;
5159 
5160     ptr = ml_get(lnum);
5161     if (do_comments)
5162 	*leader_len = get_leader_len(ptr, leader_flags, FALSE, TRUE);
5163     else
5164 	*leader_len = 0;
5165 
5166     if (*leader_len > 0)
5167     {
5168 	/*
5169 	 * Search for 'e' flag in comment leader flags.
5170 	 */
5171 	flags = *leader_flags;
5172 	while (*flags && *flags != ':' && *flags != COM_END)
5173 	    ++flags;
5174     }
5175 
5176     return (*skipwhite(ptr + *leader_len) == NUL
5177 	    || (*leader_len > 0 && *flags == COM_END)
5178 	    || startPS(lnum, NUL, FALSE));
5179 }
5180 #else
5181     static int
5182 fmt_check_par(linenr_T lnum)
5183 {
5184     return (*skipwhite(ml_get(lnum)) == NUL || startPS(lnum, NUL, FALSE));
5185 }
5186 #endif
5187 
5188 /*
5189  * Return TRUE when a paragraph starts in line "lnum".  Return FALSE when the
5190  * previous line is in the same paragraph.  Used for auto-formatting.
5191  */
5192     int
5193 paragraph_start(linenr_T lnum)
5194 {
5195     char_u	*p;
5196 #ifdef FEAT_COMMENTS
5197     int		leader_len = 0;		/* leader len of current line */
5198     char_u	*leader_flags = NULL;	/* flags for leader of current line */
5199     int		next_leader_len;	/* leader len of next line */
5200     char_u	*next_leader_flags;	/* flags for leader of next line */
5201     int		do_comments;		/* format comments */
5202 #endif
5203 
5204     if (lnum <= 1)
5205 	return TRUE;		/* start of the file */
5206 
5207     p = ml_get(lnum - 1);
5208     if (*p == NUL)
5209 	return TRUE;		/* after empty line */
5210 
5211 #ifdef FEAT_COMMENTS
5212     do_comments = has_format_option(FO_Q_COMS);
5213 #endif
5214     if (fmt_check_par(lnum - 1
5215 #ifdef FEAT_COMMENTS
5216 				, &leader_len, &leader_flags, do_comments
5217 #endif
5218 		))
5219 	return TRUE;		/* after non-paragraph line */
5220 
5221     if (fmt_check_par(lnum
5222 #ifdef FEAT_COMMENTS
5223 			   , &next_leader_len, &next_leader_flags, do_comments
5224 #endif
5225 		))
5226 	return TRUE;		/* "lnum" is not a paragraph line */
5227 
5228     if (has_format_option(FO_WHITE_PAR) && !ends_in_white(lnum - 1))
5229 	return TRUE;		/* missing trailing space in previous line. */
5230 
5231     if (has_format_option(FO_Q_NUMBER) && (get_number_indent(lnum) > 0))
5232 	return TRUE;		/* numbered item starts in "lnum". */
5233 
5234 #ifdef FEAT_COMMENTS
5235     if (!same_leader(lnum - 1, leader_len, leader_flags,
5236 					  next_leader_len, next_leader_flags))
5237 	return TRUE;		/* change of comment leader. */
5238 #endif
5239 
5240     return FALSE;
5241 }
5242 
5243 /*
5244  * prepare a few things for block mode yank/delete/tilde
5245  *
5246  * for delete:
5247  * - textlen includes the first/last char to be (partly) deleted
5248  * - start/endspaces is the number of columns that are taken by the
5249  *   first/last deleted char minus the number of columns that have to be
5250  *   deleted.
5251  * for yank and tilde:
5252  * - textlen includes the first/last char to be wholly yanked
5253  * - start/endspaces is the number of columns of the first/last yanked char
5254  *   that are to be yanked.
5255  */
5256     static void
5257 block_prep(
5258     oparg_T		*oap,
5259     struct block_def	*bdp,
5260     linenr_T		lnum,
5261     int			is_del)
5262 {
5263     int		incr = 0;
5264     char_u	*pend;
5265     char_u	*pstart;
5266     char_u	*line;
5267     char_u	*prev_pstart;
5268     char_u	*prev_pend;
5269 
5270     bdp->startspaces = 0;
5271     bdp->endspaces = 0;
5272     bdp->textlen = 0;
5273     bdp->start_vcol = 0;
5274     bdp->end_vcol = 0;
5275     bdp->is_short = FALSE;
5276     bdp->is_oneChar = FALSE;
5277     bdp->pre_whitesp = 0;
5278     bdp->pre_whitesp_c = 0;
5279     bdp->end_char_vcols = 0;
5280     bdp->start_char_vcols = 0;
5281 
5282     line = ml_get(lnum);
5283     pstart = line;
5284     prev_pstart = line;
5285     while (bdp->start_vcol < oap->start_vcol && *pstart)
5286     {
5287 	/* Count a tab for what it's worth (if list mode not on) */
5288 	incr = lbr_chartabsize(line, pstart, (colnr_T)bdp->start_vcol);
5289 	bdp->start_vcol += incr;
5290 	if (VIM_ISWHITE(*pstart))
5291 	{
5292 	    bdp->pre_whitesp += incr;
5293 	    bdp->pre_whitesp_c++;
5294 	}
5295 	else
5296 	{
5297 	    bdp->pre_whitesp = 0;
5298 	    bdp->pre_whitesp_c = 0;
5299 	}
5300 	prev_pstart = pstart;
5301 	MB_PTR_ADV(pstart);
5302     }
5303     bdp->start_char_vcols = incr;
5304     if (bdp->start_vcol < oap->start_vcol)	/* line too short */
5305     {
5306 	bdp->end_vcol = bdp->start_vcol;
5307 	bdp->is_short = TRUE;
5308 	if (!is_del || oap->op_type == OP_APPEND)
5309 	    bdp->endspaces = oap->end_vcol - oap->start_vcol + 1;
5310     }
5311     else
5312     {
5313 	/* notice: this converts partly selected Multibyte characters to
5314 	 * spaces, too. */
5315 	bdp->startspaces = bdp->start_vcol - oap->start_vcol;
5316 	if (is_del && bdp->startspaces)
5317 	    bdp->startspaces = bdp->start_char_vcols - bdp->startspaces;
5318 	pend = pstart;
5319 	bdp->end_vcol = bdp->start_vcol;
5320 	if (bdp->end_vcol > oap->end_vcol)	/* it's all in one character */
5321 	{
5322 	    bdp->is_oneChar = TRUE;
5323 	    if (oap->op_type == OP_INSERT)
5324 		bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
5325 	    else if (oap->op_type == OP_APPEND)
5326 	    {
5327 		bdp->startspaces += oap->end_vcol - oap->start_vcol + 1;
5328 		bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
5329 	    }
5330 	    else
5331 	    {
5332 		bdp->startspaces = oap->end_vcol - oap->start_vcol + 1;
5333 		if (is_del && oap->op_type != OP_LSHIFT)
5334 		{
5335 		    /* just putting the sum of those two into
5336 		     * bdp->startspaces doesn't work for Visual replace,
5337 		     * so we have to split the tab in two */
5338 		    bdp->startspaces = bdp->start_char_vcols
5339 					- (bdp->start_vcol - oap->start_vcol);
5340 		    bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
5341 		}
5342 	    }
5343 	}
5344 	else
5345 	{
5346 	    prev_pend = pend;
5347 	    while (bdp->end_vcol <= oap->end_vcol && *pend != NUL)
5348 	    {
5349 		/* Count a tab for what it's worth (if list mode not on) */
5350 		prev_pend = pend;
5351 		incr = lbr_chartabsize_adv(line, &pend, (colnr_T)bdp->end_vcol);
5352 		bdp->end_vcol += incr;
5353 	    }
5354 	    if (bdp->end_vcol <= oap->end_vcol
5355 		    && (!is_del
5356 			|| oap->op_type == OP_APPEND
5357 			|| oap->op_type == OP_REPLACE)) /* line too short */
5358 	    {
5359 		bdp->is_short = TRUE;
5360 		/* Alternative: include spaces to fill up the block.
5361 		 * Disadvantage: can lead to trailing spaces when the line is
5362 		 * short where the text is put */
5363 		/* if (!is_del || oap->op_type == OP_APPEND) */
5364 		if (oap->op_type == OP_APPEND || virtual_op)
5365 		    bdp->endspaces = oap->end_vcol - bdp->end_vcol
5366 							     + oap->inclusive;
5367 		else
5368 		    bdp->endspaces = 0; /* replace doesn't add characters */
5369 	    }
5370 	    else if (bdp->end_vcol > oap->end_vcol)
5371 	    {
5372 		bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
5373 		if (!is_del && bdp->endspaces)
5374 		{
5375 		    bdp->endspaces = incr - bdp->endspaces;
5376 		    if (pend != pstart)
5377 			pend = prev_pend;
5378 		}
5379 	    }
5380 	}
5381 	bdp->end_char_vcols = incr;
5382 	if (is_del && bdp->startspaces)
5383 	    pstart = prev_pstart;
5384 	bdp->textlen = (int)(pend - pstart);
5385     }
5386     bdp->textcol = (colnr_T) (pstart - line);
5387     bdp->textstart = pstart;
5388 }
5389 
5390 /*
5391  * Handle the add/subtract operator.
5392  */
5393     void
5394 op_addsub(
5395     oparg_T	*oap,
5396     linenr_T	Prenum1,	    /* Amount of add/subtract */
5397     int		g_cmd)		    /* was g<c-a>/g<c-x> */
5398 {
5399     pos_T		pos;
5400     struct block_def	bd;
5401     int			change_cnt = 0;
5402     linenr_T		amount = Prenum1;
5403 
5404    // do_addsub() might trigger re-evaluation of 'foldexpr' halfway, when the
5405    // buffer is not completly updated yet. Postpone updating folds until before
5406    // the call to changed_lines().
5407 #ifdef FEAT_FOLDING
5408    disable_fold_update++;
5409 #endif
5410 
5411     if (!VIsual_active)
5412     {
5413 	pos = curwin->w_cursor;
5414 	if (u_save_cursor() == FAIL)
5415 	{
5416 #ifdef FEAT_FOLDING
5417 	    disable_fold_update--;
5418 #endif
5419 	    return;
5420 	}
5421 	change_cnt = do_addsub(oap->op_type, &pos, 0, amount);
5422 #ifdef FEAT_FOLDING
5423 	disable_fold_update--;
5424 #endif
5425 	if (change_cnt)
5426 	    changed_lines(pos.lnum, 0, pos.lnum + 1, 0L);
5427     }
5428     else
5429     {
5430 	int	one_change;
5431 	int	length;
5432 	pos_T	startpos;
5433 
5434 	if (u_save((linenr_T)(oap->start.lnum - 1),
5435 					(linenr_T)(oap->end.lnum + 1)) == FAIL)
5436 	{
5437 #ifdef FEAT_FOLDING
5438 	    disable_fold_update--;
5439 #endif
5440 	    return;
5441 	}
5442 
5443 	pos = oap->start;
5444 	for (; pos.lnum <= oap->end.lnum; ++pos.lnum)
5445 	{
5446 	    if (oap->block_mode)		    /* Visual block mode */
5447 	    {
5448 		block_prep(oap, &bd, pos.lnum, FALSE);
5449 		pos.col = bd.textcol;
5450 		length = bd.textlen;
5451 	    }
5452 	    else if (oap->motion_type == MLINE)
5453 	    {
5454 		curwin->w_cursor.col = 0;
5455 		pos.col = 0;
5456 		length = (colnr_T)STRLEN(ml_get(pos.lnum));
5457 	    }
5458 	    else /* oap->motion_type == MCHAR */
5459 	    {
5460 		if (pos.lnum == oap->start.lnum && !oap->inclusive)
5461 		    dec(&(oap->end));
5462 		length = (colnr_T)STRLEN(ml_get(pos.lnum));
5463 		pos.col = 0;
5464 		if (pos.lnum == oap->start.lnum)
5465 		{
5466 		    pos.col += oap->start.col;
5467 		    length -= oap->start.col;
5468 		}
5469 		if (pos.lnum == oap->end.lnum)
5470 		{
5471 		    length = (int)STRLEN(ml_get(oap->end.lnum));
5472 		    if (oap->end.col >= length)
5473 			oap->end.col = length - 1;
5474 		    length = oap->end.col - pos.col + 1;
5475 		}
5476 	    }
5477 	    one_change = do_addsub(oap->op_type, &pos, length, amount);
5478 	    if (one_change)
5479 	    {
5480 		/* Remember the start position of the first change. */
5481 		if (change_cnt == 0)
5482 		    startpos = curbuf->b_op_start;
5483 		++change_cnt;
5484 	    }
5485 
5486 #ifdef FEAT_NETBEANS_INTG
5487 	    if (netbeans_active() && one_change)
5488 	    {
5489 		char_u *ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
5490 
5491 		netbeans_removed(curbuf, pos.lnum, pos.col, (long)length);
5492 		netbeans_inserted(curbuf, pos.lnum, pos.col,
5493 						&ptr[pos.col], length);
5494 	    }
5495 #endif
5496 	    if (g_cmd && one_change)
5497 		amount += Prenum1;
5498 	}
5499 
5500 #ifdef FEAT_FOLDING
5501 	disable_fold_update--;
5502 #endif
5503 	if (change_cnt)
5504 	    changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
5505 
5506 	if (!change_cnt && oap->is_VIsual)
5507 	    /* No change: need to remove the Visual selection */
5508 	    redraw_curbuf_later(INVERTED);
5509 
5510 	/* Set '[ mark if something changed. Keep the last end
5511 	 * position from do_addsub(). */
5512 	if (change_cnt > 0)
5513 	    curbuf->b_op_start = startpos;
5514 
5515 	if (change_cnt > p_report)
5516 	    smsg(NGETTEXT("%ld line changed", "%ld lines changed",
5517 						      change_cnt), change_cnt);
5518     }
5519 }
5520 
5521 /*
5522  * Add or subtract 'Prenum1' from a number in a line
5523  * op_type is OP_NR_ADD or OP_NR_SUB
5524  *
5525  * Returns TRUE if some character was changed.
5526  */
5527     static int
5528 do_addsub(
5529     int		op_type,
5530     pos_T	*pos,
5531     int		length,
5532     linenr_T	Prenum1)
5533 {
5534     int		col;
5535     char_u	*buf1;
5536     char_u	buf2[NUMBUFLEN];
5537     int		pre;		/* 'X'/'x': hex; '0': octal; 'B'/'b': bin */
5538     static int	hexupper = FALSE;	/* 0xABC */
5539     uvarnumber_T	n;
5540     uvarnumber_T	oldn;
5541     char_u	*ptr;
5542     int		c;
5543     int		todel;
5544     int		dohex;
5545     int		dooct;
5546     int		dobin;
5547     int		doalp;
5548     int		firstdigit;
5549     int		subtract;
5550     int		negative = FALSE;
5551     int		was_positive = TRUE;
5552     int		visual = VIsual_active;
5553     int		did_change = FALSE;
5554     pos_T	save_cursor = curwin->w_cursor;
5555     int		maxlen = 0;
5556     pos_T	startpos;
5557     pos_T	endpos;
5558 
5559     dohex = (vim_strchr(curbuf->b_p_nf, 'x') != NULL);	/* "heX" */
5560     dooct = (vim_strchr(curbuf->b_p_nf, 'o') != NULL);	/* "Octal" */
5561     dobin = (vim_strchr(curbuf->b_p_nf, 'b') != NULL);	/* "Bin" */
5562     doalp = (vim_strchr(curbuf->b_p_nf, 'p') != NULL);	/* "alPha" */
5563 
5564     curwin->w_cursor = *pos;
5565     ptr = ml_get(pos->lnum);
5566     col = pos->col;
5567 
5568     if (*ptr == NUL)
5569 	goto theend;
5570 
5571     /*
5572      * First check if we are on a hexadecimal number, after the "0x".
5573      */
5574     if (!VIsual_active)
5575     {
5576 	if (dobin)
5577 	    while (col > 0 && vim_isbdigit(ptr[col]))
5578 	    {
5579 		--col;
5580 		if (has_mbyte)
5581 		    col -= (*mb_head_off)(ptr, ptr + col);
5582 	    }
5583 
5584 	if (dohex)
5585 	    while (col > 0 && vim_isxdigit(ptr[col]))
5586 	    {
5587 		--col;
5588 		if (has_mbyte)
5589 		    col -= (*mb_head_off)(ptr, ptr + col);
5590 	    }
5591 
5592 	if (       dobin
5593 		&& dohex
5594 		&& ! ((col > 0
5595 		    && (ptr[col] == 'X'
5596 			|| ptr[col] == 'x')
5597 		    && ptr[col - 1] == '0'
5598 		    && (!has_mbyte ||
5599 			!(*mb_head_off)(ptr, ptr + col - 1))
5600 		    && vim_isxdigit(ptr[col + 1]))))
5601 	{
5602 
5603 	    /* In case of binary/hexadecimal pattern overlap match, rescan */
5604 
5605 	    col = pos->col;
5606 
5607 	    while (col > 0 && vim_isdigit(ptr[col]))
5608 	    {
5609 		col--;
5610 		if (has_mbyte)
5611 		    col -= (*mb_head_off)(ptr, ptr + col);
5612 	    }
5613 	}
5614 
5615 	if ((       dohex
5616 		&& col > 0
5617 		&& (ptr[col] == 'X'
5618 		    || ptr[col] == 'x')
5619 		&& ptr[col - 1] == '0'
5620 		&& (!has_mbyte ||
5621 		    !(*mb_head_off)(ptr, ptr + col - 1))
5622 		&& vim_isxdigit(ptr[col + 1])) ||
5623 	    (       dobin
5624 		&& col > 0
5625 		&& (ptr[col] == 'B'
5626 		    || ptr[col] == 'b')
5627 		&& ptr[col - 1] == '0'
5628 		&& (!has_mbyte ||
5629 		    !(*mb_head_off)(ptr, ptr + col - 1))
5630 		&& vim_isbdigit(ptr[col + 1])))
5631 	{
5632 	    /* Found hexadecimal or binary number, move to its start. */
5633 	    --col;
5634 	    if (has_mbyte)
5635 		col -= (*mb_head_off)(ptr, ptr + col);
5636 	}
5637 	else
5638 	{
5639 	    /*
5640 	     * Search forward and then backward to find the start of number.
5641 	     */
5642 	    col = pos->col;
5643 
5644 	    while (ptr[col] != NUL
5645 		    && !vim_isdigit(ptr[col])
5646 		    && !(doalp && ASCII_ISALPHA(ptr[col])))
5647 		col += MB_PTR2LEN(ptr + col);
5648 
5649 	    while (col > 0
5650 		    && vim_isdigit(ptr[col - 1])
5651 		    && !(doalp && ASCII_ISALPHA(ptr[col])))
5652 	    {
5653 		--col;
5654 		if (has_mbyte)
5655 		    col -= (*mb_head_off)(ptr, ptr + col);
5656 	    }
5657 	}
5658     }
5659 
5660     if (visual)
5661     {
5662 	while (ptr[col] != NUL && length > 0
5663 		&& !vim_isdigit(ptr[col])
5664 		&& !(doalp && ASCII_ISALPHA(ptr[col])))
5665 	{
5666 	    int mb_len = MB_PTR2LEN(ptr + col);
5667 
5668 	    col += mb_len;
5669 	    length -= mb_len;
5670 	}
5671 
5672 	if (length == 0)
5673 	    goto theend;
5674 
5675 	if (col > pos->col && ptr[col - 1] == '-'
5676 		&& (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1)))
5677 	{
5678 	    negative = TRUE;
5679 	    was_positive = FALSE;
5680 	}
5681     }
5682 
5683     /*
5684      * If a number was found, and saving for undo works, replace the number.
5685      */
5686     firstdigit = ptr[col];
5687     if (!VIM_ISDIGIT(firstdigit) && !(doalp && ASCII_ISALPHA(firstdigit)))
5688     {
5689 	beep_flush();
5690 	goto theend;
5691     }
5692 
5693     if (doalp && ASCII_ISALPHA(firstdigit))
5694     {
5695 	/* decrement or increment alphabetic character */
5696 	if (op_type == OP_NR_SUB)
5697 	{
5698 	    if (CharOrd(firstdigit) < Prenum1)
5699 	    {
5700 		if (isupper(firstdigit))
5701 		    firstdigit = 'A';
5702 		else
5703 		    firstdigit = 'a';
5704 	    }
5705 	    else
5706 #ifdef EBCDIC
5707 		firstdigit = EBCDIC_CHAR_ADD(firstdigit, -Prenum1);
5708 #else
5709 		firstdigit -= Prenum1;
5710 #endif
5711 	}
5712 	else
5713 	{
5714 	    if (26 - CharOrd(firstdigit) - 1 < Prenum1)
5715 	    {
5716 		if (isupper(firstdigit))
5717 		    firstdigit = 'Z';
5718 		else
5719 		    firstdigit = 'z';
5720 	    }
5721 	    else
5722 #ifdef EBCDIC
5723 		firstdigit = EBCDIC_CHAR_ADD(firstdigit, Prenum1);
5724 #else
5725 		firstdigit += Prenum1;
5726 #endif
5727 	}
5728 	curwin->w_cursor.col = col;
5729 	if (!did_change)
5730 	    startpos = curwin->w_cursor;
5731 	did_change = TRUE;
5732 	(void)del_char(FALSE);
5733 	ins_char(firstdigit);
5734 	endpos = curwin->w_cursor;
5735 	curwin->w_cursor.col = col;
5736     }
5737     else
5738     {
5739 	if (col > 0 && ptr[col - 1] == '-'
5740 		&& (!has_mbyte ||
5741 		    !(*mb_head_off)(ptr, ptr + col - 1))
5742 		&& !visual)
5743 	{
5744 	    /* negative number */
5745 	    --col;
5746 	    negative = TRUE;
5747 	}
5748 	/* get the number value (unsigned) */
5749 	if (visual && VIsual_mode != 'V')
5750 	    maxlen = (curbuf->b_visual.vi_curswant == MAXCOL
5751 		    ? (int)STRLEN(ptr) - col
5752 		    : length);
5753 
5754 	vim_str2nr(ptr + col, &pre, &length,
5755 		0 + (dobin ? STR2NR_BIN : 0)
5756 		    + (dooct ? STR2NR_OCT : 0)
5757 		    + (dohex ? STR2NR_HEX : 0),
5758 		NULL, &n, maxlen);
5759 
5760 	/* ignore leading '-' for hex and octal and bin numbers */
5761 	if (pre && negative)
5762 	{
5763 	    ++col;
5764 	    --length;
5765 	    negative = FALSE;
5766 	}
5767 	/* add or subtract */
5768 	subtract = FALSE;
5769 	if (op_type == OP_NR_SUB)
5770 	    subtract ^= TRUE;
5771 	if (negative)
5772 	    subtract ^= TRUE;
5773 
5774 	oldn = n;
5775 	if (subtract)
5776 	    n -= (uvarnumber_T)Prenum1;
5777 	else
5778 	    n += (uvarnumber_T)Prenum1;
5779 	/* handle wraparound for decimal numbers */
5780 	if (!pre)
5781 	{
5782 	    if (subtract)
5783 	    {
5784 		if (n > oldn)
5785 		{
5786 		    n = 1 + (n ^ (uvarnumber_T)-1);
5787 		    negative ^= TRUE;
5788 		}
5789 	    }
5790 	    else
5791 	    {
5792 		/* add */
5793 		if (n < oldn)
5794 		{
5795 		    n = (n ^ (uvarnumber_T)-1);
5796 		    negative ^= TRUE;
5797 		}
5798 	    }
5799 	    if (n == 0)
5800 		negative = FALSE;
5801 	}
5802 
5803 	if (visual && !was_positive && !negative && col > 0)
5804 	{
5805 	    /* need to remove the '-' */
5806 	    col--;
5807 	    length++;
5808 	}
5809 
5810 	/*
5811 	 * Delete the old number.
5812 	 */
5813 	curwin->w_cursor.col = col;
5814 	if (!did_change)
5815 	    startpos = curwin->w_cursor;
5816 	did_change = TRUE;
5817 	todel = length;
5818 	c = gchar_cursor();
5819 	/*
5820 	 * Don't include the '-' in the length, only the length of the
5821 	 * part after it is kept the same.
5822 	 */
5823 	if (c == '-')
5824 	    --length;
5825 	while (todel-- > 0)
5826 	{
5827 	    if (c < 0x100 && isalpha(c))
5828 	    {
5829 		if (isupper(c))
5830 		    hexupper = TRUE;
5831 		else
5832 		    hexupper = FALSE;
5833 	    }
5834 	    /* del_char() will mark line needing displaying */
5835 	    (void)del_char(FALSE);
5836 	    c = gchar_cursor();
5837 	}
5838 
5839 	/*
5840 	 * Prepare the leading characters in buf1[].
5841 	 * When there are many leading zeros it could be very long.
5842 	 * Allocate a bit too much.
5843 	 */
5844 	buf1 = alloc((unsigned)length + NUMBUFLEN);
5845 	if (buf1 == NULL)
5846 	    goto theend;
5847 	ptr = buf1;
5848 	if (negative && (!visual || was_positive))
5849 	{
5850 	    *ptr++ = '-';
5851 	}
5852 	if (pre)
5853 	{
5854 	    *ptr++ = '0';
5855 	    --length;
5856 	}
5857 	if (pre == 'b' || pre == 'B' ||
5858 	    pre == 'x' || pre == 'X')
5859 	{
5860 	    *ptr++ = pre;
5861 	    --length;
5862 	}
5863 
5864 	/*
5865 	 * Put the number characters in buf2[].
5866 	 */
5867 	if (pre == 'b' || pre == 'B')
5868 	{
5869 	    int i;
5870 	    int bit = 0;
5871 	    int bits = sizeof(uvarnumber_T) * 8;
5872 
5873 	    /* leading zeros */
5874 	    for (bit = bits; bit > 0; bit--)
5875 		if ((n >> (bit - 1)) & 0x1) break;
5876 
5877 	    for (i = 0; bit > 0; bit--)
5878 		buf2[i++] = ((n >> (bit - 1)) & 0x1) ? '1' : '0';
5879 
5880 	    buf2[i] = '\0';
5881 	}
5882 	else if (pre == 0)
5883 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llu",
5884 							(long_long_u_T)n);
5885 	else if (pre == '0')
5886 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llo",
5887 							(long_long_u_T)n);
5888 	else if (pre && hexupper)
5889 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llX",
5890 							(long_long_u_T)n);
5891 	else
5892 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llx",
5893 							(long_long_u_T)n);
5894 	length -= (int)STRLEN(buf2);
5895 
5896 	/*
5897 	 * Adjust number of zeros to the new number of digits, so the
5898 	 * total length of the number remains the same.
5899 	 * Don't do this when
5900 	 * the result may look like an octal number.
5901 	 */
5902 	if (firstdigit == '0' && !(dooct && pre == 0))
5903 	    while (length-- > 0)
5904 		*ptr++ = '0';
5905 	*ptr = NUL;
5906 	STRCAT(buf1, buf2);
5907 	ins_str(buf1);		/* insert the new number */
5908 	vim_free(buf1);
5909 	endpos = curwin->w_cursor;
5910 	if (did_change && curwin->w_cursor.col)
5911 	    --curwin->w_cursor.col;
5912     }
5913 
5914     if (did_change)
5915     {
5916 	/* set the '[ and '] marks */
5917 	curbuf->b_op_start = startpos;
5918 	curbuf->b_op_end = endpos;
5919 	if (curbuf->b_op_end.col > 0)
5920 	    --curbuf->b_op_end.col;
5921     }
5922 
5923 theend:
5924     if (visual)
5925 	curwin->w_cursor = save_cursor;
5926     else if (did_change)
5927 	curwin->w_set_curswant = TRUE;
5928 
5929     return did_change;
5930 }
5931 
5932 #ifdef FEAT_VIMINFO
5933 
5934 static yankreg_T *y_read_regs = NULL;
5935 
5936 #define REG_PREVIOUS 1
5937 #define REG_EXEC 2
5938 
5939 /*
5940  * Prepare for reading viminfo registers when writing viminfo later.
5941  */
5942     void
5943 prepare_viminfo_registers(void)
5944 {
5945      y_read_regs = (yankreg_T *)alloc_clear(NUM_REGISTERS
5946 						    * (int)sizeof(yankreg_T));
5947 }
5948 
5949     void
5950 finish_viminfo_registers(void)
5951 {
5952     int		i;
5953     int		j;
5954 
5955     if (y_read_regs != NULL)
5956     {
5957 	for (i = 0; i < NUM_REGISTERS; ++i)
5958 	    if (y_read_regs[i].y_array != NULL)
5959 	    {
5960 		for (j = 0; j < y_read_regs[i].y_size; j++)
5961 		    vim_free(y_read_regs[i].y_array[j]);
5962 		vim_free(y_read_regs[i].y_array);
5963 	    }
5964 	VIM_CLEAR(y_read_regs);
5965     }
5966 }
5967 
5968     int
5969 read_viminfo_register(vir_T *virp, int force)
5970 {
5971     int		eof;
5972     int		do_it = TRUE;
5973     int		size;
5974     int		limit;
5975     int		i;
5976     int		set_prev = FALSE;
5977     char_u	*str;
5978     char_u	**array = NULL;
5979     int		new_type = MCHAR; /* init to shut up compiler */
5980     colnr_T	new_width = 0; /* init to shut up compiler */
5981 
5982     /* We only get here (hopefully) if line[0] == '"' */
5983     str = virp->vir_line + 1;
5984 
5985     /* If the line starts with "" this is the y_previous register. */
5986     if (*str == '"')
5987     {
5988 	set_prev = TRUE;
5989 	str++;
5990     }
5991 
5992     if (!ASCII_ISALNUM(*str) && *str != '-')
5993     {
5994 	if (viminfo_error("E577: ", _("Illegal register name"), virp->vir_line))
5995 	    return TRUE;	/* too many errors, pretend end-of-file */
5996 	do_it = FALSE;
5997     }
5998     get_yank_register(*str++, FALSE);
5999     if (!force && y_current->y_array != NULL)
6000 	do_it = FALSE;
6001 
6002     if (*str == '@')
6003     {
6004 	/* "x@: register x used for @@ */
6005 	if (force || execreg_lastc == NUL)
6006 	    execreg_lastc = str[-1];
6007     }
6008 
6009     size = 0;
6010     limit = 100;	/* Optimized for registers containing <= 100 lines */
6011     if (do_it)
6012     {
6013 	/*
6014 	 * Build the new register in array[].
6015 	 * y_array is kept as-is until done.
6016 	 * The "do_it" flag is reset when something is wrong, in which case
6017 	 * array[] needs to be freed.
6018 	 */
6019 	if (set_prev)
6020 	    y_previous = y_current;
6021 	array = (char_u **)alloc((unsigned)(limit * sizeof(char_u *)));
6022 	str = skipwhite(skiptowhite(str));
6023 	if (STRNCMP(str, "CHAR", 4) == 0)
6024 	    new_type = MCHAR;
6025 	else if (STRNCMP(str, "BLOCK", 5) == 0)
6026 	    new_type = MBLOCK;
6027 	else
6028 	    new_type = MLINE;
6029 	/* get the block width; if it's missing we get a zero, which is OK */
6030 	str = skipwhite(skiptowhite(str));
6031 	new_width = getdigits(&str);
6032     }
6033 
6034     while (!(eof = viminfo_readline(virp))
6035 		    && (virp->vir_line[0] == TAB || virp->vir_line[0] == '<'))
6036     {
6037 	if (do_it)
6038 	{
6039 	    if (size == limit)
6040 	    {
6041 		char_u **new_array = (char_u **)
6042 			      alloc((unsigned)(limit * 2 * sizeof(char_u *)));
6043 
6044 		if (new_array == NULL)
6045 		{
6046 		    do_it = FALSE;
6047 		    break;
6048 		}
6049 		for (i = 0; i < limit; i++)
6050 		    new_array[i] = array[i];
6051 		vim_free(array);
6052 		array = new_array;
6053 		limit *= 2;
6054 	    }
6055 	    str = viminfo_readstring(virp, 1, TRUE);
6056 	    if (str != NULL)
6057 		array[size++] = str;
6058 	    else
6059 		/* error, don't store the result */
6060 		do_it = FALSE;
6061 	}
6062     }
6063 
6064     if (do_it)
6065     {
6066 	/* free y_array[] */
6067 	for (i = 0; i < y_current->y_size; i++)
6068 	    vim_free(y_current->y_array[i]);
6069 	vim_free(y_current->y_array);
6070 
6071 	y_current->y_type = new_type;
6072 	y_current->y_width = new_width;
6073 	y_current->y_size = size;
6074 	y_current->y_time_set = 0;
6075 	if (size == 0)
6076 	{
6077 	    y_current->y_array = NULL;
6078 	}
6079 	else
6080 	{
6081 	    /* Move the lines from array[] to y_array[]. */
6082 	    y_current->y_array =
6083 			(char_u **)alloc((unsigned)(size * sizeof(char_u *)));
6084 	    for (i = 0; i < size; i++)
6085 	    {
6086 		if (y_current->y_array == NULL)
6087 		    vim_free(array[i]);
6088 		else
6089 		    y_current->y_array[i] = array[i];
6090 	    }
6091 	}
6092     }
6093     else
6094     {
6095 	/* Free array[] if it was filled. */
6096 	for (i = 0; i < size; i++)
6097 	    vim_free(array[i]);
6098     }
6099     vim_free(array);
6100 
6101     return eof;
6102 }
6103 
6104 /*
6105  * Accept a new style register line from the viminfo, store it when it's new.
6106  */
6107     void
6108 handle_viminfo_register(garray_T *values, int force)
6109 {
6110     bval_T	*vp = (bval_T *)values->ga_data;
6111     int		flags;
6112     int		name;
6113     int		type;
6114     int		linecount;
6115     int		width;
6116     time_t	timestamp;
6117     yankreg_T	*y_ptr;
6118     int		i;
6119 
6120     /* Check the format:
6121      * |{bartype},{flags},{name},{type},
6122      *      {linecount},{width},{timestamp},"line1","line2"
6123      */
6124     if (values->ga_len < 6
6125 	    || vp[0].bv_type != BVAL_NR
6126 	    || vp[1].bv_type != BVAL_NR
6127 	    || vp[2].bv_type != BVAL_NR
6128 	    || vp[3].bv_type != BVAL_NR
6129 	    || vp[4].bv_type != BVAL_NR
6130 	    || vp[5].bv_type != BVAL_NR)
6131 	return;
6132     flags = vp[0].bv_nr;
6133     name = vp[1].bv_nr;
6134     if (name < 0 || name >= NUM_REGISTERS)
6135 	return;
6136     type = vp[2].bv_nr;
6137     if (type != MCHAR && type != MLINE && type != MBLOCK)
6138 	return;
6139     linecount = vp[3].bv_nr;
6140     if (values->ga_len < 6 + linecount)
6141 	return;
6142     width = vp[4].bv_nr;
6143     if (width < 0)
6144 	return;
6145 
6146     if (y_read_regs != NULL)
6147 	/* Reading viminfo for merging and writing.  Store the register
6148 	 * content, don't update the current registers. */
6149 	y_ptr = &y_read_regs[name];
6150     else
6151 	y_ptr = &y_regs[name];
6152 
6153     /* Do not overwrite unless forced or the timestamp is newer. */
6154     timestamp = (time_t)vp[5].bv_nr;
6155     if (y_ptr->y_array != NULL && !force
6156 			 && (timestamp == 0 || y_ptr->y_time_set > timestamp))
6157 	return;
6158 
6159     if (y_ptr->y_array != NULL)
6160 	for (i = 0; i < y_ptr->y_size; i++)
6161 	    vim_free(y_ptr->y_array[i]);
6162     vim_free(y_ptr->y_array);
6163 
6164     if (y_read_regs == NULL)
6165     {
6166 	if (flags & REG_PREVIOUS)
6167 	    y_previous = y_ptr;
6168 	if ((flags & REG_EXEC) && (force || execreg_lastc == NUL))
6169 	    execreg_lastc = get_register_name(name);
6170     }
6171     y_ptr->y_type = type;
6172     y_ptr->y_width = width;
6173     y_ptr->y_size = linecount;
6174     y_ptr->y_time_set = timestamp;
6175     if (linecount == 0)
6176 	y_ptr->y_array = NULL;
6177     else
6178     {
6179 	y_ptr->y_array =
6180 		   (char_u **)alloc((unsigned)(linecount * sizeof(char_u *)));
6181 	for (i = 0; i < linecount; i++)
6182 	{
6183 	    if (vp[i + 6].bv_allocated)
6184 	    {
6185 		y_ptr->y_array[i] = vp[i + 6].bv_string;
6186 		vp[i + 6].bv_string = NULL;
6187 	    }
6188 	    else
6189 		y_ptr->y_array[i] = vim_strsave(vp[i + 6].bv_string);
6190 	}
6191     }
6192 }
6193 
6194     void
6195 write_viminfo_registers(FILE *fp)
6196 {
6197     int		i, j;
6198     char_u	*type;
6199     char_u	c;
6200     int		num_lines;
6201     int		max_num_lines;
6202     int		max_kbyte;
6203     long	len;
6204     yankreg_T	*y_ptr;
6205 
6206     fputs(_("\n# Registers:\n"), fp);
6207 
6208     /* Get '<' value, use old '"' value if '<' is not found. */
6209     max_num_lines = get_viminfo_parameter('<');
6210     if (max_num_lines < 0)
6211 	max_num_lines = get_viminfo_parameter('"');
6212     if (max_num_lines == 0)
6213 	return;
6214     max_kbyte = get_viminfo_parameter('s');
6215     if (max_kbyte == 0)
6216 	return;
6217 
6218     for (i = 0; i < NUM_REGISTERS; i++)
6219     {
6220 #ifdef FEAT_CLIPBOARD
6221 	/* Skip '*'/'+' register, we don't want them back next time */
6222 	if (i == STAR_REGISTER || i == PLUS_REGISTER)
6223 	    continue;
6224 #endif
6225 #ifdef FEAT_DND
6226 	/* Neither do we want the '~' register */
6227 	if (i == TILDE_REGISTER)
6228 	    continue;
6229 #endif
6230 	/* When reading viminfo for merging and writing: Use the register from
6231 	 * viminfo if it's newer. */
6232 	if (y_read_regs != NULL
6233 		&& y_read_regs[i].y_array != NULL
6234 		&& (y_regs[i].y_array == NULL ||
6235 			    y_read_regs[i].y_time_set > y_regs[i].y_time_set))
6236 	    y_ptr = &y_read_regs[i];
6237 	else if (y_regs[i].y_array == NULL)
6238 	    continue;
6239 	else
6240 	    y_ptr = &y_regs[i];
6241 
6242 	/* Skip empty registers. */
6243 	num_lines = y_ptr->y_size;
6244 	if (num_lines == 0
6245 		|| (num_lines == 1 && y_ptr->y_type == MCHAR
6246 					&& *y_ptr->y_array[0] == NUL))
6247 	    continue;
6248 
6249 	if (max_kbyte > 0)
6250 	{
6251 	    /* Skip register if there is more text than the maximum size. */
6252 	    len = 0;
6253 	    for (j = 0; j < num_lines; j++)
6254 		len += (long)STRLEN(y_ptr->y_array[j]) + 1L;
6255 	    if (len > (long)max_kbyte * 1024L)
6256 		continue;
6257 	}
6258 
6259 	switch (y_ptr->y_type)
6260 	{
6261 	    case MLINE:
6262 		type = (char_u *)"LINE";
6263 		break;
6264 	    case MCHAR:
6265 		type = (char_u *)"CHAR";
6266 		break;
6267 	    case MBLOCK:
6268 		type = (char_u *)"BLOCK";
6269 		break;
6270 	    default:
6271 		semsg(_("E574: Unknown register type %d"), y_ptr->y_type);
6272 		type = (char_u *)"LINE";
6273 		break;
6274 	}
6275 	if (y_previous == &y_regs[i])
6276 	    fprintf(fp, "\"");
6277 	c = get_register_name(i);
6278 	fprintf(fp, "\"%c", c);
6279 	if (c == execreg_lastc)
6280 	    fprintf(fp, "@");
6281 	fprintf(fp, "\t%s\t%d\n", type, (int)y_ptr->y_width);
6282 
6283 	/* If max_num_lines < 0, then we save ALL the lines in the register */
6284 	if (max_num_lines > 0 && num_lines > max_num_lines)
6285 	    num_lines = max_num_lines;
6286 	for (j = 0; j < num_lines; j++)
6287 	{
6288 	    putc('\t', fp);
6289 	    viminfo_writestring(fp, y_ptr->y_array[j]);
6290 	}
6291 
6292 	{
6293 	    int	    flags = 0;
6294 	    int	    remaining;
6295 
6296 	    /* New style with a bar line. Format:
6297 	     * |{bartype},{flags},{name},{type},
6298 	     *      {linecount},{width},{timestamp},"line1","line2"
6299 	     * flags: REG_PREVIOUS - register is y_previous
6300 	     *	      REG_EXEC - used for @@
6301 	     */
6302 	    if (y_previous == &y_regs[i])
6303 		flags |= REG_PREVIOUS;
6304 	    if (c == execreg_lastc)
6305 		flags |= REG_EXEC;
6306 	    fprintf(fp, "|%d,%d,%d,%d,%d,%d,%ld", BARTYPE_REGISTER, flags,
6307 		    i, y_ptr->y_type, num_lines, (int)y_ptr->y_width,
6308 		    (long)y_ptr->y_time_set);
6309 	    /* 11 chars for type/flags/name/type, 3 * 20 for numbers */
6310 	    remaining = LSIZE - 71;
6311 	    for (j = 0; j < num_lines; j++)
6312 	    {
6313 		putc(',', fp);
6314 		--remaining;
6315 		remaining = barline_writestring(fp, y_ptr->y_array[j],
6316 								   remaining);
6317 	    }
6318 	    putc('\n', fp);
6319 	}
6320     }
6321 }
6322 #endif /* FEAT_VIMINFO */
6323 
6324 #if defined(FEAT_CLIPBOARD) || defined(PROTO)
6325 /*
6326  * SELECTION / PRIMARY ('*')
6327  *
6328  * Text selection stuff that uses the GUI selection register '*'.  When using a
6329  * GUI this may be text from another window, otherwise it is the last text we
6330  * had highlighted with VIsual mode.  With mouse support, clicking the middle
6331  * button performs the paste, otherwise you will need to do <"*p>. "
6332  * If not under X, it is synonymous with the clipboard register '+'.
6333  *
6334  * X CLIPBOARD ('+')
6335  *
6336  * Text selection stuff that uses the GUI clipboard register '+'.
6337  * Under X, this matches the standard cut/paste buffer CLIPBOARD selection.
6338  * It will be used for unnamed cut/pasting is 'clipboard' contains "unnamed",
6339  * otherwise you will need to do <"+p>. "
6340  * If not under X, it is synonymous with the selection register '*'.
6341  */
6342 
6343 /*
6344  * Routine to export any final X selection we had to the environment
6345  * so that the text is still available after Vim has exited. X selections
6346  * only exist while the owning application exists, so we write to the
6347  * permanent (while X runs) store CUT_BUFFER0.
6348  * Dump the CLIPBOARD selection if we own it (it's logically the more
6349  * 'permanent' of the two), otherwise the PRIMARY one.
6350  * For now, use a hard-coded sanity limit of 1Mb of data.
6351  */
6352 #if (defined(FEAT_X11) && defined(FEAT_CLIPBOARD)) || defined(PROTO)
6353     void
6354 x11_export_final_selection(void)
6355 {
6356     Display	*dpy;
6357     char_u	*str = NULL;
6358     long_u	len = 0;
6359     int		motion_type = -1;
6360 
6361 # ifdef FEAT_GUI
6362     if (gui.in_use)
6363 	dpy = X_DISPLAY;
6364     else
6365 # endif
6366 # ifdef FEAT_XCLIPBOARD
6367 	dpy = xterm_dpy;
6368 # else
6369 	return;
6370 # endif
6371 
6372     /* Get selection to export */
6373     if (clip_plus.owned)
6374 	motion_type = clip_convert_selection(&str, &len, &clip_plus);
6375     else if (clip_star.owned)
6376 	motion_type = clip_convert_selection(&str, &len, &clip_star);
6377 
6378     /* Check it's OK */
6379     if (dpy != NULL && str != NULL && motion_type >= 0
6380 					       && len < 1024*1024 && len > 0)
6381     {
6382 	int ok = TRUE;
6383 
6384 	/* The CUT_BUFFER0 is supposed to always contain latin1.  Convert from
6385 	 * 'enc' when it is a multi-byte encoding.  When 'enc' is an 8-bit
6386 	 * encoding conversion usually doesn't work, so keep the text as-is.
6387 	 */
6388 	if (has_mbyte)
6389 	{
6390 	    vimconv_T	vc;
6391 
6392 	    vc.vc_type = CONV_NONE;
6393 	    if (convert_setup(&vc, p_enc, (char_u *)"latin1") == OK)
6394 	    {
6395 		int	intlen = len;
6396 		char_u	*conv_str;
6397 
6398 		vc.vc_fail = TRUE;
6399 		conv_str = string_convert(&vc, str, &intlen);
6400 		len = intlen;
6401 		if (conv_str != NULL)
6402 		{
6403 		    vim_free(str);
6404 		    str = conv_str;
6405 		}
6406 		else
6407 		{
6408 		    ok = FALSE;
6409 		}
6410 		convert_setup(&vc, NULL, NULL);
6411 	    }
6412 	    else
6413 	    {
6414 		ok = FALSE;
6415 	    }
6416 	}
6417 
6418 	/* Do not store the string if conversion failed.  Better to use any
6419 	 * other selection than garbled text. */
6420 	if (ok)
6421 	{
6422 	    XStoreBuffer(dpy, (char *)str, (int)len, 0);
6423 	    XFlush(dpy);
6424 	}
6425     }
6426 
6427     vim_free(str);
6428 }
6429 #endif
6430 
6431     void
6432 clip_free_selection(VimClipboard *cbd)
6433 {
6434     yankreg_T *y_ptr = y_current;
6435 
6436     if (cbd == &clip_plus)
6437 	y_current = &y_regs[PLUS_REGISTER];
6438     else
6439 	y_current = &y_regs[STAR_REGISTER];
6440     free_yank_all();
6441     y_current->y_size = 0;
6442     y_current = y_ptr;
6443 }
6444 
6445 /*
6446  * Get the selected text and put it in register '*' or '+'.
6447  */
6448     void
6449 clip_get_selection(VimClipboard *cbd)
6450 {
6451     yankreg_T	*old_y_previous, *old_y_current;
6452     pos_T	old_cursor;
6453     pos_T	old_visual;
6454     int		old_visual_mode;
6455     colnr_T	old_curswant;
6456     int		old_set_curswant;
6457     pos_T	old_op_start, old_op_end;
6458     oparg_T	oa;
6459     cmdarg_T	ca;
6460 
6461     if (cbd->owned)
6462     {
6463 	if ((cbd == &clip_plus && y_regs[PLUS_REGISTER].y_array != NULL)
6464 		|| (cbd == &clip_star && y_regs[STAR_REGISTER].y_array != NULL))
6465 	    return;
6466 
6467 	/* Get the text between clip_star.start & clip_star.end */
6468 	old_y_previous = y_previous;
6469 	old_y_current = y_current;
6470 	old_cursor = curwin->w_cursor;
6471 	old_curswant = curwin->w_curswant;
6472 	old_set_curswant = curwin->w_set_curswant;
6473 	old_op_start = curbuf->b_op_start;
6474 	old_op_end = curbuf->b_op_end;
6475 	old_visual = VIsual;
6476 	old_visual_mode = VIsual_mode;
6477 	clear_oparg(&oa);
6478 	oa.regname = (cbd == &clip_plus ? '+' : '*');
6479 	oa.op_type = OP_YANK;
6480 	vim_memset(&ca, 0, sizeof(ca));
6481 	ca.oap = &oa;
6482 	ca.cmdchar = 'y';
6483 	ca.count1 = 1;
6484 	ca.retval = CA_NO_ADJ_OP_END;
6485 	do_pending_operator(&ca, 0, TRUE);
6486 	y_previous = old_y_previous;
6487 	y_current = old_y_current;
6488 	curwin->w_cursor = old_cursor;
6489 	changed_cline_bef_curs();   /* need to update w_virtcol et al */
6490 	curwin->w_curswant = old_curswant;
6491 	curwin->w_set_curswant = old_set_curswant;
6492 	curbuf->b_op_start = old_op_start;
6493 	curbuf->b_op_end = old_op_end;
6494 	VIsual = old_visual;
6495 	VIsual_mode = old_visual_mode;
6496     }
6497     else if (!is_clipboard_needs_update())
6498     {
6499 	clip_free_selection(cbd);
6500 
6501 	/* Try to get selected text from another window */
6502 	clip_gen_request_selection(cbd);
6503     }
6504 }
6505 
6506 /*
6507  * Convert from the GUI selection string into the '*'/'+' register.
6508  */
6509     void
6510 clip_yank_selection(
6511     int		type,
6512     char_u	*str,
6513     long	len,
6514     VimClipboard *cbd)
6515 {
6516     yankreg_T *y_ptr;
6517 
6518     if (cbd == &clip_plus)
6519 	y_ptr = &y_regs[PLUS_REGISTER];
6520     else
6521 	y_ptr = &y_regs[STAR_REGISTER];
6522 
6523     clip_free_selection(cbd);
6524 
6525     str_to_reg(y_ptr, type, str, len, 0L, FALSE);
6526 }
6527 
6528 /*
6529  * Convert the '*'/'+' register into a GUI selection string returned in *str
6530  * with length *len.
6531  * Returns the motion type, or -1 for failure.
6532  */
6533     int
6534 clip_convert_selection(char_u **str, long_u *len, VimClipboard *cbd)
6535 {
6536     char_u	*p;
6537     int		lnum;
6538     int		i, j;
6539     int_u	eolsize;
6540     yankreg_T	*y_ptr;
6541 
6542     if (cbd == &clip_plus)
6543 	y_ptr = &y_regs[PLUS_REGISTER];
6544     else
6545 	y_ptr = &y_regs[STAR_REGISTER];
6546 
6547 #ifdef USE_CRNL
6548     eolsize = 2;
6549 #else
6550     eolsize = 1;
6551 #endif
6552 
6553     *str = NULL;
6554     *len = 0;
6555     if (y_ptr->y_array == NULL)
6556 	return -1;
6557 
6558     for (i = 0; i < y_ptr->y_size; i++)
6559 	*len += (long_u)STRLEN(y_ptr->y_array[i]) + eolsize;
6560 
6561     /*
6562      * Don't want newline character at end of last line if we're in MCHAR mode.
6563      */
6564     if (y_ptr->y_type == MCHAR && *len >= eolsize)
6565 	*len -= eolsize;
6566 
6567     p = *str = lalloc(*len + 1, TRUE);	/* add one to avoid zero */
6568     if (p == NULL)
6569 	return -1;
6570     lnum = 0;
6571     for (i = 0, j = 0; i < (int)*len; i++, j++)
6572     {
6573 	if (y_ptr->y_array[lnum][j] == '\n')
6574 	    p[i] = NUL;
6575 	else if (y_ptr->y_array[lnum][j] == NUL)
6576 	{
6577 #ifdef USE_CRNL
6578 	    p[i++] = '\r';
6579 #endif
6580 #ifdef USE_CR
6581 	    p[i] = '\r';
6582 #else
6583 	    p[i] = '\n';
6584 #endif
6585 	    lnum++;
6586 	    j = -1;
6587 	}
6588 	else
6589 	    p[i] = y_ptr->y_array[lnum][j];
6590     }
6591     return y_ptr->y_type;
6592 }
6593 
6594 
6595 /*
6596  * If we have written to a clipboard register, send the text to the clipboard.
6597  */
6598     static void
6599 may_set_selection(void)
6600 {
6601     if (y_current == &(y_regs[STAR_REGISTER]) && clip_star.available)
6602     {
6603 	clip_own_selection(&clip_star);
6604 	clip_gen_set_selection(&clip_star);
6605     }
6606     else if (y_current == &(y_regs[PLUS_REGISTER]) && clip_plus.available)
6607     {
6608 	clip_own_selection(&clip_plus);
6609 	clip_gen_set_selection(&clip_plus);
6610     }
6611 }
6612 
6613 #endif /* FEAT_CLIPBOARD || PROTO */
6614 
6615 
6616 #if defined(FEAT_DND) || defined(PROTO)
6617 /*
6618  * Replace the contents of the '~' register with str.
6619  */
6620     void
6621 dnd_yank_drag_data(char_u *str, long len)
6622 {
6623     yankreg_T *curr;
6624 
6625     curr = y_current;
6626     y_current = &y_regs[TILDE_REGISTER];
6627     free_yank_all();
6628     str_to_reg(y_current, MCHAR, str, len, 0L, FALSE);
6629     y_current = curr;
6630 }
6631 #endif
6632 
6633 
6634 #if defined(FEAT_EVAL) || defined(PROTO)
6635 /*
6636  * Return the type of a register.
6637  * Used for getregtype()
6638  * Returns MAUTO for error.
6639  */
6640     char_u
6641 get_reg_type(int regname, long *reglen)
6642 {
6643     switch (regname)
6644     {
6645 	case '%':		/* file name */
6646 	case '#':		/* alternate file name */
6647 	case '=':		/* expression */
6648 	case ':':		/* last command line */
6649 	case '/':		/* last search-pattern */
6650 	case '.':		/* last inserted text */
6651 #ifdef FEAT_SEARCHPATH
6652 	case Ctrl_F:		/* Filename under cursor */
6653 	case Ctrl_P:		/* Path under cursor, expand via "path" */
6654 #endif
6655 	case Ctrl_W:		/* word under cursor */
6656 	case Ctrl_A:		/* WORD (mnemonic All) under cursor */
6657 	case '_':		/* black hole: always empty */
6658 	    return MCHAR;
6659     }
6660 
6661 #ifdef FEAT_CLIPBOARD
6662     regname = may_get_selection(regname);
6663 #endif
6664 
6665     if (regname != NUL && !valid_yank_reg(regname, FALSE))
6666 	return MAUTO;
6667 
6668     get_yank_register(regname, FALSE);
6669 
6670     if (y_current->y_array != NULL)
6671     {
6672 	if (reglen != NULL && y_current->y_type == MBLOCK)
6673 	    *reglen = y_current->y_width;
6674 	return y_current->y_type;
6675     }
6676     return MAUTO;
6677 }
6678 
6679 /*
6680  * When "flags" has GREG_LIST return a list with text "s".
6681  * Otherwise just return "s".
6682  */
6683     static char_u *
6684 getreg_wrap_one_line(char_u *s, int flags)
6685 {
6686     if (flags & GREG_LIST)
6687     {
6688 	list_T *list = list_alloc();
6689 
6690 	if (list != NULL)
6691 	{
6692 	    if (list_append_string(list, NULL, -1) == FAIL)
6693 	    {
6694 		list_free(list);
6695 		return NULL;
6696 	    }
6697 	    list->lv_first->li_tv.vval.v_string = s;
6698 	}
6699 	return (char_u *)list;
6700     }
6701     return s;
6702 }
6703 
6704 /*
6705  * Return the contents of a register as a single allocated string.
6706  * Used for "@r" in expressions and for getreg().
6707  * Returns NULL for error.
6708  * Flags:
6709  *	GREG_NO_EXPR	Do not allow expression register
6710  *	GREG_EXPR_SRC	For the expression register: return expression itself,
6711  *			not the result of its evaluation.
6712  *	GREG_LIST	Return a list of lines in place of a single string.
6713  */
6714     char_u *
6715 get_reg_contents(int regname, int flags)
6716 {
6717     long	i;
6718     char_u	*retval;
6719     int		allocated;
6720     long	len;
6721 
6722     /* Don't allow using an expression register inside an expression */
6723     if (regname == '=')
6724     {
6725 	if (flags & GREG_NO_EXPR)
6726 	    return NULL;
6727 	if (flags & GREG_EXPR_SRC)
6728 	    return getreg_wrap_one_line(get_expr_line_src(), flags);
6729 	return getreg_wrap_one_line(get_expr_line(), flags);
6730     }
6731 
6732     if (regname == '@')	    /* "@@" is used for unnamed register */
6733 	regname = '"';
6734 
6735     /* check for valid regname */
6736     if (regname != NUL && !valid_yank_reg(regname, FALSE))
6737 	return NULL;
6738 
6739 #ifdef FEAT_CLIPBOARD
6740     regname = may_get_selection(regname);
6741 #endif
6742 
6743     if (get_spec_reg(regname, &retval, &allocated, FALSE))
6744     {
6745 	if (retval == NULL)
6746 	    return NULL;
6747 	if (allocated)
6748 	    return getreg_wrap_one_line(retval, flags);
6749 	return getreg_wrap_one_line(vim_strsave(retval), flags);
6750     }
6751 
6752     get_yank_register(regname, FALSE);
6753     if (y_current->y_array == NULL)
6754 	return NULL;
6755 
6756     if (flags & GREG_LIST)
6757     {
6758 	list_T	*list = list_alloc();
6759 	int	error = FALSE;
6760 
6761 	if (list == NULL)
6762 	    return NULL;
6763 	for (i = 0; i < y_current->y_size; ++i)
6764 	    if (list_append_string(list, y_current->y_array[i], -1) == FAIL)
6765 		error = TRUE;
6766 	if (error)
6767 	{
6768 	    list_free(list);
6769 	    return NULL;
6770 	}
6771 	return (char_u *)list;
6772     }
6773 
6774     /*
6775      * Compute length of resulting string.
6776      */
6777     len = 0;
6778     for (i = 0; i < y_current->y_size; ++i)
6779     {
6780 	len += (long)STRLEN(y_current->y_array[i]);
6781 	/*
6782 	 * Insert a newline between lines and after last line if
6783 	 * y_type is MLINE.
6784 	 */
6785 	if (y_current->y_type == MLINE || i < y_current->y_size - 1)
6786 	    ++len;
6787     }
6788 
6789     retval = lalloc(len + 1, TRUE);
6790 
6791     /*
6792      * Copy the lines of the yank register into the string.
6793      */
6794     if (retval != NULL)
6795     {
6796 	len = 0;
6797 	for (i = 0; i < y_current->y_size; ++i)
6798 	{
6799 	    STRCPY(retval + len, y_current->y_array[i]);
6800 	    len += (long)STRLEN(retval + len);
6801 
6802 	    /*
6803 	     * Insert a NL between lines and after the last line if y_type is
6804 	     * MLINE.
6805 	     */
6806 	    if (y_current->y_type == MLINE || i < y_current->y_size - 1)
6807 		retval[len++] = '\n';
6808 	}
6809 	retval[len] = NUL;
6810     }
6811 
6812     return retval;
6813 }
6814 
6815     static int
6816 init_write_reg(
6817     int		name,
6818     yankreg_T	**old_y_previous,
6819     yankreg_T	**old_y_current,
6820     int		must_append,
6821     int		*yank_type UNUSED)
6822 {
6823     if (!valid_yank_reg(name, TRUE))	    /* check for valid reg name */
6824     {
6825 	emsg_invreg(name);
6826 	return FAIL;
6827     }
6828 
6829     /* Don't want to change the current (unnamed) register */
6830     *old_y_previous = y_previous;
6831     *old_y_current = y_current;
6832 
6833     get_yank_register(name, TRUE);
6834     if (!y_append && !must_append)
6835 	free_yank_all();
6836     return OK;
6837 }
6838 
6839     static void
6840 finish_write_reg(
6841     int		name,
6842     yankreg_T	*old_y_previous,
6843     yankreg_T	*old_y_current)
6844 {
6845 # ifdef FEAT_CLIPBOARD
6846     /* Send text of clipboard register to the clipboard. */
6847     may_set_selection();
6848 # endif
6849 
6850     /* ':let @" = "val"' should change the meaning of the "" register */
6851     if (name != '"')
6852 	y_previous = old_y_previous;
6853     y_current = old_y_current;
6854 }
6855 
6856 /*
6857  * Store string "str" in register "name".
6858  * "maxlen" is the maximum number of bytes to use, -1 for all bytes.
6859  * If "must_append" is TRUE, always append to the register.  Otherwise append
6860  * if "name" is an uppercase letter.
6861  * Note: "maxlen" and "must_append" don't work for the "/" register.
6862  * Careful: 'str' is modified, you may have to use a copy!
6863  * If "str" ends in '\n' or '\r', use linewise, otherwise use characterwise.
6864  */
6865     void
6866 write_reg_contents(
6867     int		name,
6868     char_u	*str,
6869     int		maxlen,
6870     int		must_append)
6871 {
6872     write_reg_contents_ex(name, str, maxlen, must_append, MAUTO, 0L);
6873 }
6874 
6875     void
6876 write_reg_contents_lst(
6877     int		name,
6878     char_u	**strings,
6879     int		maxlen UNUSED,
6880     int		must_append,
6881     int		yank_type,
6882     long	block_len)
6883 {
6884     yankreg_T  *old_y_previous, *old_y_current;
6885 
6886     if (name == '/'
6887 #ifdef FEAT_EVAL
6888 	    || name == '='
6889 #endif
6890 	    )
6891     {
6892 	char_u	*s;
6893 
6894 	if (strings[0] == NULL)
6895 	    s = (char_u *)"";
6896 	else if (strings[1] != NULL)
6897 	{
6898 	    emsg(_("E883: search pattern and expression register may not "
6899 			"contain two or more lines"));
6900 	    return;
6901 	}
6902 	else
6903 	    s = strings[0];
6904 	write_reg_contents_ex(name, s, -1, must_append, yank_type, block_len);
6905 	return;
6906     }
6907 
6908     if (name == '_')	    /* black hole: nothing to do */
6909 	return;
6910 
6911     if (init_write_reg(name, &old_y_previous, &old_y_current, must_append,
6912 		&yank_type) == FAIL)
6913 	return;
6914 
6915     str_to_reg(y_current, yank_type, (char_u *) strings, -1, block_len, TRUE);
6916 
6917     finish_write_reg(name, old_y_previous, old_y_current);
6918 }
6919 
6920     void
6921 write_reg_contents_ex(
6922     int		name,
6923     char_u	*str,
6924     int		maxlen,
6925     int		must_append,
6926     int		yank_type,
6927     long	block_len)
6928 {
6929     yankreg_T	*old_y_previous, *old_y_current;
6930     long	len;
6931 
6932     if (maxlen >= 0)
6933 	len = maxlen;
6934     else
6935 	len = (long)STRLEN(str);
6936 
6937     /* Special case: '/' search pattern */
6938     if (name == '/')
6939     {
6940 	set_last_search_pat(str, RE_SEARCH, TRUE, TRUE);
6941 	return;
6942     }
6943 
6944     if (name == '#')
6945     {
6946 	buf_T	*buf;
6947 
6948 	if (VIM_ISDIGIT(*str))
6949 	{
6950 	    int	num = atoi((char *)str);
6951 
6952 	    buf = buflist_findnr(num);
6953 	    if (buf == NULL)
6954 		semsg(_(e_nobufnr), (long)num);
6955 	}
6956 	else
6957 	    buf = buflist_findnr(buflist_findpat(str, str + STRLEN(str),
6958 							 TRUE, FALSE, FALSE));
6959 	if (buf == NULL)
6960 	    return;
6961 	curwin->w_alt_fnum = buf->b_fnum;
6962 	return;
6963     }
6964 
6965 #ifdef FEAT_EVAL
6966     if (name == '=')
6967     {
6968 	char_u	    *p, *s;
6969 
6970 	p = vim_strnsave(str, (int)len);
6971 	if (p == NULL)
6972 	    return;
6973 	if (must_append)
6974 	{
6975 	    s = concat_str(get_expr_line_src(), p);
6976 	    vim_free(p);
6977 	    p = s;
6978 	}
6979 	set_expr_line(p);
6980 	return;
6981     }
6982 #endif
6983 
6984     if (name == '_')	    /* black hole: nothing to do */
6985 	return;
6986 
6987     if (init_write_reg(name, &old_y_previous, &old_y_current, must_append,
6988 		&yank_type) == FAIL)
6989 	return;
6990 
6991     str_to_reg(y_current, yank_type, str, len, block_len, FALSE);
6992 
6993     finish_write_reg(name, old_y_previous, old_y_current);
6994 }
6995 #endif	/* FEAT_EVAL */
6996 
6997 #if defined(FEAT_CLIPBOARD) || defined(FEAT_EVAL)
6998 /*
6999  * Put a string into a register.  When the register is not empty, the string
7000  * is appended.
7001  */
7002     static void
7003 str_to_reg(
7004     yankreg_T	*y_ptr,		/* pointer to yank register */
7005     int		yank_type,	/* MCHAR, MLINE, MBLOCK, MAUTO */
7006     char_u	*str,		/* string to put in register */
7007     long	len,		/* length of string */
7008     long	blocklen,	/* width of Visual block */
7009     int		str_list)	/* TRUE if str is char_u ** */
7010 {
7011     int		type;			/* MCHAR, MLINE or MBLOCK */
7012     int		lnum;
7013     long	start;
7014     long	i;
7015     int		extra;
7016     int		newlines;		/* number of lines added */
7017     int		extraline = 0;		/* extra line at the end */
7018     int		append = FALSE;		/* append to last line in register */
7019     char_u	*s;
7020     char_u	**ss;
7021     char_u	**pp;
7022     long	maxlen;
7023 
7024     if (y_ptr->y_array == NULL)		/* NULL means empty register */
7025 	y_ptr->y_size = 0;
7026 
7027     if (yank_type == MAUTO)
7028 	type = ((str_list || (len > 0 && (str[len - 1] == NL
7029 					    || str[len - 1] == CAR)))
7030 							     ? MLINE : MCHAR);
7031     else
7032 	type = yank_type;
7033 
7034     /*
7035      * Count the number of lines within the string
7036      */
7037     newlines = 0;
7038     if (str_list)
7039     {
7040 	for (ss = (char_u **) str; *ss != NULL; ++ss)
7041 	    ++newlines;
7042     }
7043     else
7044     {
7045 	for (i = 0; i < len; i++)
7046 	    if (str[i] == '\n')
7047 		++newlines;
7048 	if (type == MCHAR || len == 0 || str[len - 1] != '\n')
7049 	{
7050 	    extraline = 1;
7051 	    ++newlines;	/* count extra newline at the end */
7052 	}
7053 	if (y_ptr->y_size > 0 && y_ptr->y_type == MCHAR)
7054 	{
7055 	    append = TRUE;
7056 	    --newlines;	/* uncount newline when appending first line */
7057 	}
7058     }
7059 
7060     /* Without any lines make the register empty. */
7061     if (y_ptr->y_size + newlines == 0)
7062     {
7063 	VIM_CLEAR(y_ptr->y_array);
7064 	return;
7065     }
7066 
7067     /*
7068      * Allocate an array to hold the pointers to the new register lines.
7069      * If the register was not empty, move the existing lines to the new array.
7070      */
7071     pp = (char_u **)lalloc_clear((y_ptr->y_size + newlines)
7072 						    * sizeof(char_u *), TRUE);
7073     if (pp == NULL)	/* out of memory */
7074 	return;
7075     for (lnum = 0; lnum < y_ptr->y_size; ++lnum)
7076 	pp[lnum] = y_ptr->y_array[lnum];
7077     vim_free(y_ptr->y_array);
7078     y_ptr->y_array = pp;
7079     maxlen = 0;
7080 
7081     /*
7082      * Find the end of each line and save it into the array.
7083      */
7084     if (str_list)
7085     {
7086 	for (ss = (char_u **) str; *ss != NULL; ++ss, ++lnum)
7087 	{
7088 	    i = (long)STRLEN(*ss);
7089 	    pp[lnum] = vim_strnsave(*ss, i);
7090 	    if (i > maxlen)
7091 		maxlen = i;
7092 	}
7093     }
7094     else
7095     {
7096 	for (start = 0; start < len + extraline; start += i + 1)
7097 	{
7098 	    for (i = start; i < len; ++i)	/* find the end of the line */
7099 		if (str[i] == '\n')
7100 		    break;
7101 	    i -= start;			/* i is now length of line */
7102 	    if (i > maxlen)
7103 		maxlen = i;
7104 	    if (append)
7105 	    {
7106 		--lnum;
7107 		extra = (int)STRLEN(y_ptr->y_array[lnum]);
7108 	    }
7109 	    else
7110 		extra = 0;
7111 	    s = alloc((unsigned)(i + extra + 1));
7112 	    if (s == NULL)
7113 		break;
7114 	    if (extra)
7115 		mch_memmove(s, y_ptr->y_array[lnum], (size_t)extra);
7116 	    if (append)
7117 		vim_free(y_ptr->y_array[lnum]);
7118 	    if (i)
7119 		mch_memmove(s + extra, str + start, (size_t)i);
7120 	    extra += i;
7121 	    s[extra] = NUL;
7122 	    y_ptr->y_array[lnum++] = s;
7123 	    while (--extra >= 0)
7124 	    {
7125 		if (*s == NUL)
7126 		    *s = '\n';	    /* replace NUL with newline */
7127 		++s;
7128 	    }
7129 	    append = FALSE;		    /* only first line is appended */
7130 	}
7131     }
7132     y_ptr->y_type = type;
7133     y_ptr->y_size = lnum;
7134     if (type == MBLOCK)
7135 	y_ptr->y_width = (blocklen < 0 ? maxlen - 1 : blocklen);
7136     else
7137 	y_ptr->y_width = 0;
7138 #ifdef FEAT_VIMINFO
7139     y_ptr->y_time_set = vim_time();
7140 #endif
7141 }
7142 #endif /* FEAT_CLIPBOARD || FEAT_EVAL || PROTO */
7143 
7144     void
7145 clear_oparg(oparg_T *oap)
7146 {
7147     vim_memset(oap, 0, sizeof(oparg_T));
7148 }
7149 
7150 /*
7151  *  Count the number of bytes, characters and "words" in a line.
7152  *
7153  *  "Words" are counted by looking for boundaries between non-space and
7154  *  space characters.  (it seems to produce results that match 'wc'.)
7155  *
7156  *  Return value is byte count; word count for the line is added to "*wc".
7157  *  Char count is added to "*cc".
7158  *
7159  *  The function will only examine the first "limit" characters in the
7160  *  line, stopping if it encounters an end-of-line (NUL byte).  In that
7161  *  case, eol_size will be added to the character count to account for
7162  *  the size of the EOL character.
7163  */
7164     static varnumber_T
7165 line_count_info(
7166     char_u	*line,
7167     varnumber_T	*wc,
7168     varnumber_T	*cc,
7169     varnumber_T	limit,
7170     int		eol_size)
7171 {
7172     varnumber_T	i;
7173     varnumber_T	words = 0;
7174     varnumber_T	chars = 0;
7175     int		is_word = 0;
7176 
7177     for (i = 0; i < limit && line[i] != NUL; )
7178     {
7179 	if (is_word)
7180 	{
7181 	    if (vim_isspace(line[i]))
7182 	    {
7183 		words++;
7184 		is_word = 0;
7185 	    }
7186 	}
7187 	else if (!vim_isspace(line[i]))
7188 	    is_word = 1;
7189 	++chars;
7190 	i += (*mb_ptr2len)(line + i);
7191     }
7192 
7193     if (is_word)
7194 	words++;
7195     *wc += words;
7196 
7197     /* Add eol_size if the end of line was reached before hitting limit. */
7198     if (i < limit && line[i] == NUL)
7199     {
7200 	i += eol_size;
7201 	chars += eol_size;
7202     }
7203     *cc += chars;
7204     return i;
7205 }
7206 
7207 /*
7208  * Give some info about the position of the cursor (for "g CTRL-G").
7209  * In Visual mode, give some info about the selected region.  (In this case,
7210  * the *_count_cursor variables store running totals for the selection.)
7211  * When "dict" is not NULL store the info there instead of showing it.
7212  */
7213     void
7214 cursor_pos_info(dict_T *dict)
7215 {
7216     char_u	*p;
7217     char_u	buf1[50];
7218     char_u	buf2[40];
7219     linenr_T	lnum;
7220     varnumber_T	byte_count = 0;
7221     varnumber_T	bom_count  = 0;
7222     varnumber_T	byte_count_cursor = 0;
7223     varnumber_T	char_count = 0;
7224     varnumber_T	char_count_cursor = 0;
7225     varnumber_T	word_count = 0;
7226     varnumber_T	word_count_cursor = 0;
7227     int		eol_size;
7228     varnumber_T	last_check = 100000L;
7229     long	line_count_selected = 0;
7230     pos_T	min_pos, max_pos;
7231     oparg_T	oparg;
7232     struct block_def	bd;
7233 
7234     /*
7235      * Compute the length of the file in characters.
7236      */
7237     if (curbuf->b_ml.ml_flags & ML_EMPTY)
7238     {
7239 	if (dict == NULL)
7240 	{
7241 	    msg(_(no_lines_msg));
7242 	    return;
7243 	}
7244     }
7245     else
7246     {
7247 	if (get_fileformat(curbuf) == EOL_DOS)
7248 	    eol_size = 2;
7249 	else
7250 	    eol_size = 1;
7251 
7252 	if (VIsual_active)
7253 	{
7254 	    if (LT_POS(VIsual, curwin->w_cursor))
7255 	    {
7256 		min_pos = VIsual;
7257 		max_pos = curwin->w_cursor;
7258 	    }
7259 	    else
7260 	    {
7261 		min_pos = curwin->w_cursor;
7262 		max_pos = VIsual;
7263 	    }
7264 	    if (*p_sel == 'e' && max_pos.col > 0)
7265 		--max_pos.col;
7266 
7267 	    if (VIsual_mode == Ctrl_V)
7268 	    {
7269 #ifdef FEAT_LINEBREAK
7270 		char_u * saved_sbr = p_sbr;
7271 
7272 		/* Make 'sbr' empty for a moment to get the correct size. */
7273 		p_sbr = empty_option;
7274 #endif
7275 		oparg.is_VIsual = 1;
7276 		oparg.block_mode = TRUE;
7277 		oparg.op_type = OP_NOP;
7278 		getvcols(curwin, &min_pos, &max_pos,
7279 					  &oparg.start_vcol, &oparg.end_vcol);
7280 #ifdef FEAT_LINEBREAK
7281 		p_sbr = saved_sbr;
7282 #endif
7283 		if (curwin->w_curswant == MAXCOL)
7284 		    oparg.end_vcol = MAXCOL;
7285 		/* Swap the start, end vcol if needed */
7286 		if (oparg.end_vcol < oparg.start_vcol)
7287 		{
7288 		    oparg.end_vcol += oparg.start_vcol;
7289 		    oparg.start_vcol = oparg.end_vcol - oparg.start_vcol;
7290 		    oparg.end_vcol -= oparg.start_vcol;
7291 		}
7292 	    }
7293 	    line_count_selected = max_pos.lnum - min_pos.lnum + 1;
7294 	}
7295 
7296 	for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
7297 	{
7298 	    /* Check for a CTRL-C every 100000 characters. */
7299 	    if (byte_count > last_check)
7300 	    {
7301 		ui_breakcheck();
7302 		if (got_int)
7303 		    return;
7304 		last_check = byte_count + 100000L;
7305 	    }
7306 
7307 	    /* Do extra processing for VIsual mode. */
7308 	    if (VIsual_active
7309 		    && lnum >= min_pos.lnum && lnum <= max_pos.lnum)
7310 	    {
7311 		char_u	    *s = NULL;
7312 		long	    len = 0L;
7313 
7314 		switch (VIsual_mode)
7315 		{
7316 		    case Ctrl_V:
7317 			virtual_op = virtual_active();
7318 			block_prep(&oparg, &bd, lnum, 0);
7319 			virtual_op = MAYBE;
7320 			s = bd.textstart;
7321 			len = (long)bd.textlen;
7322 			break;
7323 		    case 'V':
7324 			s = ml_get(lnum);
7325 			len = MAXCOL;
7326 			break;
7327 		    case 'v':
7328 			{
7329 			    colnr_T start_col = (lnum == min_pos.lnum)
7330 							   ? min_pos.col : 0;
7331 			    colnr_T end_col = (lnum == max_pos.lnum)
7332 				      ? max_pos.col - start_col + 1 : MAXCOL;
7333 
7334 			    s = ml_get(lnum) + start_col;
7335 			    len = end_col;
7336 			}
7337 			break;
7338 		}
7339 		if (s != NULL)
7340 		{
7341 		    byte_count_cursor += line_count_info(s, &word_count_cursor,
7342 					   &char_count_cursor, len, eol_size);
7343 		    if (lnum == curbuf->b_ml.ml_line_count
7344 			    && !curbuf->b_p_eol
7345 			    && (curbuf->b_p_bin || !curbuf->b_p_fixeol)
7346 			    && (long)STRLEN(s) < len)
7347 			byte_count_cursor -= eol_size;
7348 		}
7349 	    }
7350 	    else
7351 	    {
7352 		/* In non-visual mode, check for the line the cursor is on */
7353 		if (lnum == curwin->w_cursor.lnum)
7354 		{
7355 		    word_count_cursor += word_count;
7356 		    char_count_cursor += char_count;
7357 		    byte_count_cursor = byte_count +
7358 			line_count_info(ml_get(lnum),
7359 				&word_count_cursor, &char_count_cursor,
7360 				(varnumber_T)(curwin->w_cursor.col + 1),
7361 				eol_size);
7362 		}
7363 	    }
7364 	    /* Add to the running totals */
7365 	    byte_count += line_count_info(ml_get(lnum), &word_count,
7366 					 &char_count, (varnumber_T)MAXCOL,
7367 					 eol_size);
7368 	}
7369 
7370 	/* Correction for when last line doesn't have an EOL. */
7371 	if (!curbuf->b_p_eol && (curbuf->b_p_bin || !curbuf->b_p_fixeol))
7372 	    byte_count -= eol_size;
7373 
7374 	if (dict == NULL)
7375 	{
7376 	    if (VIsual_active)
7377 	    {
7378 		if (VIsual_mode == Ctrl_V && curwin->w_curswant < MAXCOL)
7379 		{
7380 		    getvcols(curwin, &min_pos, &max_pos, &min_pos.col,
7381 								    &max_pos.col);
7382 		    vim_snprintf((char *)buf1, sizeof(buf1), _("%ld Cols; "),
7383 			    (long)(oparg.end_vcol - oparg.start_vcol + 1));
7384 		}
7385 		else
7386 		    buf1[0] = NUL;
7387 
7388 		if (char_count_cursor == byte_count_cursor
7389 						    && char_count == byte_count)
7390 		    vim_snprintf((char *)IObuff, IOSIZE,
7391 			    _("Selected %s%ld of %ld Lines; %lld of %lld Words; %lld of %lld Bytes"),
7392 			    buf1, line_count_selected,
7393 			    (long)curbuf->b_ml.ml_line_count,
7394 			    (long_long_T)word_count_cursor,
7395 			    (long_long_T)word_count,
7396 			    (long_long_T)byte_count_cursor,
7397 			    (long_long_T)byte_count);
7398 		else
7399 		    vim_snprintf((char *)IObuff, IOSIZE,
7400 			    _("Selected %s%ld of %ld Lines; %lld of %lld Words; %lld of %lld Chars; %lld of %lld Bytes"),
7401 			    buf1, line_count_selected,
7402 			    (long)curbuf->b_ml.ml_line_count,
7403 			    (long_long_T)word_count_cursor,
7404 			    (long_long_T)word_count,
7405 			    (long_long_T)char_count_cursor,
7406 			    (long_long_T)char_count,
7407 			    (long_long_T)byte_count_cursor,
7408 			    (long_long_T)byte_count);
7409 	    }
7410 	    else
7411 	    {
7412 		p = ml_get_curline();
7413 		validate_virtcol();
7414 		col_print(buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1,
7415 			(int)curwin->w_virtcol + 1);
7416 		col_print(buf2, sizeof(buf2), (int)STRLEN(p),
7417 				    linetabsize(p));
7418 
7419 		if (char_count_cursor == byte_count_cursor
7420 			&& char_count == byte_count)
7421 		    vim_snprintf((char *)IObuff, IOSIZE,
7422 			_("Col %s of %s; Line %ld of %ld; Word %lld of %lld; Byte %lld of %lld"),
7423 			(char *)buf1, (char *)buf2,
7424 			(long)curwin->w_cursor.lnum,
7425 			(long)curbuf->b_ml.ml_line_count,
7426 			(long_long_T)word_count_cursor, (long_long_T)word_count,
7427 			(long_long_T)byte_count_cursor, (long_long_T)byte_count);
7428 		else
7429 		    vim_snprintf((char *)IObuff, IOSIZE,
7430 			_("Col %s of %s; Line %ld of %ld; Word %lld of %lld; Char %lld of %lld; Byte %lld of %lld"),
7431 			(char *)buf1, (char *)buf2,
7432 			(long)curwin->w_cursor.lnum,
7433 			(long)curbuf->b_ml.ml_line_count,
7434 			(long_long_T)word_count_cursor, (long_long_T)word_count,
7435 			(long_long_T)char_count_cursor, (long_long_T)char_count,
7436 			(long_long_T)byte_count_cursor, (long_long_T)byte_count);
7437 	    }
7438 	}
7439 
7440 	bom_count = bomb_size();
7441 	if (bom_count > 0)
7442 	    vim_snprintf((char *)IObuff + STRLEN(IObuff), IOSIZE,
7443 				 _("(+%lld for BOM)"), (long_long_T)bom_count);
7444 	if (dict == NULL)
7445 	{
7446 	    /* Don't shorten this message, the user asked for it. */
7447 	    p = p_shm;
7448 	    p_shm = (char_u *)"";
7449 	    msg((char *)IObuff);
7450 	    p_shm = p;
7451 	}
7452     }
7453 #if defined(FEAT_EVAL)
7454     if (dict != NULL)
7455     {
7456 	dict_add_number(dict, "words", word_count);
7457 	dict_add_number(dict, "chars", char_count);
7458 	dict_add_number(dict, "bytes", byte_count + bom_count);
7459 	dict_add_number(dict, VIsual_active ? "visual_bytes" : "cursor_bytes",
7460 		byte_count_cursor);
7461 	dict_add_number(dict, VIsual_active ? "visual_chars" : "cursor_chars",
7462 		char_count_cursor);
7463 	dict_add_number(dict, VIsual_active ? "visual_words" : "cursor_words",
7464 		word_count_cursor);
7465     }
7466 #endif
7467 }
7468