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