robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

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