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