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