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