xref: /vim-8.2.3635/src/ops.c (revision 71ccd03e)
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 static void shift_block(oparg_T *oap, int amount);
18 static void	mb_adjust_opend(oparg_T *oap);
19 static int	do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1);
20 
21 // Flags for third item in "opchars".
22 #define OPF_LINES  1	// operator always works on lines
23 #define OPF_CHANGE 2	// operator changes text
24 
25 /*
26  * The names of operators.
27  * IMPORTANT: Index must correspond with defines in vim.h!!!
28  * The third field holds OPF_ flags.
29  */
30 static char opchars[][3] =
31 {
32     {NUL, NUL, 0},			// OP_NOP
33     {'d', NUL, OPF_CHANGE},		// OP_DELETE
34     {'y', NUL, 0},			// OP_YANK
35     {'c', NUL, OPF_CHANGE},		// OP_CHANGE
36     {'<', NUL, OPF_LINES | OPF_CHANGE},	// OP_LSHIFT
37     {'>', NUL, OPF_LINES | OPF_CHANGE},	// OP_RSHIFT
38     {'!', NUL, OPF_LINES | OPF_CHANGE},	// OP_FILTER
39     {'g', '~', OPF_CHANGE},		// OP_TILDE
40     {'=', NUL, OPF_LINES | OPF_CHANGE},	// OP_INDENT
41     {'g', 'q', OPF_LINES | OPF_CHANGE},	// OP_FORMAT
42     {':', NUL, OPF_LINES},		// OP_COLON
43     {'g', 'U', OPF_CHANGE},		// OP_UPPER
44     {'g', 'u', OPF_CHANGE},		// OP_LOWER
45     {'J', NUL, OPF_LINES | OPF_CHANGE},	// DO_JOIN
46     {'g', 'J', OPF_LINES | OPF_CHANGE},	// DO_JOIN_NS
47     {'g', '?', OPF_CHANGE},		// OP_ROT13
48     {'r', NUL, OPF_CHANGE},		// OP_REPLACE
49     {'I', NUL, OPF_CHANGE},		// OP_INSERT
50     {'A', NUL, OPF_CHANGE},		// OP_APPEND
51     {'z', 'f', OPF_LINES},		// OP_FOLD
52     {'z', 'o', OPF_LINES},		// OP_FOLDOPEN
53     {'z', 'O', OPF_LINES},		// OP_FOLDOPENREC
54     {'z', 'c', OPF_LINES},		// OP_FOLDCLOSE
55     {'z', 'C', OPF_LINES},		// OP_FOLDCLOSEREC
56     {'z', 'd', OPF_LINES},		// OP_FOLDDEL
57     {'z', 'D', OPF_LINES},		// OP_FOLDDELREC
58     {'g', 'w', OPF_LINES | OPF_CHANGE},	// OP_FORMAT2
59     {'g', '@', OPF_CHANGE},		// OP_FUNCTION
60     {Ctrl_A, NUL, OPF_CHANGE},		// OP_NR_ADD
61     {Ctrl_X, NUL, OPF_CHANGE},		// OP_NR_SUB
62 };
63 
64 /*
65  * Translate a command name into an operator type.
66  * Must only be called with a valid operator name!
67  */
68     int
69 get_op_type(int char1, int char2)
70 {
71     int		i;
72 
73     if (char1 == 'r')		// ignore second character
74 	return OP_REPLACE;
75     if (char1 == '~')		// when tilde is an operator
76 	return OP_TILDE;
77     if (char1 == 'g' && char2 == Ctrl_A)	// add
78 	return OP_NR_ADD;
79     if (char1 == 'g' && char2 == Ctrl_X)	// subtract
80 	return OP_NR_SUB;
81     for (i = 0; ; ++i)
82     {
83 	if (opchars[i][0] == char1 && opchars[i][1] == char2)
84 	    break;
85 	if (i == (int)(sizeof(opchars) / sizeof(char [3]) - 1))
86 	{
87 	    internal_error("get_op_type()");
88 	    break;
89 	}
90     }
91     return i;
92 }
93 
94 /*
95  * Return TRUE if operator "op" always works on whole lines.
96  */
97     static int
98 op_on_lines(int op)
99 {
100     return opchars[op][2] & OPF_LINES;
101 }
102 
103 #if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
104 /*
105  * Return TRUE if operator "op" changes text.
106  */
107     int
108 op_is_change(int op)
109 {
110     return opchars[op][2] & OPF_CHANGE;
111 }
112 #endif
113 
114 /*
115  * Get first operator command character.
116  * Returns 'g' or 'z' if there is another command character.
117  */
118     int
119 get_op_char(int optype)
120 {
121     return opchars[optype][0];
122 }
123 
124 /*
125  * Get second operator command character.
126  */
127     int
128 get_extra_op_char(int optype)
129 {
130     return opchars[optype][1];
131 }
132 
133 /*
134  * op_shift - handle a shift operation
135  */
136     void
137 op_shift(oparg_T *oap, int curs_top, int amount)
138 {
139     long	    i;
140     int		    first_char;
141     int		    block_col = 0;
142 
143     if (u_save((linenr_T)(oap->start.lnum - 1),
144 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
145 	return;
146 
147     if (oap->block_mode)
148 	block_col = curwin->w_cursor.col;
149 
150     for (i = oap->line_count; --i >= 0; )
151     {
152 	first_char = *ml_get_curline();
153 	if (first_char == NUL)				// empty line
154 	    curwin->w_cursor.col = 0;
155 	else if (oap->block_mode)
156 	    shift_block(oap, amount);
157 	else
158 	    // Move the line right if it doesn't start with '#', 'smartindent'
159 	    // isn't set or 'cindent' isn't set or '#' isn't in 'cino'.
160 #if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT)
161 	    if (first_char != '#' || !preprocs_left())
162 #endif
163 	    shift_line(oap->op_type == OP_LSHIFT, p_sr, amount, FALSE);
164 	++curwin->w_cursor.lnum;
165     }
166 
167     changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
168     if (oap->block_mode)
169     {
170 	curwin->w_cursor.lnum = oap->start.lnum;
171 	curwin->w_cursor.col = block_col;
172     }
173     else if (curs_top)	    // put cursor on first line, for ">>"
174     {
175 	curwin->w_cursor.lnum = oap->start.lnum;
176 	beginline(BL_SOL | BL_FIX);   // shift_line() may have set cursor.col
177     }
178     else
179 	--curwin->w_cursor.lnum;	// put cursor on last line, for ":>"
180 
181 #ifdef FEAT_FOLDING
182     // The cursor line is not in a closed fold
183     foldOpenCursor();
184 #endif
185 
186 
187     if (oap->line_count > p_report)
188     {
189 	char	    *op;
190 	char	    *msg_line_single;
191 	char	    *msg_line_plural;
192 
193 	if (oap->op_type == OP_RSHIFT)
194 	    op = ">";
195 	else
196 	    op = "<";
197 	msg_line_single = NGETTEXT("%ld line %sed %d time",
198 					     "%ld line %sed %d times", amount);
199 	msg_line_plural = NGETTEXT("%ld lines %sed %d time",
200 					    "%ld lines %sed %d times", amount);
201 	vim_snprintf((char *)IObuff, IOSIZE,
202 		NGETTEXT(msg_line_single, msg_line_plural, oap->line_count),
203 		oap->line_count, op, amount);
204 	msg_attr_keep((char *)IObuff, 0, TRUE);
205     }
206 
207     if (!cmdmod.lockmarks)
208     {
209 	// Set "'[" and "']" marks.
210 	curbuf->b_op_start = oap->start;
211 	curbuf->b_op_end.lnum = oap->end.lnum;
212 	curbuf->b_op_end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
213 	if (curbuf->b_op_end.col > 0)
214 	    --curbuf->b_op_end.col;
215     }
216 }
217 
218 /*
219  * Shift the current line one shiftwidth left (if left != 0) or right
220  * leaves cursor on first blank in the line.
221  */
222     void
223 shift_line(
224     int	left,
225     int	round,
226     int	amount,
227     int call_changed_bytes)	// call changed_bytes()
228 {
229     int		count;
230     int		i, j;
231     int		sw_val = (int)get_sw_value_indent(curbuf);
232 
233     count = get_indent();	// get current indent
234 
235     if (round)			// round off indent
236     {
237 	i = count / sw_val;	// number of 'shiftwidth' rounded down
238 	j = count % sw_val;	// extra spaces
239 	if (j && left)		// first remove extra spaces
240 	    --amount;
241 	if (left)
242 	{
243 	    i -= amount;
244 	    if (i < 0)
245 		i = 0;
246 	}
247 	else
248 	    i += amount;
249 	count = i * sw_val;
250     }
251     else		// original vi indent
252     {
253 	if (left)
254 	{
255 	    count -= sw_val * amount;
256 	    if (count < 0)
257 		count = 0;
258 	}
259 	else
260 	    count += sw_val * amount;
261     }
262 
263     // Set new indent
264     if (State & VREPLACE_FLAG)
265 	change_indent(INDENT_SET, count, FALSE, NUL, call_changed_bytes);
266     else
267 	(void)set_indent(count, call_changed_bytes ? SIN_CHANGED : 0);
268 }
269 
270 /*
271  * Shift one line of the current block one shiftwidth right or left.
272  * Leaves cursor on first character in block.
273  */
274     static void
275 shift_block(oparg_T *oap, int amount)
276 {
277     int			left = (oap->op_type == OP_LSHIFT);
278     int			oldstate = State;
279     int			total;
280     char_u		*newp, *oldp;
281     int			oldcol = curwin->w_cursor.col;
282     int			sw_val = (int)get_sw_value_indent(curbuf);
283     int			ts_val = (int)curbuf->b_p_ts;
284     struct block_def	bd;
285     int			incr;
286     colnr_T		ws_vcol;
287     int			i = 0, j = 0;
288     int			len;
289 #ifdef FEAT_RIGHTLEFT
290     int			old_p_ri = p_ri;
291 
292     p_ri = 0;			// don't want revins in indent
293 #endif
294 
295     State = INSERT;		// don't want REPLACE for State
296     block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE);
297     if (bd.is_short)
298 	return;
299 
300     // total is number of screen columns to be inserted/removed
301     total = (int)((unsigned)amount * (unsigned)sw_val);
302     if ((total / sw_val) != amount)
303 	return; // multiplication overflow
304 
305     oldp = ml_get_curline();
306 
307     if (!left)
308     {
309 	/*
310 	 *  1. Get start vcol
311 	 *  2. Total ws vcols
312 	 *  3. Divvy into TABs & spp
313 	 *  4. Construct new string
314 	 */
315 	total += bd.pre_whitesp; // all virtual WS up to & incl a split TAB
316 	ws_vcol = bd.start_vcol - bd.pre_whitesp;
317 	if (bd.startspaces)
318 	{
319 	    if (has_mbyte)
320 	    {
321 		if ((*mb_ptr2len)(bd.textstart) == 1)
322 		    ++bd.textstart;
323 		else
324 		{
325 		    ws_vcol = 0;
326 		    bd.startspaces = 0;
327 		}
328 	    }
329 	    else
330 		++bd.textstart;
331 	}
332 	for ( ; VIM_ISWHITE(*bd.textstart); )
333 	{
334 	    // TODO: is passing bd.textstart for start of the line OK?
335 	    incr = lbr_chartabsize_adv(bd.textstart, &bd.textstart,
336 						    (colnr_T)(bd.start_vcol));
337 	    total += incr;
338 	    bd.start_vcol += incr;
339 	}
340 	// OK, now total=all the VWS reqd, and textstart points at the 1st
341 	// non-ws char in the block.
342 #ifdef FEAT_VARTABS
343 	if (!curbuf->b_p_et)
344 	    tabstop_fromto(ws_vcol, ws_vcol + total,
345 					ts_val, curbuf->b_p_vts_array, &i, &j);
346 	else
347 	    j = total;
348 #else
349 	if (!curbuf->b_p_et)
350 	    i = ((ws_vcol % ts_val) + total) / ts_val; // number of tabs
351 	if (i)
352 	    j = ((ws_vcol % ts_val) + total) % ts_val; // number of spp
353 	else
354 	    j = total;
355 #endif
356 	// if we're splitting a TAB, allow for it
357 	bd.textcol -= bd.pre_whitesp_c - (bd.startspaces != 0);
358 	len = (int)STRLEN(bd.textstart) + 1;
359 	newp = alloc(bd.textcol + i + j + len);
360 	if (newp == NULL)
361 	    return;
362 	vim_memset(newp, NUL, (size_t)(bd.textcol + i + j + len));
363 	mch_memmove(newp, oldp, (size_t)bd.textcol);
364 	vim_memset(newp + bd.textcol, TAB, (size_t)i);
365 	vim_memset(newp + bd.textcol + i, ' ', (size_t)j);
366 	// the end
367 	mch_memmove(newp + bd.textcol + i + j, bd.textstart, (size_t)len);
368     }
369     else // left
370     {
371 	colnr_T	    destination_col;	// column to which text in block will
372 					// be shifted
373 	char_u	    *verbatim_copy_end;	// end of the part of the line which is
374 					// copied verbatim
375 	colnr_T	    verbatim_copy_width;// the (displayed) width of this part
376 					// of line
377 	unsigned    fill;		// nr of spaces that replace a TAB
378 	unsigned    new_line_len;	// the length of the line after the
379 					// block shift
380 	size_t	    block_space_width;
381 	size_t	    shift_amount;
382 	char_u	    *non_white = bd.textstart;
383 	colnr_T	    non_white_col;
384 
385 	/*
386 	 * Firstly, let's find the first non-whitespace character that is
387 	 * displayed after the block's start column and the character's column
388 	 * number. Also, let's calculate the width of all the whitespace
389 	 * characters that are displayed in the block and precede the searched
390 	 * non-whitespace character.
391 	 */
392 
393 	// If "bd.startspaces" is set, "bd.textstart" points to the character,
394 	// the part of which is displayed at the block's beginning. Let's start
395 	// searching from the next character.
396 	if (bd.startspaces)
397 	    MB_PTR_ADV(non_white);
398 
399 	// The character's column is in "bd.start_vcol".
400 	non_white_col = bd.start_vcol;
401 
402 	while (VIM_ISWHITE(*non_white))
403 	{
404 	    incr = lbr_chartabsize_adv(bd.textstart, &non_white, non_white_col);
405 	    non_white_col += incr;
406 	}
407 
408 	block_space_width = non_white_col - oap->start_vcol;
409 	// We will shift by "total" or "block_space_width", whichever is less.
410 	shift_amount = (block_space_width < (size_t)total
411 					 ? block_space_width : (size_t)total);
412 
413 	// The column to which we will shift the text.
414 	destination_col = (colnr_T)(non_white_col - shift_amount);
415 
416 	// Now let's find out how much of the beginning of the line we can
417 	// reuse without modification.
418 	verbatim_copy_end = bd.textstart;
419 	verbatim_copy_width = bd.start_vcol;
420 
421 	// If "bd.startspaces" is set, "bd.textstart" points to the character
422 	// preceding the block. We have to subtract its width to obtain its
423 	// column number.
424 	if (bd.startspaces)
425 	    verbatim_copy_width -= bd.start_char_vcols;
426 	while (verbatim_copy_width < destination_col)
427 	{
428 	    char_u *line = verbatim_copy_end;
429 
430 	    // TODO: is passing verbatim_copy_end for start of the line OK?
431 	    incr = lbr_chartabsize(line, verbatim_copy_end,
432 							 verbatim_copy_width);
433 	    if (verbatim_copy_width + incr > destination_col)
434 		break;
435 	    verbatim_copy_width += incr;
436 	    MB_PTR_ADV(verbatim_copy_end);
437 	}
438 
439 	// If "destination_col" is different from the width of the initial
440 	// part of the line that will be copied, it means we encountered a tab
441 	// character, which we will have to partly replace with spaces.
442 	fill = destination_col - verbatim_copy_width;
443 
444 	// The replacement line will consist of:
445 	// - the beginning of the original line up to "verbatim_copy_end",
446 	// - "fill" number of spaces,
447 	// - the rest of the line, pointed to by non_white.
448 	new_line_len = (unsigned)(verbatim_copy_end - oldp)
449 		       + fill
450 		       + (unsigned)STRLEN(non_white) + 1;
451 
452 	newp = alloc(new_line_len);
453 	if (newp == NULL)
454 	    return;
455 	mch_memmove(newp, oldp, (size_t)(verbatim_copy_end - oldp));
456 	vim_memset(newp + (verbatim_copy_end - oldp), ' ', (size_t)fill);
457 	STRMOVE(newp + (verbatim_copy_end - oldp) + fill, non_white);
458     }
459     // replace the line
460     ml_replace(curwin->w_cursor.lnum, newp, FALSE);
461     changed_bytes(curwin->w_cursor.lnum, (colnr_T)bd.textcol);
462     State = oldstate;
463     curwin->w_cursor.col = oldcol;
464 #ifdef FEAT_RIGHTLEFT
465     p_ri = old_p_ri;
466 #endif
467 }
468 
469 /*
470  * Insert string "s" (b_insert ? before : after) block :AKelly
471  * Caller must prepare for undo.
472  */
473     static void
474 block_insert(
475     oparg_T		*oap,
476     char_u		*s,
477     int			b_insert,
478     struct block_def	*bdp)
479 {
480     int		ts_val;
481     int		count = 0;	// extra spaces to replace a cut TAB
482     int		spaces = 0;	// non-zero if cutting a TAB
483     colnr_T	offset;		// pointer along new line
484     unsigned	s_len;		// STRLEN(s)
485     char_u	*newp, *oldp;	// new, old lines
486     linenr_T	lnum;		// loop var
487     int		oldstate = State;
488 
489     State = INSERT;		// don't want REPLACE for State
490     s_len = (unsigned)STRLEN(s);
491 
492     for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)
493     {
494 	block_prep(oap, bdp, lnum, TRUE);
495 	if (bdp->is_short && b_insert)
496 	    continue;	// OP_INSERT, line ends before block start
497 
498 	oldp = ml_get(lnum);
499 
500 	if (b_insert)
501 	{
502 	    ts_val = bdp->start_char_vcols;
503 	    spaces = bdp->startspaces;
504 	    if (spaces != 0)
505 		count = ts_val - 1; // we're cutting a TAB
506 	    offset = bdp->textcol;
507 	}
508 	else // append
509 	{
510 	    ts_val = bdp->end_char_vcols;
511 	    if (!bdp->is_short) // spaces = padding after block
512 	    {
513 		spaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0);
514 		if (spaces != 0)
515 		    count = ts_val - 1; // we're cutting a TAB
516 		offset = bdp->textcol + bdp->textlen - (spaces != 0);
517 	    }
518 	    else // spaces = padding to block edge
519 	    {
520 		// if $ used, just append to EOL (ie spaces==0)
521 		if (!bdp->is_MAX)
522 		    spaces = (oap->end_vcol - bdp->end_vcol) + 1;
523 		count = spaces;
524 		offset = bdp->textcol + bdp->textlen;
525 	    }
526 	}
527 
528 	if (has_mbyte && spaces > 0)
529 	{
530 	    int off;
531 
532 	    // Avoid starting halfway a multi-byte character.
533 	    if (b_insert)
534 	    {
535 		off = (*mb_head_off)(oldp, oldp + offset + spaces);
536 	    }
537 	    else
538 	    {
539 		off = (*mb_off_next)(oldp, oldp + offset);
540 		offset += off;
541 	    }
542 	    spaces -= off;
543 	    count -= off;
544 	}
545 
546 	newp = alloc(STRLEN(oldp) + s_len + count + 1);
547 	if (newp == NULL)
548 	    continue;
549 
550 	// copy up to shifted part
551 	mch_memmove(newp, oldp, (size_t)(offset));
552 	oldp += offset;
553 
554 	// insert pre-padding
555 	vim_memset(newp + offset, ' ', (size_t)spaces);
556 
557 	// copy the new text
558 	mch_memmove(newp + offset + spaces, s, (size_t)s_len);
559 	offset += s_len;
560 
561 	if (spaces && !bdp->is_short)
562 	{
563 	    // insert post-padding
564 	    vim_memset(newp + offset + spaces, ' ', (size_t)(ts_val - spaces));
565 	    // We're splitting a TAB, don't copy it.
566 	    oldp++;
567 	    // We allowed for that TAB, remember this now
568 	    count++;
569 	}
570 
571 	if (spaces > 0)
572 	    offset += count;
573 	STRMOVE(newp + offset, oldp);
574 
575 	ml_replace(lnum, newp, FALSE);
576 
577 	if (lnum == oap->end.lnum)
578 	{
579 	    // Set "']" mark to the end of the block instead of the end of
580 	    // the insert in the first line.
581 	    curbuf->b_op_end.lnum = oap->end.lnum;
582 	    curbuf->b_op_end.col = offset;
583 	}
584     } // for all lnum
585 
586     changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
587 
588     State = oldstate;
589 }
590 
591 /*
592  * Handle a delete operation.
593  *
594  * Return FAIL if undo failed, OK otherwise.
595  */
596     int
597 op_delete(oparg_T *oap)
598 {
599     int			n;
600     linenr_T		lnum;
601     char_u		*ptr;
602     char_u		*newp, *oldp;
603     struct block_def	bd;
604     linenr_T		old_lcount = curbuf->b_ml.ml_line_count;
605     int			did_yank = FALSE;
606 
607     if (curbuf->b_ml.ml_flags & ML_EMPTY)	    // nothing to do
608 	return OK;
609 
610     // Nothing to delete, return here.	Do prepare undo, for op_change().
611     if (oap->empty)
612 	return u_save_cursor();
613 
614     if (!curbuf->b_p_ma)
615     {
616 	emsg(_(e_modifiable));
617 	return FAIL;
618     }
619 
620 #ifdef FEAT_CLIPBOARD
621     adjust_clip_reg(&oap->regname);
622 #endif
623 
624     if (has_mbyte)
625 	mb_adjust_opend(oap);
626 
627     /*
628      * Imitate the strange Vi behaviour: If the delete spans more than one
629      * line and motion_type == MCHAR and the result is a blank line, make the
630      * delete linewise.  Don't do this for the change command or Visual mode.
631      */
632     if (       oap->motion_type == MCHAR
633 	    && !oap->is_VIsual
634 	    && !oap->block_mode
635 	    && oap->line_count > 1
636 	    && oap->motion_force == NUL
637 	    && oap->op_type == OP_DELETE)
638     {
639 	ptr = ml_get(oap->end.lnum) + oap->end.col;
640 	if (*ptr != NUL)
641 	    ptr += oap->inclusive;
642 	ptr = skipwhite(ptr);
643 	if (*ptr == NUL && inindent(0))
644 	    oap->motion_type = MLINE;
645     }
646 
647     /*
648      * Check for trying to delete (e.g. "D") in an empty line.
649      * Note: For the change operator it is ok.
650      */
651     if (       oap->motion_type == MCHAR
652 	    && oap->line_count == 1
653 	    && oap->op_type == OP_DELETE
654 	    && *ml_get(oap->start.lnum) == NUL)
655     {
656 	/*
657 	 * It's an error to operate on an empty region, when 'E' included in
658 	 * 'cpoptions' (Vi compatible).
659 	 */
660 	if (virtual_op)
661 	    // Virtual editing: Nothing gets deleted, but we set the '[ and ']
662 	    // marks as if it happened.
663 	    goto setmarks;
664 	if (vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL)
665 	    beep_flush();
666 	return OK;
667     }
668 
669     /*
670      * Do a yank of whatever we're about to delete.
671      * If a yank register was specified, put the deleted text into that
672      * register.  For the black hole register '_' don't yank anything.
673      */
674     if (oap->regname != '_')
675     {
676 	if (oap->regname != 0)
677 	{
678 	    // check for read-only register
679 	    if (!valid_yank_reg(oap->regname, TRUE))
680 	    {
681 		beep_flush();
682 		return OK;
683 	    }
684 	    get_yank_register(oap->regname, TRUE); // yank into specif'd reg.
685 	    if (op_yank(oap, TRUE, FALSE) == OK)   // yank without message
686 		did_yank = TRUE;
687 	}
688 
689 	/*
690 	 * Put deleted text into register 1 and shift number registers if the
691 	 * delete contains a line break, or when using a specific operator (Vi
692 	 * compatible)
693 	 * Use the register name from before adjust_clip_reg() may have
694 	 * changed it.
695 	 */
696 	if (oap->motion_type == MLINE || oap->line_count > 1
697 							   || oap->use_reg_one)
698 	{
699 	    shift_delete_registers();
700 	    if (op_yank(oap, TRUE, FALSE) == OK)
701 		did_yank = TRUE;
702 	}
703 
704 	// Yank into small delete register when no named register specified
705 	// and the delete is within one line.
706 	if ((
707 #ifdef FEAT_CLIPBOARD
708 	    ((clip_unnamed & CLIP_UNNAMED) && oap->regname == '*') ||
709 	    ((clip_unnamed & CLIP_UNNAMED_PLUS) && oap->regname == '+') ||
710 #endif
711 	    oap->regname == 0) && oap->motion_type != MLINE
712 						      && oap->line_count == 1)
713 	{
714 	    oap->regname = '-';
715 	    get_yank_register(oap->regname, TRUE);
716 	    if (op_yank(oap, TRUE, FALSE) == OK)
717 		did_yank = TRUE;
718 	    oap->regname = 0;
719 	}
720 
721 	/*
722 	 * If there's too much stuff to fit in the yank register, then get a
723 	 * confirmation before doing the delete. This is crude, but simple.
724 	 * And it avoids doing a delete of something we can't put back if we
725 	 * want.
726 	 */
727 	if (!did_yank)
728 	{
729 	    int msg_silent_save = msg_silent;
730 
731 	    msg_silent = 0;	// must display the prompt
732 	    n = ask_yesno((char_u *)_("cannot yank; delete anyway"), TRUE);
733 	    msg_silent = msg_silent_save;
734 	    if (n != 'y')
735 	    {
736 		emsg(_(e_abort));
737 		return FAIL;
738 	    }
739 	}
740 
741 #if defined(FEAT_EVAL)
742 	if (did_yank && has_textyankpost())
743 	    yank_do_autocmd(oap, get_y_current());
744 #endif
745     }
746 
747     /*
748      * block mode delete
749      */
750     if (oap->block_mode)
751     {
752 	if (u_save((linenr_T)(oap->start.lnum - 1),
753 			       (linenr_T)(oap->end.lnum + 1)) == FAIL)
754 	    return FAIL;
755 
756 	for (lnum = curwin->w_cursor.lnum; lnum <= oap->end.lnum; ++lnum)
757 	{
758 	    block_prep(oap, &bd, lnum, TRUE);
759 	    if (bd.textlen == 0)	// nothing to delete
760 		continue;
761 
762 	    // Adjust cursor position for tab replaced by spaces and 'lbr'.
763 	    if (lnum == curwin->w_cursor.lnum)
764 	    {
765 		curwin->w_cursor.col = bd.textcol + bd.startspaces;
766 		curwin->w_cursor.coladd = 0;
767 	    }
768 
769 	    // "n" == number of chars deleted
770 	    // If we delete a TAB, it may be replaced by several characters.
771 	    // Thus the number of characters may increase!
772 	    n = bd.textlen - bd.startspaces - bd.endspaces;
773 	    oldp = ml_get(lnum);
774 	    newp = alloc(STRLEN(oldp) + 1 - n);
775 	    if (newp == NULL)
776 		continue;
777 	    // copy up to deleted part
778 	    mch_memmove(newp, oldp, (size_t)bd.textcol);
779 	    // insert spaces
780 	    vim_memset(newp + bd.textcol, ' ',
781 				     (size_t)(bd.startspaces + bd.endspaces));
782 	    // copy the part after the deleted part
783 	    oldp += bd.textcol + bd.textlen;
784 	    STRMOVE(newp + bd.textcol + bd.startspaces + bd.endspaces, oldp);
785 	    // replace the line
786 	    ml_replace(lnum, newp, FALSE);
787 
788 #ifdef FEAT_PROP_POPUP
789 	    if (curbuf->b_has_textprop && n != 0)
790 		adjust_prop_columns(lnum, bd.textcol, -n, 0);
791 #endif
792 	}
793 
794 	check_cursor_col();
795 	changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
796 						       oap->end.lnum + 1, 0L);
797 	oap->line_count = 0;	    // no lines deleted
798     }
799     else if (oap->motion_type == MLINE)
800     {
801 	if (oap->op_type == OP_CHANGE)
802 	{
803 	    // Delete the lines except the first one.  Temporarily move the
804 	    // cursor to the next line.  Save the current line number, if the
805 	    // last line is deleted it may be changed.
806 	    if (oap->line_count > 1)
807 	    {
808 		lnum = curwin->w_cursor.lnum;
809 		++curwin->w_cursor.lnum;
810 		del_lines((long)(oap->line_count - 1), TRUE);
811 		curwin->w_cursor.lnum = lnum;
812 	    }
813 	    if (u_save_cursor() == FAIL)
814 		return FAIL;
815 	    if (curbuf->b_p_ai)		    // don't delete indent
816 	    {
817 		beginline(BL_WHITE);	    // cursor on first non-white
818 		did_ai = TRUE;		    // delete the indent when ESC hit
819 		ai_col = curwin->w_cursor.col;
820 	    }
821 	    else
822 		beginline(0);		    // cursor in column 0
823 	    truncate_line(FALSE);   // delete the rest of the line
824 				    // leave cursor past last char in line
825 	    if (oap->line_count > 1)
826 		u_clearline();	    // "U" command not possible after "2cc"
827 	}
828 	else
829 	{
830 	    del_lines(oap->line_count, TRUE);
831 	    beginline(BL_WHITE | BL_FIX);
832 	    u_clearline();	// "U" command not possible after "dd"
833 	}
834     }
835     else
836     {
837 	if (virtual_op)
838 	{
839 	    int		endcol = 0;
840 
841 	    // For virtualedit: break the tabs that are partly included.
842 	    if (gchar_pos(&oap->start) == '\t')
843 	    {
844 		if (u_save_cursor() == FAIL)	// save first line for undo
845 		    return FAIL;
846 		if (oap->line_count == 1)
847 		    endcol = getviscol2(oap->end.col, oap->end.coladd);
848 		coladvance_force(getviscol2(oap->start.col, oap->start.coladd));
849 		oap->start = curwin->w_cursor;
850 		if (oap->line_count == 1)
851 		{
852 		    coladvance(endcol);
853 		    oap->end.col = curwin->w_cursor.col;
854 		    oap->end.coladd = curwin->w_cursor.coladd;
855 		    curwin->w_cursor = oap->start;
856 		}
857 	    }
858 
859 	    // Break a tab only when it's included in the area.
860 	    if (gchar_pos(&oap->end) == '\t'
861 				     && (int)oap->end.coladd < oap->inclusive)
862 	    {
863 		// save last line for undo
864 		if (u_save((linenr_T)(oap->end.lnum - 1),
865 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
866 		    return FAIL;
867 		curwin->w_cursor = oap->end;
868 		coladvance_force(getviscol2(oap->end.col, oap->end.coladd));
869 		oap->end = curwin->w_cursor;
870 		curwin->w_cursor = oap->start;
871 	    }
872 	    if (has_mbyte)
873 		mb_adjust_opend(oap);
874 	}
875 
876 	if (oap->line_count == 1)	// delete characters within one line
877 	{
878 	    if (u_save_cursor() == FAIL)	// save line for undo
879 		return FAIL;
880 
881 	    // if 'cpoptions' contains '$', display '$' at end of change
882 	    if (       vim_strchr(p_cpo, CPO_DOLLAR) != NULL
883 		    && oap->op_type == OP_CHANGE
884 		    && oap->end.lnum == curwin->w_cursor.lnum
885 		    && !oap->is_VIsual)
886 		display_dollar(oap->end.col - !oap->inclusive);
887 
888 	    n = oap->end.col - oap->start.col + 1 - !oap->inclusive;
889 
890 	    if (virtual_op)
891 	    {
892 		// fix up things for virtualedit-delete:
893 		// break the tabs which are going to get in our way
894 		char_u		*curline = ml_get_curline();
895 		int		len = (int)STRLEN(curline);
896 
897 		if (oap->end.coladd != 0
898 			&& (int)oap->end.col >= len - 1
899 			&& !(oap->start.coladd && (int)oap->end.col >= len - 1))
900 		    n++;
901 		// Delete at least one char (e.g, when on a control char).
902 		if (n == 0 && oap->start.coladd != oap->end.coladd)
903 		    n = 1;
904 
905 		// When deleted a char in the line, reset coladd.
906 		if (gchar_cursor() != NUL)
907 		    curwin->w_cursor.coladd = 0;
908 	    }
909 	    (void)del_bytes((long)n, !virtual_op,
910 			    oap->op_type == OP_DELETE && !oap->is_VIsual);
911 	}
912 	else				// delete characters between lines
913 	{
914 	    pos_T   curpos;
915 
916 	    // save deleted and changed lines for undo
917 	    if (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
918 		 (linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL)
919 		return FAIL;
920 
921 	    truncate_line(TRUE);	// delete from cursor to end of line
922 
923 	    curpos = curwin->w_cursor;	// remember curwin->w_cursor
924 	    ++curwin->w_cursor.lnum;
925 	    del_lines((long)(oap->line_count - 2), FALSE);
926 
927 	    // delete from start of line until op_end
928 	    n = (oap->end.col + 1 - !oap->inclusive);
929 	    curwin->w_cursor.col = 0;
930 	    (void)del_bytes((long)n, !virtual_op,
931 			    oap->op_type == OP_DELETE && !oap->is_VIsual);
932 	    curwin->w_cursor = curpos;	// restore curwin->w_cursor
933 	    (void)do_join(2, FALSE, FALSE, FALSE, FALSE);
934 	}
935     }
936 
937     msgmore(curbuf->b_ml.ml_line_count - old_lcount);
938 
939 setmarks:
940     if (!cmdmod.lockmarks)
941     {
942 	if (oap->block_mode)
943 	{
944 	    curbuf->b_op_end.lnum = oap->end.lnum;
945 	    curbuf->b_op_end.col = oap->start.col;
946 	}
947 	else
948 	    curbuf->b_op_end = oap->start;
949 	curbuf->b_op_start = oap->start;
950     }
951 
952     return OK;
953 }
954 
955 /*
956  * Adjust end of operating area for ending on a multi-byte character.
957  * Used for deletion.
958  */
959     static void
960 mb_adjust_opend(oparg_T *oap)
961 {
962     char_u	*p;
963 
964     if (oap->inclusive)
965     {
966 	p = ml_get(oap->end.lnum);
967 	oap->end.col += mb_tail_off(p, p + oap->end.col);
968     }
969 }
970 
971 /*
972  * Replace the character under the cursor with "c".
973  * This takes care of multi-byte characters.
974  */
975     static void
976 replace_character(int c)
977 {
978     int n = State;
979 
980     State = REPLACE;
981     ins_char(c);
982     State = n;
983     // Backup to the replaced character.
984     dec_cursor();
985 }
986 
987 /*
988  * Replace a whole area with one character.
989  */
990     int
991 op_replace(oparg_T *oap, int c)
992 {
993     int			n, numc;
994     int			num_chars;
995     char_u		*newp, *oldp;
996     size_t		oldlen;
997     struct block_def	bd;
998     char_u		*after_p = NULL;
999     int			had_ctrl_v_cr = FALSE;
1000 
1001     if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty)
1002 	return OK;	    // nothing to do
1003 
1004     if (c == REPLACE_CR_NCHAR)
1005     {
1006 	had_ctrl_v_cr = TRUE;
1007 	c = CAR;
1008     }
1009     else if (c == REPLACE_NL_NCHAR)
1010     {
1011 	had_ctrl_v_cr = TRUE;
1012 	c = NL;
1013     }
1014 
1015     if (has_mbyte)
1016 	mb_adjust_opend(oap);
1017 
1018     if (u_save((linenr_T)(oap->start.lnum - 1),
1019 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
1020 	return FAIL;
1021 
1022     /*
1023      * block mode replace
1024      */
1025     if (oap->block_mode)
1026     {
1027 	bd.is_MAX = (curwin->w_curswant == MAXCOL);
1028 	for ( ; curwin->w_cursor.lnum <= oap->end.lnum; ++curwin->w_cursor.lnum)
1029 	{
1030 	    curwin->w_cursor.col = 0;  // make sure cursor position is valid
1031 	    block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE);
1032 	    if (bd.textlen == 0 && (!virtual_op || bd.is_MAX))
1033 		continue;	    // nothing to replace
1034 
1035 	    // n == number of extra chars required
1036 	    // If we split a TAB, it may be replaced by several characters.
1037 	    // Thus the number of characters may increase!
1038 	    // If the range starts in virtual space, count the initial
1039 	    // coladd offset as part of "startspaces"
1040 	    if (virtual_op && bd.is_short && *bd.textstart == NUL)
1041 	    {
1042 		pos_T vpos;
1043 
1044 		vpos.lnum = curwin->w_cursor.lnum;
1045 		getvpos(&vpos, oap->start_vcol);
1046 		bd.startspaces += vpos.coladd;
1047 		n = bd.startspaces;
1048 	    }
1049 	    else
1050 		// allow for pre spaces
1051 		n = (bd.startspaces ? bd.start_char_vcols - 1 : 0);
1052 
1053 	    // allow for post spp
1054 	    n += (bd.endspaces
1055 		    && !bd.is_oneChar
1056 		    && bd.end_char_vcols > 0) ? bd.end_char_vcols - 1 : 0;
1057 	    // Figure out how many characters to replace.
1058 	    numc = oap->end_vcol - oap->start_vcol + 1;
1059 	    if (bd.is_short && (!virtual_op || bd.is_MAX))
1060 		numc -= (oap->end_vcol - bd.end_vcol) + 1;
1061 
1062 	    // A double-wide character can be replaced only up to half the
1063 	    // times.
1064 	    if ((*mb_char2cells)(c) > 1)
1065 	    {
1066 		if ((numc & 1) && !bd.is_short)
1067 		{
1068 		    ++bd.endspaces;
1069 		    ++n;
1070 		}
1071 		numc = numc / 2;
1072 	    }
1073 
1074 	    // Compute bytes needed, move character count to num_chars.
1075 	    num_chars = numc;
1076 	    numc *= (*mb_char2len)(c);
1077 	    // oldlen includes textlen, so don't double count
1078 	    n += numc - bd.textlen;
1079 
1080 	    oldp = ml_get_curline();
1081 	    oldlen = STRLEN(oldp);
1082 	    newp = alloc(oldlen + 1 + n);
1083 	    if (newp == NULL)
1084 		continue;
1085 	    vim_memset(newp, NUL, (size_t)(oldlen + 1 + n));
1086 	    // copy up to deleted part
1087 	    mch_memmove(newp, oldp, (size_t)bd.textcol);
1088 	    oldp += bd.textcol + bd.textlen;
1089 	    // insert pre-spaces
1090 	    vim_memset(newp + bd.textcol, ' ', (size_t)bd.startspaces);
1091 	    // insert replacement chars CHECK FOR ALLOCATED SPACE
1092 	    // REPLACE_CR_NCHAR/REPLACE_NL_NCHAR is used for entering CR
1093 	    // literally.
1094 	    if (had_ctrl_v_cr || (c != '\r' && c != '\n'))
1095 	    {
1096 		if (has_mbyte)
1097 		{
1098 		    n = (int)STRLEN(newp);
1099 		    while (--num_chars >= 0)
1100 			n += (*mb_char2bytes)(c, newp + n);
1101 		}
1102 		else
1103 		    vim_memset(newp + STRLEN(newp), c, (size_t)numc);
1104 		if (!bd.is_short)
1105 		{
1106 		    // insert post-spaces
1107 		    vim_memset(newp + STRLEN(newp), ' ', (size_t)bd.endspaces);
1108 		    // copy the part after the changed part
1109 		    STRMOVE(newp + STRLEN(newp), oldp);
1110 		}
1111 	    }
1112 	    else
1113 	    {
1114 		// Replacing with \r or \n means splitting the line.
1115 		after_p = alloc(oldlen + 1 + n - STRLEN(newp));
1116 		if (after_p != NULL)
1117 		    STRMOVE(after_p, oldp);
1118 	    }
1119 	    // replace the line
1120 	    ml_replace(curwin->w_cursor.lnum, newp, FALSE);
1121 	    if (after_p != NULL)
1122 	    {
1123 		ml_append(curwin->w_cursor.lnum++, after_p, 0, FALSE);
1124 		appended_lines_mark(curwin->w_cursor.lnum, 1L);
1125 		oap->end.lnum++;
1126 		vim_free(after_p);
1127 	    }
1128 	}
1129     }
1130     else
1131     {
1132 	/*
1133 	 * MCHAR and MLINE motion replace.
1134 	 */
1135 	if (oap->motion_type == MLINE)
1136 	{
1137 	    oap->start.col = 0;
1138 	    curwin->w_cursor.col = 0;
1139 	    oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
1140 	    if (oap->end.col)
1141 		--oap->end.col;
1142 	}
1143 	else if (!oap->inclusive)
1144 	    dec(&(oap->end));
1145 
1146 	while (LTOREQ_POS(curwin->w_cursor, oap->end))
1147 	{
1148 	    n = gchar_cursor();
1149 	    if (n != NUL)
1150 	    {
1151 		if ((*mb_char2len)(c) > 1 || (*mb_char2len)(n) > 1)
1152 		{
1153 		    // This is slow, but it handles replacing a single-byte
1154 		    // with a multi-byte and the other way around.
1155 		    if (curwin->w_cursor.lnum == oap->end.lnum)
1156 			oap->end.col += (*mb_char2len)(c) - (*mb_char2len)(n);
1157 		    replace_character(c);
1158 		}
1159 		else
1160 		{
1161 		    if (n == TAB)
1162 		    {
1163 			int end_vcol = 0;
1164 
1165 			if (curwin->w_cursor.lnum == oap->end.lnum)
1166 			{
1167 			    // oap->end has to be recalculated when
1168 			    // the tab breaks
1169 			    end_vcol = getviscol2(oap->end.col,
1170 							     oap->end.coladd);
1171 			}
1172 			coladvance_force(getviscol());
1173 			if (curwin->w_cursor.lnum == oap->end.lnum)
1174 			    getvpos(&oap->end, end_vcol);
1175 		    }
1176 		    PBYTE(curwin->w_cursor, c);
1177 		}
1178 	    }
1179 	    else if (virtual_op && curwin->w_cursor.lnum == oap->end.lnum)
1180 	    {
1181 		int virtcols = oap->end.coladd;
1182 
1183 		if (curwin->w_cursor.lnum == oap->start.lnum
1184 			&& oap->start.col == oap->end.col && oap->start.coladd)
1185 		    virtcols -= oap->start.coladd;
1186 
1187 		// oap->end has been trimmed so it's effectively inclusive;
1188 		// as a result an extra +1 must be counted so we don't
1189 		// trample the NUL byte.
1190 		coladvance_force(getviscol2(oap->end.col, oap->end.coladd) + 1);
1191 		curwin->w_cursor.col -= (virtcols + 1);
1192 		for (; virtcols >= 0; virtcols--)
1193 		{
1194                    if ((*mb_char2len)(c) > 1)
1195 		       replace_character(c);
1196                    else
1197 			PBYTE(curwin->w_cursor, c);
1198 		   if (inc(&curwin->w_cursor) == -1)
1199 		       break;
1200 		}
1201 	    }
1202 
1203 	    // Advance to next character, stop at the end of the file.
1204 	    if (inc_cursor() == -1)
1205 		break;
1206 	}
1207     }
1208 
1209     curwin->w_cursor = oap->start;
1210     check_cursor();
1211     changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L);
1212 
1213     if (!cmdmod.lockmarks)
1214     {
1215 	// Set "'[" and "']" marks.
1216 	curbuf->b_op_start = oap->start;
1217 	curbuf->b_op_end = oap->end;
1218     }
1219 
1220     return OK;
1221 }
1222 
1223 static int swapchars(int op_type, pos_T *pos, int length);
1224 
1225 /*
1226  * Handle the (non-standard vi) tilde operator.  Also for "gu", "gU" and "g?".
1227  */
1228     static void
1229 op_tilde(oparg_T *oap)
1230 {
1231     pos_T		pos;
1232     struct block_def	bd;
1233     int			did_change = FALSE;
1234 
1235     if (u_save((linenr_T)(oap->start.lnum - 1),
1236 				       (linenr_T)(oap->end.lnum + 1)) == FAIL)
1237 	return;
1238 
1239     pos = oap->start;
1240     if (oap->block_mode)		    // Visual block mode
1241     {
1242 	for (; pos.lnum <= oap->end.lnum; ++pos.lnum)
1243 	{
1244 	    int one_change;
1245 
1246 	    block_prep(oap, &bd, pos.lnum, FALSE);
1247 	    pos.col = bd.textcol;
1248 	    one_change = swapchars(oap->op_type, &pos, bd.textlen);
1249 	    did_change |= one_change;
1250 
1251 #ifdef FEAT_NETBEANS_INTG
1252 	    if (netbeans_active() && one_change)
1253 	    {
1254 		char_u *ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
1255 
1256 		netbeans_removed(curbuf, pos.lnum, bd.textcol,
1257 							    (long)bd.textlen);
1258 		netbeans_inserted(curbuf, pos.lnum, bd.textcol,
1259 						&ptr[bd.textcol], bd.textlen);
1260 	    }
1261 #endif
1262 	}
1263 	if (did_change)
1264 	    changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
1265     }
1266     else				    // not block mode
1267     {
1268 	if (oap->motion_type == MLINE)
1269 	{
1270 	    oap->start.col = 0;
1271 	    pos.col = 0;
1272 	    oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
1273 	    if (oap->end.col)
1274 		--oap->end.col;
1275 	}
1276 	else if (!oap->inclusive)
1277 	    dec(&(oap->end));
1278 
1279 	if (pos.lnum == oap->end.lnum)
1280 	    did_change = swapchars(oap->op_type, &pos,
1281 						  oap->end.col - pos.col + 1);
1282 	else
1283 	    for (;;)
1284 	    {
1285 		did_change |= swapchars(oap->op_type, &pos,
1286 				pos.lnum == oap->end.lnum ? oap->end.col + 1:
1287 					   (int)STRLEN(ml_get_pos(&pos)));
1288 		if (LTOREQ_POS(oap->end, pos) || inc(&pos) == -1)
1289 		    break;
1290 	    }
1291 	if (did_change)
1292 	{
1293 	    changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1,
1294 									  0L);
1295 #ifdef FEAT_NETBEANS_INTG
1296 	    if (netbeans_active() && did_change)
1297 	    {
1298 		char_u *ptr;
1299 		int count;
1300 
1301 		pos = oap->start;
1302 		while (pos.lnum < oap->end.lnum)
1303 		{
1304 		    ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
1305 		    count = (int)STRLEN(ptr) - pos.col;
1306 		    netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
1307 		    netbeans_inserted(curbuf, pos.lnum, pos.col,
1308 							&ptr[pos.col], count);
1309 		    pos.col = 0;
1310 		    pos.lnum++;
1311 		}
1312 		ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
1313 		count = oap->end.col - pos.col + 1;
1314 		netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
1315 		netbeans_inserted(curbuf, pos.lnum, pos.col,
1316 							&ptr[pos.col], count);
1317 	    }
1318 #endif
1319 	}
1320     }
1321 
1322     if (!did_change && oap->is_VIsual)
1323 	// No change: need to remove the Visual selection
1324 	redraw_curbuf_later(INVERTED);
1325 
1326     if (!cmdmod.lockmarks)
1327     {
1328 	// Set '[ and '] marks.
1329 	curbuf->b_op_start = oap->start;
1330 	curbuf->b_op_end = oap->end;
1331     }
1332 
1333     if (oap->line_count > p_report)
1334 	smsg(NGETTEXT("%ld line changed", "%ld lines changed",
1335 					    oap->line_count), oap->line_count);
1336 }
1337 
1338 /*
1339  * Invoke swapchar() on "length" bytes at position "pos".
1340  * "pos" is advanced to just after the changed characters.
1341  * "length" is rounded up to include the whole last multi-byte character.
1342  * Also works correctly when the number of bytes changes.
1343  * Returns TRUE if some character was changed.
1344  */
1345     static int
1346 swapchars(int op_type, pos_T *pos, int length)
1347 {
1348     int todo;
1349     int	did_change = 0;
1350 
1351     for (todo = length; todo > 0; --todo)
1352     {
1353 	if (has_mbyte)
1354 	{
1355 	    int len = (*mb_ptr2len)(ml_get_pos(pos));
1356 
1357 	    // we're counting bytes, not characters
1358 	    if (len > 0)
1359 		todo -= len - 1;
1360 	}
1361 	did_change |= swapchar(op_type, pos);
1362 	if (inc(pos) == -1)    // at end of file
1363 	    break;
1364     }
1365     return did_change;
1366 }
1367 
1368 /*
1369  * If op_type == OP_UPPER: make uppercase,
1370  * if op_type == OP_LOWER: make lowercase,
1371  * if op_type == OP_ROT13: do rot13 encoding,
1372  * else swap case of character at 'pos'
1373  * returns TRUE when something actually changed.
1374  */
1375     int
1376 swapchar(int op_type, pos_T *pos)
1377 {
1378     int	    c;
1379     int	    nc;
1380 
1381     c = gchar_pos(pos);
1382 
1383     // Only do rot13 encoding for ASCII characters.
1384     if (c >= 0x80 && op_type == OP_ROT13)
1385 	return FALSE;
1386 
1387     if (op_type == OP_UPPER && c == 0xdf
1388 		      && (enc_latin1like || STRCMP(p_enc, "iso-8859-2") == 0))
1389     {
1390 	pos_T   sp = curwin->w_cursor;
1391 
1392 	// Special handling of German sharp s: change to "SS".
1393 	curwin->w_cursor = *pos;
1394 	del_char(FALSE);
1395 	ins_char('S');
1396 	ins_char('S');
1397 	curwin->w_cursor = sp;
1398 	inc(pos);
1399     }
1400 
1401     if (enc_dbcs != 0 && c >= 0x100)	// No lower/uppercase letter
1402 	return FALSE;
1403     nc = c;
1404     if (MB_ISLOWER(c))
1405     {
1406 	if (op_type == OP_ROT13)
1407 	    nc = ROT13(c, 'a');
1408 	else if (op_type != OP_LOWER)
1409 	    nc = MB_TOUPPER(c);
1410     }
1411     else if (MB_ISUPPER(c))
1412     {
1413 	if (op_type == OP_ROT13)
1414 	    nc = ROT13(c, 'A');
1415 	else if (op_type != OP_UPPER)
1416 	    nc = MB_TOLOWER(c);
1417     }
1418     if (nc != c)
1419     {
1420 	if (enc_utf8 && (c >= 0x80 || nc >= 0x80))
1421 	{
1422 	    pos_T   sp = curwin->w_cursor;
1423 
1424 	    curwin->w_cursor = *pos;
1425 	    // don't use del_char(), it also removes composing chars
1426 	    del_bytes(utf_ptr2len(ml_get_cursor()), FALSE, FALSE);
1427 	    ins_char(nc);
1428 	    curwin->w_cursor = sp;
1429 	}
1430 	else
1431 	    PBYTE(*pos, nc);
1432 	return TRUE;
1433     }
1434     return FALSE;
1435 }
1436 
1437 /*
1438  * op_insert - Insert and append operators for Visual mode.
1439  */
1440     void
1441 op_insert(oparg_T *oap, long count1)
1442 {
1443     long		ins_len, pre_textlen = 0;
1444     char_u		*firstline, *ins_text;
1445     colnr_T		ind_pre = 0, ind_post;
1446     struct block_def	bd;
1447     int			i;
1448     pos_T		t1;
1449 
1450     // edit() changes this - record it for OP_APPEND
1451     bd.is_MAX = (curwin->w_curswant == MAXCOL);
1452 
1453     // vis block is still marked. Get rid of it now.
1454     curwin->w_cursor.lnum = oap->start.lnum;
1455     update_screen(INVERTED);
1456 
1457     if (oap->block_mode)
1458     {
1459 	// When 'virtualedit' is used, need to insert the extra spaces before
1460 	// doing block_prep().  When only "block" is used, virtual edit is
1461 	// already disabled, but still need it when calling
1462 	// coladvance_force().
1463 	if (curwin->w_cursor.coladd > 0)
1464 	{
1465 	    int		old_ve_flags = ve_flags;
1466 
1467 	    ve_flags = VE_ALL;
1468 	    if (u_save_cursor() == FAIL)
1469 		return;
1470 	    coladvance_force(oap->op_type == OP_APPEND
1471 					   ? oap->end_vcol + 1 : getviscol());
1472 	    if (oap->op_type == OP_APPEND)
1473 		--curwin->w_cursor.col;
1474 	    ve_flags = old_ve_flags;
1475 	}
1476 	// Get the info about the block before entering the text
1477 	block_prep(oap, &bd, oap->start.lnum, TRUE);
1478 	// Get indent information
1479 	ind_pre = (colnr_T)getwhitecols_curline();
1480 	firstline = ml_get(oap->start.lnum) + bd.textcol;
1481 
1482 	if (oap->op_type == OP_APPEND)
1483 	    firstline += bd.textlen;
1484 	pre_textlen = (long)STRLEN(firstline);
1485     }
1486 
1487     if (oap->op_type == OP_APPEND)
1488     {
1489 	if (oap->block_mode && curwin->w_cursor.coladd == 0)
1490 	{
1491 	    // Move the cursor to the character right of the block.
1492 	    curwin->w_set_curswant = TRUE;
1493 	    while (*ml_get_cursor() != NUL
1494 		    && (curwin->w_cursor.col < bd.textcol + bd.textlen))
1495 		++curwin->w_cursor.col;
1496 	    if (bd.is_short && !bd.is_MAX)
1497 	    {
1498 		// First line was too short, make it longer and adjust the
1499 		// values in "bd".
1500 		if (u_save_cursor() == FAIL)
1501 		    return;
1502 		for (i = 0; i < bd.endspaces; ++i)
1503 		    ins_char(' ');
1504 		bd.textlen += bd.endspaces;
1505 	    }
1506 	}
1507 	else
1508 	{
1509 	    curwin->w_cursor = oap->end;
1510 	    check_cursor_col();
1511 
1512 	    // Works just like an 'i'nsert on the next character.
1513 	    if (!LINEEMPTY(curwin->w_cursor.lnum)
1514 		    && oap->start_vcol != oap->end_vcol)
1515 		inc_cursor();
1516 	}
1517     }
1518 
1519     t1 = oap->start;
1520     (void)edit(NUL, FALSE, (linenr_T)count1);
1521 
1522     // When a tab was inserted, and the characters in front of the tab
1523     // have been converted to a tab as well, the column of the cursor
1524     // might have actually been reduced, so need to adjust here.
1525     if (t1.lnum == curbuf->b_op_start_orig.lnum
1526 	    && LT_POS(curbuf->b_op_start_orig, t1))
1527 	oap->start = curbuf->b_op_start_orig;
1528 
1529     // If user has moved off this line, we don't know what to do, so do
1530     // nothing.
1531     // Also don't repeat the insert when Insert mode ended with CTRL-C.
1532     if (curwin->w_cursor.lnum != oap->start.lnum || got_int)
1533 	return;
1534 
1535     if (oap->block_mode)
1536     {
1537 	struct block_def	bd2;
1538 	int			did_indent = FALSE;
1539 	size_t			len;
1540 	int			add;
1541 
1542 	// If indent kicked in, the firstline might have changed
1543 	// but only do that, if the indent actually increased.
1544 	ind_post = (colnr_T)getwhitecols_curline();
1545 	if (curbuf->b_op_start.col > ind_pre && ind_post > ind_pre)
1546 	{
1547 	    bd.textcol += ind_post - ind_pre;
1548 	    bd.start_vcol += ind_post - ind_pre;
1549 	    did_indent = TRUE;
1550 	}
1551 
1552 	// The user may have moved the cursor before inserting something, try
1553 	// to adjust the block for that.  But only do it, if the difference
1554 	// does not come from indent kicking in.
1555 	if (oap->start.lnum == curbuf->b_op_start_orig.lnum
1556 						  && !bd.is_MAX && !did_indent)
1557 	{
1558 	    if (oap->op_type == OP_INSERT
1559 		    && oap->start.col + oap->start.coladd
1560 			!= curbuf->b_op_start_orig.col
1561 					      + curbuf->b_op_start_orig.coladd)
1562 	    {
1563 		int t = getviscol2(curbuf->b_op_start_orig.col,
1564 					      curbuf->b_op_start_orig.coladd);
1565 		oap->start.col = curbuf->b_op_start_orig.col;
1566 		pre_textlen -= t - oap->start_vcol;
1567 		oap->start_vcol = t;
1568 	    }
1569 	    else if (oap->op_type == OP_APPEND
1570 		      && oap->end.col + oap->end.coladd
1571 			>= curbuf->b_op_start_orig.col
1572 					      + curbuf->b_op_start_orig.coladd)
1573 	    {
1574 		int t = getviscol2(curbuf->b_op_start_orig.col,
1575 					      curbuf->b_op_start_orig.coladd);
1576 		oap->start.col = curbuf->b_op_start_orig.col;
1577 		// reset pre_textlen to the value of OP_INSERT
1578 		pre_textlen += bd.textlen;
1579 		pre_textlen -= t - oap->start_vcol;
1580 		oap->start_vcol = t;
1581 		oap->op_type = OP_INSERT;
1582 	    }
1583 	}
1584 
1585 	/*
1586 	 * Spaces and tabs in the indent may have changed to other spaces and
1587 	 * tabs.  Get the starting column again and correct the length.
1588 	 * Don't do this when "$" used, end-of-line will have changed.
1589 	 */
1590 	block_prep(oap, &bd2, oap->start.lnum, TRUE);
1591 	if (!bd.is_MAX || bd2.textlen < bd.textlen)
1592 	{
1593 	    if (oap->op_type == OP_APPEND)
1594 	    {
1595 		pre_textlen += bd2.textlen - bd.textlen;
1596 		if (bd2.endspaces)
1597 		    --bd2.textlen;
1598 	    }
1599 	    bd.textcol = bd2.textcol;
1600 	    bd.textlen = bd2.textlen;
1601 	}
1602 
1603 	/*
1604 	 * Subsequent calls to ml_get() flush the firstline data - take a
1605 	 * copy of the required string.
1606 	 */
1607 	firstline = ml_get(oap->start.lnum);
1608 	len = STRLEN(firstline);
1609 	add = bd.textcol;
1610 	if (oap->op_type == OP_APPEND)
1611 	    add += bd.textlen;
1612 	if ((size_t)add > len)
1613 	    firstline += len;  // short line, point to the NUL
1614 	else
1615 	    firstline += add;
1616 	if (pre_textlen >= 0
1617 		     && (ins_len = (long)STRLEN(firstline) - pre_textlen) > 0)
1618 	{
1619 	    ins_text = vim_strnsave(firstline, ins_len);
1620 	    if (ins_text != NULL)
1621 	    {
1622 		// block handled here
1623 		if (u_save(oap->start.lnum,
1624 					 (linenr_T)(oap->end.lnum + 1)) == OK)
1625 		    block_insert(oap, ins_text, (oap->op_type == OP_INSERT),
1626 									 &bd);
1627 
1628 		curwin->w_cursor.col = oap->start.col;
1629 		check_cursor();
1630 		vim_free(ins_text);
1631 	    }
1632 	}
1633     }
1634 }
1635 
1636 /*
1637  * op_change - handle a change operation
1638  *
1639  * return TRUE if edit() returns because of a CTRL-O command
1640  */
1641     int
1642 op_change(oparg_T *oap)
1643 {
1644     colnr_T		l;
1645     int			retval;
1646     long		offset;
1647     linenr_T		linenr;
1648     long		ins_len;
1649     long		pre_textlen = 0;
1650     long		pre_indent = 0;
1651     char_u		*firstline;
1652     char_u		*ins_text, *newp, *oldp;
1653     struct block_def	bd;
1654 
1655     l = oap->start.col;
1656     if (oap->motion_type == MLINE)
1657     {
1658 	l = 0;
1659 #ifdef FEAT_SMARTINDENT
1660 	if (!p_paste && curbuf->b_p_si
1661 # ifdef FEAT_CINDENT
1662 		&& !curbuf->b_p_cin
1663 # endif
1664 		)
1665 	    can_si = TRUE;	// It's like opening a new line, do si
1666 #endif
1667     }
1668 
1669     // First delete the text in the region.  In an empty buffer only need to
1670     // save for undo
1671     if (curbuf->b_ml.ml_flags & ML_EMPTY)
1672     {
1673 	if (u_save_cursor() == FAIL)
1674 	    return FALSE;
1675     }
1676     else if (op_delete(oap) == FAIL)
1677 	return FALSE;
1678 
1679     if ((l > curwin->w_cursor.col) && !LINEEMPTY(curwin->w_cursor.lnum)
1680 							 && !virtual_op)
1681 	inc_cursor();
1682 
1683     // check for still on same line (<CR> in inserted text meaningless)
1684     // skip blank lines too
1685     if (oap->block_mode)
1686     {
1687 	// Add spaces before getting the current line length.
1688 	if (virtual_op && (curwin->w_cursor.coladd > 0
1689 						    || gchar_cursor() == NUL))
1690 	    coladvance_force(getviscol());
1691 	firstline = ml_get(oap->start.lnum);
1692 	pre_textlen = (long)STRLEN(firstline);
1693 	pre_indent = (long)getwhitecols(firstline);
1694 	bd.textcol = curwin->w_cursor.col;
1695     }
1696 
1697 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
1698     if (oap->motion_type == MLINE)
1699 	fix_indent();
1700 #endif
1701 
1702     retval = edit(NUL, FALSE, (linenr_T)1);
1703 
1704     /*
1705      * In Visual block mode, handle copying the new text to all lines of the
1706      * block.
1707      * Don't repeat the insert when Insert mode ended with CTRL-C.
1708      */
1709     if (oap->block_mode && oap->start.lnum != oap->end.lnum && !got_int)
1710     {
1711 	// Auto-indenting may have changed the indent.  If the cursor was past
1712 	// the indent, exclude that indent change from the inserted text.
1713 	firstline = ml_get(oap->start.lnum);
1714 	if (bd.textcol > (colnr_T)pre_indent)
1715 	{
1716 	    long new_indent = (long)getwhitecols(firstline);
1717 
1718 	    pre_textlen += new_indent - pre_indent;
1719 	    bd.textcol += new_indent - pre_indent;
1720 	}
1721 
1722 	ins_len = (long)STRLEN(firstline) - pre_textlen;
1723 	if (ins_len > 0)
1724 	{
1725 	    // Subsequent calls to ml_get() flush the firstline data - take a
1726 	    // copy of the inserted text.
1727 	    if ((ins_text = alloc(ins_len + 1)) != NULL)
1728 	    {
1729 		vim_strncpy(ins_text, firstline + bd.textcol, (size_t)ins_len);
1730 		for (linenr = oap->start.lnum + 1; linenr <= oap->end.lnum;
1731 								     linenr++)
1732 		{
1733 		    block_prep(oap, &bd, linenr, TRUE);
1734 		    if (!bd.is_short || virtual_op)
1735 		    {
1736 			pos_T vpos;
1737 
1738 			// If the block starts in virtual space, count the
1739 			// initial coladd offset as part of "startspaces"
1740 			if (bd.is_short)
1741 			{
1742 			    vpos.lnum = linenr;
1743 			    (void)getvpos(&vpos, oap->start_vcol);
1744 			}
1745 			else
1746 			    vpos.coladd = 0;
1747 			oldp = ml_get(linenr);
1748 			newp = alloc(STRLEN(oldp) + vpos.coladd + ins_len + 1);
1749 			if (newp == NULL)
1750 			    continue;
1751 			// copy up to block start
1752 			mch_memmove(newp, oldp, (size_t)bd.textcol);
1753 			offset = bd.textcol;
1754 			vim_memset(newp + offset, ' ', (size_t)vpos.coladd);
1755 			offset += vpos.coladd;
1756 			mch_memmove(newp + offset, ins_text, (size_t)ins_len);
1757 			offset += ins_len;
1758 			oldp += bd.textcol;
1759 			STRMOVE(newp + offset, oldp);
1760 			ml_replace(linenr, newp, FALSE);
1761 		    }
1762 		}
1763 		check_cursor();
1764 
1765 		changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
1766 	    }
1767 	    vim_free(ins_text);
1768 	}
1769     }
1770 
1771     return retval;
1772 }
1773 
1774 /*
1775  * When the cursor is on the NUL past the end of the line and it should not be
1776  * there move it left.
1777  */
1778     void
1779 adjust_cursor_eol(void)
1780 {
1781     if (curwin->w_cursor.col > 0
1782 	    && gchar_cursor() == NUL
1783 	    && (ve_flags & VE_ONEMORE) == 0
1784 	    && !(restart_edit || (State & INSERT)))
1785     {
1786 	// Put the cursor on the last character in the line.
1787 	dec_cursor();
1788 
1789 	if (ve_flags == VE_ALL)
1790 	{
1791 	    colnr_T	    scol, ecol;
1792 
1793 	    // Coladd is set to the width of the last character.
1794 	    getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
1795 	    curwin->w_cursor.coladd = ecol - scol + 1;
1796 	}
1797     }
1798 }
1799 
1800 /*
1801  * If "process" is TRUE and the line begins with a comment leader (possibly
1802  * after some white space), return a pointer to the text after it. Put a boolean
1803  * value indicating whether the line ends with an unclosed comment in
1804  * "is_comment".
1805  * line - line to be processed,
1806  * process - if FALSE, will only check whether the line ends with an unclosed
1807  *	     comment,
1808  * include_space - whether to also skip space following the comment leader,
1809  * is_comment - will indicate whether the current line ends with an unclosed
1810  *		comment.
1811  */
1812     char_u *
1813 skip_comment(
1814     char_u   *line,
1815     int      process,
1816     int	     include_space,
1817     int      *is_comment)
1818 {
1819     char_u *comment_flags = NULL;
1820     int    lead_len;
1821     int    leader_offset = get_last_leader_offset(line, &comment_flags);
1822 
1823     *is_comment = FALSE;
1824     if (leader_offset != -1)
1825     {
1826 	// Let's check whether the line ends with an unclosed comment.
1827 	// If the last comment leader has COM_END in flags, there's no comment.
1828 	while (*comment_flags)
1829 	{
1830 	    if (*comment_flags == COM_END
1831 		    || *comment_flags == ':')
1832 		break;
1833 	    ++comment_flags;
1834 	}
1835 	if (*comment_flags != COM_END)
1836 	    *is_comment = TRUE;
1837     }
1838 
1839     if (process == FALSE)
1840 	return line;
1841 
1842     lead_len = get_leader_len(line, &comment_flags, FALSE, include_space);
1843 
1844     if (lead_len == 0)
1845 	return line;
1846 
1847     // Find:
1848     // - COM_END,
1849     // - colon,
1850     // whichever comes first.
1851     while (*comment_flags)
1852     {
1853 	if (*comment_flags == COM_END
1854 		|| *comment_flags == ':')
1855 	    break;
1856 	++comment_flags;
1857     }
1858 
1859     // If we found a colon, it means that we are not processing a line
1860     // starting with a closing part of a three-part comment. That's good,
1861     // because we don't want to remove those as this would be annoying.
1862     if (*comment_flags == ':' || *comment_flags == NUL)
1863 	line += lead_len;
1864 
1865     return line;
1866 }
1867 
1868 /*
1869  * Join 'count' lines (minimal 2) at cursor position.
1870  * When "save_undo" is TRUE save lines for undo first.
1871  * Set "use_formatoptions" to FALSE when e.g. processing backspace and comment
1872  * leaders should not be removed.
1873  * When setmark is TRUE, sets the '[ and '] mark, else, the caller is expected
1874  * to set those marks.
1875  *
1876  * return FAIL for failure, OK otherwise
1877  */
1878     int
1879 do_join(
1880     long    count,
1881     int	    insert_space,
1882     int	    save_undo,
1883     int	    use_formatoptions UNUSED,
1884     int	    setmark)
1885 {
1886     char_u	*curr = NULL;
1887     char_u      *curr_start = NULL;
1888     char_u	*cend;
1889     char_u	*newp;
1890     size_t	newp_len;
1891     char_u	*spaces;	// number of spaces inserted before a line
1892     int		endcurr1 = NUL;
1893     int		endcurr2 = NUL;
1894     int		currsize = 0;	// size of the current line
1895     int		sumsize = 0;	// size of the long new line
1896     linenr_T	t;
1897     colnr_T	col = 0;
1898     int		ret = OK;
1899     int		*comments = NULL;
1900     int		remove_comments = (use_formatoptions == TRUE)
1901 				  && has_format_option(FO_REMOVE_COMS);
1902     int		prev_was_comment;
1903 #ifdef FEAT_PROP_POPUP
1904     int		propcount = 0;	// number of props over all joined lines
1905     int		props_remaining;
1906 #endif
1907 
1908     if (save_undo && u_save((linenr_T)(curwin->w_cursor.lnum - 1),
1909 			    (linenr_T)(curwin->w_cursor.lnum + count)) == FAIL)
1910 	return FAIL;
1911 
1912     // Allocate an array to store the number of spaces inserted before each
1913     // line.  We will use it to pre-compute the length of the new line and the
1914     // proper placement of each original line in the new one.
1915     spaces = lalloc_clear(count, TRUE);
1916     if (spaces == NULL)
1917 	return FAIL;
1918     if (remove_comments)
1919     {
1920 	comments = lalloc_clear(count * sizeof(int), TRUE);
1921 	if (comments == NULL)
1922 	{
1923 	    vim_free(spaces);
1924 	    return FAIL;
1925 	}
1926     }
1927 
1928     /*
1929      * Don't move anything yet, just compute the final line length
1930      * and setup the array of space strings lengths
1931      * This loops forward over the joined lines.
1932      */
1933     for (t = 0; t < count; ++t)
1934     {
1935 	curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t));
1936 #ifdef FEAT_PROP_POPUP
1937 	propcount += count_props((linenr_T) (curwin->w_cursor.lnum + t), t > 0);
1938 #endif
1939 	if (t == 0 && setmark && !cmdmod.lockmarks)
1940 	{
1941 	    // Set the '[ mark.
1942 	    curwin->w_buffer->b_op_start.lnum = curwin->w_cursor.lnum;
1943 	    curwin->w_buffer->b_op_start.col  = (colnr_T)STRLEN(curr);
1944 	}
1945 	if (remove_comments)
1946 	{
1947 	    // We don't want to remove the comment leader if the
1948 	    // previous line is not a comment.
1949 	    if (t > 0 && prev_was_comment)
1950 	    {
1951 
1952 		char_u *new_curr = skip_comment(curr, TRUE, insert_space,
1953 							   &prev_was_comment);
1954 		comments[t] = (int)(new_curr - curr);
1955 		curr = new_curr;
1956 	    }
1957 	    else
1958 		curr = skip_comment(curr, FALSE, insert_space,
1959 							   &prev_was_comment);
1960 	}
1961 
1962 	if (insert_space && t > 0)
1963 	{
1964 	    curr = skipwhite(curr);
1965 	    if (*curr != NUL && *curr != ')'
1966 		    && sumsize != 0 && endcurr1 != TAB
1967 		    && (!has_format_option(FO_MBYTE_JOIN)
1968 			|| (mb_ptr2char(curr) < 0x100 && endcurr1 < 0x100))
1969 		    && (!has_format_option(FO_MBYTE_JOIN2)
1970 			|| (mb_ptr2char(curr) < 0x100
1971 			    && !(enc_utf8 && utf_eat_space(endcurr1)))
1972 			|| (endcurr1 < 0x100
1973 			    && !(enc_utf8 && utf_eat_space(mb_ptr2char(curr)))))
1974 	       )
1975 	    {
1976 		// don't add a space if the line is ending in a space
1977 		if (endcurr1 == ' ')
1978 		    endcurr1 = endcurr2;
1979 		else
1980 		    ++spaces[t];
1981 		// extra space when 'joinspaces' set and line ends in '.'
1982 		if (       p_js
1983 			&& (endcurr1 == '.'
1984 			    || (vim_strchr(p_cpo, CPO_JOINSP) == NULL
1985 				&& (endcurr1 == '?' || endcurr1 == '!'))))
1986 		    ++spaces[t];
1987 	    }
1988 	}
1989 	currsize = (int)STRLEN(curr);
1990 	sumsize += currsize + spaces[t];
1991 	endcurr1 = endcurr2 = NUL;
1992 	if (insert_space && currsize > 0)
1993 	{
1994 	    if (has_mbyte)
1995 	    {
1996 		cend = curr + currsize;
1997 		MB_PTR_BACK(curr, cend);
1998 		endcurr1 = (*mb_ptr2char)(cend);
1999 		if (cend > curr)
2000 		{
2001 		    MB_PTR_BACK(curr, cend);
2002 		    endcurr2 = (*mb_ptr2char)(cend);
2003 		}
2004 	    }
2005 	    else
2006 	    {
2007 		endcurr1 = *(curr + currsize - 1);
2008 		if (currsize > 1)
2009 		    endcurr2 = *(curr + currsize - 2);
2010 	    }
2011 	}
2012 	line_breakcheck();
2013 	if (got_int)
2014 	{
2015 	    ret = FAIL;
2016 	    goto theend;
2017 	}
2018     }
2019 
2020     // store the column position before last line
2021     col = sumsize - currsize - spaces[count - 1];
2022 
2023     // allocate the space for the new line
2024     newp_len = sumsize + 1;
2025 #ifdef FEAT_PROP_POPUP
2026     newp_len += propcount * sizeof(textprop_T);
2027 #endif
2028     newp = alloc(newp_len);
2029     if (newp == NULL)
2030     {
2031 	ret = FAIL;
2032 	goto theend;
2033     }
2034     cend = newp + sumsize;
2035     *cend = 0;
2036 
2037     /*
2038      * Move affected lines to the new long one.
2039      * This loops backwards over the joined lines, including the original line.
2040      *
2041      * Move marks from each deleted line to the joined line, adjusting the
2042      * column.  This is not Vi compatible, but Vi deletes the marks, thus that
2043      * should not really be a problem.
2044      */
2045 #ifdef FEAT_PROP_POPUP
2046     props_remaining = propcount;
2047 #endif
2048     for (t = count - 1; ; --t)
2049     {
2050 	int spaces_removed;
2051 
2052 	cend -= currsize;
2053 	mch_memmove(cend, curr, (size_t)currsize);
2054 
2055 	if (spaces[t] > 0)
2056 	{
2057 	    cend -= spaces[t];
2058 	    vim_memset(cend, ' ', (size_t)(spaces[t]));
2059 	}
2060 
2061 	// If deleting more spaces than adding, the cursor moves no more than
2062 	// what is added if it is inside these spaces.
2063 	spaces_removed = (curr - curr_start) - spaces[t];
2064 
2065 	mark_col_adjust(curwin->w_cursor.lnum + t, (colnr_T)0, (linenr_T)-t,
2066 			 (long)(cend - newp - spaces_removed), spaces_removed);
2067 #ifdef FEAT_PROP_POPUP
2068 	prepend_joined_props(newp + sumsize + 1, propcount, &props_remaining,
2069 		curwin->w_cursor.lnum + t, t == count - 1,
2070 		(long)(cend - newp), spaces_removed);
2071 #endif
2072 
2073 	if (t == 0)
2074 	    break;
2075 	curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1));
2076 	if (remove_comments)
2077 	    curr += comments[t - 1];
2078 	if (insert_space && t > 1)
2079 	    curr = skipwhite(curr);
2080 	currsize = (int)STRLEN(curr);
2081     }
2082 
2083     ml_replace_len(curwin->w_cursor.lnum, newp, (colnr_T)newp_len, TRUE, FALSE);
2084 
2085     if (setmark && !cmdmod.lockmarks)
2086     {
2087 	// Set the '] mark.
2088 	curwin->w_buffer->b_op_end.lnum = curwin->w_cursor.lnum;
2089 	curwin->w_buffer->b_op_end.col  = (colnr_T)sumsize;
2090     }
2091 
2092     // Only report the change in the first line here, del_lines() will report
2093     // the deleted line.
2094     changed_lines(curwin->w_cursor.lnum, currsize,
2095 					       curwin->w_cursor.lnum + 1, 0L);
2096     /*
2097      * Delete following lines. To do this we move the cursor there
2098      * briefly, and then move it back. After del_lines() the cursor may
2099      * have moved up (last line deleted), so the current lnum is kept in t.
2100      */
2101     t = curwin->w_cursor.lnum;
2102     ++curwin->w_cursor.lnum;
2103     del_lines(count - 1, FALSE);
2104     curwin->w_cursor.lnum = t;
2105 
2106     /*
2107      * Set the cursor column:
2108      * Vi compatible: use the column of the first join
2109      * vim:	      use the column of the last join
2110      */
2111     curwin->w_cursor.col =
2112 		    (vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col);
2113     check_cursor_col();
2114 
2115     curwin->w_cursor.coladd = 0;
2116     curwin->w_set_curswant = TRUE;
2117 
2118 theend:
2119     vim_free(spaces);
2120     if (remove_comments)
2121 	vim_free(comments);
2122     return ret;
2123 }
2124 
2125 /*
2126  * prepare a few things for block mode yank/delete/tilde
2127  *
2128  * for delete:
2129  * - textlen includes the first/last char to be (partly) deleted
2130  * - start/endspaces is the number of columns that are taken by the
2131  *   first/last deleted char minus the number of columns that have to be
2132  *   deleted.
2133  * for yank and tilde:
2134  * - textlen includes the first/last char to be wholly yanked
2135  * - start/endspaces is the number of columns of the first/last yanked char
2136  *   that are to be yanked.
2137  */
2138     void
2139 block_prep(
2140     oparg_T		*oap,
2141     struct block_def	*bdp,
2142     linenr_T		lnum,
2143     int			is_del)
2144 {
2145     int		incr = 0;
2146     char_u	*pend;
2147     char_u	*pstart;
2148     char_u	*line;
2149     char_u	*prev_pstart;
2150     char_u	*prev_pend;
2151 #ifdef FEAT_LINEBREAK
2152     int		lbr_saved = curwin->w_p_lbr;
2153 
2154     // Avoid a problem with unwanted linebreaks in block mode.
2155     curwin->w_p_lbr = FALSE;
2156 #endif
2157     bdp->startspaces = 0;
2158     bdp->endspaces = 0;
2159     bdp->textlen = 0;
2160     bdp->start_vcol = 0;
2161     bdp->end_vcol = 0;
2162     bdp->is_short = FALSE;
2163     bdp->is_oneChar = FALSE;
2164     bdp->pre_whitesp = 0;
2165     bdp->pre_whitesp_c = 0;
2166     bdp->end_char_vcols = 0;
2167     bdp->start_char_vcols = 0;
2168 
2169     line = ml_get(lnum);
2170     pstart = line;
2171     prev_pstart = line;
2172     while (bdp->start_vcol < oap->start_vcol && *pstart)
2173     {
2174 	// Count a tab for what it's worth (if list mode not on)
2175 	incr = lbr_chartabsize(line, pstart, (colnr_T)bdp->start_vcol);
2176 	bdp->start_vcol += incr;
2177 	if (VIM_ISWHITE(*pstart))
2178 	{
2179 	    bdp->pre_whitesp += incr;
2180 	    bdp->pre_whitesp_c++;
2181 	}
2182 	else
2183 	{
2184 	    bdp->pre_whitesp = 0;
2185 	    bdp->pre_whitesp_c = 0;
2186 	}
2187 	prev_pstart = pstart;
2188 	MB_PTR_ADV(pstart);
2189     }
2190     bdp->start_char_vcols = incr;
2191     if (bdp->start_vcol < oap->start_vcol)	// line too short
2192     {
2193 	bdp->end_vcol = bdp->start_vcol;
2194 	bdp->is_short = TRUE;
2195 	if (!is_del || oap->op_type == OP_APPEND)
2196 	    bdp->endspaces = oap->end_vcol - oap->start_vcol + 1;
2197     }
2198     else
2199     {
2200 	// notice: this converts partly selected Multibyte characters to
2201 	// spaces, too.
2202 	bdp->startspaces = bdp->start_vcol - oap->start_vcol;
2203 	if (is_del && bdp->startspaces)
2204 	    bdp->startspaces = bdp->start_char_vcols - bdp->startspaces;
2205 	pend = pstart;
2206 	bdp->end_vcol = bdp->start_vcol;
2207 	if (bdp->end_vcol > oap->end_vcol)	// it's all in one character
2208 	{
2209 	    bdp->is_oneChar = TRUE;
2210 	    if (oap->op_type == OP_INSERT)
2211 		bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
2212 	    else if (oap->op_type == OP_APPEND)
2213 	    {
2214 		bdp->startspaces += oap->end_vcol - oap->start_vcol + 1;
2215 		bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
2216 	    }
2217 	    else
2218 	    {
2219 		bdp->startspaces = oap->end_vcol - oap->start_vcol + 1;
2220 		if (is_del && oap->op_type != OP_LSHIFT)
2221 		{
2222 		    // just putting the sum of those two into
2223 		    // bdp->startspaces doesn't work for Visual replace,
2224 		    // so we have to split the tab in two
2225 		    bdp->startspaces = bdp->start_char_vcols
2226 					- (bdp->start_vcol - oap->start_vcol);
2227 		    bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
2228 		}
2229 	    }
2230 	}
2231 	else
2232 	{
2233 	    prev_pend = pend;
2234 	    while (bdp->end_vcol <= oap->end_vcol && *pend != NUL)
2235 	    {
2236 		// Count a tab for what it's worth (if list mode not on)
2237 		prev_pend = pend;
2238 		incr = lbr_chartabsize_adv(line, &pend, (colnr_T)bdp->end_vcol);
2239 		bdp->end_vcol += incr;
2240 	    }
2241 	    if (bdp->end_vcol <= oap->end_vcol
2242 		    && (!is_del
2243 			|| oap->op_type == OP_APPEND
2244 			|| oap->op_type == OP_REPLACE)) // line too short
2245 	    {
2246 		bdp->is_short = TRUE;
2247 		// Alternative: include spaces to fill up the block.
2248 		// Disadvantage: can lead to trailing spaces when the line is
2249 		// short where the text is put
2250 		// if (!is_del || oap->op_type == OP_APPEND)
2251 		if (oap->op_type == OP_APPEND || virtual_op)
2252 		    bdp->endspaces = oap->end_vcol - bdp->end_vcol
2253 							     + oap->inclusive;
2254 		else
2255 		    bdp->endspaces = 0; // replace doesn't add characters
2256 	    }
2257 	    else if (bdp->end_vcol > oap->end_vcol)
2258 	    {
2259 		bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
2260 		if (!is_del && bdp->endspaces)
2261 		{
2262 		    bdp->endspaces = incr - bdp->endspaces;
2263 		    if (pend != pstart)
2264 			pend = prev_pend;
2265 		}
2266 	    }
2267 	}
2268 	bdp->end_char_vcols = incr;
2269 	if (is_del && bdp->startspaces)
2270 	    pstart = prev_pstart;
2271 	bdp->textlen = (int)(pend - pstart);
2272     }
2273     bdp->textcol = (colnr_T) (pstart - line);
2274     bdp->textstart = pstart;
2275 #ifdef FEAT_LINEBREAK
2276     curwin->w_p_lbr = lbr_saved;
2277 #endif
2278 }
2279 
2280 /*
2281  * Handle the add/subtract operator.
2282  */
2283     void
2284 op_addsub(
2285     oparg_T	*oap,
2286     linenr_T	Prenum1,	    // Amount of add/subtract
2287     int		g_cmd)		    // was g<c-a>/g<c-x>
2288 {
2289     pos_T		pos;
2290     struct block_def	bd;
2291     int			change_cnt = 0;
2292     linenr_T		amount = Prenum1;
2293 
2294    // do_addsub() might trigger re-evaluation of 'foldexpr' halfway, when the
2295    // buffer is not completely updated yet. Postpone updating folds until before
2296    // the call to changed_lines().
2297 #ifdef FEAT_FOLDING
2298    disable_fold_update++;
2299 #endif
2300 
2301     if (!VIsual_active)
2302     {
2303 	pos = curwin->w_cursor;
2304 	if (u_save_cursor() == FAIL)
2305 	{
2306 #ifdef FEAT_FOLDING
2307 	    disable_fold_update--;
2308 #endif
2309 	    return;
2310 	}
2311 	change_cnt = do_addsub(oap->op_type, &pos, 0, amount);
2312 #ifdef FEAT_FOLDING
2313 	disable_fold_update--;
2314 #endif
2315 	if (change_cnt)
2316 	    changed_lines(pos.lnum, 0, pos.lnum + 1, 0L);
2317     }
2318     else
2319     {
2320 	int	one_change;
2321 	int	length;
2322 	pos_T	startpos;
2323 
2324 	if (u_save((linenr_T)(oap->start.lnum - 1),
2325 					(linenr_T)(oap->end.lnum + 1)) == FAIL)
2326 	{
2327 #ifdef FEAT_FOLDING
2328 	    disable_fold_update--;
2329 #endif
2330 	    return;
2331 	}
2332 
2333 	pos = oap->start;
2334 	for (; pos.lnum <= oap->end.lnum; ++pos.lnum)
2335 	{
2336 	    if (oap->block_mode)		    // Visual block mode
2337 	    {
2338 		block_prep(oap, &bd, pos.lnum, FALSE);
2339 		pos.col = bd.textcol;
2340 		length = bd.textlen;
2341 	    }
2342 	    else if (oap->motion_type == MLINE)
2343 	    {
2344 		curwin->w_cursor.col = 0;
2345 		pos.col = 0;
2346 		length = (colnr_T)STRLEN(ml_get(pos.lnum));
2347 	    }
2348 	    else // oap->motion_type == MCHAR
2349 	    {
2350 		if (pos.lnum == oap->start.lnum && !oap->inclusive)
2351 		    dec(&(oap->end));
2352 		length = (colnr_T)STRLEN(ml_get(pos.lnum));
2353 		pos.col = 0;
2354 		if (pos.lnum == oap->start.lnum)
2355 		{
2356 		    pos.col += oap->start.col;
2357 		    length -= oap->start.col;
2358 		}
2359 		if (pos.lnum == oap->end.lnum)
2360 		{
2361 		    length = (int)STRLEN(ml_get(oap->end.lnum));
2362 		    if (oap->end.col >= length)
2363 			oap->end.col = length - 1;
2364 		    length = oap->end.col - pos.col + 1;
2365 		}
2366 	    }
2367 	    one_change = do_addsub(oap->op_type, &pos, length, amount);
2368 	    if (one_change)
2369 	    {
2370 		// Remember the start position of the first change.
2371 		if (change_cnt == 0)
2372 		    startpos = curbuf->b_op_start;
2373 		++change_cnt;
2374 	    }
2375 
2376 #ifdef FEAT_NETBEANS_INTG
2377 	    if (netbeans_active() && one_change)
2378 	    {
2379 		char_u *ptr = ml_get_buf(curbuf, pos.lnum, FALSE);
2380 
2381 		netbeans_removed(curbuf, pos.lnum, pos.col, (long)length);
2382 		netbeans_inserted(curbuf, pos.lnum, pos.col,
2383 						&ptr[pos.col], length);
2384 	    }
2385 #endif
2386 	    if (g_cmd && one_change)
2387 		amount += Prenum1;
2388 	}
2389 
2390 #ifdef FEAT_FOLDING
2391 	disable_fold_update--;
2392 #endif
2393 	if (change_cnt)
2394 	    changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L);
2395 
2396 	if (!change_cnt && oap->is_VIsual)
2397 	    // No change: need to remove the Visual selection
2398 	    redraw_curbuf_later(INVERTED);
2399 
2400 	// Set '[ mark if something changed. Keep the last end
2401 	// position from do_addsub().
2402 	if (change_cnt > 0 && !cmdmod.lockmarks)
2403 	    curbuf->b_op_start = startpos;
2404 
2405 	if (change_cnt > p_report)
2406 	    smsg(NGETTEXT("%d line changed", "%d lines changed",
2407 						      change_cnt), change_cnt);
2408     }
2409 }
2410 
2411 /*
2412  * Add or subtract 'Prenum1' from a number in a line
2413  * op_type is OP_NR_ADD or OP_NR_SUB
2414  *
2415  * Returns TRUE if some character was changed.
2416  */
2417     static int
2418 do_addsub(
2419     int		op_type,
2420     pos_T	*pos,
2421     int		length,
2422     linenr_T	Prenum1)
2423 {
2424     int		col;
2425     char_u	*buf1;
2426     char_u	buf2[NUMBUFLEN];
2427     int		pre;		// 'X'/'x': hex; '0': octal; 'B'/'b': bin
2428     static int	hexupper = FALSE;	// 0xABC
2429     uvarnumber_T	n;
2430     uvarnumber_T	oldn;
2431     char_u	*ptr;
2432     int		c;
2433     int		todel;
2434     int		do_hex;
2435     int		do_oct;
2436     int		do_bin;
2437     int		do_alpha;
2438     int		do_unsigned;
2439     int		firstdigit;
2440     int		subtract;
2441     int		negative = FALSE;
2442     int		was_positive = TRUE;
2443     int		visual = VIsual_active;
2444     int		did_change = FALSE;
2445     pos_T	save_cursor = curwin->w_cursor;
2446     int		maxlen = 0;
2447     pos_T	startpos;
2448     pos_T	endpos;
2449     colnr_T	save_coladd = 0;
2450 
2451     do_hex = (vim_strchr(curbuf->b_p_nf, 'x') != NULL);	// "heX"
2452     do_oct = (vim_strchr(curbuf->b_p_nf, 'o') != NULL);	// "Octal"
2453     do_bin = (vim_strchr(curbuf->b_p_nf, 'b') != NULL);	// "Bin"
2454     do_alpha = (vim_strchr(curbuf->b_p_nf, 'p') != NULL);	// "alPha"
2455     do_unsigned = (vim_strchr(curbuf->b_p_nf, 'u') != NULL);	// "Unsigned"
2456 
2457     if (virtual_active())
2458     {
2459 	save_coladd = pos->coladd;
2460 	pos->coladd = 0;
2461     }
2462 
2463     curwin->w_cursor = *pos;
2464     ptr = ml_get(pos->lnum);
2465     col = pos->col;
2466 
2467     if (*ptr == NUL || col + !!save_coladd >= (int)STRLEN(ptr))
2468 	goto theend;
2469 
2470     /*
2471      * First check if we are on a hexadecimal number, after the "0x".
2472      */
2473     if (!VIsual_active)
2474     {
2475 	if (do_bin)
2476 	    while (col > 0 && vim_isbdigit(ptr[col]))
2477 	    {
2478 		--col;
2479 		if (has_mbyte)
2480 		    col -= (*mb_head_off)(ptr, ptr + col);
2481 	    }
2482 
2483 	if (do_hex)
2484 	    while (col > 0 && vim_isxdigit(ptr[col]))
2485 	    {
2486 		--col;
2487 		if (has_mbyte)
2488 		    col -= (*mb_head_off)(ptr, ptr + col);
2489 	    }
2490 
2491 	if (       do_bin
2492 		&& do_hex
2493 		&& ! ((col > 0
2494 		    && (ptr[col] == 'X'
2495 			|| ptr[col] == 'x')
2496 		    && ptr[col - 1] == '0'
2497 		    && (!has_mbyte ||
2498 			!(*mb_head_off)(ptr, ptr + col - 1))
2499 		    && vim_isxdigit(ptr[col + 1]))))
2500 	{
2501 
2502 	    // In case of binary/hexadecimal pattern overlap match, rescan
2503 
2504 	    col = pos->col;
2505 
2506 	    while (col > 0 && vim_isdigit(ptr[col]))
2507 	    {
2508 		col--;
2509 		if (has_mbyte)
2510 		    col -= (*mb_head_off)(ptr, ptr + col);
2511 	    }
2512 	}
2513 
2514 	if ((       do_hex
2515 		&& col > 0
2516 		&& (ptr[col] == 'X'
2517 		    || ptr[col] == 'x')
2518 		&& ptr[col - 1] == '0'
2519 		&& (!has_mbyte ||
2520 		    !(*mb_head_off)(ptr, ptr + col - 1))
2521 		&& vim_isxdigit(ptr[col + 1])) ||
2522 	    (       do_bin
2523 		&& col > 0
2524 		&& (ptr[col] == 'B'
2525 		    || ptr[col] == 'b')
2526 		&& ptr[col - 1] == '0'
2527 		&& (!has_mbyte ||
2528 		    !(*mb_head_off)(ptr, ptr + col - 1))
2529 		&& vim_isbdigit(ptr[col + 1])))
2530 	{
2531 	    // Found hexadecimal or binary number, move to its start.
2532 	    --col;
2533 	    if (has_mbyte)
2534 		col -= (*mb_head_off)(ptr, ptr + col);
2535 	}
2536 	else
2537 	{
2538 	    /*
2539 	     * Search forward and then backward to find the start of number.
2540 	     */
2541 	    col = pos->col;
2542 
2543 	    while (ptr[col] != NUL
2544 		    && !vim_isdigit(ptr[col])
2545 		    && !(do_alpha && ASCII_ISALPHA(ptr[col])))
2546 		col += mb_ptr2len(ptr + col);
2547 
2548 	    while (col > 0
2549 		    && vim_isdigit(ptr[col - 1])
2550 		    && !(do_alpha && ASCII_ISALPHA(ptr[col])))
2551 	    {
2552 		--col;
2553 		if (has_mbyte)
2554 		    col -= (*mb_head_off)(ptr, ptr + col);
2555 	    }
2556 	}
2557     }
2558 
2559     if (visual)
2560     {
2561 	while (ptr[col] != NUL && length > 0
2562 		&& !vim_isdigit(ptr[col])
2563 		&& !(do_alpha && ASCII_ISALPHA(ptr[col])))
2564 	{
2565 	    int mb_len = mb_ptr2len(ptr + col);
2566 
2567 	    col += mb_len;
2568 	    length -= mb_len;
2569 	}
2570 
2571 	if (length == 0)
2572 	    goto theend;
2573 
2574 	if (col > pos->col && ptr[col - 1] == '-'
2575 		&& (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1))
2576 		&& !do_unsigned)
2577 	{
2578 	    negative = TRUE;
2579 	    was_positive = FALSE;
2580 	}
2581     }
2582 
2583     /*
2584      * If a number was found, and saving for undo works, replace the number.
2585      */
2586     firstdigit = ptr[col];
2587     if (!VIM_ISDIGIT(firstdigit) && !(do_alpha && ASCII_ISALPHA(firstdigit)))
2588     {
2589 	beep_flush();
2590 	goto theend;
2591     }
2592 
2593     if (do_alpha && ASCII_ISALPHA(firstdigit))
2594     {
2595 	// decrement or increment alphabetic character
2596 	if (op_type == OP_NR_SUB)
2597 	{
2598 	    if (CharOrd(firstdigit) < Prenum1)
2599 	    {
2600 		if (isupper(firstdigit))
2601 		    firstdigit = 'A';
2602 		else
2603 		    firstdigit = 'a';
2604 	    }
2605 	    else
2606 #ifdef EBCDIC
2607 		firstdigit = EBCDIC_CHAR_ADD(firstdigit, -Prenum1);
2608 #else
2609 		firstdigit -= Prenum1;
2610 #endif
2611 	}
2612 	else
2613 	{
2614 	    if (26 - CharOrd(firstdigit) - 1 < Prenum1)
2615 	    {
2616 		if (isupper(firstdigit))
2617 		    firstdigit = 'Z';
2618 		else
2619 		    firstdigit = 'z';
2620 	    }
2621 	    else
2622 #ifdef EBCDIC
2623 		firstdigit = EBCDIC_CHAR_ADD(firstdigit, Prenum1);
2624 #else
2625 		firstdigit += Prenum1;
2626 #endif
2627 	}
2628 	curwin->w_cursor.col = col;
2629 	if (!did_change)
2630 	    startpos = curwin->w_cursor;
2631 	did_change = TRUE;
2632 	(void)del_char(FALSE);
2633 	ins_char(firstdigit);
2634 	endpos = curwin->w_cursor;
2635 	curwin->w_cursor.col = col;
2636     }
2637     else
2638     {
2639 	if (col > 0 && ptr[col - 1] == '-'
2640 		&& (!has_mbyte ||
2641 		    !(*mb_head_off)(ptr, ptr + col - 1))
2642 		&& !visual
2643 		&& !do_unsigned)
2644 	{
2645 	    // negative number
2646 	    --col;
2647 	    negative = TRUE;
2648 	}
2649 	// get the number value (unsigned)
2650 	if (visual && VIsual_mode != 'V')
2651 	    maxlen = (curbuf->b_visual.vi_curswant == MAXCOL
2652 		    ? (int)STRLEN(ptr) - col
2653 		    : length);
2654 
2655 	vim_str2nr(ptr + col, &pre, &length,
2656 		0 + (do_bin ? STR2NR_BIN : 0)
2657 		    + (do_oct ? STR2NR_OCT : 0)
2658 		    + (do_hex ? STR2NR_HEX : 0),
2659 		NULL, &n, maxlen, FALSE);
2660 
2661 	// ignore leading '-' for hex and octal and bin numbers
2662 	if (pre && negative)
2663 	{
2664 	    ++col;
2665 	    --length;
2666 	    negative = FALSE;
2667 	}
2668 	// add or subtract
2669 	subtract = FALSE;
2670 	if (op_type == OP_NR_SUB)
2671 	    subtract ^= TRUE;
2672 	if (negative)
2673 	    subtract ^= TRUE;
2674 
2675 	oldn = n;
2676 	if (subtract)
2677 	    n -= (uvarnumber_T)Prenum1;
2678 	else
2679 	    n += (uvarnumber_T)Prenum1;
2680 	// handle wraparound for decimal numbers
2681 	if (!pre)
2682 	{
2683 	    if (subtract)
2684 	    {
2685 		if (n > oldn)
2686 		{
2687 		    n = 1 + (n ^ (uvarnumber_T)-1);
2688 		    negative ^= TRUE;
2689 		}
2690 	    }
2691 	    else
2692 	    {
2693 		// add
2694 		if (n < oldn)
2695 		{
2696 		    n = (n ^ (uvarnumber_T)-1);
2697 		    negative ^= TRUE;
2698 		}
2699 	    }
2700 	    if (n == 0)
2701 		negative = FALSE;
2702 	}
2703 
2704 	if (do_unsigned && negative)
2705 	{
2706 	    if (subtract)
2707 		// sticking at zero.
2708 		n = (uvarnumber_T)0;
2709 	    else
2710 		// sticking at 2^64 - 1.
2711 		n = (uvarnumber_T)(-1);
2712 	    negative = FALSE;
2713 	}
2714 
2715 	if (visual && !was_positive && !negative && col > 0)
2716 	{
2717 	    // need to remove the '-'
2718 	    col--;
2719 	    length++;
2720 	}
2721 
2722 	/*
2723 	 * Delete the old number.
2724 	 */
2725 	curwin->w_cursor.col = col;
2726 	if (!did_change)
2727 	    startpos = curwin->w_cursor;
2728 	did_change = TRUE;
2729 	todel = length;
2730 	c = gchar_cursor();
2731 	/*
2732 	 * Don't include the '-' in the length, only the length of the
2733 	 * part after it is kept the same.
2734 	 */
2735 	if (c == '-')
2736 	    --length;
2737 	while (todel-- > 0)
2738 	{
2739 	    if (c < 0x100 && isalpha(c))
2740 	    {
2741 		if (isupper(c))
2742 		    hexupper = TRUE;
2743 		else
2744 		    hexupper = FALSE;
2745 	    }
2746 	    // del_char() will mark line needing displaying
2747 	    (void)del_char(FALSE);
2748 	    c = gchar_cursor();
2749 	}
2750 
2751 	/*
2752 	 * Prepare the leading characters in buf1[].
2753 	 * When there are many leading zeros it could be very long.
2754 	 * Allocate a bit too much.
2755 	 */
2756 	buf1 = alloc(length + NUMBUFLEN);
2757 	if (buf1 == NULL)
2758 	    goto theend;
2759 	ptr = buf1;
2760 	if (negative && (!visual || was_positive))
2761 	    *ptr++ = '-';
2762 	if (pre)
2763 	{
2764 	    *ptr++ = '0';
2765 	    --length;
2766 	}
2767 	if (pre == 'b' || pre == 'B' ||
2768 	    pre == 'x' || pre == 'X')
2769 	{
2770 	    *ptr++ = pre;
2771 	    --length;
2772 	}
2773 
2774 	/*
2775 	 * Put the number characters in buf2[].
2776 	 */
2777 	if (pre == 'b' || pre == 'B')
2778 	{
2779 	    int i;
2780 	    int bit = 0;
2781 	    int bits = sizeof(uvarnumber_T) * 8;
2782 
2783 	    // leading zeros
2784 	    for (bit = bits; bit > 0; bit--)
2785 		if ((n >> (bit - 1)) & 0x1) break;
2786 
2787 	    for (i = 0; bit > 0; bit--)
2788 		buf2[i++] = ((n >> (bit - 1)) & 0x1) ? '1' : '0';
2789 
2790 	    buf2[i] = '\0';
2791 	}
2792 	else if (pre == 0)
2793 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llu", (uvarnumber_T)n);
2794 	else if (pre == '0')
2795 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llo", (uvarnumber_T)n);
2796 	else if (pre && hexupper)
2797 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llX", (uvarnumber_T)n);
2798 	else
2799 	    vim_snprintf((char *)buf2, NUMBUFLEN, "%llx", (uvarnumber_T)n);
2800 	length -= (int)STRLEN(buf2);
2801 
2802 	/*
2803 	 * Adjust number of zeros to the new number of digits, so the
2804 	 * total length of the number remains the same.
2805 	 * Don't do this when
2806 	 * the result may look like an octal number.
2807 	 */
2808 	if (firstdigit == '0' && !(do_oct && pre == 0))
2809 	    while (length-- > 0)
2810 		*ptr++ = '0';
2811 	*ptr = NUL;
2812 	STRCAT(buf1, buf2);
2813 	ins_str(buf1);		// insert the new number
2814 	vim_free(buf1);
2815 	endpos = curwin->w_cursor;
2816 	if (did_change && curwin->w_cursor.col)
2817 	    --curwin->w_cursor.col;
2818     }
2819 
2820     if (did_change && !cmdmod.lockmarks)
2821     {
2822 	// set the '[ and '] marks
2823 	curbuf->b_op_start = startpos;
2824 	curbuf->b_op_end = endpos;
2825 	if (curbuf->b_op_end.col > 0)
2826 	    --curbuf->b_op_end.col;
2827     }
2828 
2829 theend:
2830     if (visual)
2831 	curwin->w_cursor = save_cursor;
2832     else if (did_change)
2833 	curwin->w_set_curswant = TRUE;
2834     else if (virtual_active())
2835 	curwin->w_cursor.coladd = save_coladd;
2836 
2837     return did_change;
2838 }
2839 
2840     void
2841 clear_oparg(oparg_T *oap)
2842 {
2843     CLEAR_POINTER(oap);
2844 }
2845 
2846 /*
2847  *  Count the number of bytes, characters and "words" in a line.
2848  *
2849  *  "Words" are counted by looking for boundaries between non-space and
2850  *  space characters.  (it seems to produce results that match 'wc'.)
2851  *
2852  *  Return value is byte count; word count for the line is added to "*wc".
2853  *  Char count is added to "*cc".
2854  *
2855  *  The function will only examine the first "limit" characters in the
2856  *  line, stopping if it encounters an end-of-line (NUL byte).  In that
2857  *  case, eol_size will be added to the character count to account for
2858  *  the size of the EOL character.
2859  */
2860     static varnumber_T
2861 line_count_info(
2862     char_u	*line,
2863     varnumber_T	*wc,
2864     varnumber_T	*cc,
2865     varnumber_T	limit,
2866     int		eol_size)
2867 {
2868     varnumber_T	i;
2869     varnumber_T	words = 0;
2870     varnumber_T	chars = 0;
2871     int		is_word = 0;
2872 
2873     for (i = 0; i < limit && line[i] != NUL; )
2874     {
2875 	if (is_word)
2876 	{
2877 	    if (vim_isspace(line[i]))
2878 	    {
2879 		words++;
2880 		is_word = 0;
2881 	    }
2882 	}
2883 	else if (!vim_isspace(line[i]))
2884 	    is_word = 1;
2885 	++chars;
2886 	i += (*mb_ptr2len)(line + i);
2887     }
2888 
2889     if (is_word)
2890 	words++;
2891     *wc += words;
2892 
2893     // Add eol_size if the end of line was reached before hitting limit.
2894     if (i < limit && line[i] == NUL)
2895     {
2896 	i += eol_size;
2897 	chars += eol_size;
2898     }
2899     *cc += chars;
2900     return i;
2901 }
2902 
2903 /*
2904  * Give some info about the position of the cursor (for "g CTRL-G").
2905  * In Visual mode, give some info about the selected region.  (In this case,
2906  * the *_count_cursor variables store running totals for the selection.)
2907  * When "dict" is not NULL store the info there instead of showing it.
2908  */
2909     void
2910 cursor_pos_info(dict_T *dict)
2911 {
2912     char_u	*p;
2913     char_u	buf1[50];
2914     char_u	buf2[40];
2915     linenr_T	lnum;
2916     varnumber_T	byte_count = 0;
2917     varnumber_T	bom_count  = 0;
2918     varnumber_T	byte_count_cursor = 0;
2919     varnumber_T	char_count = 0;
2920     varnumber_T	char_count_cursor = 0;
2921     varnumber_T	word_count = 0;
2922     varnumber_T	word_count_cursor = 0;
2923     int		eol_size;
2924     varnumber_T	last_check = 100000L;
2925     long	line_count_selected = 0;
2926     pos_T	min_pos, max_pos;
2927     oparg_T	oparg;
2928     struct block_def	bd;
2929 
2930     /*
2931      * Compute the length of the file in characters.
2932      */
2933     if (curbuf->b_ml.ml_flags & ML_EMPTY)
2934     {
2935 	if (dict == NULL)
2936 	{
2937 	    msg(_(no_lines_msg));
2938 	    return;
2939 	}
2940     }
2941     else
2942     {
2943 	if (get_fileformat(curbuf) == EOL_DOS)
2944 	    eol_size = 2;
2945 	else
2946 	    eol_size = 1;
2947 
2948 	if (VIsual_active)
2949 	{
2950 	    if (LT_POS(VIsual, curwin->w_cursor))
2951 	    {
2952 		min_pos = VIsual;
2953 		max_pos = curwin->w_cursor;
2954 	    }
2955 	    else
2956 	    {
2957 		min_pos = curwin->w_cursor;
2958 		max_pos = VIsual;
2959 	    }
2960 	    if (*p_sel == 'e' && max_pos.col > 0)
2961 		--max_pos.col;
2962 
2963 	    if (VIsual_mode == Ctrl_V)
2964 	    {
2965 #ifdef FEAT_LINEBREAK
2966 		char_u * saved_sbr = p_sbr;
2967 		char_u * saved_w_sbr = curwin->w_p_sbr;
2968 
2969 		// Make 'sbr' empty for a moment to get the correct size.
2970 		p_sbr = empty_option;
2971 		curwin->w_p_sbr = empty_option;
2972 #endif
2973 		oparg.is_VIsual = 1;
2974 		oparg.block_mode = TRUE;
2975 		oparg.op_type = OP_NOP;
2976 		getvcols(curwin, &min_pos, &max_pos,
2977 					  &oparg.start_vcol, &oparg.end_vcol);
2978 #ifdef FEAT_LINEBREAK
2979 		p_sbr = saved_sbr;
2980 		curwin->w_p_sbr = saved_w_sbr;
2981 #endif
2982 		if (curwin->w_curswant == MAXCOL)
2983 		    oparg.end_vcol = MAXCOL;
2984 		// Swap the start, end vcol if needed
2985 		if (oparg.end_vcol < oparg.start_vcol)
2986 		{
2987 		    oparg.end_vcol += oparg.start_vcol;
2988 		    oparg.start_vcol = oparg.end_vcol - oparg.start_vcol;
2989 		    oparg.end_vcol -= oparg.start_vcol;
2990 		}
2991 	    }
2992 	    line_count_selected = max_pos.lnum - min_pos.lnum + 1;
2993 	}
2994 
2995 	for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
2996 	{
2997 	    // Check for a CTRL-C every 100000 characters.
2998 	    if (byte_count > last_check)
2999 	    {
3000 		ui_breakcheck();
3001 		if (got_int)
3002 		    return;
3003 		last_check = byte_count + 100000L;
3004 	    }
3005 
3006 	    // Do extra processing for VIsual mode.
3007 	    if (VIsual_active
3008 		    && lnum >= min_pos.lnum && lnum <= max_pos.lnum)
3009 	    {
3010 		char_u	    *s = NULL;
3011 		long	    len = 0L;
3012 
3013 		switch (VIsual_mode)
3014 		{
3015 		    case Ctrl_V:
3016 			virtual_op = virtual_active();
3017 			block_prep(&oparg, &bd, lnum, 0);
3018 			virtual_op = MAYBE;
3019 			s = bd.textstart;
3020 			len = (long)bd.textlen;
3021 			break;
3022 		    case 'V':
3023 			s = ml_get(lnum);
3024 			len = MAXCOL;
3025 			break;
3026 		    case 'v':
3027 			{
3028 			    colnr_T start_col = (lnum == min_pos.lnum)
3029 							   ? min_pos.col : 0;
3030 			    colnr_T end_col = (lnum == max_pos.lnum)
3031 				      ? max_pos.col - start_col + 1 : MAXCOL;
3032 
3033 			    s = ml_get(lnum) + start_col;
3034 			    len = end_col;
3035 			}
3036 			break;
3037 		}
3038 		if (s != NULL)
3039 		{
3040 		    byte_count_cursor += line_count_info(s, &word_count_cursor,
3041 					   &char_count_cursor, len, eol_size);
3042 		    if (lnum == curbuf->b_ml.ml_line_count
3043 			    && !curbuf->b_p_eol
3044 			    && (curbuf->b_p_bin || !curbuf->b_p_fixeol)
3045 			    && (long)STRLEN(s) < len)
3046 			byte_count_cursor -= eol_size;
3047 		}
3048 	    }
3049 	    else
3050 	    {
3051 		// In non-visual mode, check for the line the cursor is on
3052 		if (lnum == curwin->w_cursor.lnum)
3053 		{
3054 		    word_count_cursor += word_count;
3055 		    char_count_cursor += char_count;
3056 		    byte_count_cursor = byte_count +
3057 			line_count_info(ml_get(lnum),
3058 				&word_count_cursor, &char_count_cursor,
3059 				(varnumber_T)(curwin->w_cursor.col + 1),
3060 				eol_size);
3061 		}
3062 	    }
3063 	    // Add to the running totals
3064 	    byte_count += line_count_info(ml_get(lnum), &word_count,
3065 					 &char_count, (varnumber_T)MAXCOL,
3066 					 eol_size);
3067 	}
3068 
3069 	// Correction for when last line doesn't have an EOL.
3070 	if (!curbuf->b_p_eol && (curbuf->b_p_bin || !curbuf->b_p_fixeol))
3071 	    byte_count -= eol_size;
3072 
3073 	if (dict == NULL)
3074 	{
3075 	    if (VIsual_active)
3076 	    {
3077 		if (VIsual_mode == Ctrl_V && curwin->w_curswant < MAXCOL)
3078 		{
3079 		    getvcols(curwin, &min_pos, &max_pos, &min_pos.col,
3080 								    &max_pos.col);
3081 		    vim_snprintf((char *)buf1, sizeof(buf1), _("%ld Cols; "),
3082 			    (long)(oparg.end_vcol - oparg.start_vcol + 1));
3083 		}
3084 		else
3085 		    buf1[0] = NUL;
3086 
3087 		if (char_count_cursor == byte_count_cursor
3088 						    && char_count == byte_count)
3089 		    vim_snprintf((char *)IObuff, IOSIZE,
3090 			    _("Selected %s%ld of %ld Lines; %lld of %lld Words; %lld of %lld Bytes"),
3091 			    buf1, line_count_selected,
3092 			    (long)curbuf->b_ml.ml_line_count,
3093 			    (varnumber_T)word_count_cursor,
3094 			    (varnumber_T)word_count,
3095 			    (varnumber_T)byte_count_cursor,
3096 			    (varnumber_T)byte_count);
3097 		else
3098 		    vim_snprintf((char *)IObuff, IOSIZE,
3099 			    _("Selected %s%ld of %ld Lines; %lld of %lld Words; %lld of %lld Chars; %lld of %lld Bytes"),
3100 			    buf1, line_count_selected,
3101 			    (long)curbuf->b_ml.ml_line_count,
3102 			    (varnumber_T)word_count_cursor,
3103 			    (varnumber_T)word_count,
3104 			    (varnumber_T)char_count_cursor,
3105 			    (varnumber_T)char_count,
3106 			    (varnumber_T)byte_count_cursor,
3107 			    (varnumber_T)byte_count);
3108 	    }
3109 	    else
3110 	    {
3111 		p = ml_get_curline();
3112 		validate_virtcol();
3113 		col_print(buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1,
3114 			(int)curwin->w_virtcol + 1);
3115 		col_print(buf2, sizeof(buf2), (int)STRLEN(p),
3116 				    linetabsize(p));
3117 
3118 		if (char_count_cursor == byte_count_cursor
3119 			&& char_count == byte_count)
3120 		    vim_snprintf((char *)IObuff, IOSIZE,
3121 			_("Col %s of %s; Line %ld of %ld; Word %lld of %lld; Byte %lld of %lld"),
3122 			(char *)buf1, (char *)buf2,
3123 			(long)curwin->w_cursor.lnum,
3124 			(long)curbuf->b_ml.ml_line_count,
3125 			(varnumber_T)word_count_cursor, (varnumber_T)word_count,
3126 			(varnumber_T)byte_count_cursor, (varnumber_T)byte_count);
3127 		else
3128 		    vim_snprintf((char *)IObuff, IOSIZE,
3129 			_("Col %s of %s; Line %ld of %ld; Word %lld of %lld; Char %lld of %lld; Byte %lld of %lld"),
3130 			(char *)buf1, (char *)buf2,
3131 			(long)curwin->w_cursor.lnum,
3132 			(long)curbuf->b_ml.ml_line_count,
3133 			(varnumber_T)word_count_cursor, (varnumber_T)word_count,
3134 			(varnumber_T)char_count_cursor, (varnumber_T)char_count,
3135 			(varnumber_T)byte_count_cursor, (varnumber_T)byte_count);
3136 	    }
3137 	}
3138 
3139 	bom_count = bomb_size();
3140 	if (dict == NULL && bom_count > 0)
3141 	{
3142 	    size_t len = STRLEN(IObuff);
3143 
3144 	    vim_snprintf((char *)IObuff + len, IOSIZE - len,
3145 				 _("(+%lld for BOM)"), (varnumber_T)bom_count);
3146 	}
3147 	if (dict == NULL)
3148 	{
3149 	    // Don't shorten this message, the user asked for it.
3150 	    p = p_shm;
3151 	    p_shm = (char_u *)"";
3152 	    msg((char *)IObuff);
3153 	    p_shm = p;
3154 	}
3155     }
3156 #if defined(FEAT_EVAL)
3157     if (dict != NULL)
3158     {
3159 	dict_add_number(dict, "words", word_count);
3160 	dict_add_number(dict, "chars", char_count);
3161 	dict_add_number(dict, "bytes", byte_count + bom_count);
3162 	dict_add_number(dict, VIsual_active ? "visual_bytes" : "cursor_bytes",
3163 		byte_count_cursor);
3164 	dict_add_number(dict, VIsual_active ? "visual_chars" : "cursor_chars",
3165 		char_count_cursor);
3166 	dict_add_number(dict, VIsual_active ? "visual_words" : "cursor_words",
3167 		word_count_cursor);
3168     }
3169 #endif
3170 }
3171 
3172 /*
3173  * Handle indent and format operators and visual mode ":".
3174  */
3175     static void
3176 op_colon(oparg_T *oap)
3177 {
3178     stuffcharReadbuff(':');
3179     if (oap->is_VIsual)
3180 	stuffReadbuff((char_u *)"'<,'>");
3181     else
3182     {
3183 	// Make the range look nice, so it can be repeated.
3184 	if (oap->start.lnum == curwin->w_cursor.lnum)
3185 	    stuffcharReadbuff('.');
3186 	else
3187 	    stuffnumReadbuff((long)oap->start.lnum);
3188 	if (oap->end.lnum != oap->start.lnum)
3189 	{
3190 	    stuffcharReadbuff(',');
3191 	    if (oap->end.lnum == curwin->w_cursor.lnum)
3192 		stuffcharReadbuff('.');
3193 	    else if (oap->end.lnum == curbuf->b_ml.ml_line_count)
3194 		stuffcharReadbuff('$');
3195 	    else if (oap->start.lnum == curwin->w_cursor.lnum)
3196 	    {
3197 		stuffReadbuff((char_u *)".+");
3198 		stuffnumReadbuff((long)oap->line_count - 1);
3199 	    }
3200 	    else
3201 		stuffnumReadbuff((long)oap->end.lnum);
3202 	}
3203     }
3204     if (oap->op_type != OP_COLON)
3205 	stuffReadbuff((char_u *)"!");
3206     if (oap->op_type == OP_INDENT)
3207     {
3208 #ifndef FEAT_CINDENT
3209 	if (*get_equalprg() == NUL)
3210 	    stuffReadbuff((char_u *)"indent");
3211 	else
3212 #endif
3213 	    stuffReadbuff(get_equalprg());
3214 	stuffReadbuff((char_u *)"\n");
3215     }
3216     else if (oap->op_type == OP_FORMAT)
3217     {
3218 	if (*curbuf->b_p_fp != NUL)
3219 	    stuffReadbuff(curbuf->b_p_fp);
3220 	else if (*p_fp != NUL)
3221 	    stuffReadbuff(p_fp);
3222 	else
3223 	    stuffReadbuff((char_u *)"fmt");
3224 	stuffReadbuff((char_u *)"\n']");
3225     }
3226 
3227     // do_cmdline() does the rest
3228 }
3229 
3230 /*
3231  * Handle the "g@" operator: call 'operatorfunc'.
3232  */
3233     static void
3234 op_function(oparg_T *oap UNUSED)
3235 {
3236 #ifdef FEAT_EVAL
3237     typval_T	argv[2];
3238     int		save_virtual_op = virtual_op;
3239     pos_T	orig_start = curbuf->b_op_start;
3240     pos_T	orig_end = curbuf->b_op_end;
3241 
3242     if (*p_opfunc == NUL)
3243 	emsg(_("E774: 'operatorfunc' is empty"));
3244     else
3245     {
3246 	// Set '[ and '] marks to text to be operated on.
3247 	curbuf->b_op_start = oap->start;
3248 	curbuf->b_op_end = oap->end;
3249 	if (oap->motion_type != MLINE && !oap->inclusive)
3250 	    // Exclude the end position.
3251 	    decl(&curbuf->b_op_end);
3252 
3253 	argv[0].v_type = VAR_STRING;
3254 	if (oap->block_mode)
3255 	    argv[0].vval.v_string = (char_u *)"block";
3256 	else if (oap->motion_type == MLINE)
3257 	    argv[0].vval.v_string = (char_u *)"line";
3258 	else
3259 	    argv[0].vval.v_string = (char_u *)"char";
3260 	argv[1].v_type = VAR_UNKNOWN;
3261 
3262 	// Reset virtual_op so that 'virtualedit' can be changed in the
3263 	// function.
3264 	virtual_op = MAYBE;
3265 
3266 	(void)call_func_retnr(p_opfunc, 1, argv);
3267 
3268 	virtual_op = save_virtual_op;
3269 	if (cmdmod.lockmarks)
3270 	{
3271 	    curbuf->b_op_start = orig_start;
3272 	    curbuf->b_op_end = orig_end;
3273 	}
3274     }
3275 #else
3276     emsg(_("E775: Eval feature not available"));
3277 #endif
3278 }
3279 
3280 /*
3281  * Calculate start/end virtual columns for operating in block mode.
3282  */
3283     static void
3284 get_op_vcol(
3285     oparg_T	*oap,
3286     colnr_T	redo_VIsual_vcol,
3287     int		initial)    // when TRUE adjust position for 'selectmode'
3288 {
3289     colnr_T	    start, end;
3290 
3291     if (VIsual_mode != Ctrl_V
3292 	    || (!initial && oap->end.col < curwin->w_width))
3293 	return;
3294 
3295     oap->block_mode = TRUE;
3296 
3297     // prevent from moving onto a trail byte
3298     if (has_mbyte)
3299 	mb_adjustpos(curwin->w_buffer, &oap->end);
3300 
3301     getvvcol(curwin, &(oap->start), &oap->start_vcol, NULL, &oap->end_vcol);
3302 
3303     if (!redo_VIsual_busy)
3304     {
3305 	getvvcol(curwin, &(oap->end), &start, NULL, &end);
3306 
3307 	if (start < oap->start_vcol)
3308 	    oap->start_vcol = start;
3309 	if (end > oap->end_vcol)
3310 	{
3311 	    if (initial && *p_sel == 'e' && start >= 1
3312 				    && start - 1 >= oap->end_vcol)
3313 		oap->end_vcol = start - 1;
3314 	    else
3315 		oap->end_vcol = end;
3316 	}
3317     }
3318 
3319     // if '$' was used, get oap->end_vcol from longest line
3320     if (curwin->w_curswant == MAXCOL)
3321     {
3322 	curwin->w_cursor.col = MAXCOL;
3323 	oap->end_vcol = 0;
3324 	for (curwin->w_cursor.lnum = oap->start.lnum;
3325 		curwin->w_cursor.lnum <= oap->end.lnum;
3326 					++curwin->w_cursor.lnum)
3327 	{
3328 	    getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &end);
3329 	    if (end > oap->end_vcol)
3330 		oap->end_vcol = end;
3331 	}
3332     }
3333     else if (redo_VIsual_busy)
3334 	oap->end_vcol = oap->start_vcol + redo_VIsual_vcol - 1;
3335     // Correct oap->end.col and oap->start.col to be the
3336     // upper-left and lower-right corner of the block area.
3337     //
3338     // (Actually, this does convert column positions into character
3339     // positions)
3340     curwin->w_cursor.lnum = oap->end.lnum;
3341     coladvance(oap->end_vcol);
3342     oap->end = curwin->w_cursor;
3343 
3344     curwin->w_cursor = oap->start;
3345     coladvance(oap->start_vcol);
3346     oap->start = curwin->w_cursor;
3347 }
3348 
3349 /*
3350  * Handle an operator after Visual mode or when the movement is finished.
3351  * "gui_yank" is true when yanking text for the clipboard.
3352  */
3353     void
3354 do_pending_operator(cmdarg_T *cap, int old_col, int gui_yank)
3355 {
3356     oparg_T	*oap = cap->oap;
3357     pos_T	old_cursor;
3358     int		empty_region_error;
3359     int		restart_edit_save;
3360 #ifdef FEAT_LINEBREAK
3361     int		lbr_saved = curwin->w_p_lbr;
3362 #endif
3363 
3364     // The visual area is remembered for redo
3365     static int	    redo_VIsual_mode = NUL; // 'v', 'V', or Ctrl-V
3366     static linenr_T redo_VIsual_line_count; // number of lines
3367     static colnr_T  redo_VIsual_vcol;	    // number of cols or end column
3368     static long	    redo_VIsual_count;	    // count for Visual operator
3369     static int	    redo_VIsual_arg;	    // extra argument
3370     int		    include_line_break = FALSE;
3371 
3372 #if defined(FEAT_CLIPBOARD)
3373     // Yank the visual area into the GUI selection register before we operate
3374     // on it and lose it forever.
3375     // Don't do it if a specific register was specified, so that ""x"*P works.
3376     // This could call do_pending_operator() recursively, but that's OK
3377     // because gui_yank will be TRUE for the nested call.
3378     if ((clip_star.available || clip_plus.available)
3379 	    && oap->op_type != OP_NOP
3380 	    && !gui_yank
3381 	    && VIsual_active
3382 	    && !redo_VIsual_busy
3383 	    && oap->regname == 0)
3384 	clip_auto_select();
3385 #endif
3386     old_cursor = curwin->w_cursor;
3387 
3388     // If an operation is pending, handle it...
3389     if ((finish_op || VIsual_active) && oap->op_type != OP_NOP)
3390     {
3391 	// Yank can be redone when 'y' is in 'cpoptions', but not when yanking
3392 	// for the clipboard.
3393 	int	redo_yank = vim_strchr(p_cpo, CPO_YANK) != NULL && !gui_yank;
3394 
3395 #ifdef FEAT_LINEBREAK
3396 	// Avoid a problem with unwanted linebreaks in block mode.
3397 	if (curwin->w_p_lbr)
3398 	    curwin->w_valid &= ~VALID_VIRTCOL;
3399 	curwin->w_p_lbr = FALSE;
3400 #endif
3401 	oap->is_VIsual = VIsual_active;
3402 	if (oap->motion_force == 'V')
3403 	    oap->motion_type = MLINE;
3404 	else if (oap->motion_force == 'v')
3405 	{
3406 	    // If the motion was linewise, "inclusive" will not have been set.
3407 	    // Use "exclusive" to be consistent.  Makes "dvj" work nice.
3408 	    if (oap->motion_type == MLINE)
3409 		oap->inclusive = FALSE;
3410 	    // If the motion already was characterwise, toggle "inclusive"
3411 	    else if (oap->motion_type == MCHAR)
3412 		oap->inclusive = !oap->inclusive;
3413 	    oap->motion_type = MCHAR;
3414 	}
3415 	else if (oap->motion_force == Ctrl_V)
3416 	{
3417 	    // Change line- or characterwise motion into Visual block mode.
3418 	    if (!VIsual_active)
3419 	    {
3420 		VIsual_active = TRUE;
3421 		VIsual = oap->start;
3422 	    }
3423 	    VIsual_mode = Ctrl_V;
3424 	    VIsual_select = FALSE;
3425 	    VIsual_reselect = FALSE;
3426 	}
3427 
3428 	// Only redo yank when 'y' flag is in 'cpoptions'.
3429 	// Never redo "zf" (define fold).
3430 	if ((redo_yank || oap->op_type != OP_YANK)
3431 		&& ((!VIsual_active || oap->motion_force)
3432 		    // Also redo Operator-pending Visual mode mappings
3433 		    || (VIsual_active && cap->cmdchar == ':'
3434 						 && oap->op_type != OP_COLON))
3435 		&& cap->cmdchar != 'D'
3436 #ifdef FEAT_FOLDING
3437 		&& oap->op_type != OP_FOLD
3438 		&& oap->op_type != OP_FOLDOPEN
3439 		&& oap->op_type != OP_FOLDOPENREC
3440 		&& oap->op_type != OP_FOLDCLOSE
3441 		&& oap->op_type != OP_FOLDCLOSEREC
3442 		&& oap->op_type != OP_FOLDDEL
3443 		&& oap->op_type != OP_FOLDDELREC
3444 #endif
3445 		)
3446 	{
3447 	    prep_redo(oap->regname, cap->count0,
3448 		    get_op_char(oap->op_type), get_extra_op_char(oap->op_type),
3449 		    oap->motion_force, cap->cmdchar, cap->nchar);
3450 	    if (cap->cmdchar == '/' || cap->cmdchar == '?') // was a search
3451 	    {
3452 		// If 'cpoptions' does not contain 'r', insert the search
3453 		// pattern to really repeat the same command.
3454 		if (vim_strchr(p_cpo, CPO_REDO) == NULL)
3455 		    AppendToRedobuffLit(cap->searchbuf, -1);
3456 		AppendToRedobuff(NL_STR);
3457 	    }
3458 	    else if (cap->cmdchar == ':')
3459 	    {
3460 		// do_cmdline() has stored the first typed line in
3461 		// "repeat_cmdline".  When several lines are typed repeating
3462 		// won't be possible.
3463 		if (repeat_cmdline == NULL)
3464 		    ResetRedobuff();
3465 		else
3466 		{
3467 		    AppendToRedobuffLit(repeat_cmdline, -1);
3468 		    AppendToRedobuff(NL_STR);
3469 		    VIM_CLEAR(repeat_cmdline);
3470 		}
3471 	    }
3472 	}
3473 
3474 	if (redo_VIsual_busy)
3475 	{
3476 	    // Redo of an operation on a Visual area. Use the same size from
3477 	    // redo_VIsual_line_count and redo_VIsual_vcol.
3478 	    oap->start = curwin->w_cursor;
3479 	    curwin->w_cursor.lnum += redo_VIsual_line_count - 1;
3480 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
3481 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3482 	    VIsual_mode = redo_VIsual_mode;
3483 	    if (redo_VIsual_vcol == MAXCOL || VIsual_mode == 'v')
3484 	    {
3485 		if (VIsual_mode == 'v')
3486 		{
3487 		    if (redo_VIsual_line_count <= 1)
3488 		    {
3489 			validate_virtcol();
3490 			curwin->w_curswant =
3491 				     curwin->w_virtcol + redo_VIsual_vcol - 1;
3492 		    }
3493 		    else
3494 			curwin->w_curswant = redo_VIsual_vcol;
3495 		}
3496 		else
3497 		{
3498 		    curwin->w_curswant = MAXCOL;
3499 		}
3500 		coladvance(curwin->w_curswant);
3501 	    }
3502 	    cap->count0 = redo_VIsual_count;
3503 	    if (redo_VIsual_count != 0)
3504 		cap->count1 = redo_VIsual_count;
3505 	    else
3506 		cap->count1 = 1;
3507 	}
3508 	else if (VIsual_active)
3509 	{
3510 	    if (!gui_yank)
3511 	    {
3512 		// Save the current VIsual area for '< and '> marks, and "gv"
3513 		curbuf->b_visual.vi_start = VIsual;
3514 		curbuf->b_visual.vi_end = curwin->w_cursor;
3515 		curbuf->b_visual.vi_mode = VIsual_mode;
3516 		restore_visual_mode();
3517 		curbuf->b_visual.vi_curswant = curwin->w_curswant;
3518 # ifdef FEAT_EVAL
3519 		curbuf->b_visual_mode_eval = VIsual_mode;
3520 # endif
3521 	    }
3522 
3523 	    // In Select mode, a linewise selection is operated upon like a
3524 	    // characterwise selection.
3525 	    // Special case: gH<Del> deletes the last line.
3526 	    if (VIsual_select && VIsual_mode == 'V'
3527 					    && cap->oap->op_type != OP_DELETE)
3528 	    {
3529 		if (LT_POS(VIsual, curwin->w_cursor))
3530 		{
3531 		    VIsual.col = 0;
3532 		    curwin->w_cursor.col =
3533 			       (colnr_T)STRLEN(ml_get(curwin->w_cursor.lnum));
3534 		}
3535 		else
3536 		{
3537 		    curwin->w_cursor.col = 0;
3538 		    VIsual.col = (colnr_T)STRLEN(ml_get(VIsual.lnum));
3539 		}
3540 		VIsual_mode = 'v';
3541 	    }
3542 	    // If 'selection' is "exclusive", backup one character for
3543 	    // charwise selections.
3544 	    else if (VIsual_mode == 'v')
3545 		include_line_break = unadjust_for_sel();
3546 
3547 	    oap->start = VIsual;
3548 	    if (VIsual_mode == 'V')
3549 	    {
3550 		oap->start.col = 0;
3551 		oap->start.coladd = 0;
3552 	    }
3553 	}
3554 
3555 	// Set oap->start to the first position of the operated text, oap->end
3556 	// to the end of the operated text.  w_cursor is equal to oap->start.
3557 	if (LT_POS(oap->start, curwin->w_cursor))
3558 	{
3559 #ifdef FEAT_FOLDING
3560 	    // Include folded lines completely.
3561 	    if (!VIsual_active)
3562 	    {
3563 		if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL))
3564 		    oap->start.col = 0;
3565 		if ((curwin->w_cursor.col > 0 || oap->inclusive
3566 						  || oap->motion_type == MLINE)
3567 			&& hasFolding(curwin->w_cursor.lnum, NULL,
3568 						      &curwin->w_cursor.lnum))
3569 		    curwin->w_cursor.col = (colnr_T)STRLEN(ml_get_curline());
3570 	    }
3571 #endif
3572 	    oap->end = curwin->w_cursor;
3573 	    curwin->w_cursor = oap->start;
3574 
3575 	    // w_virtcol may have been updated; if the cursor goes back to its
3576 	    // previous position w_virtcol becomes invalid and isn't updated
3577 	    // automatically.
3578 	    curwin->w_valid &= ~VALID_VIRTCOL;
3579 	}
3580 	else
3581 	{
3582 #ifdef FEAT_FOLDING
3583 	    // Include folded lines completely.
3584 	    if (!VIsual_active && oap->motion_type == MLINE)
3585 	    {
3586 		if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum,
3587 									NULL))
3588 		    curwin->w_cursor.col = 0;
3589 		if (hasFolding(oap->start.lnum, NULL, &oap->start.lnum))
3590 		    oap->start.col = (colnr_T)STRLEN(ml_get(oap->start.lnum));
3591 	    }
3592 #endif
3593 	    oap->end = oap->start;
3594 	    oap->start = curwin->w_cursor;
3595 	}
3596 
3597 	// Just in case lines were deleted that make the position invalid.
3598 	check_pos(curwin->w_buffer, &oap->end);
3599 	oap->line_count = oap->end.lnum - oap->start.lnum + 1;
3600 
3601 	// Set "virtual_op" before resetting VIsual_active.
3602 	virtual_op = virtual_active();
3603 
3604 	if (VIsual_active || redo_VIsual_busy)
3605 	{
3606 	    get_op_vcol(oap, redo_VIsual_vcol, TRUE);
3607 
3608 	    if (!redo_VIsual_busy && !gui_yank)
3609 	    {
3610 		// Prepare to reselect and redo Visual: this is based on the
3611 		// size of the Visual text
3612 		resel_VIsual_mode = VIsual_mode;
3613 		if (curwin->w_curswant == MAXCOL)
3614 		    resel_VIsual_vcol = MAXCOL;
3615 		else
3616 		{
3617 		    if (VIsual_mode != Ctrl_V)
3618 			getvvcol(curwin, &(oap->end),
3619 						  NULL, NULL, &oap->end_vcol);
3620 		    if (VIsual_mode == Ctrl_V || oap->line_count <= 1)
3621 		    {
3622 			if (VIsual_mode != Ctrl_V)
3623 			    getvvcol(curwin, &(oap->start),
3624 						&oap->start_vcol, NULL, NULL);
3625 			resel_VIsual_vcol = oap->end_vcol - oap->start_vcol + 1;
3626 		    }
3627 		    else
3628 			resel_VIsual_vcol = oap->end_vcol;
3629 		}
3630 		resel_VIsual_line_count = oap->line_count;
3631 	    }
3632 
3633 	    // can't redo yank (unless 'y' is in 'cpoptions') and ":"
3634 	    if ((redo_yank || oap->op_type != OP_YANK)
3635 		    && oap->op_type != OP_COLON
3636 #ifdef FEAT_FOLDING
3637 		    && oap->op_type != OP_FOLD
3638 		    && oap->op_type != OP_FOLDOPEN
3639 		    && oap->op_type != OP_FOLDOPENREC
3640 		    && oap->op_type != OP_FOLDCLOSE
3641 		    && oap->op_type != OP_FOLDCLOSEREC
3642 		    && oap->op_type != OP_FOLDDEL
3643 		    && oap->op_type != OP_FOLDDELREC
3644 #endif
3645 		    && oap->motion_force == NUL
3646 		    )
3647 	    {
3648 		// Prepare for redoing.  Only use the nchar field for "r",
3649 		// otherwise it might be the second char of the operator.
3650 		if (cap->cmdchar == 'g' && (cap->nchar == 'n'
3651 							|| cap->nchar == 'N'))
3652 		    prep_redo(oap->regname, cap->count0,
3653 			    get_op_char(oap->op_type),
3654 			    get_extra_op_char(oap->op_type),
3655 			    oap->motion_force, cap->cmdchar, cap->nchar);
3656 		else if (cap->cmdchar != ':')
3657 		{
3658 		    int nchar = oap->op_type == OP_REPLACE ? cap->nchar : NUL;
3659 
3660 		    // reverse what nv_replace() did
3661 		    if (nchar == REPLACE_CR_NCHAR)
3662 			nchar = CAR;
3663 		    else if (nchar == REPLACE_NL_NCHAR)
3664 			nchar = NL;
3665 		    prep_redo(oap->regname, 0L, NUL, 'v',
3666 					get_op_char(oap->op_type),
3667 					get_extra_op_char(oap->op_type),
3668 					nchar);
3669 		}
3670 		if (!redo_VIsual_busy)
3671 		{
3672 		    redo_VIsual_mode = resel_VIsual_mode;
3673 		    redo_VIsual_vcol = resel_VIsual_vcol;
3674 		    redo_VIsual_line_count = resel_VIsual_line_count;
3675 		    redo_VIsual_count = cap->count0;
3676 		    redo_VIsual_arg = cap->arg;
3677 		}
3678 	    }
3679 
3680 	    // oap->inclusive defaults to TRUE.
3681 	    // If oap->end is on a NUL (empty line) oap->inclusive becomes
3682 	    // FALSE.  This makes "d}P" and "v}dP" work the same.
3683 	    if (oap->motion_force == NUL || oap->motion_type == MLINE)
3684 		oap->inclusive = TRUE;
3685 	    if (VIsual_mode == 'V')
3686 		oap->motion_type = MLINE;
3687 	    else
3688 	    {
3689 		oap->motion_type = MCHAR;
3690 		if (VIsual_mode != Ctrl_V && *ml_get_pos(&(oap->end)) == NUL
3691 			&& (include_line_break || !virtual_op))
3692 		{
3693 		    oap->inclusive = FALSE;
3694 		    // Try to include the newline, unless it's an operator
3695 		    // that works on lines only.
3696 		    if (*p_sel != 'o'
3697 			    && !op_on_lines(oap->op_type)
3698 			    && oap->end.lnum < curbuf->b_ml.ml_line_count)
3699 		    {
3700 			++oap->end.lnum;
3701 			oap->end.col = 0;
3702 			oap->end.coladd = 0;
3703 			++oap->line_count;
3704 		    }
3705 		}
3706 	    }
3707 
3708 	    redo_VIsual_busy = FALSE;
3709 
3710 	    // Switch Visual off now, so screen updating does
3711 	    // not show inverted text when the screen is redrawn.
3712 	    // With OP_YANK and sometimes with OP_COLON and OP_FILTER there is
3713 	    // no screen redraw, so it is done here to remove the inverted
3714 	    // part.
3715 	    if (!gui_yank)
3716 	    {
3717 		VIsual_active = FALSE;
3718 		setmouse();
3719 		mouse_dragging = 0;
3720 		may_clear_cmdline();
3721 		if ((oap->op_type == OP_YANK
3722 			    || oap->op_type == OP_COLON
3723 			    || oap->op_type == OP_FUNCTION
3724 			    || oap->op_type == OP_FILTER)
3725 			&& oap->motion_force == NUL)
3726 		{
3727 #ifdef FEAT_LINEBREAK
3728 		    // make sure redrawing is correct
3729 		    curwin->w_p_lbr = lbr_saved;
3730 #endif
3731 		    redraw_curbuf_later(INVERTED);
3732 		}
3733 	    }
3734 	}
3735 
3736 	// Include the trailing byte of a multi-byte char.
3737 	if (has_mbyte && oap->inclusive)
3738 	{
3739 	    int		l;
3740 
3741 	    l = (*mb_ptr2len)(ml_get_pos(&oap->end));
3742 	    if (l > 1)
3743 		oap->end.col += l - 1;
3744 	}
3745 	curwin->w_set_curswant = TRUE;
3746 
3747 	// oap->empty is set when start and end are the same.  The inclusive
3748 	// flag affects this too, unless yanking and the end is on a NUL.
3749 	oap->empty = (oap->motion_type == MCHAR
3750 		    && (!oap->inclusive
3751 			|| (oap->op_type == OP_YANK
3752 			    && gchar_pos(&oap->end) == NUL))
3753 		    && EQUAL_POS(oap->start, oap->end)
3754 		    && !(virtual_op && oap->start.coladd != oap->end.coladd));
3755 	// For delete, change and yank, it's an error to operate on an
3756 	// empty region, when 'E' included in 'cpoptions' (Vi compatible).
3757 	empty_region_error = (oap->empty
3758 				&& vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL);
3759 
3760 	// Force a redraw when operating on an empty Visual region, when
3761 	// 'modifiable is off or creating a fold.
3762 	if (oap->is_VIsual && (oap->empty || !curbuf->b_p_ma
3763 #ifdef FEAT_FOLDING
3764 		    || oap->op_type == OP_FOLD
3765 #endif
3766 		    ))
3767 	{
3768 #ifdef FEAT_LINEBREAK
3769 	    curwin->w_p_lbr = lbr_saved;
3770 #endif
3771 	    redraw_curbuf_later(INVERTED);
3772 	}
3773 
3774 	// If the end of an operator is in column one while oap->motion_type
3775 	// is MCHAR and oap->inclusive is FALSE, we put op_end after the last
3776 	// character in the previous line. If op_start is on or before the
3777 	// first non-blank in the line, the operator becomes linewise
3778 	// (strange, but that's the way vi does it).
3779 	if (	   oap->motion_type == MCHAR
3780 		&& oap->inclusive == FALSE
3781 		&& !(cap->retval & CA_NO_ADJ_OP_END)
3782 		&& oap->end.col == 0
3783 		&& (!oap->is_VIsual || *p_sel == 'o')
3784 		&& !oap->block_mode
3785 		&& oap->line_count > 1)
3786 	{
3787 	    oap->end_adjusted = TRUE;	    // remember that we did this
3788 	    --oap->line_count;
3789 	    --oap->end.lnum;
3790 	    if (inindent(0))
3791 		oap->motion_type = MLINE;
3792 	    else
3793 	    {
3794 		oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
3795 		if (oap->end.col)
3796 		{
3797 		    --oap->end.col;
3798 		    oap->inclusive = TRUE;
3799 		}
3800 	    }
3801 	}
3802 	else
3803 	    oap->end_adjusted = FALSE;
3804 
3805 	switch (oap->op_type)
3806 	{
3807 	case OP_LSHIFT:
3808 	case OP_RSHIFT:
3809 	    op_shift(oap, TRUE, oap->is_VIsual ? (int)cap->count1 : 1);
3810 	    auto_format(FALSE, TRUE);
3811 	    break;
3812 
3813 	case OP_JOIN_NS:
3814 	case OP_JOIN:
3815 	    if (oap->line_count < 2)
3816 		oap->line_count = 2;
3817 	    if (curwin->w_cursor.lnum + oap->line_count - 1 >
3818 						   curbuf->b_ml.ml_line_count)
3819 		beep_flush();
3820 	    else
3821 	    {
3822 		(void)do_join(oap->line_count, oap->op_type == OP_JOIN,
3823 							    TRUE, TRUE, TRUE);
3824 		auto_format(FALSE, TRUE);
3825 	    }
3826 	    break;
3827 
3828 	case OP_DELETE:
3829 	    VIsual_reselect = FALSE;	    // don't reselect now
3830 	    if (empty_region_error)
3831 	    {
3832 		vim_beep(BO_OPER);
3833 		CancelRedo();
3834 	    }
3835 	    else
3836 	    {
3837 		(void)op_delete(oap);
3838 		if (oap->motion_type == MLINE && has_format_option(FO_AUTO))
3839 		    u_save_cursor();	    // cursor line wasn't saved yet
3840 		auto_format(FALSE, TRUE);
3841 	    }
3842 	    break;
3843 
3844 	case OP_YANK:
3845 	    if (empty_region_error)
3846 	    {
3847 		if (!gui_yank)
3848 		{
3849 		    vim_beep(BO_OPER);
3850 		    CancelRedo();
3851 		}
3852 	    }
3853 	    else
3854 	    {
3855 #ifdef FEAT_LINEBREAK
3856 		curwin->w_p_lbr = lbr_saved;
3857 #endif
3858 		(void)op_yank(oap, FALSE, !gui_yank);
3859 	    }
3860 	    check_cursor_col();
3861 	    break;
3862 
3863 	case OP_CHANGE:
3864 	    VIsual_reselect = FALSE;	    // don't reselect now
3865 	    if (empty_region_error)
3866 	    {
3867 		vim_beep(BO_OPER);
3868 		CancelRedo();
3869 	    }
3870 	    else
3871 	    {
3872 		// This is a new edit command, not a restart.  Need to
3873 		// remember it to make 'insertmode' work with mappings for
3874 		// Visual mode.  But do this only once and not when typed and
3875 		// 'insertmode' isn't set.
3876 		if (p_im || !KeyTyped)
3877 		    restart_edit_save = restart_edit;
3878 		else
3879 		    restart_edit_save = 0;
3880 		restart_edit = 0;
3881 #ifdef FEAT_LINEBREAK
3882 		// Restore linebreak, so that when the user edits it looks as
3883 		// before.
3884 		curwin->w_p_lbr = lbr_saved;
3885 #endif
3886 		// Reset finish_op now, don't want it set inside edit().
3887 		finish_op = FALSE;
3888 		if (op_change(oap))	// will call edit()
3889 		    cap->retval |= CA_COMMAND_BUSY;
3890 		if (restart_edit == 0)
3891 		    restart_edit = restart_edit_save;
3892 	    }
3893 	    break;
3894 
3895 	case OP_FILTER:
3896 	    if (vim_strchr(p_cpo, CPO_FILTER) != NULL)
3897 		AppendToRedobuff((char_u *)"!\r");  // use any last used !cmd
3898 	    else
3899 		bangredo = TRUE;    // do_bang() will put cmd in redo buffer
3900 	    // FALLTHROUGH
3901 
3902 	case OP_INDENT:
3903 	case OP_COLON:
3904 
3905 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
3906 	    // If 'equalprg' is empty, do the indenting internally.
3907 	    if (oap->op_type == OP_INDENT && *get_equalprg() == NUL)
3908 	    {
3909 # ifdef FEAT_LISP
3910 		if (curbuf->b_p_lisp)
3911 		{
3912 		    op_reindent(oap, get_lisp_indent);
3913 		    break;
3914 		}
3915 # endif
3916 # ifdef FEAT_CINDENT
3917 		op_reindent(oap,
3918 #  ifdef FEAT_EVAL
3919 			*curbuf->b_p_inde != NUL ? get_expr_indent :
3920 #  endif
3921 			    get_c_indent);
3922 		break;
3923 # endif
3924 	    }
3925 #endif
3926 
3927 	    op_colon(oap);
3928 	    break;
3929 
3930 	case OP_TILDE:
3931 	case OP_UPPER:
3932 	case OP_LOWER:
3933 	case OP_ROT13:
3934 	    if (empty_region_error)
3935 	    {
3936 		vim_beep(BO_OPER);
3937 		CancelRedo();
3938 	    }
3939 	    else
3940 		op_tilde(oap);
3941 	    check_cursor_col();
3942 	    break;
3943 
3944 	case OP_FORMAT:
3945 #if defined(FEAT_EVAL)
3946 	    if (*curbuf->b_p_fex != NUL)
3947 		op_formatexpr(oap);	// use expression
3948 	    else
3949 #endif
3950 		if (*p_fp != NUL || *curbuf->b_p_fp != NUL)
3951 		op_colon(oap);		// use external command
3952 	    else
3953 		op_format(oap, FALSE);	// use internal function
3954 	    break;
3955 
3956 	case OP_FORMAT2:
3957 	    op_format(oap, TRUE);	// use internal function
3958 	    break;
3959 
3960 	case OP_FUNCTION:
3961 #ifdef FEAT_LINEBREAK
3962 	    // Restore linebreak, so that when the user edits it looks as
3963 	    // before.
3964 	    curwin->w_p_lbr = lbr_saved;
3965 #endif
3966 	    op_function(oap);		// call 'operatorfunc'
3967 	    break;
3968 
3969 	case OP_INSERT:
3970 	case OP_APPEND:
3971 	    VIsual_reselect = FALSE;	// don't reselect now
3972 	    if (empty_region_error)
3973 	    {
3974 		vim_beep(BO_OPER);
3975 		CancelRedo();
3976 	    }
3977 	    else
3978 	    {
3979 		// This is a new edit command, not a restart.  Need to
3980 		// remember it to make 'insertmode' work with mappings for
3981 		// Visual mode.  But do this only once.
3982 		restart_edit_save = restart_edit;
3983 		restart_edit = 0;
3984 #ifdef FEAT_LINEBREAK
3985 		// Restore linebreak, so that when the user edits it looks as
3986 		// before.
3987 		curwin->w_p_lbr = lbr_saved;
3988 #endif
3989 		op_insert(oap, cap->count1);
3990 #ifdef FEAT_LINEBREAK
3991 		// Reset linebreak, so that formatting works correctly.
3992 		curwin->w_p_lbr = FALSE;
3993 #endif
3994 
3995 		// TODO: when inserting in several lines, should format all
3996 		// the lines.
3997 		auto_format(FALSE, TRUE);
3998 
3999 		if (restart_edit == 0)
4000 		    restart_edit = restart_edit_save;
4001 		else
4002 		    cap->retval |= CA_COMMAND_BUSY;
4003 	    }
4004 	    break;
4005 
4006 	case OP_REPLACE:
4007 	    VIsual_reselect = FALSE;	// don't reselect now
4008 	    if (empty_region_error)
4009 	    {
4010 		vim_beep(BO_OPER);
4011 		CancelRedo();
4012 	    }
4013 	    else
4014 	    {
4015 #ifdef FEAT_LINEBREAK
4016 		// Restore linebreak, so that when the user edits it looks as
4017 		// before.
4018 		curwin->w_p_lbr = lbr_saved;
4019 #endif
4020 		op_replace(oap, cap->nchar);
4021 	    }
4022 	    break;
4023 
4024 #ifdef FEAT_FOLDING
4025 	case OP_FOLD:
4026 	    VIsual_reselect = FALSE;	// don't reselect now
4027 	    foldCreate(oap->start.lnum, oap->end.lnum);
4028 	    break;
4029 
4030 	case OP_FOLDOPEN:
4031 	case OP_FOLDOPENREC:
4032 	case OP_FOLDCLOSE:
4033 	case OP_FOLDCLOSEREC:
4034 	    VIsual_reselect = FALSE;	// don't reselect now
4035 	    opFoldRange(oap->start.lnum, oap->end.lnum,
4036 		    oap->op_type == OP_FOLDOPEN
4037 					    || oap->op_type == OP_FOLDOPENREC,
4038 		    oap->op_type == OP_FOLDOPENREC
4039 					  || oap->op_type == OP_FOLDCLOSEREC,
4040 					  oap->is_VIsual);
4041 	    break;
4042 
4043 	case OP_FOLDDEL:
4044 	case OP_FOLDDELREC:
4045 	    VIsual_reselect = FALSE;	// don't reselect now
4046 	    deleteFold(oap->start.lnum, oap->end.lnum,
4047 			       oap->op_type == OP_FOLDDELREC, oap->is_VIsual);
4048 	    break;
4049 #endif
4050 	case OP_NR_ADD:
4051 	case OP_NR_SUB:
4052 	    if (empty_region_error)
4053 	    {
4054 		vim_beep(BO_OPER);
4055 		CancelRedo();
4056 	    }
4057 	    else
4058 	    {
4059 		VIsual_active = TRUE;
4060 #ifdef FEAT_LINEBREAK
4061 		curwin->w_p_lbr = lbr_saved;
4062 #endif
4063 		op_addsub(oap, cap->count1, redo_VIsual_arg);
4064 		VIsual_active = FALSE;
4065 	    }
4066 	    check_cursor_col();
4067 	    break;
4068 	default:
4069 	    clearopbeep(oap);
4070 	}
4071 	virtual_op = MAYBE;
4072 	if (!gui_yank)
4073 	{
4074 	    // if 'sol' not set, go back to old column for some commands
4075 	    if (!p_sol && oap->motion_type == MLINE && !oap->end_adjusted
4076 		    && (oap->op_type == OP_LSHIFT || oap->op_type == OP_RSHIFT
4077 						|| oap->op_type == OP_DELETE))
4078 	    {
4079 #ifdef FEAT_LINEBREAK
4080 		curwin->w_p_lbr = FALSE;
4081 #endif
4082 		coladvance(curwin->w_curswant = old_col);
4083 	    }
4084 	}
4085 	else
4086 	{
4087 	    curwin->w_cursor = old_cursor;
4088 	}
4089 	oap->block_mode = FALSE;
4090 	clearop(oap);
4091 	motion_force = NUL;
4092     }
4093 #ifdef FEAT_LINEBREAK
4094     curwin->w_p_lbr = lbr_saved;
4095 #endif
4096 }
4097