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