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