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