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