robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
157.1 KiB5049 linesraw
1// ex_cmds.c: some functions for command line commands
2
3#include <assert.h>
4#include <ctype.h>
5#include <float.h>
6#include <inttypes.h>
7#include <limits.h>
8#include <math.h>
9#include <stdbool.h>
10#include <stddef.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <time.h>
15
16#include "auto/config.h"
17#include "klib/kvec.h"
18#include "nvim/api/private/helpers.h"
19#include "nvim/arglist.h"
20#include "nvim/ascii_defs.h"
21#include "nvim/autocmd.h"
22#include "nvim/autocmd_defs.h"
23#include "nvim/buffer.h"
24#include "nvim/buffer_defs.h"
25#include "nvim/buffer_updates.h"
26#include "nvim/bufwrite.h"
27#include "nvim/change.h"
28#include "nvim/channel.h"
29#include "nvim/charset.h"
30#include "nvim/cmdexpand_defs.h"
31#include "nvim/cmdhist.h"
32#include "nvim/cursor.h"
33#include "nvim/decoration.h"
34#include "nvim/dialog.h"
35#include "nvim/diff.h"
36#include "nvim/digraph.h"
37#include "nvim/drawscreen.h"
38#include "nvim/errors.h"
39#include "nvim/eval/typval.h"
40#include "nvim/eval/typval_defs.h"
41#include "nvim/eval/vars.h"
42#include "nvim/ex_cmds.h"
43#include "nvim/ex_cmds2.h"
44#include "nvim/ex_cmds_defs.h"
45#include "nvim/ex_docmd.h"
46#include "nvim/ex_eval.h"
47#include "nvim/ex_getln.h"
48#include "nvim/extmark.h"
49#include "nvim/extmark_defs.h"
50#include "nvim/fileio.h"
51#include "nvim/fold.h"
52#include "nvim/gettext_defs.h"
53#include "nvim/globals.h"
54#include "nvim/help.h"
55#include "nvim/highlight_defs.h"
56#include "nvim/highlight_group.h"
57#include "nvim/indent.h"
58#include "nvim/input.h"
59#include "nvim/insert.h"
60#include "nvim/lua/executor.h"
61#include "nvim/macros_defs.h"
62#include "nvim/main.h"
63#include "nvim/mark.h"
64#include "nvim/mark_defs.h"
65#include "nvim/mbyte.h"
66#include "nvim/memline.h"
67#include "nvim/memline_defs.h"
68#include "nvim/memory.h"
69#include "nvim/message.h"
70#include "nvim/mouse.h"
71#include "nvim/move.h"
72#include "nvim/normal.h"
73#include "nvim/ops.h"
74#include "nvim/option.h"
75#include "nvim/option_defs.h"
76#include "nvim/option_vars.h"
77#include "nvim/os/fs.h"
78#include "nvim/os/fs_defs.h"
79#include "nvim/os/input.h"
80#include "nvim/os/os.h"
81#include "nvim/os/os_defs.h"
82#include "nvim/os/shell.h"
83#include "nvim/os/time.h"
84#include "nvim/path.h"
85#include "nvim/plines.h"
86#include "nvim/pos_defs.h"
87#include "nvim/profile.h"
88#include "nvim/quickfix.h"
89#include "nvim/regexp.h"
90#include "nvim/regexp_defs.h"
91#include "nvim/search.h"
92#include "nvim/spell.h"
93#include "nvim/state_defs.h"
94#include "nvim/strings.h"
95#include "nvim/terminal.h"
96#include "nvim/types_defs.h"
97#include "nvim/ui.h"
98#include "nvim/ui_defs.h"
99#include "nvim/undo.h"
100#include "nvim/vim_defs.h"
101#include "nvim/window.h"
102#include "nvim/winfloat.h"
103
104/// Case matching style to use for :substitute
105typedef enum {
106  kSubHonorOptions = 0,  ///< Honor the user's 'ignorecase'/'smartcase' options
107  kSubIgnoreCase,        ///< Ignore case of the search
108  kSubMatchCase,         ///< Match case of the search
109} SubIgnoreType;
110
111/// Flags kept between calls to :substitute.
112typedef struct {
113  bool do_all;          ///< do multiple substitutions per line
114  bool do_ask;          ///< ask for confirmation
115  bool do_count;        ///< count only
116  bool do_error;        ///< if false, ignore errors
117  bool do_print;        ///< print last line with subs
118  bool do_list;         ///< list last line with subs
119  bool do_number;       ///< list last line with line nr
120  SubIgnoreType do_ic;  ///< ignore case flag
121} subflags_T;
122
123/// Partial result of a substitution during :substitute.
124/// Numbers refer to the buffer _after_ substitution
125typedef struct {
126  lpos_T start;  // start of the match
127  lpos_T end;    // end of the match
128  linenr_T pre_match;  // where to begin showing lines before the match
129} SubResult;
130
131// Collected results of a substitution for showing them in
132// the preview window
133typedef struct {
134  kvec_t(SubResult) subresults;
135  linenr_T lines_needed;  // lines needed in the preview window
136} PreviewLines;
137
138#include "ex_cmds.c.generated.h"
139
140static const char e_non_numeric_argument_to_z[]
141  = N_("E144: Non-numeric argument to :z");
142
143/// ":ascii" and "ga" implementation
144void do_ascii(exarg_T *eap)
145{
146  char *data = get_cursor_pos_ptr();
147  size_t len = (size_t)utfc_ptr2len(data);
148
149  if (len == 0) {
150    msg("NUL", 0);
151    return;
152  }
153
154  bool need_clear = true;
155  msg_sb_eol();
156  msg_start();
157
158  int c = utf_ptr2char(data);
159  size_t off = 0;
160
161  // TODO(bfredl): merge this with the main loop
162  if (c < 0x80) {
163    if (c == NL) {  // NUL is stored as NL.
164      c = NUL;
165    }
166    const int cval = (c == CAR && get_fileformat(curbuf) == EOL_MAC
167                      ? NL  // NL is stored as CR.
168                      : c);
169    char buf1[20];
170    if (vim_isprintc(c) && (c < ' ' || c > '~')) {
171      char buf3[7];
172      transchar_nonprint(curbuf, buf3, c);
173      vim_snprintf(buf1, sizeof(buf1), "  <%s>", buf3);
174    } else {
175      buf1[0] = NUL;
176    }
177    char buf2[20];
178    buf2[0] = NUL;
179
180    char *dig = get_digraph_for_char(cval);
181    if (dig != NULL) {
182      vim_snprintf(IObuff, sizeof(IObuff),
183                   _("<%s>%s%s  %d,  Hex %02x,  Oct %03o, Digr %s"),
184                   transchar(c), buf1, buf2, cval, cval, cval, dig);
185    } else {
186      vim_snprintf(IObuff, sizeof(IObuff),
187                   _("<%s>%s%s  %d,  Hex %02x,  Octal %03o"),
188                   transchar(c), buf1, buf2, cval, cval, cval);
189    }
190
191    msg_multiline(cstr_as_string(IObuff), 0, true, false, &need_clear);
192
193    off += (size_t)utf_ptr2len(data);  // needed for overlong ascii?
194  }
195
196  // Repeat for combining characters, also handle multiby here.
197  while (off < len) {
198    c = utf_ptr2char(data + off);
199
200    size_t iobuff_len = 0;
201    // This assumes every multi-byte char is printable...
202    if (off > 0) {
203      IObuff[iobuff_len++] = ' ';
204    }
205    IObuff[iobuff_len++] = '<';
206    if (utf_iscomposing_first(c)) {
207      IObuff[iobuff_len++] = ' ';  // Draw composing char on top of a space.
208    }
209    iobuff_len += (size_t)utf_char2bytes(c, IObuff + iobuff_len);
210
211    char *dig = get_digraph_for_char(c);
212    if (dig != NULL) {
213      vim_snprintf(IObuff + iobuff_len, sizeof(IObuff) - iobuff_len,
214                   (c < 0x10000
215                    ? _("> %d, Hex %04x, Oct %o, Digr %s")
216                    : _("> %d, Hex %08x, Oct %o, Digr %s")),
217                   c, c, c, dig);
218    } else {
219      vim_snprintf(IObuff + iobuff_len, sizeof(IObuff) - iobuff_len,
220                   (c < 0x10000
221                    ? _("> %d, Hex %04x, Octal %o")
222                    : _("> %d, Hex %08x, Octal %o")),
223                   c, c, c);
224    }
225
226    msg_multiline(cstr_as_string(IObuff), 0, true, false, &need_clear);
227
228    off += (size_t)utf_ptr2len(data + off);  // needed for overlong ascii?
229  }
230
231  if (need_clear) {
232    msg_clr_eos();
233  }
234  msg_end();
235}
236
237/// ":left", ":center" and ":right": align text.
238void ex_align(exarg_T *eap)
239{
240  int indent = 0;
241  int new_indent;
242
243  if (curwin->w_p_rl) {
244    // switch left and right aligning
245    if (eap->cmdidx == CMD_right) {
246      eap->cmdidx = CMD_left;
247    } else if (eap->cmdidx == CMD_left) {
248      eap->cmdidx = CMD_right;
249    }
250  }
251
252  int width = atoi(eap->arg);
253  pos_T save_curpos = curwin->w_cursor;
254  if (eap->cmdidx == CMD_left) {    // width is used for new indent
255    if (width >= 0) {
256      indent = width;
257    }
258  } else {
259    // if 'textwidth' set, use it
260    // else if 'wrapmargin' set, use it
261    // if invalid value, use 80
262    if (width <= 0) {
263      width = (int)curbuf->b_p_tw;
264    }
265    if (width == 0 && curbuf->b_p_wm > 0) {
266      width = curwin->w_view_width - (int)curbuf->b_p_wm;
267    }
268    if (width <= 0) {
269      width = 80;
270    }
271  }
272
273  if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL) {
274    return;
275  }
276
277  for (curwin->w_cursor.lnum = eap->line1;
278       curwin->w_cursor.lnum <= eap->line2; curwin->w_cursor.lnum++) {
279    if (eap->cmdidx == CMD_left) {              // left align
280      new_indent = indent;
281    } else {
282      int has_tab = false;          // avoid uninit warnings
283      int len = linelen(eap->cmdidx == CMD_right ? &has_tab : NULL) - get_indent();
284
285      if (len <= 0) {                           // skip blank lines
286        continue;
287      }
288
289      if (eap->cmdidx == CMD_center) {
290        new_indent = (width - len) / 2;
291      } else {
292        new_indent = width - len;               // right align
293
294        // Make sure that embedded TABs don't make the text go too far
295        // to the right.
296        if (has_tab) {
297          while (new_indent > 0) {
298            set_indent(new_indent, 0);
299            if (linelen(NULL) <= width) {
300              // Now try to move the line as much as possible to
301              // the right.  Stop when it moves too far.
302              do {
303                set_indent(++new_indent, 0);
304              } while (linelen(NULL) <= width);
305              new_indent--;
306              break;
307            }
308            new_indent--;
309          }
310        }
311      }
312    }
313    new_indent = MAX(new_indent, 0);
314    set_indent(new_indent, 0);                    // set indent
315  }
316  changed_lines(curbuf, eap->line1, 0, eap->line2 + 1, 0, true);
317  curwin->w_cursor = save_curpos;
318  beginline(BL_WHITE | BL_FIX);
319}
320
321/// @return  the length of the current line, excluding trailing white space.
322static int linelen(int *has_tab)
323{
324  char *last;
325
326  // Get the line.  If it's empty bail out early (could be the empty string
327  // for an unloaded buffer).
328  char *line = get_cursor_line_ptr();
329  if (*line == NUL) {
330    return 0;
331  }
332  // find the first non-blank character
333  char *first = skipwhite(line);
334
335  // find the character after the last non-blank character
336  for (last = first + strlen(first);
337       last > first && ascii_iswhite(last[-1]); last--) {}
338  char save = *last;
339  *last = NUL;
340  int len = linetabsize_str(line);  // Get line length.
341  if (has_tab != NULL) {        // Check for embedded TAB.
342    *has_tab = vim_strchr(first, TAB) != NULL;
343  }
344  *last = save;
345
346  return len;
347}
348
349// Buffer for two lines used during sorting.  They are allocated to
350// contain the longest line being sorted.
351static char *sortbuf1;
352static char *sortbuf2;
353
354static bool sort_lc;      ///< sort using locale
355static bool sort_ic;      ///< ignore case
356static bool sort_nr;      ///< sort on number
357static bool sort_rx;      ///< sort on regex instead of skipping it
358static bool sort_flt;     ///< sort on floating number
359
360static bool sort_abort;   ///< flag to indicate if sorting has been interrupted
361
362/// Struct to store info to be sorted.
363typedef struct {
364  linenr_T lnum;          ///< line number
365  union {
366    struct {
367      varnumber_T start_col_nr;  ///< starting column number
368      varnumber_T end_col_nr;    ///< ending column number
369    } line;
370    struct {
371      varnumber_T value;         ///< value if sorting by integer
372      bool is_number;            ///< true when line contains a number
373    } num;
374    float_T value_flt;    ///< value if sorting by float
375  } st_u;
376} sorti_T;
377
378static int string_compare(const void *s1, const void *s2) FUNC_ATTR_NONNULL_ALL
379{
380  if (sort_lc) {
381    return strcoll((const char *)s1, (const char *)s2);
382  }
383  return sort_ic ? STRICMP(s1, s2) : strcmp(s1, s2);
384}
385
386static int sort_compare(const void *s1, const void *s2)
387{
388  sorti_T l1 = *(sorti_T *)s1;
389  sorti_T l2 = *(sorti_T *)s2;
390  int result = 0;
391
392  // If the user interrupts, there's no way to stop qsort() immediately, but
393  // if we return 0 every time, qsort will assume it's done sorting and
394  // exit.
395  if (sort_abort) {
396    return 0;
397  }
398  fast_breakcheck();
399  if (got_int) {
400    sort_abort = true;
401  }
402
403  // When sorting numbers "start_col_nr" is the number, not the column
404  // number.
405  if (sort_nr) {
406    if (l1.st_u.num.is_number != l2.st_u.num.is_number) {
407      result = l1.st_u.num.is_number > l2.st_u.num.is_number ? 1 : -1;
408    } else {
409      result = l1.st_u.num.value == l2.st_u.num.value
410               ? 0
411               : l1.st_u.num.value > l2.st_u.num.value ? 1 : -1;
412    }
413  } else if (sort_flt) {
414    result = l1.st_u.value_flt == l2.st_u.value_flt
415             ? 0
416             : l1.st_u.value_flt > l2.st_u.value_flt ? 1 : -1;
417  } else {
418    // We need to copy one line into "sortbuf1", because there is no
419    // guarantee that the first pointer becomes invalid when obtaining the
420    // second one.
421    memcpy(sortbuf1, ml_get(l1.lnum) + l1.st_u.line.start_col_nr,
422           (size_t)(l1.st_u.line.end_col_nr - l1.st_u.line.start_col_nr + 1));
423    sortbuf1[l1.st_u.line.end_col_nr - l1.st_u.line.start_col_nr] = NUL;
424    memcpy(sortbuf2, ml_get(l2.lnum) + l2.st_u.line.start_col_nr,
425           (size_t)(l2.st_u.line.end_col_nr - l2.st_u.line.start_col_nr + 1));
426    sortbuf2[l2.st_u.line.end_col_nr - l2.st_u.line.start_col_nr] = NUL;
427
428    result = string_compare(sortbuf1, sortbuf2);
429  }
430
431  // If two lines have the same value, preserve the original line order.
432  if (result == 0) {
433    return l1.lnum - l2.lnum;
434  }
435  return result;
436}
437
438/// ":sort".
439void ex_sort(exarg_T *eap)
440{
441  regmatch_T regmatch;
442  int maxlen = 0;
443  size_t count = (size_t)(eap->line2 - eap->line1) + 1;
444  size_t i;
445  bool unique = false;
446  int sort_what = 0;
447
448  // Sorting one line is really quick!
449  if (count <= 1) {
450    return;
451  }
452
453  if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL) {
454    return;
455  }
456  sortbuf1 = NULL;
457  sortbuf2 = NULL;
458  regmatch.regprog = NULL;
459  sorti_T *nrs = xmalloc(count * sizeof(sorti_T));
460
461  sort_abort = sort_ic = sort_lc = sort_rx = sort_nr = sort_flt = false;
462  size_t format_found = 0;
463  bool change_occurred = false;   // Buffer contents changed.
464
465  for (char *p = eap->arg; *p != NUL; p++) {
466    if (ascii_iswhite(*p)) {
467      // Skip
468    } else if (*p == 'i') {
469      sort_ic = true;
470    } else if (*p == 'l') {
471      sort_lc = true;
472    } else if (*p == 'r') {
473      sort_rx = true;
474    } else if (*p == 'n') {
475      sort_nr = true;
476      format_found++;
477    } else if (*p == 'f') {
478      sort_flt = true;
479      format_found++;
480    } else if (*p == 'b') {
481      sort_what = STR2NR_BIN + STR2NR_FORCE;
482      format_found++;
483    } else if (*p == 'o') {
484      sort_what = STR2NR_OCT + STR2NR_FORCE;
485      format_found++;
486    } else if (*p == 'x') {
487      sort_what = STR2NR_HEX + STR2NR_FORCE;
488      format_found++;
489    } else if (*p == 'u') {
490      unique = true;
491    } else if (*p == '"') {  // comment start
492      break;
493    } else if (check_nextcmd(p) != NULL) {
494      eap->nextcmd = check_nextcmd(p);
495      break;
496    } else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL) {
497      char *s = skip_regexp_err(p + 1, *p, true);
498      if (s == NULL) {
499        goto sortend;
500      }
501      *s = NUL;
502      // Use last search pattern if sort pattern is empty.
503      if (s == p + 1) {
504        if (last_search_pat() == NULL) {
505          emsg(_(e_noprevre));
506          goto sortend;
507        }
508        regmatch.regprog = vim_regcomp(last_search_pat(), RE_MAGIC);
509      } else {
510        regmatch.regprog = vim_regcomp(p + 1, RE_MAGIC);
511      }
512      if (regmatch.regprog == NULL) {
513        goto sortend;
514      }
515      p = s;                    // continue after the regexp
516      regmatch.rm_ic = p_ic;
517    } else {
518      semsg(_(e_invarg2), p);
519      goto sortend;
520    }
521  }
522
523  // Can only have one of 'n', 'b', 'o' and 'x'.
524  if (format_found > 1) {
525    emsg(_(e_invarg));
526    goto sortend;
527  }
528
529  // From here on "sort_nr" is used as a flag for any integer number
530  // sorting.
531  sort_nr |= sort_what;
532
533  // Make an array with all line numbers.  This avoids having to copy all
534  // the lines into allocated memory.
535  // When sorting on strings "start_col_nr" is the offset in the line, for
536  // numbers sorting it's the number to sort on.  This means the pattern
537  // matching and number conversion only has to be done once per line.
538  // Also get the longest line length for allocating "sortbuf".
539  for (linenr_T lnum = eap->line1; lnum <= eap->line2; lnum++) {
540    char *s = ml_get(lnum);
541    int len = ml_get_len(lnum);
542    maxlen = MAX(maxlen, len);
543
544    colnr_T start_col = 0;
545    colnr_T end_col = len;
546    if (regmatch.regprog != NULL && vim_regexec(&regmatch, s, 0)) {
547      if (sort_rx) {
548        start_col = (colnr_T)(regmatch.startp[0] - s);
549        end_col = (colnr_T)(regmatch.endp[0] - s);
550      } else {
551        start_col = (colnr_T)(regmatch.endp[0] - s);
552      }
553    } else if (regmatch.regprog != NULL) {
554      end_col = 0;
555    }
556
557    if (sort_nr || sort_flt) {
558      // Make sure vim_str2nr() doesn't read any digits past the end
559      // of the match, by temporarily terminating the string there
560      char *s2 = s + end_col;
561      char c = *s2;  // temporary character storage
562      *s2 = NUL;
563      // Sorting on number: Store the number itself.
564      char *p = s + start_col;
565      if (sort_nr) {
566        if (sort_what & STR2NR_HEX) {
567          s = skiptohex(p);
568        } else if (sort_what & STR2NR_BIN) {
569          s = (char *)skiptobin(p);
570        } else {
571          s = skiptodigit(p);
572        }
573        if (s > p && s[-1] == '-') {
574          s--;  // include preceding negative sign
575        }
576        if (*s == NUL) {
577          // line without number should sort before any number
578          nrs[lnum - eap->line1].st_u.num.is_number = false;
579          nrs[lnum - eap->line1].st_u.num.value = 0;
580        } else {
581          nrs[lnum - eap->line1].st_u.num.is_number = true;
582          vim_str2nr(s, NULL, NULL, sort_what,
583                     &nrs[lnum - eap->line1].st_u.num.value, NULL, 0, false, NULL);
584        }
585      } else {
586        s = skipwhite(p);
587        if (*s == '+') {
588          s = skipwhite(s + 1);
589        }
590
591        if (*s == NUL) {
592          // empty line should sort before any number
593          nrs[lnum - eap->line1].st_u.value_flt = -DBL_MAX;
594        } else {
595          nrs[lnum - eap->line1].st_u.value_flt = strtod(s, NULL);
596        }
597      }
598      *s2 = c;
599    } else {
600      // Store the column to sort at.
601      nrs[lnum - eap->line1].st_u.line.start_col_nr = start_col;
602      nrs[lnum - eap->line1].st_u.line.end_col_nr = end_col;
603    }
604
605    nrs[lnum - eap->line1].lnum = lnum;
606
607    if (regmatch.regprog != NULL) {
608      fast_breakcheck();
609    }
610    if (got_int) {
611      goto sortend;
612    }
613  }
614
615  // Allocate a buffer that can hold the longest line.
616  sortbuf1 = xmalloc((size_t)maxlen + 1);
617  sortbuf2 = xmalloc((size_t)maxlen + 1);
618
619  // Sort the array of line numbers.  Note: can't be interrupted!
620  qsort((void *)nrs, count, sizeof(sorti_T), sort_compare);
621
622  if (sort_abort) {
623    goto sortend;
624  }
625
626  bcount_t old_count = 0;
627  bcount_t new_count = 0;
628
629  // Insert the lines in the sorted order below the last one.
630  linenr_T lnum = eap->line2;
631  for (i = 0; i < count; i++) {
632    const linenr_T get_lnum = nrs[eap->forceit ? count - i - 1 : i].lnum;
633
634    // If the original line number of the line being placed is not the same
635    // as "lnum" (accounting for offset), we know that the buffer changed.
636    if (get_lnum + ((linenr_T)count - 1) != lnum) {
637      change_occurred = true;
638    }
639
640    char *s = ml_get(get_lnum);
641    colnr_T bytelen = ml_get_len(get_lnum) + 1;  // include EOL in bytelen
642    old_count += bytelen;
643    if (!unique || i == 0 || string_compare(s, sortbuf1) != 0) {
644      // Copy the line into a buffer, it may become invalid in
645      // ml_append(). And it's needed for "unique".
646      STRCPY(sortbuf1, s);
647      if (ml_append(lnum++, sortbuf1, 0, false) == FAIL) {
648        break;
649      }
650      new_count += bytelen;
651    }
652    fast_breakcheck();
653    if (got_int) {
654      goto sortend;
655    }
656  }
657
658  // delete the original lines if appending worked
659  if (i == count) {
660    for (i = 0; i < count; i++) {
661      ml_delete(eap->line1);
662    }
663  } else {
664    count = 0;
665  }
666
667  // Adjust marks for deleted (or added) lines and prepare for displaying.
668  linenr_T deleted = (linenr_T)count - (lnum - eap->line2);
669  if (deleted > 0) {
670    mark_adjust(eap->line2 - deleted, eap->line2, MAXLNUM, -deleted, kExtmarkNOOP);
671    msgmore(-deleted);
672  } else if (deleted < 0) {
673    mark_adjust(eap->line2, MAXLNUM, -deleted, 0, kExtmarkNOOP);
674  }
675
676  if (change_occurred || deleted != 0) {
677    extmark_splice(curbuf, eap->line1 - 1, 0,
678                   (int)count, 0, old_count,
679                   lnum - eap->line2, 0, new_count, kExtmarkUndo);
680    changed_lines(curbuf, eap->line1, 0, eap->line2 + 1, -deleted, true);
681  }
682
683  curwin->w_cursor.lnum = eap->line1;
684  beginline(BL_WHITE | BL_FIX);
685
686sortend:
687  xfree(nrs);
688  xfree(sortbuf1);
689  xfree(sortbuf2);
690  vim_regfree(regmatch.regprog);
691  if (got_int) {
692    emsg(_(e_interr));
693  }
694}
695
696/// ":uniq".
697void ex_uniq(exarg_T *eap)
698{
699  regmatch_T regmatch;
700  int maxlen = 0;
701  linenr_T count = eap->line2 - eap->line1 + 1;
702  bool keep_only_unique = false;
703  bool keep_only_not_unique = eap->forceit;
704  linenr_T deleted = 0;
705
706  // Uniq one line is really quick!
707  if (count <= 1) {
708    return;
709  }
710
711  if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL) {
712    return;
713  }
714  sortbuf1 = NULL;
715  regmatch.regprog = NULL;
716
717  sort_abort = sort_ic = sort_lc = sort_rx = sort_nr = sort_flt = false;
718  bool change_occurred = false;    // Buffer contents changed.
719
720  for (char *p = eap->arg; *p != NUL; p++) {
721    if (ascii_iswhite(*p)) {
722      // Skip
723    } else if (*p == 'i') {
724      sort_ic = true;
725    } else if (*p == 'l') {
726      sort_lc = true;
727    } else if (*p == 'r') {
728      sort_rx = true;
729    } else if (*p == 'u') {
730      // 'u' is only valid when '!' is not given.
731      if (!keep_only_not_unique) {
732        keep_only_unique = true;
733      }
734    } else if (*p == '"') {  // comment start
735      break;
736    } else if (eap->nextcmd == NULL && check_nextcmd(p) != NULL) {
737      eap->nextcmd = check_nextcmd(p);
738      break;
739    } else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL) {
740      char *s = skip_regexp_err(p + 1, *p, true);
741      if (s == NULL) {
742        goto uniqend;
743      }
744      *s = NUL;
745      // Use last search pattern if uniq pattern is empty.
746      if (s == p + 1) {
747        if (last_search_pat() == NULL) {
748          emsg(_(e_noprevre));
749          goto uniqend;
750        }
751        regmatch.regprog = vim_regcomp(last_search_pat(), RE_MAGIC);
752      } else {
753        regmatch.regprog = vim_regcomp(p + 1, RE_MAGIC);
754      }
755      if (regmatch.regprog == NULL) {
756        goto uniqend;
757      }
758      p = s;              // continue after the regexp
759      regmatch.rm_ic = p_ic;
760    } else {
761      semsg(_(e_invarg2), p);
762      goto uniqend;
763    }
764  }
765
766  // Find the length of the longest line.
767  for (linenr_T lnum = eap->line1; lnum <= eap->line2; lnum++) {
768    int len = ml_get_len(lnum);
769    if (maxlen < len) {
770      maxlen = len;
771    }
772
773    if (got_int) {
774      goto uniqend;
775    }
776  }
777
778  // Allocate a buffer that can hold the longest line.
779  sortbuf1 = xmalloc((size_t)maxlen + 1);
780
781  // Delete lines according to options.
782  bool match_continue = false;
783  bool next_is_unmatch = false;
784  linenr_T done_lnum = eap->line1 - 1;
785  linenr_T delete_lnum = 0;
786  for (linenr_T i = 0; i < count; i++) {
787    linenr_T get_lnum = eap->line1 + i;
788
789    char *s = ml_get(get_lnum);
790    int len = ml_get_len(get_lnum);
791
792    colnr_T start_col = 0;
793    colnr_T end_col = len;
794    if (regmatch.regprog != NULL && vim_regexec(&regmatch, s, 0)) {
795      if (sort_rx) {
796        start_col = (colnr_T)(regmatch.startp[0] - s);
797        end_col = (colnr_T)(regmatch.endp[0] - s);
798      } else {
799        start_col = (colnr_T)(regmatch.endp[0] - s);
800      }
801    } else if (regmatch.regprog != NULL) {
802      end_col = 0;
803    }
804    char save_c = NUL;  // temporary character storage
805    if (end_col > 0) {
806      save_c = s[end_col];
807      s[end_col] = NUL;
808    }
809
810    bool is_match = i > 0 ? !string_compare(&s[start_col], sortbuf1) : false;
811    delete_lnum = 0;
812    if (next_is_unmatch) {
813      is_match = false;
814      next_is_unmatch = false;
815    }
816
817    if (!keep_only_unique && !keep_only_not_unique) {
818      if (is_match) {
819        delete_lnum = get_lnum;
820      } else {
821        STRCPY(sortbuf1, &s[start_col]);
822      }
823    } else if (keep_only_not_unique) {
824      if (is_match) {
825        done_lnum = get_lnum - 1;
826        delete_lnum = get_lnum;
827        match_continue = true;
828      } else {
829        if (i > 0 && !match_continue && get_lnum - 1 > done_lnum) {
830          delete_lnum = get_lnum - 1;
831          next_is_unmatch = true;
832        } else if (i >= count - 1) {
833          delete_lnum = get_lnum;
834        }
835        match_continue = false;
836        STRCPY(sortbuf1, &s[start_col]);
837      }
838    } else {  // keep_only_unique
839      if (is_match) {
840        if (!match_continue) {
841          delete_lnum = get_lnum - 1;
842        } else {
843          delete_lnum = get_lnum;
844        }
845        match_continue = true;
846      } else {
847        if (i == 0 && match_continue) {
848          delete_lnum = get_lnum;
849        }
850        match_continue = false;
851        STRCPY(sortbuf1, &s[start_col]);
852      }
853    }
854
855    if (end_col > 0) {
856      s[end_col] = save_c;
857    }
858
859    if (delete_lnum > 0) {
860      ml_delete(delete_lnum);
861      i -= get_lnum - delete_lnum + 1;
862      count--;
863      deleted++;
864      change_occurred = true;
865    }
866
867    fast_breakcheck();
868    if (got_int) {
869      goto uniqend;
870    }
871  }
872
873  // Adjust marks for deleted lines and prepare for displaying.
874  mark_adjust(eap->line2 - deleted, eap->line2, MAXLNUM, -deleted,
875              change_occurred ? kExtmarkUndo : kExtmarkNOOP);
876  msgmore(-deleted);
877
878  if (change_occurred) {
879    changed_lines(curbuf, eap->line1, 0, eap->line2 + 1, -deleted, true);
880  }
881
882  curwin->w_cursor.lnum = eap->line1;
883  beginline(BL_WHITE | BL_FIX);
884
885uniqend:
886  xfree(sortbuf1);
887  vim_regfree(regmatch.regprog);
888  if (got_int) {
889    emsg(_(e_interr));
890  }
891}
892
893/// :move command - move lines line1-line2 to line dest
894///
895/// @return  FAIL for failure, OK otherwise
896int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
897{
898  if (dest >= line1 && dest < line2) {
899    emsg(_("E134: Cannot move a range of lines into itself"));
900    return FAIL;
901  }
902
903  // Do nothing if we are not actually moving any lines.  This will prevent
904  // the 'modified' flag from being set without cause.
905  if (dest == line1 - 1 || dest == line2) {
906    // Move the cursor as if lines were moved (see below) to be backwards
907    // compatible.
908    curwin->w_cursor.lnum = dest >= line1
909                            ? dest
910                            : dest + (line2 - line1) + 1;
911    return OK;
912  }
913
914  bcount_t start_byte = ml_find_line_or_offset(curbuf, line1, NULL, true);
915  bcount_t end_byte = ml_find_line_or_offset(curbuf, line2 + 1, NULL, true);
916  bcount_t extent_byte = end_byte - start_byte;
917  bcount_t dest_byte = ml_find_line_or_offset(curbuf, dest + 1, NULL, true);
918
919  linenr_T num_lines = line2 - line1 + 1;  // Num lines moved
920
921  // First we copy the old text to its new location -- webb
922  // Also copy the flag that ":global" command uses.
923  if (u_save(dest, dest + 1) == FAIL) {
924    return FAIL;
925  }
926
927  linenr_T l;
928  linenr_T extra;      // Num lines added before line1
929  for (extra = 0, l = line1; l <= line2; l++) {
930    char *str = xstrnsave(ml_get(l + extra), (size_t)ml_get_len(l + extra));
931    ml_append(dest + l - line1, str, 0, false);
932    xfree(str);
933    if (dest < line1) {
934      extra++;
935    }
936  }
937
938  // Now we must be careful adjusting our marks so that we don't overlap our
939  // mark_adjust() calls.
940  //
941  // We adjust the marks within the old text so that they refer to the
942  // last lines of the file (temporarily), because we know no other marks
943  // will be set there since these line numbers did not exist until we added
944  // our new lines.
945  //
946  // Then we adjust the marks on lines between the old and new text positions
947  // (either forwards or backwards).
948  //
949  // And Finally we adjust the marks we put at the end of the file back to
950  // their final destination at the new text position -- webb
951  linenr_T last_line = curbuf->b_ml.ml_line_count;  // Last line in file after adding new text
952  mark_adjust_nofold(line1, line2, last_line - line2, 0, kExtmarkNOOP);
953
954  disable_fold_update++;
955  changed_lines(curbuf, last_line - num_lines + 1, 0, last_line + 1, num_lines, false);
956  disable_fold_update--;
957
958  int line_off = 0;
959  bcount_t byte_off = 0;
960  if (dest >= line2) {
961    mark_adjust_nofold(line2 + 1, dest, -num_lines, 0, kExtmarkNOOP);
962    FOR_ALL_TAB_WINDOWS(tab, win) {
963      if (win->w_buffer == curbuf) {
964        foldMoveRange(win, &win->w_folds, line1, line2, dest);
965      }
966    }
967    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
968      curbuf->b_op_start.lnum = dest - num_lines + 1;
969      curbuf->b_op_end.lnum = dest;
970    }
971    line_off = -num_lines;
972    byte_off = -extent_byte;
973  } else {
974    mark_adjust_nofold(dest + 1, line1 - 1, num_lines, 0, kExtmarkNOOP);
975    FOR_ALL_TAB_WINDOWS(tab, win) {
976      if (win->w_buffer == curbuf) {
977        foldMoveRange(win, &win->w_folds, dest + 1, line1 - 1, line2);
978      }
979    }
980    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
981      curbuf->b_op_start.lnum = dest + 1;
982      curbuf->b_op_end.lnum = dest + num_lines;
983    }
984  }
985  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
986    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
987  }
988  mark_adjust_nofold(last_line - num_lines + 1, last_line,
989                     -(last_line - dest - extra), 0, kExtmarkNOOP);
990
991  disable_fold_update++;
992  changed_lines(curbuf, last_line - num_lines + 1, 0, last_line + 1, -extra, false);
993  disable_fold_update--;
994
995  // send update regarding the new lines that were added
996  buf_updates_send_changes(curbuf, dest + 1, num_lines, 0);
997
998  // Now we delete the original text -- webb
999  if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL) {
1000    return FAIL;
1001  }
1002
1003  for (l = line1; l <= line2; l++) {
1004    ml_delete_flags(line1 + extra, ML_DEL_MESSAGE);
1005  }
1006  if (!global_busy && num_lines > p_report) {
1007    smsg(0, NGETTEXT("%" PRId64 " line moved",
1008                     "%" PRId64 " lines moved", num_lines),
1009         (int64_t)num_lines);
1010  }
1011
1012  extmark_move_region(curbuf, line1 - 1, 0, start_byte,
1013                      line2 - line1 + 1, 0, extent_byte,
1014                      dest + line_off, 0, dest_byte + byte_off,
1015                      kExtmarkUndo);
1016
1017  // Leave the cursor on the last of the moved lines.
1018  if (dest >= line1) {
1019    curwin->w_cursor.lnum = dest;
1020  } else {
1021    curwin->w_cursor.lnum = dest + (line2 - line1) + 1;
1022  }
1023
1024  if (line1 < dest) {
1025    dest += num_lines + 1;
1026    last_line = curbuf->b_ml.ml_line_count;
1027    dest = MIN(dest, last_line + 1);
1028    changed_lines(curbuf, line1, 0, dest, 0, false);
1029  } else {
1030    changed_lines(curbuf, dest + 1, 0, line1 + num_lines, 0, false);
1031  }
1032
1033  // send nvim_buf_lines_event regarding lines that were deleted
1034  buf_updates_send_changes(curbuf, line1 + extra, 0, num_lines);
1035
1036  return OK;
1037}
1038
1039/// ":copy"
1040void ex_copy(linenr_T line1, linenr_T line2, linenr_T n)
1041{
1042  linenr_T count = line2 - line1 + 1;
1043  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
1044    curbuf->b_op_start.lnum = n + 1;
1045    curbuf->b_op_end.lnum = n + count;
1046    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
1047  }
1048
1049  // there are three situations:
1050  // 1. destination is above line1
1051  // 2. destination is between line1 and line2
1052  // 3. destination is below line2
1053  //
1054  // n = destination (when starting)
1055  // curwin->w_cursor.lnum = destination (while copying)
1056  // line1 = start of source (while copying)
1057  // line2 = end of source (while copying)
1058  if (u_save(n, n + 1) == FAIL) {
1059    return;
1060  }
1061
1062  curwin->w_cursor.lnum = n;
1063  while (line1 <= line2) {
1064    // need to make a copy because the line will be unlocked within ml_append()
1065    char *p = xstrnsave(ml_get(line1), (size_t)ml_get_len(line1));
1066    ml_append(curwin->w_cursor.lnum, p, 0, false);
1067    xfree(p);
1068
1069    // situation 2: skip already copied lines
1070    if (line1 == n) {
1071      line1 = curwin->w_cursor.lnum;
1072    }
1073    line1++;
1074    if (curwin->w_cursor.lnum < line1) {
1075      line1++;
1076    }
1077    if (curwin->w_cursor.lnum < line2) {
1078      line2++;
1079    }
1080    curwin->w_cursor.lnum++;
1081  }
1082
1083  appended_lines_mark(n, count);
1084  if (Visual.active) {
1085    check_pos(curbuf, &Visual.start);
1086  }
1087
1088  msgmore(count);
1089}
1090
1091static char *prevcmd = NULL;        // the previous command
1092
1093#ifdef EXITFREE
1094void free_prev_shellcmd(void)
1095{
1096  xfree(prevcmd);
1097}
1098
1099#endif
1100
1101/// Check that "prevcmd" is not NULL.  If it is NULL then give an error message
1102/// and return false.
1103static int prevcmd_is_set(void)
1104{
1105  if (prevcmd == NULL) {
1106    emsg(_(e_noprev));
1107    return false;
1108  }
1109  return true;
1110}
1111
1112/// Handle the ":!cmd" command.  Also for ":r !cmd" and ":w !cmd"
1113/// Bangs in the argument are replaced with the previously entered command.
1114/// Remember the argument.
1115void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out)
1116  FUNC_ATTR_NONNULL_ALL
1117{
1118  char *arg = eap->arg;             // command
1119  linenr_T line1 = eap->line1;        // start of range
1120  linenr_T line2 = eap->line2;        // end of range
1121  char *newcmd = NULL;              // the new command
1122  bool free_newcmd = false;           // need to free() newcmd
1123  int scroll_save = msg_scroll;
1124
1125  // Disallow shell commands in secure mode
1126  if (check_secure()) {
1127    return;
1128  }
1129
1130  if (addr_count == 0) {                // :!
1131    msg_scroll = false;             // don't scroll here
1132    autowrite_all();
1133    msg_scroll = scroll_save;
1134  }
1135
1136  // Try to find an embedded bang, like in ":!<cmd> ! [args]"
1137  // ":!!" is indicated by the 'forceit' variable.
1138  bool ins_prevcmd = forceit;
1139
1140  // Skip leading white space to avoid a strange error with some shells.
1141  char *trailarg = skipwhite(arg);
1142  do {
1143    size_t len = strlen(trailarg) + 1;
1144    if (newcmd != NULL) {
1145      len += strlen(newcmd);
1146    }
1147    if (ins_prevcmd) {
1148      if (!prevcmd_is_set()) {
1149        xfree(newcmd);
1150        return;
1151      }
1152      len += strlen(prevcmd);
1153    }
1154    char *t = xmalloc(len);
1155    *t = NUL;
1156    if (newcmd != NULL) {
1157      strcat(t, newcmd);
1158    }
1159    if (ins_prevcmd) {
1160      strcat(t, prevcmd);
1161    }
1162    char *p = t + strlen(t);
1163    strcat(t, trailarg);
1164    xfree(newcmd);
1165    newcmd = t;
1166
1167    // Scan the rest of the argument for '!', which is replaced by the
1168    // previous command.  "\!" is replaced by "!" (this is vi compatible).
1169    trailarg = NULL;
1170    while (*p) {
1171      if (*p == '!') {
1172        if (p > newcmd && p[-1] == '\\') {
1173          STRMOVE(p - 1, p);
1174        } else {
1175          trailarg = p;
1176          *trailarg++ = NUL;
1177          ins_prevcmd = true;
1178          break;
1179        }
1180      }
1181      p++;
1182    }
1183  } while (trailarg != NULL);
1184
1185  // Only set "prevcmd" if there is a command to run, otherwise keep te one
1186  // we have.
1187  if (strlen(newcmd) > 0) {
1188    xfree(prevcmd);
1189    prevcmd = newcmd;
1190  } else {
1191    free_newcmd = true;
1192  }
1193
1194  if (bangredo) {  // put cmd in redo buffer for ! command
1195    if (!prevcmd_is_set()) {
1196      goto theend;
1197    }
1198
1199    // If % or # appears in the command, it must have been escaped.
1200    // Reescape them, so that redoing them does not substitute them by the
1201    // buffername.
1202    char *cmd = vim_strsave_escaped(prevcmd, "%#");
1203
1204    redo_append_lit(cmd, -1);
1205    xfree(cmd);
1206    redo_append_str(S_LEN("\n"));
1207    bangredo = false;
1208  }
1209  // Add quotes around the command, for shells that need them.
1210  if (*p_shq != NUL) {
1211    if (free_newcmd) {
1212      xfree(newcmd);
1213    }
1214    newcmd = xmalloc(strlen(prevcmd) + 2 * strlen(p_shq) + 1);
1215    STRCPY(newcmd, p_shq);
1216    strcat(newcmd, prevcmd);
1217    strcat(newcmd, p_shq);
1218    free_newcmd = true;
1219  }
1220  if (addr_count == 0) {                // :!
1221    // echo the command
1222    msg_start();
1223    msg_ext_no_fast();
1224    msg_ext_set_kind("shell_cmd");
1225    msg_putchar(':');
1226    msg_putchar('!');
1227    msg_outtrans(newcmd, 0, false);
1228    msg_clr_eos();
1229    ui_cursor_goto(msg_row, msg_col);
1230
1231    do_shell(newcmd, 0);
1232  } else {                            // :range!
1233    // Careful: This may recursively call do_bang() again! (because of
1234    // autocommands)
1235    do_filter(line1, line2, eap, newcmd, do_in, do_out);
1236    apply_autocmds(EVENT_SHELLFILTERPOST, NULL, NULL, false, curbuf);
1237  }
1238
1239theend:
1240  if (free_newcmd) {
1241    xfree(newcmd);
1242  }
1243}
1244
1245/// do_filter: filter lines through a command given by the user
1246///
1247/// We mostly use temp files and the call_shell() routine here. This would
1248/// normally be done using pipes on a Unix system, but this is more portable
1249/// to non-Unix systems. The call_shell() routine needs to be able
1250/// to deal with redirection somehow, and should handle things like looking
1251/// at the PATH env. variable, and adding reasonable extensions to the
1252/// command name given by the user. All reasonable versions of call_shell()
1253/// do this.
1254/// Alternatively, if on Unix and redirecting input or output, but not both,
1255/// and the 'shelltemp' option isn't set, use pipes.
1256/// We use input redirection if do_in is true.
1257/// We use output redirection if do_out is true.
1258///
1259/// @param eap  for forced 'ff' and 'fenc'
1260static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char *cmd, bool do_in,
1261                      bool do_out)
1262{
1263  char *itmp = NULL;
1264  char *otmp = NULL;
1265  buf_T *old_curbuf = curbuf;
1266  int shell_flags = 0;
1267  const pos_T orig_start = curbuf->b_op_start;
1268  const pos_T orig_end = curbuf->b_op_end;
1269  const int stmp = p_stmp;
1270
1271  if (*cmd == NUL) {        // no filter command
1272    return;
1273  }
1274
1275  const int save_cmod_flags = cmdmod.cmod_flags;
1276  // Temporarily disable lockmarks since that's needed to propagate changed
1277  // regions of the buffer for foldUpdate(), linecount, etc.
1278  cmdmod.cmod_flags &= ~CMOD_LOCKMARKS;
1279
1280  pos_T cursor_save = curwin->w_cursor;
1281  linenr_T linecount = line2 - line1 + 1;
1282  curwin->w_cursor.lnum = line1;
1283  curwin->w_cursor.col = 0;
1284  changed_line_abv_curs();
1285  invalidate_botline_win(curwin);
1286
1287  // When using temp files:
1288  // 1. * Form temp file names
1289  // 2. * Write the lines to a temp file
1290  // 3.   Run the filter command on the temp file
1291  // 4. * Read the output of the command into the buffer
1292  // 5. * Delete the original lines to be filtered
1293  // 6. * Remove the temp files
1294  //
1295  // When writing the input with a pipe or when catching the output with a
1296  // pipe only need to do 3.
1297
1298  if (do_out) {
1299    shell_flags |= kShellOptDoOut;
1300  }
1301
1302  if (!do_in && do_out && !stmp) {
1303    // Use a pipe to fetch stdout of the command, do not use a temp file.
1304    shell_flags |= kShellOptRead;
1305    curwin->w_cursor.lnum = line2;
1306  } else if (do_in && !do_out && !stmp) {
1307    // Use a pipe to write stdin of the command, do not use a temp file.
1308    shell_flags |= kShellOptWrite;
1309    curbuf->b_op_start.lnum = line1;
1310    curbuf->b_op_end.lnum = line2;
1311  } else if (do_in && do_out && !stmp) {
1312    // Use a pipe to write stdin and fetch stdout of the command, do not
1313    // use a temp file.
1314    shell_flags |= kShellOptRead | kShellOptWrite;
1315    curbuf->b_op_start.lnum = line1;
1316    curbuf->b_op_end.lnum = line2;
1317    curwin->w_cursor.lnum = line2;
1318  } else if ((do_in && (itmp = vim_tempname()) == NULL)
1319             || (do_out && (otmp = vim_tempname()) == NULL)) {
1320    emsg(_(e_notmp));
1321    goto filterend;
1322  }
1323
1324  // The writing and reading of temp files will not be shown.
1325  // Vi also doesn't do this and the messages are not very informative.
1326  no_wait_return++;             // don't call wait_return() while busy
1327  if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap,
1328                                false, false, false, true) == FAIL) {
1329    if (!ui_has(kUIMessages)) {
1330      msg_putchar('\n');  // Keep message from buf_write().
1331    }
1332    no_wait_return--;
1333    if (!aborting()) {
1334      // will call wait_return()
1335      semsg(_("E482: Can't create file %s"), itmp);
1336    }
1337    goto filterend;
1338  }
1339  if (curbuf != old_curbuf) {
1340    goto filterend;
1341  }
1342
1343  if (!do_out && !ui_has(kUIMessages)) {
1344    msg_putchar('\n');
1345  }
1346
1347  // Create the shell command in allocated memory.
1348  char *cmd_buf = make_filter_cmd(cmd, itmp, otmp, do_in);
1349  ui_cursor_goto(Rows - 1, 0);
1350
1351  if (do_out) {
1352    if (u_save(line2, (linenr_T)(line2 + 1)) == FAIL) {
1353      xfree(cmd_buf);
1354      goto error;
1355    }
1356    redraw_curbuf_later(UPD_VALID);
1357  }
1358  linenr_T read_linecount = curbuf->b_ml.ml_line_count;
1359
1360  // Pass on the kShellOptDoOut flag when the output is being redirected.
1361  call_shell(cmd_buf, kShellOptFilter | shell_flags, NULL);
1362  xfree(cmd_buf);
1363
1364  did_check_timestamps = false;
1365  need_check_timestamps = true;
1366
1367  // When interrupting the shell command, it may still have produced some
1368  // useful output.  Reset got_int here, so that readfile() won't cancel
1369  // reading.
1370  os_breakcheck();
1371  got_int = false;
1372
1373  if (do_out) {
1374    if (otmp != NULL) {
1375      if (readfile(otmp, NULL, line2, 0, (linenr_T)MAXLNUM, eap,
1376                   READ_FILTER, false) != OK) {
1377        if (!aborting()) {
1378          msg_putchar('\n');
1379          semsg(_(e_cant_read_file_str), otmp);
1380        }
1381        goto error;
1382      }
1383      if (curbuf != old_curbuf) {
1384        goto filterend;
1385      }
1386    }
1387
1388    read_linecount = curbuf->b_ml.ml_line_count - read_linecount;
1389
1390    if (shell_flags & kShellOptRead) {
1391      curbuf->b_op_start.lnum = line2 + 1;
1392      curbuf->b_op_end.lnum = curwin->w_cursor.lnum;
1393      appended_lines_mark(line2, read_linecount);
1394    }
1395
1396    if (do_in) {
1397      if ((cmdmod.cmod_flags & CMOD_KEEPMARKS)
1398          || vim_strchr(p_cpo, kCpoRemmark) == NULL) {
1399        // TODO(bfredl): Currently not active for extmarks. What would we
1400        // do if columns don't match, assume added/deleted bytes at the
1401        // end of each line?
1402        if (read_linecount >= linecount) {
1403          // move all marks from old lines to new lines
1404          mark_adjust(line1, line2, linecount, 0, kExtmarkNOOP);
1405        } else {
1406          // move marks from old lines to new lines, delete marks
1407          // that are in deleted lines
1408          mark_adjust(line1, line1 + read_linecount - 1, linecount, 0,
1409                      kExtmarkNOOP);
1410          mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0,
1411                      kExtmarkNOOP);
1412        }
1413      }
1414
1415      // Put cursor on first filtered line for ":range!cmd".
1416      // Adjust '[ and '] (set by buf_write()).
1417      curwin->w_cursor.lnum = line1;
1418      del_lines(linecount, true);
1419      if (read_linecount == 0) {
1420        // no filter output: clamp '[ and '] to a valid line
1421        curbuf->b_op_start.lnum = curbuf->b_op_end.lnum = MIN(line1, curbuf->b_ml.ml_line_count);
1422        curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
1423      } else {
1424        curbuf->b_op_start.lnum -= linecount;   // adjust '[
1425        curbuf->b_op_end.lnum -= linecount;     // adjust ']
1426      }
1427      write_lnum_adjust(-linecount);                    // adjust last line
1428                                                        // for next write
1429      foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum);
1430    } else {
1431      // Put cursor on last new line for ":r !cmd".
1432      linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1;
1433      curwin->w_cursor.lnum = curbuf->b_op_end.lnum;
1434    }
1435
1436    beginline(BL_WHITE | BL_FIX);           // cursor on first non-blank
1437    no_wait_return--;
1438
1439    if (linecount > p_report) {
1440      if (do_in) {
1441        vim_snprintf(msg_buf, sizeof(msg_buf),
1442                     _("%" PRId64 " lines filtered"), (int64_t)linecount);
1443        if (msg(msg_buf, 0) && !msg_scroll) {
1444          // save message to display it after redraw
1445          set_keep_msg(msg_buf, 0);
1446        }
1447      } else {
1448        msgmore(linecount);
1449      }
1450    }
1451  } else {
1452error:
1453    // put cursor back in same position for ":w !cmd"
1454    curwin->w_cursor = cursor_save;
1455    no_wait_return--;
1456    if (!ui_has(kUIMessages)) {
1457      wait_return(false);
1458    }
1459  }
1460
1461filterend:
1462
1463  cmdmod.cmod_flags = save_cmod_flags;
1464  if (curbuf != old_curbuf) {
1465    no_wait_return--;
1466    emsg(_("E135: *Filter* Autocommands must not change current buffer"));
1467  } else if (cmdmod.cmod_flags & CMOD_LOCKMARKS) {
1468    curbuf->b_op_start = orig_start;
1469    curbuf->b_op_end = orig_end;
1470  }
1471
1472  if (itmp != NULL) {
1473    os_remove(itmp);
1474  }
1475  if (otmp != NULL) {
1476    os_remove(otmp);
1477  }
1478  xfree(itmp);
1479  xfree(otmp);
1480}
1481
1482/// Call a shell to execute a command.
1483/// When "cmd" is NULL start an interactive shell.
1484///
1485/// @param flags  may be SHELL_DOOUT when output is redirected
1486void do_shell(char *cmd, int flags)
1487{
1488  // Disallow shell commands in secure mode
1489  if (check_secure()) {
1490    msg_end();
1491    return;
1492  }
1493
1494  // For autocommands we want to get the output on the current screen, to
1495  // avoid having to type return below.
1496  msg_putchar('\r');                    // put cursor at start of line
1497  msg_putchar('\n');                    // may shift screen one line up
1498
1499  // warning message before calling the shell
1500  if (p_warn
1501      && !autocmd_busy
1502      && msg_silent == 0) {
1503    FOR_ALL_BUFFERS(buf) {
1504      if (bufIsChanged(buf)) {
1505        msg_puts(_("[No write since last change]\n"));
1506        break;
1507      }
1508    }
1509  }
1510
1511  // This ui_cursor_goto is required for when the '\n' resulted in a "delete line
1512  // 1" command to the terminal.
1513  ui_cursor_goto(msg_row, msg_col);
1514  call_shell(cmd, flags, NULL);
1515  if (msg_silent == 0) {
1516    msg_didout = true;
1517  }
1518  did_check_timestamps = false;
1519  need_check_timestamps = true;
1520
1521  // put the message cursor at the end of the screen, avoids wait_return()
1522  // to overwrite the text that the external command showed
1523  msg_row = Rows - 1;
1524  msg_col = 0;
1525
1526  apply_autocmds(EVENT_SHELLCMDPOST, NULL, NULL, false, curbuf);
1527}
1528
1529#ifndef UNIX
1530static char *find_pipe(const char *cmd)
1531{
1532  bool inquote = false;
1533
1534  for (const char *p = cmd; *p != NUL; p++) {
1535    if (!inquote && *p == '|') {
1536      return (char *)p;
1537    }
1538    if (*p == '"') {
1539      inquote = !inquote;
1540    } else if (rem_backslash(p)) {
1541      p++;
1542    }
1543  }
1544  return NULL;
1545}
1546#endif
1547
1548/// Create a shell command from a command string, input redirection file and
1549/// output redirection file.
1550///
1551/// @param cmd  Command to execute.
1552/// @param itmp NULL or the input file.
1553/// @param otmp NULL or the output file.
1554/// @param do_in true if stdin is needed.
1555/// @returns an allocated string with the shell command.
1556char *make_filter_cmd(char *cmd, char *itmp, char *otmp, bool do_in)
1557{
1558  bool is_fish_shell =
1559#ifdef UNIX
1560    strncmp(invocation_path_tail(p_sh, NULL), "fish", 4) == 0;
1561#else
1562    false;
1563#endif
1564  bool is_pwsh = strncmp(invocation_path_tail(p_sh, NULL), "pwsh", 4) == 0
1565                 || strncmp(invocation_path_tail(p_sh, NULL), "powershell",
1566                            10) == 0;
1567
1568  size_t len = strlen(cmd) + 1;  // At least enough space for cmd + NULL.
1569
1570  len += is_fish_shell ? sizeof("begin; " "; end") - 1
1571                       : !is_pwsh ? sizeof("(" ")") - 1
1572                                  : 0;
1573
1574  if (itmp != NULL) {
1575    len += is_pwsh ? strlen(itmp) + sizeof("& { Get-Content " " | & " " }") - 1 + 6  // +6: #20530
1576                   : strlen(itmp) + sizeof(" { " " < " " } ") - 1;
1577  }
1578
1579  if (do_in && is_pwsh) {
1580    len += sizeof(" $input | ");
1581  }
1582
1583  if (otmp != NULL) {
1584    len += strlen(otmp) + strlen(p_srr) + 2;  // two extra spaces ("  "),
1585  }
1586
1587  char *const buf = xmalloc(len);
1588
1589  if (is_pwsh) {
1590    if (itmp != NULL) {
1591      xstrlcpy(buf, "& { Get-Content ", len - 1);  // FIXME: should we add "-Encoding utf8"?
1592      xstrlcat(buf, itmp, len - 1);
1593      xstrlcat(buf, " | & ", len - 1);  // FIXME: add `&` ourself or leave to user?
1594      xstrlcat(buf, cmd, len - 1);
1595      xstrlcat(buf, " }", len - 1);
1596    } else if (do_in) {
1597      xstrlcpy(buf, " $input | ", len - 1);
1598      xstrlcat(buf, cmd, len);
1599    } else {
1600      xstrlcpy(buf, cmd, len);
1601    }
1602  } else {
1603#ifdef UNIX
1604    // Put delimiters around the command (for concatenated commands) when
1605    // redirecting input and/or output.
1606    if (itmp != NULL || otmp != NULL) {
1607      char *fmt = is_fish_shell ? "begin; %s; end"
1608                                : "(%s)";
1609      vim_snprintf(buf, len, fmt, cmd);
1610    } else {
1611      xstrlcpy(buf, cmd, len);
1612    }
1613
1614    if (itmp != NULL) {
1615      xstrlcat(buf, " < ", len - 1);
1616      xstrlcat(buf, itmp, len - 1);
1617    }
1618#else
1619    // For shells that don't understand braces around commands, at least allow
1620    // the use of commands in a pipe.
1621    xstrlcpy(buf, cmd, len);
1622    if (itmp != NULL) {
1623      // If there is a pipe, we have to put the '<' in front of it.
1624      // Don't do this when 'shellquote' is not empty, otherwise the
1625      // redirection would be inside the quotes.
1626      if (*p_shq == NUL) {
1627        char *const p = find_pipe(buf);
1628        if (p != NULL) {
1629          *p = NUL;
1630        }
1631      }
1632      xstrlcat(buf, " < ", len);
1633      xstrlcat(buf, itmp, len);
1634      if (*p_shq == NUL) {
1635        const char *const p = find_pipe(cmd);
1636        if (p != NULL) {
1637          xstrlcat(buf, " ", len - 1);  // Insert a space before the '|' for DOS
1638          xstrlcat(buf, p, len - 1);
1639        }
1640      }
1641    }
1642#endif
1643  }
1644  if (otmp != NULL) {
1645    append_redir(buf, len, p_srr, otmp);
1646  }
1647  return buf;
1648}
1649
1650/// Append output redirection for the given file to the end of the buffer
1651///
1652/// @param[out]  buf  Buffer to append to.
1653/// @param[in]  buflen  Buffer length.
1654/// @param[in]  opt  Separator or format string to append: will append
1655///                  `printf(' ' . opt, fname)` if `%s` is found in `opt` or
1656///                  a space, opt, a space and then fname if `%s` is not found
1657///                  there.
1658/// @param[in]  fname  File name to append.
1659void append_redir(char *const buf, const size_t buflen, const char *const opt,
1660                  const char *const fname)
1661{
1662  char *const end = buf + strlen(buf);
1663  // find "%s"
1664  const char *p = opt;
1665  for (; (p = strchr(p, '%')) != NULL; p++) {
1666    if (p[1] == 's') {  // found %s
1667      break;
1668    } else if (p[1] == '%') {  // skip %%
1669      p++;
1670    }
1671  }
1672  if (p != NULL) {
1673    *end = ' ';  // not really needed? Not with sh, ksh or bash
1674
1675// This looks incredibly suss because it is: we are allowing a user option to
1676// define a snprintf format string. Such code should normally not be written.
1677// The validity of these option values is checked in `validate_shellpipe_redir`.
1678    PRAGMA_DIAG_PUSH_IGNORE_MISSING_FORMAT_ATTRIBUTE;
1679    vim_snprintf(end + 1, (size_t)((ptrdiff_t)buflen - (end + 1 - buf)), opt, fname);
1680    PRAGMA_DIAG_POP;
1681  } else {
1682    vim_snprintf(end, (size_t)((ptrdiff_t)buflen - (end - buf)), " %s %s", opt, fname);
1683  }
1684}
1685
1686void print_line_no_prefix(linenr_T lnum, bool use_number, bool list)
1687{
1688  char numbuf[30];
1689
1690  if (curwin->w_p_nu || use_number) {
1691    vim_snprintf(numbuf, sizeof(numbuf), "%*" PRIdLINENR " ",
1692                 number_width(curwin), lnum);
1693    msg_puts_hl(numbuf, HLF_N + 1, false);  // Highlight line nrs.
1694  }
1695  msg_prt_line(ml_get(lnum), list);
1696}
1697
1698static bool global_need_msg_kind = false;  // Start new message only once during :global.
1699
1700/// Print a text line.  Also in silent mode ("ex -s").
1701void print_line(linenr_T lnum, bool use_number, bool list, bool first)
1702{
1703  bool save_silent = silent_mode;
1704
1705  // apply :filter /pat/
1706  if (message_filtered(ml_get(lnum))) {
1707    return;
1708  }
1709
1710  silent_mode = false;
1711  info_message = true;  // use stdout, not stderr
1712  if ((!global_busy || global_need_msg_kind) && first) {
1713    msg_start();
1714    msg_ext_set_kind("list_cmd");
1715    global_need_msg_kind = false;
1716  } else if (!save_silent) {
1717    msg_putchar('\n');  // don't want trailing newline with regular messaging
1718  }
1719  print_line_no_prefix(lnum, use_number, list);
1720  if (save_silent) {
1721    msg_putchar('\n');  // batch mode message should always end in newline
1722    silent_mode = save_silent;
1723  }
1724  info_message = false;
1725}
1726
1727int rename_buffer(char *new_fname)
1728{
1729  buf_T *buf = curbuf;
1730  apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, false, curbuf);
1731  // buffer changed, don't change name now
1732  if (buf != curbuf) {
1733    return FAIL;
1734  }
1735  if (aborting()) {         // autocmds may abort script processing
1736    return FAIL;
1737  }
1738  // The name of the current buffer will be changed.
1739  // A new (unlisted) buffer entry needs to be made to hold the old file
1740  // name, which will become the alternate file name.
1741  // But don't set the alternate file name if the buffer didn't have a
1742  // name.
1743  char *fname = curbuf->b_ffname;
1744  char *sfname = curbuf->b_sfname;
1745  char *xfname = curbuf->b_fname;
1746  curbuf->b_ffname = NULL;
1747  curbuf->b_sfname = NULL;
1748  if (setfname(curbuf, new_fname, NULL, true) == FAIL) {
1749    curbuf->b_ffname = fname;
1750    curbuf->b_sfname = sfname;
1751    return FAIL;
1752  }
1753  curbuf->b_flags |= BF_NOTEDITED;
1754  if (xfname != NULL && *xfname != NUL) {
1755    buf = buflist_new(fname, xfname, curwin->w_cursor.lnum, 0);
1756    if (buf != NULL && (cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
1757      curwin->w_alt_fnum = buf->b_fnum;
1758    }
1759  }
1760  xfree(fname);
1761  xfree(sfname);
1762  apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, false, curbuf);
1763  // Change directories when the 'acd' option is set.
1764  do_autochdir();
1765  return OK;
1766}
1767
1768/// ":file[!] [fname]".
1769void ex_file(exarg_T *eap)
1770{
1771  // ":0file" removes the file name.  Check for illegal uses ":3file",
1772  // "0file name", etc.
1773  if (eap->addr_count > 0
1774      && (*eap->arg != NUL
1775          || eap->line2 > 0
1776          || eap->addr_count > 1)) {
1777    emsg(_(e_invarg));
1778    return;
1779  }
1780
1781  if (*eap->arg != NUL || eap->addr_count == 1) {
1782    if (rename_buffer(eap->arg) == FAIL) {
1783      return;
1784    }
1785    redraw_tabline = true;
1786  }
1787
1788  // print file name if no argument or 'F' is not in 'shortmess'
1789  if (*eap->arg == NUL || !shortmess(kShmFileinfo)) {
1790    fileinfo(false, false, eap->forceit);
1791  }
1792}
1793
1794/// ":update".
1795void ex_update(exarg_T *eap)
1796{
1797  if (curbufIsChanged()
1798      || (!bt_nofilename(curbuf) && curbuf->b_ffname != NULL
1799          && !os_path_exists(curbuf->b_ffname))) {
1800    do_write(eap);
1801  }
1802}
1803
1804/// ":write" and ":saveas".
1805void ex_write(exarg_T *eap)
1806{
1807  if (eap->cmdidx == CMD_saveas) {
1808    // :saveas does not take a range, uses all lines.
1809    eap->line1 = 1;
1810    eap->line2 = curbuf->b_ml.ml_line_count;
1811  }
1812
1813  if (eap->usefilter) {  // input lines to shell command
1814    do_bang(1, eap, false, true, false);
1815  } else {
1816    do_write(eap);
1817  }
1818}
1819
1820#ifdef UNIX
1821static int check_writable(const char *fname)
1822{
1823  if (os_nodetype(fname) == NODE_OTHER) {
1824    semsg(_("E503: \"%s\" is not a file or writable device"), fname);
1825    return FAIL;
1826  }
1827  return OK;
1828}
1829#endif
1830
1831static int handle_mkdir_p_arg(exarg_T *eap, char *fname)
1832{
1833  if (eap->mkdir_p && os_file_mkdir(fname, 0755) < 0) {
1834    return FAIL;
1835  }
1836
1837  return OK;
1838}
1839
1840/// Write current buffer to file "eap->arg".
1841/// If "eap->append" is true, append to the file.
1842///
1843/// If "*eap->arg == NUL" write to current file.
1844///
1845/// @return  FAIL for failure, OK otherwise.
1846int do_write(exarg_T *eap)
1847{
1848  bool other;
1849  char *fname = NULL;            // init to shut up gcc
1850  int retval = FAIL;
1851  char *free_fname = NULL;
1852  buf_T *alt_buf = NULL;
1853
1854  if (not_writing()) {          // check 'write' option
1855    return FAIL;
1856  }
1857
1858  char *ffname = eap->arg;
1859  if (*ffname == NUL) {
1860    if (eap->cmdidx == CMD_saveas) {
1861      emsg(_(e_argreq));
1862      goto theend;
1863    }
1864    other = false;
1865  } else {
1866    fname = ffname;
1867    free_fname = fix_fname(ffname);
1868    // When out-of-memory, keep unexpanded file name, because we MUST be
1869    // able to write the file in this situation.
1870    if (free_fname != NULL) {
1871      ffname = free_fname;
1872    }
1873    other = otherfile(ffname);
1874  }
1875
1876  // If we have a new file, put its name in the list of alternate file names.
1877  if (other) {
1878    if (vim_strchr(p_cpo, kCpoAltwrite) != NULL
1879        || eap->cmdidx == CMD_saveas) {
1880      alt_buf = setaltfname(ffname, fname, 1);
1881    } else {
1882      alt_buf = buflist_findname(ffname);
1883    }
1884    if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL) {
1885      // Overwriting a file that is loaded in another buffer is not a
1886      // good idea.
1887      emsg(_(e_bufloaded));
1888      goto theend;
1889    }
1890  }
1891
1892  // Writing to the current file is not allowed in readonly mode
1893  // and a file name is required.
1894  // "nofile" and "nowrite" buffers cannot be written implicitly either.
1895  if (!other && (bt_dontwrite_msg(curbuf)
1896                 || check_fname() == FAIL
1897#ifdef UNIX
1898                 || check_writable(curbuf->b_ffname) == FAIL
1899#endif
1900                 || check_readonly(&eap->forceit, curbuf))) {
1901    goto theend;
1902  }
1903
1904  if (!other) {
1905    ffname = curbuf->b_ffname;
1906    fname = curbuf->b_fname;
1907    // Not writing the whole file is only allowed with '!'.
1908    if ((eap->line1 != 1
1909         || eap->line2 != curbuf->b_ml.ml_line_count)
1910        && !eap->forceit
1911        && !eap->append
1912        && !p_wa) {
1913      if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) {
1914        if (vim_dialog_yesno(VIM_QUESTION, NULL,
1915                             _("Write partial file?"), 2) != VIM_YES) {
1916          goto theend;
1917        }
1918        eap->forceit = true;
1919      } else {
1920        emsg(_("E140: Use ! to write partial buffer"));
1921        goto theend;
1922      }
1923    }
1924  }
1925
1926  if (check_overwrite(eap, curbuf, fname, ffname, other) == OK) {
1927    if (eap->cmdidx == CMD_saveas && alt_buf != NULL) {
1928      buf_T *was_curbuf = curbuf;
1929
1930      apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, false, curbuf);
1931      apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, false, alt_buf);
1932      if (curbuf != was_curbuf || aborting()) {
1933        // buffer changed, don't change name now
1934        retval = FAIL;
1935        goto theend;
1936      }
1937      // Exchange the file names for the current and the alternate
1938      // buffer.  This makes it look like we are now editing the buffer
1939      // under the new name.  Must be done before buf_write(), because
1940      // if there is no file name and 'cpo' contains 'F', it will set
1941      // the file name.
1942      fname = alt_buf->b_fname;
1943      alt_buf->b_fname = curbuf->b_fname;
1944      curbuf->b_fname = fname;
1945      fname = alt_buf->b_ffname;
1946      alt_buf->b_ffname = curbuf->b_ffname;
1947      curbuf->b_ffname = fname;
1948      fname = alt_buf->b_sfname;
1949      alt_buf->b_sfname = curbuf->b_sfname;
1950      curbuf->b_sfname = fname;
1951      buf_name_changed(curbuf);
1952      apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, false, curbuf);
1953      apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, false, alt_buf);
1954      if (!alt_buf->b_p_bl) {
1955        alt_buf->b_p_bl = true;
1956        apply_autocmds(EVENT_BUFADD, NULL, NULL, false, alt_buf);
1957      }
1958      if (curbuf != was_curbuf || aborting()) {
1959        // buffer changed, don't write the file
1960        retval = FAIL;
1961        goto theend;
1962      }
1963
1964      // If 'filetype' was empty try detecting it now.
1965      if (*curbuf->b_p_ft == NUL) {
1966        if (augroup_exists("filetypedetect")) {
1967          do_doautocmd("filetypedetect BufRead", true, NULL);
1968        }
1969        do_modelines(0);
1970      }
1971
1972      // Autocommands may have changed buffer names, esp. when
1973      // 'autochdir' is set.
1974      fname = curbuf->b_sfname;
1975    }
1976
1977    if (handle_mkdir_p_arg(eap, fname) == FAIL) {
1978      retval = FAIL;
1979      goto theend;
1980    }
1981
1982    int name_was_missing = curbuf->b_ffname == NULL;
1983    retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2,
1984                       eap, eap->append, eap->forceit, true, false);
1985
1986    // After ":saveas fname" reset 'readonly'.
1987    if (eap->cmdidx == CMD_saveas) {
1988      if (retval == OK) {
1989        curbuf->b_p_ro = false;
1990        redraw_tabline = true;
1991      }
1992    }
1993
1994    // Change directories when the 'acd' option is set and the file name
1995    // got changed or set.
1996    if (eap->cmdidx == CMD_saveas || name_was_missing) {
1997      do_autochdir();
1998    }
1999  }
2000
2001theend:
2002  xfree(free_fname);
2003  return retval;
2004}
2005
2006/// Check if it is allowed to overwrite a file.  If b_flags has BF_NOTEDITED,
2007/// BF_NEW or BF_READERR, check for overwriting current file.
2008/// May set eap->forceit if a dialog says it's OK to overwrite.
2009///
2010/// @param fname   file name to be used (can differ from buf->ffname)
2011/// @param ffname  full path version of fname
2012/// @param other   writing under other name
2013///
2014/// @return  OK if it's OK, FAIL if it is not.
2015int check_overwrite(exarg_T *eap, buf_T *buf, char *fname, char *ffname, bool other)
2016{
2017  // Write to another file or b_flags set or not writing the whole file:
2018  // overwriting only allowed with '!'
2019  // If "other" is false and bt_nofilename(buf) is true, this must be
2020  // writing an "acwrite" buffer to the same file as its b_ffname, and
2021  // buf_write() will only allow writing with BufWriteCmd autocommands,
2022  // so there is no need for an overwrite check.
2023  if ((other
2024       || (!bt_nofilename(buf)
2025           && ((buf->b_flags & BF_NOTEDITED)
2026               || ((buf->b_flags & BF_NEW)
2027                   && vim_strchr(p_cpo, kCpoOvernew) == NULL)
2028               || (buf->b_flags & BF_READERR))))
2029      && !p_wa
2030      && os_path_exists(ffname)) {
2031    if (!eap->forceit && !eap->append) {
2032      if (os_isdir(ffname)) {
2033        semsg(_(e_isadir2), ffname);
2034        return FAIL;
2035      }
2036      if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) {
2037        char buff[DIALOG_MSG_SIZE];
2038        snprintf(buff, sizeof buff, _("Overwrite existing file \"%s\"?"), fname);
2039        if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES) {
2040          return FAIL;
2041        }
2042        eap->forceit = true;
2043      } else {
2044        emsg(_(e_exists));
2045        return FAIL;
2046      }
2047    }
2048
2049    // For ":w! filename" check that no swap file exists for "filename".
2050    if (other && !emsg_silent) {
2051      char *dir;
2052
2053      // We only try the first entry in 'directory', without checking if
2054      // it's writable.  If the "." directory is not writable the write
2055      // will probably fail anyway.
2056      // Use 'shortname' of the current buffer, since there is no buffer
2057      // for the written file.
2058      if (*p_dir == NUL) {
2059        dir = xmalloc(5);
2060        STRCPY(dir, ".");
2061      } else {
2062        dir = xmalloc(MAXPATHL);
2063        char *p = p_dir;
2064        copy_option_part(&p, dir, MAXPATHL, ",");
2065      }
2066      char *swapname = makeswapname(fname, ffname, curbuf, dir);
2067      xfree(dir);
2068      if (os_path_exists(swapname)) {
2069        if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) {
2070          char buff[DIALOG_MSG_SIZE];
2071
2072          vim_snprintf(buff, sizeof buff,
2073                       _("Swap file \"%s\" exists, overwrite anyway?"),
2074                       swapname);
2075          if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2)
2076              != VIM_YES) {
2077            xfree(swapname);
2078            return FAIL;
2079          }
2080          eap->forceit = true;
2081        } else {
2082          semsg(_("E768: Swap file exists: %s (:silent! overrides)"),
2083                swapname);
2084          xfree(swapname);
2085          return FAIL;
2086        }
2087      }
2088      xfree(swapname);
2089    }
2090  }
2091  return OK;
2092}
2093
2094/// Handle ":wnext", ":wNext" and ":wprevious" commands.
2095void ex_wnext(exarg_T *eap)
2096{
2097  int i;
2098
2099  if (eap->cmd[1] == 'n') {
2100    i = curwin->w_arg_idx + (int)eap->line2;
2101  } else {
2102    i = curwin->w_arg_idx - (int)eap->line2;
2103  }
2104  eap->line1 = 1;
2105  eap->line2 = curbuf->b_ml.ml_line_count;
2106  if (do_write(eap) != FAIL) {
2107    do_argfile(eap, i);
2108  }
2109}
2110
2111/// ":wall", ":wqall" and ":xall": Write all changed files (and exit).
2112void do_wqall(exarg_T *eap)
2113{
2114  int error = 0;
2115  int save_forceit = eap->forceit;
2116  bool save_exiting = exiting;
2117
2118  if (eap->cmdidx == CMD_xall || eap->cmdidx == CMD_wqall) {
2119    if (before_quit_all(eap) == FAIL) {
2120      return;
2121    }
2122    exiting = true;
2123  }
2124
2125  FOR_ALL_BUFFERS(buf) {
2126    if (exiting && !eap->forceit
2127        && buf->terminal
2128        // TODO(zeertzjq): this always returns false for nvim_open_term() terminals.
2129        // Use terminal_running() instead?
2130        && channel_job_running((uint64_t)buf->b_p_channel)) {
2131      no_write_message_buf(buf);
2132      error++;
2133      continue;
2134    } else if (!bufIsChanged(buf) || bt_dontwrite(buf)) {
2135      continue;
2136    }
2137    // Check if there is a reason the buffer cannot be written:
2138    // 1. if the 'write' option is set
2139    // 2. if there is no file name (even after browsing)
2140    // 3. if the 'readonly' is set (even after a dialog)
2141    // 4. if overwriting is allowed (even after a dialog)
2142    if (not_writing()) {
2143      error++;
2144      break;
2145    }
2146    if (buf->b_ffname == NULL) {
2147      semsg(_("E141: No file name for buffer %" PRId64), (int64_t)buf->b_fnum);
2148      error++;
2149    } else if (check_readonly(&eap->forceit, buf)
2150               || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname, false) == FAIL) {
2151      error++;
2152    } else {
2153      bufref_T bufref;
2154      set_bufref(&bufref, buf);
2155      if (handle_mkdir_p_arg(eap, buf->b_fname) == FAIL
2156          || buf_write_all(buf, eap->forceit) == FAIL) {
2157        error++;
2158      }
2159      // An autocommand may have deleted the buffer.
2160      if (!bufref_valid(&bufref)) {
2161        buf = firstbuf;
2162      }
2163    }
2164    eap->forceit = save_forceit;          // check_overwrite() may set it
2165  }
2166  if (exiting) {
2167    if (!error) {
2168      getout(0);                // exit Vim
2169    }
2170    not_exiting(save_exiting);
2171  }
2172}
2173
2174/// Check the 'write' option.
2175///
2176/// @return  true and give a message when it's not st.
2177static bool not_writing(void)
2178{
2179  if (p_write) {
2180    return false;
2181  }
2182  emsg(_("E142: File not written: Writing is disabled by 'write' option"));
2183  return true;
2184}
2185
2186/// Check if a buffer is read-only (either 'readonly' option is set or file is
2187/// read-only). Ask for overruling in a dialog. Return true and give an error
2188/// message when the buffer is readonly.
2189static int check_readonly(int *forceit, buf_T *buf)
2190{
2191  // Handle a file being readonly when the 'readonly' option is set or when
2192  // the file exists and permissions are read-only.
2193  if (!*forceit && (buf->b_p_ro
2194                    || (os_path_exists(buf->b_ffname)
2195                        && !os_file_is_writable(buf->b_ffname)))) {
2196    if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && buf->b_fname != NULL) {
2197      char buff[DIALOG_MSG_SIZE];
2198
2199      const char *fname = buf->b_fname ? buf->b_fname : _("Untitled");
2200      if (buf->b_p_ro) {
2201        snprintf(buff, sizeof buff,
2202                 _("'readonly' option is set for \"%s\".\nDo you wish to write anyway?"),
2203                 fname);
2204      } else {
2205        snprintf(buff, sizeof buff,
2206                 _("File permissions of \"%s\" are read-only.\nIt may still be possible to "
2207                   "write it.\nDo you wish to try?"),
2208                 fname);
2209      }
2210
2211      if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES) {
2212        // Set forceit, to force the writing of a readonly file
2213        *forceit = true;
2214        return false;
2215      }
2216      return true;
2217    } else if (buf->b_p_ro) {
2218      emsg(_(e_readonly));
2219    } else {
2220      semsg(_("E505: \"%s\" is read-only (add ! to override)"),
2221            buf->b_fname);
2222    }
2223    return true;
2224  }
2225
2226  return false;
2227}
2228
2229/// Try to abandon the current file and edit a new or existing file.
2230///
2231/// @param fnum  the number of the file, if zero use "ffname_arg"/"sfname_arg".
2232/// @param lnum  the line number for the cursor in the new file (if non-zero).
2233///
2234/// @return:
2235///           GETFILE_ERROR for "normal" error,
2236///           GETFILE_NOT_WRITTEN for "not written" error,
2237///           GETFILE_SAME_FILE for success
2238///           GETFILE_OPEN_OTHER for successfully opening another file.
2239int getfile(int fnum, char *ffname_arg, char *sfname_arg, bool setpm, linenr_T lnum, bool forceit)
2240{
2241  if (!check_can_set_curbuf_forceit(forceit)) {
2242    return GETFILE_ERROR;
2243  }
2244
2245  char *ffname = ffname_arg;
2246  char *sfname = sfname_arg;
2247  bool other;
2248  int retval;
2249  char *free_me = NULL;
2250
2251  if (text_locked()) {
2252    return GETFILE_ERROR;
2253  }
2254  if (curbuf_locked()) {
2255    return GETFILE_ERROR;
2256  }
2257
2258  if (fnum == 0) {
2259    // make ffname full path, set sfname
2260    fname_expand(curbuf, &ffname, &sfname);
2261    other = otherfile(ffname);
2262    free_me = ffname;                   // has been allocated, free() later
2263  } else {
2264    other = (fnum != curbuf->b_fnum);
2265  }
2266
2267  if (other) {
2268    no_wait_return++;               // don't wait for autowrite message
2269  }
2270  if (other && !forceit && curbuf->b_nwindows == 1 && !buf_hide(curbuf)
2271      && curbufIsChanged() && autowrite(curbuf, forceit) == FAIL) {
2272    if (p_confirm && p_write) {
2273      dialog_changed(curbuf, false);
2274    }
2275    if (curbufIsChanged()) {
2276      no_wait_return--;
2277      no_write_message();
2278      retval = GETFILE_NOT_WRITTEN;     // File has been changed.
2279      goto theend;
2280    }
2281  }
2282  if (other) {
2283    no_wait_return--;
2284  }
2285  if (setpm) {
2286    setpcmark();
2287  }
2288  if (!other) {
2289    if (lnum != 0) {
2290      curwin->w_cursor.lnum = lnum;
2291    }
2292    check_cursor_lnum(curwin);
2293    beginline(BL_SOL | BL_FIX);
2294    retval = GETFILE_SAME_FILE;     // it's in the same file
2295  } else if (do_ecmd(fnum, ffname, sfname, NULL, lnum,
2296                     (buf_hide(curbuf) ? ECMD_HIDE : 0)
2297                     + (forceit ? ECMD_FORCEIT : 0), curwin) == OK) {
2298    retval = GETFILE_OPEN_OTHER;    // opened another file
2299  } else {
2300    retval = GETFILE_ERROR;         // error encountered
2301  }
2302
2303theend:
2304  xfree(free_me);
2305  return retval;
2306}
2307
2308/// set v:swapcommand for the SwapExists autocommands.
2309///
2310/// @param command  [+cmd] to be executed (e.g. +10).
2311/// @param newlnum  if > 0: put cursor on this line number (if possible)
2312//
2313/// @return 1 if swapcommand was actually set, 0 otherwise
2314bool set_swapcommand(char *command, linenr_T newlnum)
2315{
2316  if ((command == NULL && newlnum <= 0) || *get_vim_var_str(VV_SWAPCOMMAND) != NUL) {
2317    return false;
2318  }
2319  const size_t valsize = (command != NULL) ? strlen(command) + 3 : 30;
2320  String val;
2321  val.data = xmalloc(valsize);
2322  val.size = (command != NULL)
2323             ? vim_snprintf_safelen(val.data, valsize, ":%s\r", command)
2324             : vim_snprintf_safelen(val.data, valsize, "%" PRId64 "G", (int64_t)newlnum);
2325  set_vim_var_string(VV_SWAPCOMMAND, val.data, (ptrdiff_t)val.size);
2326  xfree(val.data);
2327  return true;
2328}
2329
2330/// start editing a new file
2331///
2332/// @param fnum     file number; if zero use ffname/sfname
2333/// @param ffname   the file name
2334///                 - full path if sfname used,
2335///                 - any file name if sfname is NULL
2336///                 - empty string to re-edit with the same file name (but may
2337///                   be in a different directory)
2338///                 - NULL to start an empty buffer
2339/// @param sfname   the short file name (or NULL)
2340/// @param eap      contains the command to be executed after loading the file
2341///                 and forced 'ff' and 'fenc'. Can be NULL!
2342/// @param newlnum  if > 0: put cursor on this line number (if possible)
2343///                 ECMD_LASTL: use last position in loaded file
2344///                 ECMD_LAST: use last position in all files
2345///                 ECMD_ONE: use first line
2346/// @param flags    ECMD_HIDE: if true don't free the current buffer
2347///                 ECMD_SET_HELP: set b_help flag of (new) buffer before
2348///                 opening file
2349///                 ECMD_OLDBUF: use existing buffer if it exists
2350///                 ECMD_FORCEIT: ! used for Ex command
2351///                 ECMD_ADDBUF: don't edit, just add to buffer list
2352///                 ECMD_ALTBUF: like ECMD_ADDBUF and also set the alternate
2353///                 file
2354///                 ECMD_NOWINENTER: Do not trigger BufWinEnter
2355/// @param oldwin   Should be "curwin" when editing a new buffer in the current
2356///                 window, NULL when splitting the window first.  When not NULL
2357///                 info of the previous buffer for "oldwin" is stored.
2358///
2359/// @return FAIL for failure, OK otherwise
2360int do_ecmd(int fnum, char *ffname, char *sfname, exarg_T *eap, linenr_T newlnum, int flags,
2361            win_T *oldwin)
2362{
2363  bool other_file;                      // true if editing another file
2364  int oldbuf;                           // true if using existing buffer
2365  bool auto_buf = false;                // true if autocommands brought us
2366                                        // into the buffer unexpectedly
2367  char *new_name = NULL;
2368  bool did_set_swapcommand = false;
2369  buf_T *buf;
2370  bufref_T bufref;
2371  bufref_T old_curbuf;
2372  char *free_fname = NULL;
2373  int retval = FAIL;
2374  linenr_T topline = 0;
2375  int newcol = -1;
2376  int solcol = -1;
2377  char *command = NULL;
2378  bool did_get_winopts = false;
2379  int readfile_flags = 0;
2380  bool did_inc_redrawing_disabled = false;
2381  OptInt *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;
2382
2383  if (eap != NULL) {
2384    command = eap->do_ecmd_cmd;
2385  }
2386
2387  set_bufref(&old_curbuf, curbuf);
2388
2389  if (fnum != 0) {
2390    if (fnum == curbuf->b_fnum) {       // file is already being edited
2391      return OK;                        // nothing to do
2392    }
2393    other_file = true;
2394  } else {
2395    // if no short name given, use ffname for short name
2396    if (sfname == NULL) {
2397      sfname = ffname;
2398    }
2399#ifdef CASE_INSENSITIVE_FILENAME
2400    if (sfname != NULL) {
2401      path_fix_case(sfname);             // set correct case for sfname
2402    }
2403#endif
2404
2405    if ((flags & (ECMD_ADDBUF | ECMD_ALTBUF))
2406        && (ffname == NULL || *ffname == NUL)) {
2407      goto theend;
2408    }
2409
2410    if (ffname == NULL) {
2411      other_file = true;
2412    } else if (*ffname == NUL && curbuf->b_ffname == NULL) {  // there is no file name
2413      other_file = false;
2414    } else {
2415      if (*ffname == NUL) {                 // re-edit with same file name
2416        ffname = curbuf->b_ffname;
2417        sfname = curbuf->b_fname;
2418      }
2419      free_fname = fix_fname(ffname);       // may expand to full path name
2420      if (free_fname != NULL) {
2421        ffname = free_fname;
2422      }
2423      other_file = otherfile(ffname);
2424    }
2425  }
2426
2427  // Re-editing a terminal buffer: skip most buffer re-initialization.
2428  if (!other_file && curbuf->terminal) {
2429    check_arg_idx(curwin);  // Needed when called from do_argfile().
2430    maketitle();            // Title may show the arg index, e.g. "(2 of 5)".
2431    retval = OK;
2432    goto theend;
2433  }
2434
2435  // If the file was changed we may not be allowed to abandon it:
2436  // - if we are going to re-edit the same file
2437  // - or if we are the only window on this file and if ECMD_HIDE is false
2438  if (((!other_file && !(flags & ECMD_OLDBUF))
2439       || (curbuf->b_nwindows == 1
2440           && !(flags & (ECMD_HIDE | ECMD_ADDBUF | ECMD_ALTBUF))))
2441      && check_changed(curbuf, (p_awa ? CCGD_AW : 0)
2442                       | (other_file ? 0 : CCGD_MULTWIN)
2443                       | ((flags & ECMD_FORCEIT) ? CCGD_FORCEIT : 0)
2444                       | (eap == NULL ? 0 : CCGD_EXCMD))) {
2445    if (fnum == 0 && other_file && ffname != NULL) {
2446      setaltfname(ffname, sfname, newlnum < 0 ? 0 : newlnum);
2447    }
2448    goto theend;
2449  }
2450
2451  // End Visual mode before switching to another buffer, so the text can be
2452  // copied into the GUI selection buffer.
2453  // Careful: may trigger ModeChanged() autocommand
2454
2455  // Should we block autocommands here?
2456  reset_VIsual();
2457
2458  // autocommands freed window :(
2459  if (oldwin != NULL && !win_valid(oldwin)) {
2460    oldwin = NULL;
2461  }
2462
2463  did_set_swapcommand = set_swapcommand(command, newlnum);
2464
2465  // If we are starting to edit another file, open a (new) buffer.
2466  // Otherwise we re-use the current buffer.
2467  if (other_file) {
2468    const int prev_alt_fnum = curwin->w_alt_fnum;
2469
2470    if (!(flags & (ECMD_ADDBUF | ECMD_ALTBUF))) {
2471      if ((cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
2472        curwin->w_alt_fnum = curbuf->b_fnum;
2473      }
2474      if (oldwin != NULL) {
2475        buflist_altfpos(oldwin);
2476      }
2477    }
2478
2479    if (fnum) {
2480      buf = buflist_findnr(fnum);
2481    } else {
2482      if (flags & (ECMD_ADDBUF | ECMD_ALTBUF)) {
2483        // Default the line number to zero to avoid that a wininfo item
2484        // is added for the current window.
2485        linenr_T tlnum = 0;
2486
2487        if (command != NULL) {
2488          tlnum = (linenr_T)atol(command);
2489          if (tlnum <= 0) {
2490            tlnum = 1;
2491          }
2492        }
2493        // Add BLN_NOCURWIN to avoid a new wininfo items are associated
2494        // with the current window.
2495        const buf_T *const newbuf
2496          = buflist_new(ffname, sfname, tlnum, BLN_LISTED | BLN_NOCURWIN);
2497        if (newbuf != NULL && (flags & ECMD_ALTBUF)) {
2498          curwin->w_alt_fnum = newbuf->b_fnum;
2499        }
2500        goto theend;
2501      }
2502      buf = buflist_new(ffname, sfname, 0,
2503                        BLN_CURBUF | (flags & ECMD_SET_HELP ? 0 : BLN_LISTED));
2504      // Autocmds may change curwin and curbuf.
2505      if (oldwin != NULL) {
2506        oldwin = curwin;
2507      }
2508      set_bufref(&old_curbuf, curbuf);
2509    }
2510    if (buf == NULL) {
2511      goto theend;
2512    }
2513    // autocommands try to edit a closing buffer, which like splitting, can
2514    // result in more windows displaying it; abort
2515    if (buf->b_locked_split) {
2516      emsg(_(e_cannot_switch_to_a_closing_buffer));
2517      goto theend;
2518    }
2519    if (curwin->w_alt_fnum == buf->b_fnum && prev_alt_fnum != 0) {
2520      // reusing the buffer, keep the old alternate file
2521      curwin->w_alt_fnum = prev_alt_fnum;
2522    }
2523    if (buf->b_ml.ml_mfp == NULL) {
2524      // No memfile yet.
2525      oldbuf = false;
2526    } else {
2527      // Existing memfile.
2528      oldbuf = true;
2529      set_bufref(&bufref, buf);
2530      buf_check_timestamp(buf);
2531      // Check if autocommands made buffer invalid or changed the current
2532      // buffer.
2533      if (!bufref_valid(&bufref) || curbuf != old_curbuf.br_buf) {
2534        goto theend;
2535      }
2536      if (aborting()) {
2537        // Autocmds may abort script processing.
2538        goto theend;
2539      }
2540    }
2541
2542    // May jump to last used line number for a loaded buffer or when asked
2543    // for explicitly
2544    if ((oldbuf && newlnum == ECMD_LASTL) || newlnum == ECMD_LAST) {
2545      pos_T *pos = &buflist_findfmark(buf)->mark;
2546      newlnum = pos->lnum;
2547      solcol = pos->col;
2548    }
2549
2550    // Make the (new) buffer the one used by the current window.
2551    // If the old buffer becomes unused, free it if ECMD_HIDE is false.
2552    // If the current buffer was empty and has no file name, curbuf
2553    // is returned by buflist_new(), nothing to do here.
2554    if (buf != curbuf) {
2555      // Be careful: The autocommands may delete any buffer and change
2556      // the current buffer.
2557      // - If the buffer we are going to edit is deleted, give up.
2558      // - If the current buffer is deleted, prefer to load the new
2559      //   buffer when loading a buffer is required.  This avoids
2560      //   loading another buffer which then must be closed again.
2561      // - If we ended up in the new buffer already, need to skip a few
2562      //         things, set auto_buf.
2563      if (buf->b_fname != NULL) {
2564        new_name = xstrdup(buf->b_fname);
2565      }
2566      const bufref_T save_au_new_curbuf = au_new_curbuf;
2567      set_bufref(&au_new_curbuf, buf);
2568      apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf);
2569
2570      if (!bufref_valid(&au_new_curbuf)) {
2571        // New buffer has been deleted.
2572        delbuf_msg(new_name);  // Frees new_name.
2573        au_new_curbuf = save_au_new_curbuf;
2574        goto theend;
2575      }
2576      if (aborting()) {             // autocmds may abort script processing
2577        xfree(new_name);
2578        au_new_curbuf = save_au_new_curbuf;
2579        goto theend;
2580      }
2581      if (buf == curbuf) {  // already in new buffer
2582        auto_buf = true;
2583      } else {
2584        win_T *the_curwin = curwin;
2585
2586        // Set w_locked to avoid that autocommands close the window.
2587        // Set b_locked for the same reason.
2588        the_curwin->w_locked++;
2589        buf->b_locked++;
2590
2591        if (curbuf == old_curbuf.br_buf) {
2592          buf_copy_options(buf, BCO_ENTER);
2593        }
2594
2595        // Close the link to the current buffer. This may set
2596        // curwin->w_buffer to NULL.
2597        u_sync(false);
2598        close_buffer(curwin, curbuf,
2599                     (flags & ECMD_HIDE)
2600                     || (curbuf->terminal && terminal_running(curbuf->terminal))
2601                     ? 0 : DOBUF_UNLOAD,
2602                     false, false, oldwin != NULL);
2603
2604        // Autocommands may have closed the window.
2605        if (win_valid(the_curwin)) {
2606          the_curwin->w_locked--;
2607        }
2608        buf->b_locked--;
2609
2610        // autocmds may abort script processing
2611        if (aborting() && curwin->w_buffer != NULL) {
2612          xfree(new_name);
2613          au_new_curbuf = save_au_new_curbuf;
2614          goto theend;
2615        }
2616        // Be careful again, like above.
2617        if (!bufref_valid(&au_new_curbuf)) {
2618          // New buffer was deleted.  If curwin->w_buffer is NULL, we
2619          // must enter some buffer.  Hopefully the last one is OK.
2620          if (curwin->w_buffer == NULL) {
2621            buf = lastbuf;
2622          } else {
2623            delbuf_msg(new_name);  // Frees new_name.
2624            au_new_curbuf = save_au_new_curbuf;
2625            goto theend;
2626          }
2627        }
2628        if (buf == curbuf) {  // already in new buffer
2629          auto_buf = true;
2630        } else {
2631          // <VN> We could instead free the synblock
2632          // and re-attach to buffer, perhaps.
2633          if (curwin->w_buffer == NULL
2634              || curwin->w_s == &(curwin->w_buffer->b_s)) {
2635            curwin->w_s = &(buf->b_s);
2636          }
2637
2638          if (curwin->w_buffer != NULL) {
2639            curwin->w_buffer->b_nwindows--;
2640          }
2641
2642          curwin->w_buffer = buf;
2643          curbuf = buf;
2644          curbuf->b_nwindows++;
2645
2646          // Set 'fileformat', 'binary' and 'fenc' when forced.
2647          if (!oldbuf && eap != NULL) {
2648            set_file_options(true, eap);
2649            set_forced_fenc(eap);
2650          }
2651        }
2652
2653        // May get the window options from the last time this buffer
2654        // was in this window (or another window).  If not used
2655        // before, reset the local window options to the global
2656        // values.  Also restores old folding stuff.
2657        get_winopts(curbuf);
2658        did_get_winopts = true;
2659      }
2660      xfree(new_name);
2661      au_new_curbuf = save_au_new_curbuf;
2662    }
2663
2664    curwin->w_pcmark.lnum = 1;
2665    curwin->w_pcmark.col = 0;
2666  } else {  // !other_file
2667    if ((flags & (ECMD_ADDBUF | ECMD_ALTBUF)) || check_fname() == FAIL) {
2668      goto theend;
2669    }
2670    oldbuf = (flags & ECMD_OLDBUF);
2671  }
2672
2673  // Don't redraw until the cursor is in the right line, otherwise
2674  // autocommands may cause ml_get errors.
2675  RedrawingDisabled++;
2676  did_inc_redrawing_disabled = true;
2677
2678  buf = curbuf;
2679  if ((flags & ECMD_SET_HELP) || keep_help_flag) {
2680    prepare_help_buffer();
2681  } else if (!curbuf->b_help) {
2682    // Don't make a buffer listed if it's a help buffer.  Useful when using
2683    // CTRL-O to go back to a help file.
2684    set_buflisted(true);
2685  }
2686
2687  // If autocommands change buffers under our fingers, forget about
2688  // editing the file.
2689  if (buf != curbuf) {
2690    goto theend;
2691  }
2692  if (aborting()) {         // autocmds may abort script processing
2693    goto theend;
2694  }
2695
2696  // Since we are starting to edit a file, consider the filetype to be
2697  // unset.  Helps for when an autocommand changes files and expects syntax
2698  // highlighting to work in the other file.
2699  curbuf->b_did_filetype = false;
2700
2701  // other_file oldbuf
2702  //  false     false       re-edit same file, buffer is re-used
2703  //  false     true        re-edit same file, nothing changes
2704  //  true      false       start editing new file, new buffer
2705  //  true      true        start editing in existing buffer (nothing to do)
2706  if (!other_file && !oldbuf) {         // re-use the buffer
2707    set_last_cursor(curwin);            // may set b_last_cursor
2708    if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL) {
2709      newlnum = curwin->w_cursor.lnum;
2710      solcol = curwin->w_cursor.col;
2711    }
2712    buf = curbuf;
2713    if (buf->b_fname != NULL) {
2714      new_name = xstrdup(buf->b_fname);
2715    } else {
2716      new_name = NULL;
2717    }
2718    set_bufref(&bufref, buf);
2719
2720    // If the buffer was used before, store the current contents so that
2721    // the reload can be undone.  Do not do this if the (empty) buffer is
2722    // being re-used for another file.
2723    if (!(curbuf->b_flags & BF_NEVERLOADED)
2724        && (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)) {
2725      // Sync first so that this is a separate undo-able action.
2726      u_sync(false);
2727      if (u_savecommon(curbuf, 0, curbuf->b_ml.ml_line_count + 1, 0, true)
2728          == FAIL) {
2729        xfree(new_name);
2730        goto theend;
2731      }
2732      u_unchanged(curbuf);
2733      buf_freeall(curbuf, BFA_KEEP_UNDO);
2734
2735      // Tell readfile() not to clear or reload undo info.
2736      readfile_flags = READ_KEEP_UNDO;
2737    } else {
2738      buf_freeall(curbuf, 0);  // Free all things for buffer.
2739    }
2740    // If autocommands deleted the buffer we were going to re-edit, give
2741    // up and jump to the end.
2742    if (!bufref_valid(&bufref)) {
2743      delbuf_msg(new_name);  // Frees new_name.
2744      goto theend;
2745    }
2746    xfree(new_name);
2747
2748    // If autocommands change buffers under our fingers, forget about
2749    // re-editing the file.  Should do the buf_clear_file(), but perhaps
2750    // the autocommands changed the buffer...
2751    if (buf != curbuf) {
2752      goto theend;
2753    }
2754    if (aborting()) {       // autocmds may abort script processing
2755      goto theend;
2756    }
2757    buf_clear_file(curbuf);
2758    curbuf->b_op_start.lnum = 0;        // clear '[ and '] marks
2759    curbuf->b_op_end.lnum = 0;
2760  }
2761
2762  // If we get here we are sure to start editing
2763
2764  // Assume success now
2765  retval = OK;
2766
2767  // If the file name was changed, reset the not-edit flag so that ":write"
2768  // works.
2769  if (!other_file) {
2770    curbuf->b_flags &= ~BF_NOTEDITED;
2771  }
2772
2773  // Check if we are editing the w_arg_idx file in the argument list.
2774  check_arg_idx(curwin);
2775
2776  if (!auto_buf) {
2777    // Set cursor and init window before reading the file and executing
2778    // autocommands.  This allows for the autocommands to position the
2779    // cursor.
2780    curwin_init();
2781
2782    // It's possible that all lines in the buffer changed.  Need to update
2783    // automatic folding for all windows where it's used.
2784    FOR_ALL_TAB_WINDOWS(tp, win) {
2785      if (win->w_buffer == curbuf) {
2786        foldUpdateAll(win);
2787      }
2788    }
2789
2790    // Change directories when the 'acd' option is set.
2791    do_autochdir();
2792
2793    // Careful: open_buffer() and apply_autocmds() may change the current
2794    // buffer and window.
2795    pos_T orig_pos = curwin->w_cursor;
2796    topline = curwin->w_topline;
2797    if (!oldbuf) {                          // need to read the file
2798      swap_exists_action = SEA_DIALOG;
2799      curbuf->b_flags |= BF_CHECK_RO;       // set/reset 'ro' flag
2800
2801      // Open the buffer and read the file.
2802      if (flags & ECMD_NOWINENTER) {
2803        readfile_flags |= READ_NOWINENTER;
2804      }
2805      if (should_abort(open_buffer(false, eap, readfile_flags))) {
2806        retval = FAIL;
2807      }
2808
2809      if (swap_exists_action == SEA_QUIT) {
2810        retval = FAIL;
2811      }
2812      handle_swap_exists(&old_curbuf);
2813    } else {
2814      // Read the modelines, but only to set window-local options.  Any
2815      // buffer-local options have already been set and may have been
2816      // changed by the user.
2817      do_modelines(OPT_WINONLY);
2818
2819      apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, false, curbuf,
2820                            &retval);
2821      if ((flags & ECMD_NOWINENTER) == 0) {
2822        apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, false, curbuf,
2823                              &retval);
2824      }
2825    }
2826    check_arg_idx(curwin);
2827
2828    // If autocommands change the cursor position or topline, we should
2829    // keep it.  Also when it moves within a line. But not when it moves
2830    // to the first non-blank.
2831    if (!equalpos(curwin->w_cursor, orig_pos)) {
2832      const char *text = get_cursor_line_ptr();
2833
2834      if (curwin->w_cursor.lnum != orig_pos.lnum
2835          || curwin->w_cursor.col != (int)(skipwhite(text) - text)) {
2836        newlnum = curwin->w_cursor.lnum;
2837        newcol = curwin->w_cursor.col;
2838      }
2839    }
2840    if (curwin->w_topline == topline) {
2841      topline = 0;
2842    }
2843
2844    // Even when cursor didn't move we need to recompute topline.
2845    changed_line_abv_curs();
2846
2847    maketitle();
2848    if (retval != FAIL) {
2849      win_float_update_preview(curwin);
2850    }
2851  }
2852
2853  // Tell the diff stuff that this buffer is new and/or needs updating.
2854  // Also needed when re-editing the same buffer, because unloading will
2855  // have removed it as a diff buffer.
2856  if (curwin->w_p_diff) {
2857    diff_buf_add(curbuf);
2858    diff_invalidate(curbuf);
2859  }
2860
2861  // If the window options were changed may need to set the spell language.
2862  // Can only do this after the buffer has been properly setup.
2863  if (did_get_winopts && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) {
2864    parse_spelllang(curwin);
2865  }
2866
2867  if (command == NULL) {
2868    if (newcol >= 0) {          // position set by autocommands
2869      curwin->w_cursor.lnum = newlnum;
2870      curwin->w_cursor.col = newcol;
2871      check_cursor(curwin);
2872    } else if (newlnum > 0) {  // line number from caller or old position
2873      curwin->w_cursor.lnum = newlnum;
2874      check_cursor_lnum(curwin);
2875      if (solcol >= 0 && !p_sol) {
2876        // 'sol' is off: Use last known column.
2877        curwin->w_cursor.col = solcol;
2878        check_cursor_col(curwin);
2879        curwin->w_cursor.coladd = 0;
2880        curwin->w_set_curswant = true;
2881      } else {
2882        beginline(BL_SOL | BL_FIX);
2883      }
2884    } else {
2885      beginline(BL_WHITE | BL_FIX);
2886    }
2887  }
2888
2889  // Check if cursors in other windows on the same buffer are still valid
2890  check_lnums(false);
2891
2892  // Did not read the file, need to show some info about the file.
2893  // Do this after setting the cursor.
2894  if (oldbuf
2895      && !auto_buf) {
2896    int msg_scroll_save = msg_scroll;
2897
2898    // Obey the 'O' flag in 'cpoptions': overwrite any previous file
2899    // message.
2900    if (shortmess(kShmOverall) && !msg_listdo_overwrite && !exiting && p_verbose == 0) {
2901      msg_scroll = false;
2902    }
2903    if (!msg_scroll) {          // wait a bit when overwriting an error msg
2904      msg_check_for_delay(false);
2905    }
2906    msg_start();
2907    msg_scroll = msg_scroll_save;
2908    msg_scrolled_ign = true;
2909
2910    if (!shortmess(kShmFileinfo)) {
2911      fileinfo(false, true, false);
2912    }
2913
2914    msg_scrolled_ign = false;
2915  }
2916
2917  curbuf->b_last_used = time(NULL);
2918
2919  if (command != NULL) {
2920    do_cmdline(command, NULL, NULL, DOCMD_VERBOSE);
2921  }
2922
2923  if (curbuf->b_kmap_state & KEYMAP_INIT) {
2924    keymap_init();
2925  }
2926
2927  RedrawingDisabled--;
2928  did_inc_redrawing_disabled = false;
2929  if (!skip_redraw) {
2930    OptInt n = *so_ptr;
2931    if (topline == 0 && command == NULL) {
2932      *so_ptr = 999;    // force cursor to be vertically centered in the window
2933    }
2934    update_topline(curwin);
2935    curwin->w_scbind_pos = plines_m_win_fill(curwin, 1, curwin->w_topline);
2936    *so_ptr = n;
2937    redraw_curbuf_later(UPD_NOT_VALID);  // redraw this buffer later
2938  }
2939
2940  // Update to the working directory of the new current buffer.
2941  update_cwd(kCdCauseBuffer);
2942
2943  // Change directories when the 'acd' option is set.
2944  do_autochdir();
2945
2946theend:
2947  if (bufref_valid(&old_curbuf) && old_curbuf.br_buf->terminal != NULL) {
2948    terminal_check_size(old_curbuf.br_buf->terminal);
2949  }
2950  if ((!bufref_valid(&old_curbuf) || curbuf != old_curbuf.br_buf) && curbuf->terminal != NULL) {
2951    terminal_check_size(curbuf->terminal);
2952  }
2953
2954  if (did_inc_redrawing_disabled) {
2955    RedrawingDisabled--;
2956  }
2957  if (did_set_swapcommand) {
2958    set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
2959  }
2960  xfree(free_fname);
2961  return retval;
2962}
2963
2964static void delbuf_msg(char *name)
2965{
2966  semsg(_("E143: Autocommands unexpectedly deleted new buffer %s"),
2967        name == NULL ? "" : name);
2968  xfree(name);
2969  au_new_curbuf.br_buf = NULL;
2970  au_new_curbuf.br_buf_free_count = 0;
2971}
2972
2973static int append_indent = 0;       // autoindent for first line
2974
2975/// Get the next line of text for ":append", ":insert" and ":change": the text
2976/// after the bar, the next line of the command, or a line from the script or
2977/// the user.  Returns NULL when there is no more.
2978static char *get_append_line(exarg_T *eap, int indent)
2979{
2980  char *theline;
2981  char *p;
2982
2983  if (*eap->arg == '|') {
2984    // Get the text after the trailing bar.
2985    theline = xstrdup(eap->arg + 1);
2986    *eap->arg = NUL;
2987  } else if (eap->ea_getline == NULL) {
2988    // No getline() function, use the lines that follow. This ends
2989    // when there is no more.
2990    if (eap->nextcmd == NULL) {
2991      return NULL;
2992    }
2993    p = vim_strchr(eap->nextcmd, NL);
2994    if (p == NULL) {
2995      p = eap->nextcmd + strlen(eap->nextcmd);
2996    }
2997    theline = xmemdupz(eap->nextcmd, (size_t)(p - eap->nextcmd));
2998    if (*p != NUL) {
2999      p++;
3000    } else {
3001      p = NULL;
3002    }
3003    eap->nextcmd = p;
3004  } else {
3005    int getline_State = State;
3006    // Set State to avoid the cursor shape to be set to MODE_INSERT
3007    // state when getline() returns.
3008    State = MODE_CMDLINE;
3009    theline = eap->ea_getline(eap->cstack->cs_looplevel > 0 ? -1 : NUL,
3010                              eap->cookie, indent, true);
3011    State = getline_State;
3012  }
3013  return theline;
3014}
3015
3016/// ":insert" and ":append", also used by ":change"
3017void ex_append(exarg_T *eap)
3018{
3019  char *theline;
3020  bool did_undo = false;
3021  linenr_T lnum = eap->line2;
3022  int indent = 0;
3023  char *p;
3024  bool empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
3025
3026  if (eap->skip) {
3027    // Not executing the command, only read the lines up to the ".".
3028    while ((theline = get_append_line(eap, 0)) != NULL) {
3029      bool end = theline[0] == '.' && theline[1] == NUL;
3030      xfree(theline);
3031      if (end) {
3032        break;
3033      }
3034    }
3035    return;
3036  }
3037
3038  // the ! flag toggles autoindent
3039  if (eap->forceit) {
3040    curbuf->b_p_ai = !curbuf->b_p_ai;
3041  }
3042
3043  // First autoindent comes from the line we start on
3044  if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0) {
3045    append_indent = get_indent_lnum(lnum);
3046  }
3047
3048  if (eap->cmdidx != CMD_append) {
3049    lnum--;
3050  }
3051
3052  // when the buffer is empty need to delete the dummy line
3053  if (empty && lnum == 1) {
3054    lnum = 0;
3055  }
3056
3057  const int save_State = State;
3058  State = MODE_INSERT;                   // behave like in Insert mode
3059  if (curbuf->b_p_iminsert == B_IMODE_LMAP) {
3060    State |= MODE_LANGMAP;
3061  }
3062
3063  while (true) {
3064    msg_scroll = true;
3065    need_wait_return = false;
3066    if (curbuf->b_p_ai) {
3067      if (append_indent >= 0) {
3068        indent = append_indent;
3069        append_indent = -1;
3070      } else if (lnum > 0) {
3071        indent = get_indent_lnum(lnum);
3072      }
3073    }
3074    theline = get_append_line(eap, indent);
3075    lines_left = Rows - 1;
3076    if (theline == NULL) {
3077      break;
3078    }
3079
3080    // Look for the "." after automatic indent.
3081    int vcol = 0;
3082    for (p = theline; indent > vcol; p++) {
3083      if (*p == ' ') {
3084        vcol++;
3085      } else if (*p == TAB) {
3086        vcol += 8 - vcol % 8;
3087      } else {
3088        break;
3089      }
3090    }
3091    if ((p[0] == '.' && p[1] == NUL)
3092        || (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0))
3093            == FAIL)) {
3094      xfree(theline);
3095      break;
3096    }
3097
3098    // don't use autoindent if nothing was typed.
3099    if (p[0] == NUL) {
3100      theline[0] = NUL;
3101    }
3102
3103    did_undo = true;
3104    ml_append(lnum, theline, 0, false);
3105    if (empty) {
3106      // there are no marks below the inserted lines
3107      appended_lines(lnum, 1);
3108    } else {
3109      appended_lines_mark(lnum, 1);
3110    }
3111
3112    xfree(theline);
3113    lnum++;
3114
3115    if (empty) {
3116      ml_delete(2);
3117      empty = false;
3118    }
3119  }
3120  State = save_State;
3121  ui_cursor_shape();
3122
3123  if (eap->forceit) {
3124    curbuf->b_p_ai = !curbuf->b_p_ai;
3125  }
3126
3127  // "start" is set to eap->line2+1 unless that position is invalid (when
3128  // eap->line2 pointed to the end of the buffer and nothing was appended)
3129  // "end" is set to lnum when something has been appended, otherwise
3130  // it is the same as "start"  -- Acevedo
3131  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
3132    curbuf->b_op_start.lnum
3133      = (eap->line2 < curbuf->b_ml.ml_line_count) ? eap->line2 + 1 : curbuf->b_ml.ml_line_count;
3134    if (eap->cmdidx != CMD_append) {
3135      curbuf->b_op_start.lnum--;
3136    }
3137    curbuf->b_op_end.lnum = (eap->line2 < lnum) ? lnum : curbuf->b_op_start.lnum;
3138    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
3139  }
3140  curwin->w_cursor.lnum = lnum;
3141  check_cursor_lnum(curwin);
3142  beginline(BL_SOL | BL_FIX);
3143
3144  need_wait_return = false;     // don't use wait_return() now
3145}
3146
3147/// ":change"
3148void ex_change(exarg_T *eap)
3149{
3150  linenr_T lnum;
3151
3152  if (eap->skip) {
3153    ex_append(eap);
3154    return;
3155  }
3156  if (eap->line2 >= eap->line1
3157      && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL) {
3158    return;
3159  }
3160
3161  // the ! flag toggles autoindent
3162  if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai) {
3163    append_indent = get_indent_lnum(eap->line1);
3164  }
3165
3166  for (lnum = eap->line2; lnum >= eap->line1; lnum--) {
3167    if (curbuf->b_ml.ml_flags & ML_EMPTY) {         // nothing to delete
3168      break;
3169    }
3170    ml_delete(eap->line1);
3171  }
3172
3173  // make sure the cursor is not beyond the end of the file now
3174  check_cursor_lnum(curwin);
3175  deleted_lines_mark(eap->line1, (eap->line2 - lnum));
3176
3177  // ":append" on the line above the deleted lines.
3178  eap->line2 = eap->line1;
3179  ex_append(eap);
3180}
3181
3182void ex_z(exarg_T *eap)
3183{
3184  int64_t bigness;
3185  int minus = 0;
3186  linenr_T start, end, curs;
3187  linenr_T lnum = eap->line2;
3188
3189  // Vi compatible: ":z!" uses display height, without a count uses
3190  // 'scroll'
3191  if (eap->forceit) {
3192    bigness = Rows - 1;
3193  } else if (ONE_WINDOW) {
3194    bigness = curwin->w_p_scr * 2;
3195  } else {
3196    bigness = curwin->w_view_height - 3;
3197  }
3198  bigness = MAX(bigness, 1);
3199
3200  char *x = eap->arg;
3201  char *kind = x;
3202  if (*kind == '-' || *kind == '+' || *kind == '='
3203      || *kind == '^' || *kind == '.') {
3204    x++;
3205  }
3206  while (*x == '-' || *x == '+') {
3207    x++;
3208  }
3209
3210  if (*x != 0) {
3211    if (!ascii_isdigit(*x)) {
3212      emsg(_(e_non_numeric_argument_to_z));
3213      return;
3214    }
3215    bigness = atol(x);
3216
3217    // bigness could be < 0 if atol(x) overflows.
3218    if (bigness > 2 * curbuf->b_ml.ml_line_count || bigness < 0) {
3219      bigness = 2 * curbuf->b_ml.ml_line_count;
3220    }
3221
3222    p_window = (int)bigness;
3223    if (*kind == '=') {
3224      bigness += 2;
3225    }
3226  }
3227
3228  // the number of '-' and '+' multiplies the distance
3229  if (*kind == '-' || *kind == '+') {
3230    for (x = kind + 1; *x == *kind; x++) {}
3231  }
3232
3233  switch (*kind) {
3234  case '-':
3235    start = lnum - (linenr_T)bigness * (linenr_T)(x - kind) + 1;
3236    end = start + (linenr_T)bigness - 1;
3237    curs = end;
3238    break;
3239
3240  case '=':
3241    start = lnum - ((linenr_T)bigness + 1) / 2 + 1;
3242    end = lnum + ((linenr_T)bigness + 1) / 2 - 1;
3243    curs = lnum;
3244    minus = 1;
3245    break;
3246
3247  case '^':
3248    start = lnum - (linenr_T)bigness * 2;
3249    end = lnum - (linenr_T)bigness;
3250    curs = lnum - (linenr_T)bigness;
3251    break;
3252
3253  case '.':
3254    start = lnum - ((linenr_T)bigness + 1) / 2 + 1;
3255    end = lnum + ((linenr_T)bigness + 1) / 2 - 1;
3256    curs = end;
3257    break;
3258
3259  default:        // '+'
3260    start = lnum;
3261    if (*kind == '+') {
3262      start += (linenr_T)bigness * (linenr_T)(x - kind - 1) + 1;
3263    } else if (eap->addr_count == 0) {
3264      start++;
3265    }
3266    end = start + (linenr_T)bigness - 1;
3267    curs = end;
3268    break;
3269  }
3270
3271  start = MAX(start, 1);
3272  end = MIN(end, curbuf->b_ml.ml_line_count);
3273  curs = MIN(MAX(curs, 1), curbuf->b_ml.ml_line_count);
3274
3275  for (linenr_T i = start; i <= end; i++) {
3276    if (minus && i == lnum) {
3277      msg_putchar('\n');
3278
3279      for (int j = 1; j < Columns; j++) {
3280        msg_putchar('-');
3281      }
3282    }
3283
3284    print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST, i == start);
3285
3286    if (minus && i == lnum) {
3287      msg_putchar('\n');
3288
3289      for (int j = 1; j < Columns; j++) {
3290        msg_putchar('-');
3291      }
3292    }
3293  }
3294
3295  if (curwin->w_cursor.lnum != curs) {
3296    curwin->w_cursor.lnum = curs;
3297    curwin->w_cursor.col = 0;
3298  }
3299}
3300
3301/// @return  true if the secure flag is set and also give an error message.
3302///          Otherwise, return false.
3303bool check_secure(void)
3304{
3305  if (secure) {
3306    secure = 2;
3307    emsg(_(e_curdir));
3308    return true;
3309  }
3310
3311  // In the sandbox more things are not allowed, including the things
3312  // disallowed in secure mode.
3313  if (sandbox != 0) {
3314    emsg(_(e_sandbox));
3315    return true;
3316  }
3317  return false;
3318}
3319
3320/// Previous substitute replacement string
3321static SubReplacementString old_sub = { NULL, 0, NULL };
3322
3323static int global_need_beginline;       // call beginline() after ":g"
3324
3325/// Get old substitute replacement string
3326///
3327/// @param[out]  ret_sub    Location where old string will be saved.
3328void sub_get_replacement(SubReplacementString *const ret_sub)
3329  FUNC_ATTR_NONNULL_ALL
3330{
3331  *ret_sub = old_sub;
3332}
3333
3334/// Set substitute string and timestamp
3335///
3336/// @warning `sub` must be in allocated memory. It is not copied.
3337///
3338/// @param[in]  sub  New replacement string.
3339void sub_set_replacement(SubReplacementString sub)
3340{
3341  xfree(old_sub.sub);
3342  if (sub.additional_data != old_sub.additional_data) {
3343    xfree(old_sub.additional_data);
3344  }
3345  old_sub = sub;
3346}
3347
3348/// Recognize ":%s/\n//" and turn it into a join command, which is much
3349/// more efficient.
3350///
3351/// @param[in]  eap  Ex arguments
3352/// @param[in]  pat  Search pattern
3353/// @param[in]  sub  Replacement string
3354/// @param[in]  cmd  Command from :s_flags
3355/// @param[in]  save Save pattern to options, history
3356///
3357/// @returns true if :substitute can be replaced with a join command
3358static bool sub_joining_lines(exarg_T *eap, String pat, const char *sub, const char *cmd, bool save,
3359                              bool keeppatterns)
3360  FUNC_ATTR_NONNULL_ARG(1, 3, 4)
3361{
3362  // TODO(vim): find a generic solution to make line-joining operations more
3363  // efficient, avoid allocating a string that grows in size.
3364  if (pat.data != NULL
3365      && strcmp(pat.data, "\\n") == 0
3366      && *sub == NUL
3367      && (*cmd == NUL || (cmd[1] == NUL
3368                          && (*cmd == 'g'
3369                              || *cmd == 'l'
3370                              || *cmd == 'p'
3371                              || *cmd == '#')))) {
3372    if (eap->skip) {
3373      return true;
3374    }
3375    curwin->w_cursor.lnum = eap->line1;
3376    if (*cmd == 'l') {
3377      eap->flags = EXFLAG_LIST;
3378    } else if (*cmd == '#') {
3379      eap->flags = EXFLAG_NR;
3380    } else if (*cmd == 'p') {
3381      eap->flags = EXFLAG_PRINT;
3382    }
3383
3384    // The number of lines joined is the number of lines in the range
3385    linenr_T joined_lines_count = eap->line2 - eap->line1 + 1
3386                                  // plus one extra line if not at the end of file.
3387                                  + (eap->line2 < curbuf->b_ml.ml_line_count ? 1 : 0);
3388    if (joined_lines_count > 1) {
3389      do_join((size_t)joined_lines_count, false, true, false, true);
3390      sub_nsubs = joined_lines_count - 1;
3391      sub_nlines = 1;
3392      do_sub_msg(false);
3393      ex_may_print(eap);
3394    }
3395
3396    if (save) {
3397      if (!keeppatterns) {
3398        save_re_pat(RE_SUBST, pat.data, pat.size, p_magic);
3399      }
3400      // put pattern in history
3401      add_to_history(HIST_SEARCH, pat.data, pat.size, true, NUL);
3402    }
3403
3404    return true;
3405  }
3406
3407  return false;
3408}
3409
3410/// Allocate memory to store the replacement text for :substitute.
3411///
3412/// Slightly more memory that is strictly necessary is allocated to reduce the
3413/// frequency of memory (re)allocation.
3414///
3415/// @param[in,out]  new_start       pointer to the memory for the replacement text
3416/// @param[in,out]  new_start_size  pointer to allocated size of new_start->data
3417/// @param[in]      needed_size     amount of memory needed
3418static void sub_grow_buf(String *new_start, size_t *new_start_size, size_t needed_size)
3419  FUNC_ATTR_NONNULL_ALL
3420{
3421  if (new_start->data == NULL) {
3422    // Get some space for a temporary buffer to do the
3423    // substitution into (and some extra space to avoid
3424    // too many calls to xmalloc()/free()).
3425    *new_start_size = needed_size + 50;
3426    new_start->data = xcalloc(1, *new_start_size);
3427    new_start->data[0] = NUL;
3428    new_start->size = 0;
3429  } else {
3430    // Check if the temporary buffer is long enough to do the
3431    // substitution into.  If not, make it larger (with a bit
3432    // extra to avoid too many calls to xmalloc()/free()).
3433    needed_size += new_start->size;
3434    if (needed_size > *new_start_size) {
3435      size_t prev_new_start_size = *new_start_size;
3436      *new_start_size = needed_size + 50;
3437      size_t added_len = *new_start_size - prev_new_start_size;
3438      new_start->data = xrealloc(new_start->data, *new_start_size);
3439      memset(new_start->data + prev_new_start_size, 0, added_len);
3440    }
3441  }
3442}
3443
3444/// Parse cmd string for :substitute's {flags} and update subflags accordingly
3445///
3446/// @param[in]      cmd  command string
3447/// @param[in,out]  subflags  current flags defined for the :substitute command
3448/// @param[in,out]  which_pat  pattern type from which to get default search
3449///
3450/// @returns pointer to the end of the flags, which may be the end of the string
3451static char *sub_parse_flags(char *cmd, subflags_T *subflags, int *which_pat)
3452  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
3453{
3454  // Find trailing options.  When '&' is used, keep old options.
3455  if (*cmd == '&') {
3456    cmd++;
3457  } else {
3458    subflags->do_all = p_gd;
3459    subflags->do_ask = false;
3460    subflags->do_error = true;
3461    subflags->do_print = false;
3462    subflags->do_list = false;
3463    subflags->do_count = false;
3464    subflags->do_number = false;
3465    subflags->do_ic = kSubHonorOptions;
3466  }
3467  while (*cmd) {
3468    // Note that 'g' and 'c' are always inverted.
3469    // 'r' is never inverted.
3470    if (*cmd == 'g') {
3471      subflags->do_all = !subflags->do_all;
3472    } else if (*cmd == 'c') {
3473      subflags->do_ask = !subflags->do_ask;
3474    } else if (*cmd == 'n') {
3475      subflags->do_count = true;
3476    } else if (*cmd == 'e') {
3477      subflags->do_error = !subflags->do_error;
3478    } else if (*cmd == 'r') {  // use last used regexp
3479      *which_pat = RE_LAST;
3480    } else if (*cmd == 'p') {
3481      subflags->do_print = true;
3482    } else if (*cmd == '#') {
3483      subflags->do_print = true;
3484      subflags->do_number = true;
3485    } else if (*cmd == 'l') {
3486      subflags->do_print = true;
3487      subflags->do_list = true;
3488    } else if (*cmd == 'i') {  // ignore case
3489      subflags->do_ic = kSubIgnoreCase;
3490    } else if (*cmd == 'I') {  // don't ignore case
3491      subflags->do_ic = kSubMatchCase;
3492    } else {
3493      break;
3494    }
3495    cmd++;
3496  }
3497  if (subflags->do_count) {
3498    subflags->do_ask = false;
3499  }
3500
3501  return cmd;
3502}
3503
3504/// Skip over the "sub" part in :s/pat/sub/ where "delimiter" is the separating
3505/// character.
3506static char *skip_substitute(char *start, int delimiter)
3507{
3508  char *p = start;
3509
3510  while (p[0]) {
3511    if (p[0] == delimiter) {  // end delimiter found
3512      *p++ = NUL;  // replace it with a NUL
3513      break;
3514    }
3515    if (p[0] == '\\' && p[1] != 0) {  // skip escaped characters
3516      p++;
3517    }
3518    MB_PTR_ADV(p);
3519  }
3520  return p;
3521}
3522
3523static int check_regexp_delim(int c)
3524  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
3525{
3526  if (isalpha(c)) {
3527    emsg(_("E146: Regular expressions can't be delimited by letters"));
3528    return FAIL;
3529  }
3530  return OK;
3531}
3532
3533/// Perform a substitution from line eap->line1 to line eap->line2 using the
3534/// command pointed to by eap->arg which should be of the form:
3535///
3536/// /pattern/substitution/{flags}
3537///
3538/// The usual escapes are supported as described in the regexp docs.
3539///
3540/// @param tm             Timeout limit
3541/// @param cmdpreview_ns  The namespace to show 'inccommand' preview highlights.
3542///                       If <= 0, preview shouldn't be shown.
3543/// @return  0, 1 or 2. See cmdpreview_may_show() for more information on the meaning.
3544static int do_sub(exarg_T *eap, proftime_T tm, const int cmdpreview_ns,
3545                  const handle_T cmdpreview_bufnr)
3546{
3547#define ADJUST_SUB_FIRSTLNUM() \
3548  do { \
3549    /* For a multi-line match, make a copy of the last matched */ \
3550    /* line and continue in that one. */ \
3551    if (nmatch > 1) { \
3552      sub_firstlnum += (linenr_T)nmatch - 1; \
3553      xfree(sub_firstline.data); \
3554      sub_firstline = cbuf_to_string(ml_get(sub_firstlnum), \
3555                                     (size_t)ml_get_len(sub_firstlnum)); \
3556      /* When going beyond the last line, stop substituting. */ \
3557      if (sub_firstlnum <= line2) { \
3558        do_again = true; \
3559      } else { \
3560        subflags.do_all = false; \
3561      } \
3562    } \
3563    if (skip_match) { \
3564      /* Already hit end of the buffer, sub_firstlnum is one */ \
3565      /* less than what it ought to be. */ \
3566      xfree(sub_firstline.data); \
3567      sub_firstline = STATIC_CSTR_TO_STRING(""); \
3568      copycol = 0; \
3569    } \
3570  } while (0)
3571
3572  int i = 0;
3573  regmmatch_T regmatch;
3574  static subflags_T subflags = {
3575    .do_all = false,
3576    .do_ask = false,
3577    .do_count = false,
3578    .do_error = true,
3579    .do_print = false,
3580    .do_list = false,
3581    .do_number = false,
3582    .do_ic = kSubHonorOptions
3583  };
3584  char *sub = NULL;  // init for GCC
3585  String pat = STRING_INIT;
3586  int delimiter;
3587  bool has_second_delim = false;
3588  size_t sublen;
3589  bool got_quit = false;
3590  bool got_match = false;
3591  int which_pat;
3592  char *cmd = eap->arg;
3593  linenr_T first_line = 0;  // first changed line
3594  linenr_T last_line = 0;   // below last changed line AFTER the change
3595  linenr_T old_line_count = curbuf->b_ml.ml_line_count;
3596  String sub_firstline;     // allocated copy of first sub line
3597  bool endcolumn = false;   // cursor in last column when done
3598  const bool keeppatterns = cmdmod.cmod_flags & CMOD_KEEPPATTERNS;
3599  PreviewLines preview_lines = { KV_INITIAL_VALUE, 0 };
3600  static int pre_hl_id = 0;
3601  pos_T old_cursor = curwin->w_cursor;
3602  int start_nsubs;
3603
3604  bool did_save = false;
3605
3606  if (!global_busy) {
3607    sub_nsubs = 0;
3608    sub_nlines = 0;
3609  }
3610  start_nsubs = sub_nsubs;
3611
3612  if (eap->cmdidx == CMD_tilde) {
3613    which_pat = RE_LAST;        // use last used regexp
3614  } else {
3615    which_pat = RE_SUBST;       // use last substitute regexp
3616  }
3617  // new pattern and substitution
3618  if (eap->cmd[0] == 's' && *cmd != NUL && !ascii_iswhite(*cmd)
3619      && vim_strchr("0123456789cegriIp|\"", (uint8_t)(*cmd)) == NULL) {
3620    // don't accept alphanumeric for separator
3621    if (check_regexp_delim(*cmd) == FAIL) {
3622      return 0;
3623    }
3624
3625    // undocumented vi feature:
3626    //  "\/sub/" and "\?sub?" use last used search pattern (almost like
3627    //  //sub/r).  "\&sub&" use last substitute pattern (like //sub/).
3628    if (*cmd == '\\') {
3629      cmd++;
3630      if (vim_strchr("/?&", (uint8_t)(*cmd)) == NULL) {
3631        emsg(_(e_backslash));
3632        return 0;
3633      }
3634      if (*cmd != '&') {
3635        which_pat = RE_SEARCH;              // use last '/' pattern
3636      }
3637      pat = STATIC_CSTR_AS_STRING("");      // empty search pattern
3638      delimiter = (uint8_t)(*cmd++);        // remember delimiter character
3639      has_second_delim = true;
3640    } else {          // find the end of the regexp
3641      which_pat = RE_LAST;                  // use last used regexp
3642      delimiter = (uint8_t)(*cmd++);                   // remember delimiter character
3643      pat.data = cmd;                       // remember start of search pat
3644      cmd = skip_regexp_ex(cmd, delimiter, p_magic, &eap->arg, NULL, NULL);
3645      pat.size = (size_t)(cmd - pat.data);
3646      if (cmd[0] == delimiter) {            // end delimiter found
3647        *cmd++ = NUL;                       // replace it with a NUL
3648        has_second_delim = true;
3649      }
3650    }
3651
3652    // Small incompatibility: vi sees '\n' as end of the command, but in
3653    // Vim we want to use '\n' to find/substitute a NUL.
3654    char *p = cmd;  // remember the start of the substitution
3655    cmd = skip_substitute(cmd, delimiter);
3656    sub = xstrdup(p);
3657
3658    if (!eap->skip && !keeppatterns && cmdpreview_ns <= 0) {
3659      sub_set_replacement((SubReplacementString) {
3660        .sub = xstrdup(sub),
3661        .timestamp = os_time(),
3662        .additional_data = NULL,
3663      });
3664    }
3665  } else if (!eap->skip) {    // use previous pattern and substitution
3666    if (old_sub.sub == NULL) {      // there is no previous command
3667      emsg(_(e_nopresub));
3668      return 0;
3669    }
3670    pat = NULL_STRING;              // search_regcomp() will use previous pattern
3671    sub = xstrdup(old_sub.sub);
3672
3673    // Vi compatibility quirk: repeating with ":s" keeps the cursor in the
3674    // last column after using "$".
3675    endcolumn = (curwin->w_curswant == MAXCOL);
3676  }
3677
3678  if (sub != NULL && sub_joining_lines(eap, pat, sub, cmd, cmdpreview_ns <= 0,
3679                                       keeppatterns)) {
3680    xfree(sub);
3681    return 0;
3682  }
3683
3684  cmd = sub_parse_flags(cmd, &subflags, &which_pat);
3685
3686  bool save_do_all = subflags.do_all;  // remember user specified 'g' flag
3687  bool save_do_ask = subflags.do_ask;  // remember user specified 'c' flag
3688
3689  // check for a trailing count
3690  cmd = skipwhite(cmd);
3691  if (ascii_isdigit(*cmd)) {
3692    const char *const count_arg = cmd;
3693    i = getdigits_int(&cmd, false, INT_MAX);
3694    if (i <= 0 && !eap->skip && subflags.do_error) {
3695      emsg(_(e_zerocount));
3696      xfree(sub);
3697      return 0;
3698    } else if (i >= INT_MAX) {
3699      semsg(_(e_val_too_large_len), (int)(cmd - count_arg), count_arg);
3700      xfree(sub);
3701      return 0;
3702    }
3703    eap->line1 = eap->line2;
3704    eap->line2 += (linenr_T)i - 1;
3705    eap->line2 = MIN(eap->line2, curbuf->b_ml.ml_line_count);
3706  }
3707
3708  // check for trailing command or garbage
3709  cmd = skipwhite(cmd);
3710  if (*cmd && *cmd != '"') {        // if not end-of-line or comment
3711    eap->nextcmd = check_nextcmd(cmd);
3712    if (eap->nextcmd == NULL) {
3713      semsg(_(e_trailing_arg), cmd);
3714      xfree(sub);
3715      return 0;
3716    }
3717  }
3718
3719  if (eap->skip) {          // not executing commands, only parsing
3720    xfree(sub);
3721    return 0;
3722  }
3723
3724  if (!subflags.do_count && !MODIFIABLE(curbuf)) {
3725    // Substitution is not allowed in non-'modifiable' buffer
3726    emsg(_(e_modifiable));
3727    xfree(sub);
3728    return 0;
3729  }
3730
3731  bool magic = ((eap->cmdidx == CMD_smagic)
3732                ? true : ((eap->cmdidx == CMD_snomagic) ? false : p_magic));
3733  if (search_regcomp(pat.data, pat.size, NULL, RE_SUBST, which_pat,
3734                     (cmdpreview_ns > 0 ? 0 : SEARCH_HIS), magic, &regmatch) == FAIL) {
3735    if (subflags.do_error) {
3736      emsg(_(e_invcmd));
3737    }
3738    xfree(sub);
3739    return 0;
3740  }
3741
3742  // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'
3743  if (subflags.do_ic == kSubIgnoreCase) {
3744    regmatch.rmm_ic = true;
3745  } else if (subflags.do_ic == kSubMatchCase) {
3746    regmatch.rmm_ic = false;
3747  }
3748
3749  sub_firstline = NULL_STRING;
3750
3751  assert(sub != NULL);
3752
3753  // If the substitute pattern starts with "\=" then it's an expression.
3754  // Make a copy, a recursive function may free it.
3755  // Otherwise, '~' in the substitute pattern is replaced with the old
3756  // pattern.  We do it here once to avoid it to be replaced over and over
3757  // again.
3758  if (sub[0] == '\\' && sub[1] == '=') {
3759    char *p = xstrdup(sub);
3760    xfree(sub);
3761    sub = p;
3762  } else {
3763    char *p = regtilde(sub, p_magic, cmdpreview_ns > 0);
3764    if (p != sub) {
3765      xfree(sub);
3766      sub = p;
3767    }
3768  }
3769
3770  // Check for a match on each line.
3771  // If preview: limit to max('cmdwinheight', viewport).
3772  linenr_T line2 = eap->line2;
3773
3774  int timed_out = false;
3775
3776  for (linenr_T lnum = eap->line1;
3777       lnum <= line2 && !got_quit && !timed_out && !aborting()
3778       && (cmdpreview_ns <= 0 || preview_lines.lines_needed <= (linenr_T)p_cwh
3779           || lnum <= curwin->w_botline);
3780       lnum++) {
3781    int nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
3782                                   0, &tm, &timed_out);
3783    if (nmatch) {
3784      colnr_T copycol;
3785      colnr_T matchcol;
3786      colnr_T prev_matchcol = MAXCOL;
3787      String new_start = STRING_INIT;
3788      size_t new_start_size = 0;
3789      char *new_end;
3790      bool did_sub = false;
3791      int lastone;
3792      linenr_T nmatch_tl = 0;               // nr of lines matched below lnum
3793      int do_again;                     // do it again after joining lines
3794      bool skip_match = false;
3795      linenr_T sub_firstlnum;           // nr of first sub line
3796
3797      // Track where substitutions started (set once per line).
3798      linenr_T lnum_start = 0;
3799
3800      // Track per-line data for each match.
3801      // Will be sent as a batch to `extmark_splice` after the substitution is done.
3802      typedef struct {
3803        int start_col;         // Position in new text where replacement goes
3804        lpos_T start;          // Match start position in original text
3805        lpos_T end;            // Match end position in original text
3806        int matchcols;         // Columns deleted from original text
3807        bcount_t matchbytes;   // Bytes deleted from original text
3808        int subcols;           // Columns in replacement text
3809        bcount_t subbytes;     // Bytes in replacement text
3810        linenr_T lnum_before;  // Line number before this substitution
3811        linenr_T lnum_after;   // Line number after this substitution
3812      } LineData;
3813
3814      kvec_t(LineData) line_matches = KV_INITIAL_VALUE;
3815
3816      // The new text is build up step by step, to avoid too much
3817      // copying.  There are these pieces:
3818      // sub_firstline  The old text, unmodified.
3819      // copycol                Column in the old text where we started
3820      //                        looking for a match; from here old text still
3821      //                        needs to be copied to the new text.
3822      // matchcol               Column number of the old text where to look
3823      //                        for the next match.  It's just after the
3824      //                        previous match or one further.
3825      // prev_matchcol  Column just after the previous match (if any).
3826      //                        Mostly equal to matchcol, except for the first
3827      //                        match and after skipping an empty match.
3828      // regmatch.*pos  Where the pattern matched in the old text.
3829      // new_start      The new text, all that has been produced so
3830      //                        far.
3831      // new_end                The new text, where to append new text.
3832      //
3833      // lnum           The line number where we found the start of
3834      //                        the match.  Can be below the line we searched
3835      //                        when there is a \n before a \zs in the
3836      //                        pattern.
3837      // sub_firstlnum  The line number in the buffer where to look
3838      //                        for a match.  Can be different from "lnum"
3839      //                        when the pattern or substitute string contains
3840      //                        line breaks.
3841      //
3842      // Special situations:
3843      // - When the substitute string contains a line break, the part up
3844      //   to the line break is inserted in the text, but the copy of
3845      //   the original line is kept.  "sub_firstlnum" is adjusted for
3846      //   the inserted lines.
3847      // - When the matched pattern contains a line break, the old line
3848      //   is taken from the line at the end of the pattern.  The lines
3849      //   in the match are deleted later, "sub_firstlnum" is adjusted
3850      //   accordingly.
3851      //
3852      // The new text is built up in new_start[].  It has some extra
3853      // room to avoid using xmalloc()/free() too often.  new_start_size is
3854      // the length of the allocated memory at new_start.
3855      //
3856      // Make a copy of the old line, so it won't be taken away when
3857      // updating the screen or handling a multi-line match.  The "old_"
3858      // pointers point into this copy.
3859      sub_firstlnum = lnum;
3860      copycol = 0;
3861      matchcol = 0;
3862
3863      // At first match, remember current cursor position.
3864      if (!got_match) {
3865        setpcmark();
3866        got_match = true;
3867      }
3868
3869      // Loop until nothing more to replace in this line.
3870      // 1. Handle match with empty string.
3871      // 2. If subflags.do_ask is set, ask for confirmation.
3872      // 3. substitute the string.
3873      // 4. if subflags.do_all is set, find next match
3874      // 5. break if there isn't another match in this line
3875      while (true) {
3876        SubResult current_match = {
3877          .start = { 0, 0 },
3878          .end = { 0, 0 },
3879          .pre_match = 0,
3880        };
3881        // lnum is where the match start, but maybe not the pattern match,
3882        // since we can have \n before \zs in the pattern
3883
3884        // Advance "lnum" to the line where the match starts.  The
3885        // match does not start in the first line when there is a line
3886        // break before \zs.
3887        if (regmatch.startpos[0].lnum > 0) {
3888          current_match.pre_match = lnum;
3889          lnum += regmatch.startpos[0].lnum;
3890          sub_firstlnum += regmatch.startpos[0].lnum;
3891          nmatch -= regmatch.startpos[0].lnum;
3892          API_CLEAR_STRING(sub_firstline);
3893        }
3894
3895        // Now we're at the line where the pattern match starts
3896        // Note: If not first match on a line, column can't be known here
3897        current_match.start.lnum = sub_firstlnum;
3898
3899        // Match might be after the last line for "\n\zs" matching at
3900        // the end of the last line.
3901        if (lnum > curbuf->b_ml.ml_line_count) {
3902          break;
3903        }
3904        if (sub_firstline.data == NULL) {
3905          sub_firstline = cbuf_to_string(ml_get(sub_firstlnum),
3906                                         (size_t)ml_get_len(sub_firstlnum));
3907        }
3908
3909        // Save the line number of the last change for the final
3910        // cursor position (just like Vi).
3911        curwin->w_cursor.lnum = lnum;
3912        do_again = false;
3913
3914        // 1. Match empty string does not count, except for first
3915        // match.  This reproduces the strange vi behaviour.
3916        // This also catches endless loops.
3917        if (matchcol == prev_matchcol
3918            && regmatch.endpos[0].lnum == 0
3919            && matchcol == regmatch.endpos[0].col) {
3920          if (sub_firstline.data[matchcol] == NUL) {
3921            // We already were at the end of the line.  Don't look
3922            // for a match in this line again.
3923            skip_match = true;
3924          } else {
3925            // search for a match at next column
3926            matchcol += utfc_ptr2len(sub_firstline.data + matchcol);
3927          }
3928          // match will be pushed to preview_lines, bring it into a proper state
3929          current_match.start.col = matchcol;
3930          current_match.end.lnum = sub_firstlnum;
3931          current_match.end.col = matchcol;
3932          goto skip;
3933        }
3934
3935        // Normally we continue searching for a match just after the
3936        // previous match.
3937        matchcol = regmatch.endpos[0].col;
3938        prev_matchcol = matchcol;
3939
3940        // 2. If subflags.do_count is set only increase the counter.
3941        //    If do_ask is set, ask for confirmation.
3942        if (subflags.do_count) {
3943          // For a multi-line match, put matchcol at the NUL at
3944          // the end of the line and set nmatch to one, so that
3945          // we continue looking for a match on the next line.
3946          // Avoids that ":s/\nB\@=//gc" get stuck.
3947          if (nmatch > 1) {
3948            matchcol = (colnr_T)sub_firstline.size;
3949            nmatch = 1;
3950            skip_match = true;
3951          }
3952          sub_nsubs++;
3953          did_sub = true;
3954          // Skip the substitution, unless an expression is used,
3955          // then it is evaluated in the sandbox.
3956          if (!(sub[0] == '\\' && sub[1] == '=')) {
3957            goto skip;
3958          }
3959        }
3960
3961        if (subflags.do_ask && cmdpreview_ns <= 0) {
3962          int typed = 0;
3963          int save_State = State;
3964          curwin->w_cursor.col = regmatch.startpos[0].col;
3965
3966          if (curwin->w_p_crb) {
3967            do_check_cursorbind();
3968          }
3969
3970          // When 'cpoptions' contains "u" don't sync undo when
3971          // asking for confirmation.
3972          if (vim_strchr(p_cpo, kCpoUndo) != NULL) {
3973            no_u_sync++;
3974          }
3975
3976          // Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
3977          while (subflags.do_ask) {
3978            String orig_line = STRING_INIT;
3979            int len_change = 0;
3980            const bool save_p_lz = p_lz;
3981            int save_p_fen = curwin->w_p_fen;
3982
3983            curwin->w_p_fen = false;
3984            // Invert the matched string.
3985            // Remove the inversion afterwards.
3986            int temp = RedrawingDisabled;
3987            RedrawingDisabled = 0;
3988
3989            // avoid calling update_screen() in vgetorpeek()
3990            p_lz = false;
3991
3992            if (new_start.data != NULL) {
3993              // There already was a substitution, we would
3994              // like to show this to the user.  We cannot
3995              // really update the line, it would change
3996              // what matches.  Temporarily replace the line
3997              // and change it back afterwards.
3998              orig_line = cbuf_to_string(ml_get(lnum), (size_t)ml_get_len(lnum));
3999              String new_line = {
4000                .data = concat_str(new_start.data, sub_firstline.data + copycol),
4001                .size = new_start.size + (sub_firstline.size - (size_t)copycol),
4002              };
4003
4004              // Position the cursor relative to the end of the line, the
4005              // previous substitute may have inserted or deleted characters
4006              // before the cursor.
4007              len_change = (int)new_line.size - (int)orig_line.size;
4008              curwin->w_cursor.col += len_change;
4009              ml_replace(lnum, new_line.data, false);
4010            }
4011
4012            Search.match_lines = regmatch.endpos[0].lnum - regmatch.startpos[0].lnum;
4013            Search.match_endcol = regmatch.endpos[0].col + len_change;
4014            if (Search.match_lines == 0 && Search.match_endcol == 0) {
4015              // highlight at least one character for /^/
4016              Search.match_endcol = 1;
4017            }
4018            Search.hl_match = true;
4019
4020            update_topline(curwin);
4021            validate_cursor(curwin);
4022            redraw_later(curwin, UPD_SOME_VALID);
4023            show_cursor_info_later(true);
4024            update_screen();
4025            redraw_later(curwin, UPD_SOME_VALID);
4026
4027            curwin->w_p_fen = save_p_fen;
4028
4029            char *p = _("replace with %s? (y)es/(n)o/(a)ll/(q)uit/(l)ast/scroll up(^E)/down(^Y)");
4030            snprintf(IObuff, IOSIZE, p, sub);
4031            p = xstrdup(IObuff);
4032            typed = prompt_for_input(p, HLF_R, true, NULL);
4033            Search.hl_match = false;
4034            xfree(p);
4035
4036            msg_didout = false;                 // don't scroll up
4037            gotocmdline(true);
4038            p_lz = save_p_lz;
4039            RedrawingDisabled = temp;
4040
4041            // restore the line
4042            if (orig_line.data != NULL) {
4043              ml_replace(lnum, orig_line.data, false);
4044            }
4045
4046            need_wait_return = false;             // no hit-return prompt
4047            if (typed == 'q' || typed == ESC || typed == Ctrl_C) {
4048              got_quit = true;
4049              break;
4050            }
4051            if (typed == 'n') {
4052              break;
4053            }
4054            if (typed == 'y') {
4055              break;
4056            }
4057            if (typed == 'l') {
4058              // last: replace and then stop
4059              subflags.do_all = false;
4060              line2 = lnum;
4061              break;
4062            }
4063            if (typed == 'a') {
4064              subflags.do_ask = false;
4065              break;
4066            }
4067            if (typed == Ctrl_E) {
4068              scrollup_clamp();
4069            } else if (typed == Ctrl_Y) {
4070              scrolldown_clamp();
4071            }
4072          }
4073          State = save_State;
4074          setmouse();
4075          if (vim_strchr(p_cpo, kCpoUndo) != NULL) {
4076            no_u_sync--;
4077          }
4078
4079          if (typed == 'n') {
4080            // For a multi-line match, put matchcol at the NUL at
4081            // the end of the line and set nmatch to one, so that
4082            // we continue looking for a match on the next line.
4083            // Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc"
4084            // get stuck when pressing 'n'.
4085            if (nmatch > 1) {
4086              matchcol = (colnr_T)sub_firstline.size;
4087              skip_match = true;
4088            }
4089            goto skip;
4090          }
4091          if (got_quit) {
4092            goto skip;
4093          }
4094        }
4095
4096        // Move the cursor to the start of the match, so that we can
4097        // use "\=col(".").
4098        curwin->w_cursor.col = regmatch.startpos[0].col;
4099
4100        // When the match included the "$" of the last line it may
4101        // go beyond the last line of the buffer.
4102        if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1) {
4103          nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
4104          current_match.end.lnum = sub_firstlnum + (linenr_T)nmatch;
4105          skip_match = true;
4106          // safety check
4107          if (nmatch < 0) {
4108            goto skip;
4109          }
4110        }
4111
4112        // Save the line numbers for the preview buffer
4113        // NOTE: If the pattern matches a final newline, the next line will
4114        // be shown also, but should not be highlighted. Intentional for now.
4115        if (cmdpreview_ns > 0 && !has_second_delim) {
4116          current_match.start.col = regmatch.startpos[0].col;
4117          if (current_match.end.lnum == 0) {
4118            current_match.end.lnum = sub_firstlnum + (linenr_T)nmatch - 1;
4119          }
4120          current_match.end.col = regmatch.endpos[0].col;
4121
4122          ADJUST_SUB_FIRSTLNUM();
4123          lnum += (linenr_T)nmatch - 1;
4124
4125          goto skip;
4126        }
4127
4128        // 3. Substitute the string. During 'inccommand' preview only do this if
4129        //    there is a replace pattern.
4130        if (cmdpreview_ns <= 0 || has_second_delim) {
4131          lnum_start = lnum;  // save the start lnum
4132          int save_ma = curbuf->b_p_ma;
4133          int save_sandbox = sandbox;
4134          if (subflags.do_count) {
4135            // prevent accidentally changing the buffer by a function
4136            curbuf->b_p_ma = false;
4137            sandbox++;
4138          }
4139          // Save flags for recursion.  They can change for e.g.
4140          // :s/^/\=execute("s#^##gn")
4141          subflags_T subflags_save = subflags;
4142
4143          // Disallow changing text or switching window in an expression.
4144          textlock++;
4145          // Get length of substitution part, including the NUL.
4146          // When it fails sublen is zero.
4147          sublen = (size_t)vim_regsub_multi(&regmatch,
4148                                            sub_firstlnum - regmatch.startpos[0].lnum,
4149                                            sub, sub_firstline.data, 0,
4150                                            REGSUB_BACKSLASH
4151                                            | (p_magic ? REGSUB_MAGIC : 0));
4152          textlock--;
4153
4154          // If getting the substitute string caused an error, don't do
4155          // the replacement.
4156          // Don't keep flags set by a recursive call
4157          subflags = subflags_save;
4158          if (sublen == 0 || aborting() || subflags.do_count) {
4159            curbuf->b_p_ma = save_ma;
4160            sandbox = save_sandbox;
4161            goto skip;
4162          }
4163
4164          String tmp;
4165          // Need room for:
4166          // - result so far in new_start (not for first sub in line)
4167          // - original text up to match
4168          // - length of substituted part
4169          // - original text after match
4170          if (nmatch == 1) {
4171            tmp = sub_firstline;
4172          } else {
4173            linenr_T lastlnum = sub_firstlnum + (linenr_T)nmatch - 1;
4174            tmp = cbuf_as_string(ml_get(lastlnum), (size_t)ml_get_len(lastlnum));
4175            nmatch_tl += nmatch - 1;
4176          }
4177          size_t copy_len = (size_t)(regmatch.startpos[0].col - copycol);
4178          sub_grow_buf(&new_start, &new_start_size,
4179                       copy_len
4180                       + (tmp.size - (size_t)regmatch.endpos[0].col) + sublen + 1);
4181
4182          // copy the text up to the part that matched
4183          memmove(new_start.data + new_start.size,
4184                  sub_firstline.data + copycol, copy_len);
4185          new_start.size += copy_len;
4186
4187          // new text added here
4188          new_end = new_start.data + new_start.size;
4189
4190          if (new_start_size - copy_len < sublen) {
4191            sublen = new_start_size - copy_len - 1;
4192          }
4193
4194          // Finally, at this point we can know where the match actually will
4195          // start in the new text
4196          int start_col = (int)new_start.size;
4197          current_match.start.col = start_col;
4198
4199          textlock++;
4200          size_t n = (size_t)vim_regsub_multi(&regmatch,
4201                                              sub_firstlnum - regmatch.startpos[0].lnum,
4202                                              sub, new_end, (int)sublen,
4203                                              REGSUB_COPY | REGSUB_BACKSLASH
4204                                              | (p_magic ? REGSUB_MAGIC : 0));
4205          if (n > 0) {
4206            new_start.size += n - 1;      // remove 1 for the NUL
4207          }
4208          textlock--;
4209          sub_nsubs++;
4210          did_sub = true;
4211
4212          // Move the cursor to the start of the line, to avoid that it
4213          // is beyond the end of the line after the substitution.
4214          curwin->w_cursor.col = 0;
4215
4216          // Remember next character to be copied.
4217          copycol = regmatch.endpos[0].col;
4218
4219          ADJUST_SUB_FIRSTLNUM();
4220
4221          // TODO(bfredl): this has some robustness issues, look into later.
4222          bcount_t replaced_bytes = 0;
4223          lpos_T start = regmatch.startpos[0];
4224          lpos_T end = regmatch.endpos[0];
4225          for (i = 0; i < nmatch - 1; i++) {
4226            replaced_bytes += (bcount_t)strlen(ml_get((linenr_T)(lnum_start + i))) + 1;
4227          }
4228          replaced_bytes += end.col - start.col;
4229
4230          // Save the line number before processing newlines.
4231          linenr_T lnum_before_newlines = lnum;
4232
4233          // Now the trick is to replace CTRL-M chars with a real line
4234          // break.  This would make it impossible to insert a CTRL-M in
4235          // the text.  The line break can be avoided by preceding the
4236          // CTRL-M with a backslash.  To be able to insert a backslash,
4237          // they must be doubled in the string and are halved here.
4238          // That is Vi compatible.
4239          for (char *p1 = new_end; *p1; p1++) {
4240            if (p1[0] == '\\' && p1[1] != NUL) {            // remove backslash
4241              sublen--;  // correct the byte counts for extmark_splice()
4242              n = new_start.size - (size_t)(p1 - new_start.data);
4243              memmove(p1, p1 + 1, n + 1);
4244              new_start.size--;
4245            } else if (*p1 == CAR) {
4246              if (u_inssub(lnum) == OK) {             // prepare for undo
4247                colnr_T plen = (colnr_T)(p1 - new_start.data + 1);
4248                *p1 = NUL;                            // truncate up to the CR
4249                ml_append(lnum - 1, new_start.data, plen, false);
4250                mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1, 0, kExtmarkNOOP);
4251
4252                if (subflags.do_ask) {
4253                  appended_lines(lnum - 1, 1);
4254                } else {
4255                  if (first_line == 0) {
4256                    first_line = lnum;
4257                  }
4258                  last_line = lnum + 1;
4259                }
4260                // All line numbers increase.
4261                sub_firstlnum++;
4262                lnum++;
4263                line2++;
4264                // move the cursor to the new line, like Vi
4265                curwin->w_cursor.lnum++;
4266                // copy the rest
4267                n = new_start.size - (size_t)plen;
4268                memmove(new_start.data, p1 + 1, n + 1);
4269                new_start.size = n;
4270                p1 = new_start.data - 1;
4271              }
4272            } else {
4273              p1 += utfc_ptr2len(p1) - 1;
4274            }
4275          }
4276          colnr_T new_endcol = (colnr_T)new_start.size;
4277          current_match.end.col = new_endcol;
4278          current_match.end.lnum = lnum;
4279
4280          int matchcols = end.col - ((end.lnum == start.lnum)
4281                                     ? start.col : 0);
4282          int subcols = new_endcol - ((lnum == lnum_start) ? start_col : 0);
4283          if (!did_save) {
4284            // Required for Undo to work for extmarks.
4285            u_save_cursor();
4286            did_save = true;
4287          }
4288
4289          // Store extmark data for this match.
4290          LineData *data = kv_pushp(line_matches);
4291          data->start_col = start_col;
4292          data->start = start;
4293          data->end = end;
4294          data->matchcols = matchcols;
4295          data->matchbytes = replaced_bytes;
4296          data->subcols = subcols;
4297          data->subbytes = (colnr_T)sublen - 1;
4298          data->lnum_before = lnum_before_newlines;
4299          data->lnum_after = lnum;
4300        }
4301
4302        // 4. If subflags.do_all is set, find next match.
4303        // Prevent endless loop with patterns that match empty
4304        // strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
4305        // But ":s/\n/#/" is OK.
4306skip:
4307        // We already know that we did the last subst when we are at
4308        // the end of the line, except that a pattern like
4309        // "bar\|\nfoo" may match at the NUL.  "lnum" can be below
4310        // "line2" when there is a \zs in the pattern after a line
4311        // break.
4312        lastone = (skip_match
4313                   || got_int
4314                   || got_quit
4315                   || lnum > line2
4316                   || !(subflags.do_all || do_again)
4317                   || (sub_firstline.data[matchcol] == NUL && nmatch <= 1
4318                       && !re_multiline(regmatch.regprog)));
4319        nmatch = -1;
4320
4321        // Replace the line in the buffer when needed.  This is
4322        // skipped when there are more matches.
4323        // The check for nmatch_tl is needed for when multi-line
4324        // matching must replace the lines before trying to do another
4325        // match, otherwise "\@<=" won't work.
4326        // When the match starts below where we start searching also
4327        // need to replace the line first (using \zs after \n).
4328        if (lastone
4329            || nmatch_tl > 0
4330            || (nmatch = vim_regexec_multi(&regmatch, curwin,
4331                                           curbuf, sub_firstlnum,
4332                                           matchcol, &tm, &timed_out)) == 0
4333            || regmatch.startpos[0].lnum > 0) {
4334          if (new_start.data != NULL) {
4335            // Copy the rest of the line, that didn't match.
4336            // "matchcol" has to be adjusted, we use the end of
4337            // the line as reference, because the substitute may
4338            // have changed the number of characters.  Same for
4339            // "prev_matchcol".
4340            STRCPY(new_start.data + new_start.size, sub_firstline.data + copycol);
4341            new_start.size += sub_firstline.size - (size_t)copycol;
4342            matchcol = (colnr_T)sub_firstline.size - matchcol;
4343            prev_matchcol = (colnr_T)sub_firstline.size - prev_matchcol;
4344
4345            if (u_savesub(lnum) != OK) {
4346              break;
4347            }
4348            ml_replace(lnum, new_start.data, true);
4349
4350            // Call extmark_splice for each match on this line.
4351            for (size_t match_idx = 0; match_idx < kv_size(line_matches); match_idx++) {
4352              LineData *match = &kv_A(line_matches, match_idx);
4353
4354              extmark_splice(curbuf, (int)match->lnum_before - 1, match->start_col,
4355                             match->end.lnum - match->start.lnum, match->matchcols,
4356                             match->matchbytes,
4357                             match->lnum_after - match->lnum_before,
4358                             match->subcols,
4359                             match->subbytes, kExtmarkUndo);
4360            }
4361
4362            // Reset the match data for the next line.
4363            kv_size(line_matches) = 0;
4364
4365            if (nmatch_tl > 0) {
4366              // Matched lines have now been substituted and are
4367              // useless, delete them.  The part after the match
4368              // has been appended to new_start, we don't need
4369              // it in the buffer.
4370              lnum++;
4371              if (u_savedel(lnum, nmatch_tl) != OK) {
4372                break;
4373              }
4374              for (i = 0; i < nmatch_tl; i++) {
4375                ml_delete(lnum);
4376              }
4377              mark_adjust(lnum, lnum + nmatch_tl - 1, MAXLNUM, -nmatch_tl, kExtmarkNOOP);
4378              if (subflags.do_ask) {
4379                deleted_lines(lnum, nmatch_tl);
4380              }
4381              lnum--;
4382              line2 -= nmatch_tl;  // nr of lines decreases
4383              nmatch_tl = 0;
4384            }
4385
4386            // When asking, undo is saved each time, must also set
4387            // changed flag each time.
4388            if (subflags.do_ask) {
4389              changed_bytes(lnum, 0);
4390            } else {
4391              if (first_line == 0) {
4392                first_line = lnum;
4393              }
4394              last_line = lnum + 1;
4395            }
4396
4397            sub_firstlnum = lnum;
4398            xfree(sub_firstline.data);           // free the temp buffer
4399            sub_firstline = new_start;
4400            new_start = NULL_STRING;
4401            matchcol = (colnr_T)sub_firstline.size - matchcol;
4402            prev_matchcol = (colnr_T)sub_firstline.size - prev_matchcol;
4403            copycol = 0;
4404          }
4405          if (nmatch == -1 && !lastone) {
4406            nmatch = vim_regexec_multi(&regmatch, curwin, curbuf,
4407                                       sub_firstlnum, matchcol, &tm, &timed_out);
4408          }
4409
4410          // 5. break if there isn't another match in this line
4411          if (nmatch <= 0) {
4412            // If the match found didn't start where we were
4413            // searching, do the next search in the line where we
4414            // found the match.
4415            if (nmatch == -1) {
4416              lnum -= regmatch.startpos[0].lnum;
4417            }
4418
4419            // uncrustify:off
4420
4421#define PUSH_PREVIEW_LINES() \
4422  do { \
4423    if (cmdpreview_ns > 0) { \
4424      linenr_T match_lines = current_match.end.lnum \
4425                             - current_match.start.lnum +1; \
4426      if (preview_lines.subresults.size > 0) { \
4427        linenr_T last = kv_last(preview_lines.subresults).end.lnum; \
4428        if (last == current_match.start.lnum) { \
4429          preview_lines.lines_needed += match_lines - 1; \
4430        } else { \
4431          preview_lines.lines_needed += match_lines; \
4432        } \
4433      } else { \
4434        preview_lines.lines_needed += match_lines; \
4435      } \
4436      kv_push(preview_lines.subresults, current_match); \
4437    } \
4438  } while (0)
4439
4440            // uncrustify:on
4441
4442            // Push the match to preview_lines.
4443            PUSH_PREVIEW_LINES();
4444
4445            break;
4446          }
4447        }
4448        // Push the match to preview_lines.
4449        PUSH_PREVIEW_LINES();
4450
4451        line_breakcheck();
4452      }
4453
4454      if (did_sub) {
4455        sub_nlines++;
4456      }
4457      xfree(new_start.data);            // for when substitute was cancelled
4458      API_CLEAR_STRING(sub_firstline);  // free the copy of the original line
4459      kv_destroy(line_matches);         // clean up match data
4460    }
4461
4462    line_breakcheck();
4463
4464    if (timed_out || profile_passed_limit(tm)) {
4465      got_quit = true;
4466    }
4467  }
4468
4469  curbuf->deleted_bytes2 = 0;
4470
4471  if (first_line != 0) {
4472    // Need to subtract the number of added lines from "last_line" to get
4473    // the line number before the change (same as adding the number of
4474    // deleted lines).
4475    i = curbuf->b_ml.ml_line_count - old_line_count;
4476    changed_lines(curbuf, first_line, 0, last_line - (linenr_T)i, (linenr_T)i, false);
4477
4478    int64_t num_added = last_line - first_line;
4479    int64_t num_removed = num_added - i;
4480    buf_updates_send_changes(curbuf, first_line, num_added, num_removed);
4481  }
4482
4483  xfree(sub_firstline.data);   // may have to free allocated copy of the line
4484
4485  // ":s/pat//n" doesn't move the cursor
4486  if (subflags.do_count) {
4487    curwin->w_cursor = old_cursor;
4488  }
4489
4490  if (sub_nsubs > start_nsubs) {
4491    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
4492      // Set the '[ and '] marks.
4493      curbuf->b_op_start.lnum = eap->line1;
4494      curbuf->b_op_end.lnum = line2;
4495      curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
4496    }
4497
4498    if (!global_busy) {
4499      // when interactive leave cursor on the match
4500      if (!subflags.do_ask) {
4501        if (endcolumn) {
4502          coladvance(curwin, MAXCOL);
4503        } else {
4504          beginline(BL_WHITE | BL_FIX);
4505        }
4506      }
4507      if (cmdpreview_ns <= 0 && !do_sub_msg(subflags.do_count) && subflags.do_ask && p_ch > 0) {
4508        msg("", 0);
4509      }
4510    } else {
4511      global_need_beginline = true;
4512    }
4513    if (subflags.do_print) {
4514      print_line(curwin->w_cursor.lnum, subflags.do_number, subflags.do_list, true);
4515    }
4516  } else if (!global_busy) {
4517    if (got_int) {
4518      // interrupted
4519      emsg(_(e_interr));
4520    } else if (got_match) {
4521      // did find something but nothing substituted
4522      if (p_ch > 0 && !ui_has(kUIMessages)) {
4523        msg("", 0);
4524      }
4525    } else if (subflags.do_error) {
4526      // nothing found
4527      semsg(_(e_patnotf2), get_search_pat());
4528    }
4529  }
4530
4531  if (subflags.do_ask && hasAnyFolding(curwin)) {
4532    // Cursor position may require updating
4533    changed_window_setting(curwin);
4534  }
4535
4536  vim_regfree(regmatch.regprog);
4537  xfree(sub);
4538
4539  // Restore the flag values, they can be used for ":&&".
4540  subflags.do_all = save_do_all;
4541  subflags.do_ask = save_do_ask;
4542
4543  int retv = 0;
4544
4545  // Show 'inccommand' preview if there are matched lines.
4546  if (cmdpreview_ns > 0 && !aborting()) {
4547    if (got_quit || profile_passed_limit(tm)) {  // Too slow, disable.
4548      set_option_direct(kOptInccommand, STATIC_CSTR_AS_OBJ(""), 0, SID_NONE);
4549    } else if (*p_icm != NUL && pat.data != NULL) {
4550      if (pre_hl_id == 0) {
4551        pre_hl_id = syn_check_group(S_LEN("Substitute"));
4552      }
4553      retv = show_sub(eap, old_cursor, &preview_lines, pre_hl_id, cmdpreview_ns, cmdpreview_bufnr);
4554    }
4555  }
4556
4557  kv_destroy(preview_lines.subresults);
4558  return retv;
4559#undef ADJUST_SUB_FIRSTLNUM
4560#undef PUSH_PREVIEW_LINES
4561}
4562
4563/// Give message for number of substitutions.
4564/// Can also be used after a ":global" command.
4565///
4566/// @param count_only  used 'n' flag for ":s"
4567///
4568/// @return            true if a message was given.
4569bool do_sub_msg(bool count_only)
4570{
4571  // Only report substitutions when:
4572  // - more than 'report' substitutions
4573  // - command was typed by user, or number of changed lines > 'report'
4574  // - giving messages is not disabled by 'lazyredraw'
4575  if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
4576       || count_only)
4577      && messaging()) {
4578    if (got_int) {
4579      STRCPY(msg_buf, _("(Interrupted) "));
4580    } else {
4581      *msg_buf = NUL;
4582    }
4583
4584    char *msg_single = count_only
4585                       ? NGETTEXT("%" PRId64 " match on %" PRId64 " line",
4586                                  "%" PRId64 " matches on %" PRId64 " line", sub_nsubs)
4587                       : NGETTEXT("%" PRId64 " substitution on %" PRId64 " line",
4588                                  "%" PRId64 " substitutions on %" PRId64 " line", sub_nsubs);
4589    char *msg_plural = count_only
4590                       ? NGETTEXT("%" PRId64 " match on %" PRId64 " lines",
4591                                  "%" PRId64 " matches on %" PRId64 " lines", sub_nsubs)
4592                       : NGETTEXT("%" PRId64 " substitution on %" PRId64 " lines",
4593                                  "%" PRId64 " substitutions on %" PRId64 " lines", sub_nsubs);
4594    vim_snprintf_add(msg_buf, sizeof(msg_buf),
4595                     NGETTEXT(msg_single, msg_plural, sub_nlines),
4596                     (int64_t)sub_nsubs, (int64_t)sub_nlines);
4597    if (msg(msg_buf, 0)) {
4598      // save message to display it after redraw
4599      set_keep_msg(msg_buf, 0);
4600    }
4601    return true;
4602  }
4603  if (got_int) {
4604    emsg(_(e_interr));
4605    return true;
4606  }
4607  return false;
4608}
4609
4610static void global_exe_one(char *const cmd, const linenr_T lnum)
4611{
4612  curwin->w_cursor.lnum = lnum;
4613  curwin->w_cursor.col = 0;
4614  if (*cmd == NUL || *cmd == '\n') {
4615    do_cmdline("p", NULL, NULL, DOCMD_NOWAIT);
4616  } else {
4617    do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
4618  }
4619}
4620
4621/// Execute a global command of the form:
4622///
4623/// g/pattern/X : execute X on all lines where pattern matches
4624/// v/pattern/X : execute X on all lines where pattern does not match
4625///
4626/// where 'X' is an EX command
4627///
4628/// The command character (as well as the trailing slash) is optional, and
4629/// is assumed to be 'p' if missing.
4630///
4631/// This is implemented in two passes: first we scan the file for the pattern and
4632/// set a mark for each line that (not) matches. Secondly we execute the command
4633/// for each line that has a mark. This is required because after deleting
4634/// lines we do not know where to search for the next match.
4635void ex_global(exarg_T *eap)
4636{
4637  linenr_T lnum;                // line number according to old situation
4638  int type;                     // first char of cmd: 'v' or 'g'
4639  char *cmd;                    // command argument
4640
4641  char delim;                 // delimiter, normally '/'
4642  char *pat;
4643  size_t patlen;
4644  regmmatch_T regmatch;
4645
4646  // When nesting the command works on one line.  This allows for
4647  // ":g/found/v/notfound/command".
4648  if (global_busy && (eap->line1 != 1
4649                      || eap->line2 != curbuf->b_ml.ml_line_count)) {
4650    // will increment global_busy to break out of the loop
4651    emsg(_("E147: Cannot do :global recursive with a range"));
4652    return;
4653  }
4654
4655  if (eap->forceit) {               // ":global!" is like ":vglobal"
4656    type = 'v';
4657  } else {
4658    type = (uint8_t)(*eap->cmd);
4659  }
4660  cmd = eap->arg;
4661  int which_pat = RE_LAST;              // default: use last used regexp
4662
4663  // undocumented vi feature:
4664  //    "\/" and "\?": use previous search pattern.
4665  //             "\&": use previous substitute pattern.
4666  if (*cmd == '\\') {
4667    cmd++;
4668    if (vim_strchr("/?&", (uint8_t)(*cmd)) == NULL) {
4669      emsg(_(e_backslash));
4670      return;
4671    }
4672    if (*cmd == '&') {
4673      which_pat = RE_SUBST;             // use previous substitute pattern
4674    } else {
4675      which_pat = RE_SEARCH;            // use previous search pattern
4676    }
4677    cmd++;
4678    pat = "";
4679    patlen = 0;
4680  } else if (*cmd == NUL) {
4681    emsg(_("E148: Regular expression missing from global"));
4682    return;
4683  } else if (check_regexp_delim(*cmd) == FAIL) {
4684    return;
4685  } else {
4686    delim = *cmd;               // get the delimiter
4687    cmd++;                      // skip delimiter if there is one
4688    pat = cmd;                  // remember start of pattern
4689    cmd = skip_regexp_ex(cmd, delim, p_magic, &eap->arg, NULL, NULL);
4690    if (cmd[0] == delim) {                  // end delimiter found
4691      *cmd++ = NUL;                         // replace it with a NUL
4692    }
4693    patlen = strlen(pat);
4694  }
4695
4696  char *used_pat;
4697  if (search_regcomp(pat, patlen, &used_pat, RE_BOTH, which_pat,
4698                     SEARCH_HIS, p_magic, &regmatch) == FAIL) {
4699    emsg(_(e_invcmd));
4700    return;
4701  }
4702
4703  if (global_busy) {
4704    lnum = curwin->w_cursor.lnum;
4705    int match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, 0, NULL, NULL);
4706    if ((type == 'g' && match) || (type == 'v' && !match)) {
4707      global_exe_one(cmd, lnum);
4708    }
4709  } else {
4710    int ndone = 0;
4711    // pass 1: set marks for each (not) matching line
4712    for (lnum = eap->line1; lnum <= eap->line2 && !got_int; lnum++) {
4713      // a match on this line?
4714      int match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum, 0, NULL, NULL);
4715      if (regmatch.regprog == NULL) {
4716        break;  // re-compiling regprog failed
4717      }
4718      if ((type == 'g' && match) || (type == 'v' && !match)) {
4719        ml_setmarked(lnum);
4720        ndone++;
4721      }
4722      line_breakcheck();
4723    }
4724
4725    // pass 2: execute the command for each line that has been marked
4726    if (got_int) {
4727      msg(_(e_interr), 0);
4728    } else if (ndone == 0) {
4729      if (type == 'v') {
4730        smsg(0, _("Pattern found in every line: %s"), used_pat);
4731      } else {
4732        smsg(0, _("Pattern not found: %s"), used_pat);
4733      }
4734    } else {
4735      global_exe(cmd);
4736    }
4737    ml_clearmarked();         // clear rest of the marks
4738  }
4739  vim_regfree(regmatch.regprog);
4740}
4741
4742/// Execute `cmd` on lines marked with ml_setmarked().
4743void global_exe(char *cmd)
4744{
4745  linenr_T old_lcount;      // b_ml.ml_line_count before the command
4746  buf_T *old_buf = curbuf;  // remember what buffer we started in
4747  linenr_T lnum;            // line number according to old situation
4748
4749  // Set current position only once for a global command.
4750  // If global_busy is set, setpcmark() will not do anything.
4751  // If there is an error, global_busy will be incremented.
4752  setpcmark();
4753
4754  // When the command writes a message, don't overwrite the command.
4755  msg_didout = true;
4756
4757  sub_nsubs = 0;
4758  sub_nlines = 0;
4759  global_need_msg_kind = true;
4760  global_need_beginline = false;
4761  global_busy = 1;
4762  old_lcount = curbuf->b_ml.ml_line_count;
4763
4764  while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1) {
4765    global_exe_one(cmd, lnum);
4766    os_breakcheck();
4767  }
4768
4769  global_busy = 0;
4770  if (global_need_beginline) {
4771    beginline(BL_WHITE | BL_FIX);
4772  } else {
4773    check_cursor(curwin);  // cursor may be beyond the end of the line
4774  }
4775
4776  // the cursor may not have moved in the text but a change in a previous
4777  // line may move it on the screen
4778  changed_line_abv_curs();
4779
4780  // If it looks like no message was written, allow overwriting the
4781  // command with the report for number of changes.
4782  if (msg_col == 0 && msg_scrolled == 0) {
4783    msg_didout = false;
4784  }
4785
4786  // If substitutes done, report number of substitutes, otherwise report
4787  // number of extra or deleted lines.
4788  // Don't report extra or deleted lines in the edge case where the buffer
4789  // we are in after execution is different from the buffer we started in.
4790  if (!do_sub_msg(false) && curbuf == old_buf) {
4791    msgmore(curbuf->b_ml.ml_line_count - old_lcount);
4792  }
4793}
4794
4795#ifdef EXITFREE
4796void free_old_sub(void)
4797{
4798  sub_set_replacement((SubReplacementString) { NULL, 0, NULL });
4799}
4800
4801#endif
4802
4803/// Set up for a tagpreview.
4804///
4805/// @param undo_sync        Sync undo when leaving the window.
4806/// @param use_previewpopup Use a floating window (when 'previewpopup' is set).
4807///
4808/// @return true when the preview window was created.
4809bool prepare_tagpreview(bool undo_sync, bool use_previewpopup)
4810{
4811  if (curwin->w_p_pvw) {
4812    return false;
4813  }
4814
4815  // If there is already a preview window open, use that one.
4816  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
4817    if (wp->w_p_pvw) {
4818      if (use_previewpopup ? wp->w_kind != kWinPreview : wp->w_floating) {
4819        continue;
4820      }
4821      if (use_previewpopup) {
4822        win_float_anchor_preview(wp);  // Re-anchor to the new cursor position.
4823      }
4824      win_enter(wp, undo_sync);
4825      return false;
4826    }
4827  }
4828
4829  if (use_previewpopup) {
4830    win_T *wp = win_float_special(false, true, kWinPreview);
4831    if (!wp) {
4832      return false;
4833    }
4834    win_enter(wp, undo_sync);
4835    return true;
4836  }
4837  // There is no preview window open yet. Create one.
4838  if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0) == FAIL) {
4839    return false;
4840  }
4841
4842  curwin->w_p_pvw = true;
4843  curwin->w_p_wfh = true;
4844  RESET_BINDING(curwin);                // don't take over 'scrollbind' and 'cursorbind'
4845  curwin->w_p_diff = false;             // no 'diff'
4846
4847  set_option_direct(kOptFoldcolumn, STATIC_CSTR_AS_OBJ("0"), 0, SID_NONE);  // no 'foldcolumn'
4848  return true;
4849}
4850
4851/// Shows the effects of the :substitute command being typed ('inccommand').
4852/// If inccommand=split, shows a preview window and later restores the layout.
4853///
4854/// @return 1 if preview window isn't needed, 2 if preview window is needed.
4855static int show_sub(exarg_T *eap, pos_T old_cusr, PreviewLines *preview_lines, int hl_id,
4856                    int cmdpreview_ns, handle_T cmdpreview_bufnr)
4857  FUNC_ATTR_NONNULL_ALL
4858{
4859  char *save_shm_p = xstrdup(p_shm);
4860  PreviewLines lines = *preview_lines;
4861  buf_T *orig_buf = curbuf;
4862  // We keep a special-purpose buffer around, but don't assume it exists.
4863  buf_T *cmdpreview_buf = NULL;
4864
4865  // disable file info message
4866  set_option_direct(kOptShortmess, STATIC_CSTR_AS_OBJ("F"), 0, SID_NONE);
4867
4868  // Place cursor on nearest matching line, to undo do_sub() cursor placement.
4869  for (size_t i = 0; i < lines.subresults.size; i++) {
4870    SubResult curres = lines.subresults.items[i];
4871    if (curres.start.lnum >= old_cusr.lnum) {
4872      curwin->w_cursor.lnum = curres.start.lnum;
4873      curwin->w_cursor.col = curres.start.col;
4874      break;
4875    }  // Else: All matches are above, do_sub() already placed cursor.
4876  }
4877
4878  // Update the topline to ensure that main window is on the correct line
4879  update_topline(curwin);
4880
4881  // Width of the "| lnum|..." column which displays the line numbers.
4882  int col_width = 0;
4883  // Use preview window only when inccommand=split and range is not just the current line
4884  bool preview = (*p_icm == 's') && (eap->line1 != old_cusr.lnum || eap->line2 != old_cusr.lnum);
4885
4886  if (preview) {
4887    cmdpreview_buf = buflist_findnr(cmdpreview_bufnr);
4888    assert(cmdpreview_buf != NULL);
4889
4890    if (lines.subresults.size > 0) {
4891      SubResult last_match = kv_last(lines.subresults);
4892      // `last_match.end.lnum` may be 0 when using 'n' flag.
4893      linenr_T highest_lnum = MAX(last_match.start.lnum, last_match.end.lnum);
4894      assert(highest_lnum > 0);
4895      col_width = (int)log10(highest_lnum) + 1 + 3;
4896    }
4897  }
4898
4899  char *str = NULL;  // construct the line to show in here
4900  colnr_T old_line_size = 0;
4901  colnr_T line_size = 0;
4902  linenr_T linenr_preview = 0;  // last line added to preview buffer
4903  linenr_T linenr_origbuf = 0;  // last line added to original buffer
4904  linenr_T next_linenr = 0;     // next line to show for the match
4905
4906  for (size_t matchidx = 0; matchidx < lines.subresults.size; matchidx++) {
4907    SubResult match = lines.subresults.items[matchidx];
4908
4909    if (cmdpreview_buf) {
4910      lpos_T p_start = { 0, match.start.col };  // match starts here in preview
4911      lpos_T p_end = { 0, match.end.col };    // ... and ends here
4912
4913      // You Might Gonna Need It
4914      buf_ensure_loaded(cmdpreview_buf);
4915
4916      if (match.pre_match == 0) {
4917        next_linenr = match.start.lnum;
4918      } else {
4919        next_linenr = match.pre_match;
4920      }
4921      // Don't add a line twice
4922      if (next_linenr == linenr_origbuf) {
4923        next_linenr++;
4924        p_start.lnum = linenr_preview;  // might be redefined below
4925        p_end.lnum = linenr_preview;  // might be redefined below
4926      }
4927
4928      for (; next_linenr <= match.end.lnum; next_linenr++) {
4929        if (next_linenr == match.start.lnum) {
4930          p_start.lnum = linenr_preview + 1;
4931        }
4932        if (next_linenr == match.end.lnum) {
4933          p_end.lnum = linenr_preview + 1;
4934        }
4935        char *line;
4936        if (next_linenr == orig_buf->b_ml.ml_line_count + 1) {
4937          line = "";
4938        } else {
4939          line = ml_get_buf(orig_buf, next_linenr);
4940          line_size = ml_get_buf_len(orig_buf, next_linenr) + col_width + 1;
4941
4942          // Reallocate if line not long enough
4943          if (line_size > old_line_size) {
4944            str = xrealloc(str, (size_t)line_size * sizeof(char));
4945            old_line_size = line_size;
4946          }
4947        }
4948        // Put "|lnum| line" into `str` and append it to the preview buffer.
4949        snprintf(str, (size_t)line_size, "|%*" PRIdLINENR "| %s", col_width - 3,
4950                 next_linenr, line);
4951        if (linenr_preview == 0) {
4952          ml_replace_buf(cmdpreview_buf, 1, str, true, false);
4953        } else {
4954          ml_append_buf(cmdpreview_buf, linenr_preview, str, line_size, false);
4955        }
4956        linenr_preview += 1;
4957      }
4958      linenr_origbuf = match.end.lnum;
4959
4960      bufhl_add_hl_pos_offset(cmdpreview_buf, cmdpreview_ns, hl_id, p_start, p_end, col_width);
4961    }
4962    bufhl_add_hl_pos_offset(orig_buf, cmdpreview_ns, hl_id, match.start, match.end, 0);
4963  }
4964
4965  xfree(str);
4966
4967  set_option_direct(kOptShortmess, CSTR_AS_OBJ(save_shm_p), 0, SID_NONE);
4968  xfree(save_shm_p);
4969
4970  return preview ? 2 : 1;
4971}
4972
4973/// :substitute command.
4974void ex_substitute(exarg_T *eap)
4975{
4976  do_sub(eap, profile_zero(), 0, 0);
4977}
4978
4979/// :substitute command preview callback.
4980int ex_substitute_preview(exarg_T *eap, int cmdpreview_ns, handle_T cmdpreview_bufnr)
4981{
4982  // Only preview once the pattern delimiter has been typed
4983  if (*eap->arg && !ASCII_ISALNUM(*eap->arg)) {
4984    char *save_eap = eap->arg;
4985    int retv = do_sub(eap, profile_setlimit(p_rdt), cmdpreview_ns, cmdpreview_bufnr);
4986    eap->arg = save_eap;
4987    return retv;
4988  }
4989
4990  return 0;
4991}
4992
4993/// Skip over the pattern argument of ":vimgrep /pat/[g][j]".
4994/// Put the start of the pattern in "*s", unless "s" is NULL.
4995///
4996/// @param flags  if not NULL, put the flags in it: VGR_GLOBAL, VGR_NOJUMP.
4997/// @param s      if not NULL, terminate the pattern with a NUL.
4998///
4999/// @return  a pointer to the char just past the pattern plus flags.
5000char *skip_vimgrep_pat(char *p, char **s, int *flags)
5001{
5002  if (vim_isIDc((uint8_t)(*p))) {
5003    // ":vimgrep pattern fname"
5004    if (s != NULL) {
5005      *s = p;
5006    }
5007    p = skiptowhite(p);
5008    if (s != NULL && *p != NUL) {
5009      *p++ = NUL;
5010    }
5011  } else {
5012    // ":vimgrep /pattern/[g][j] fname"
5013    if (s != NULL) {
5014      *s = p + 1;
5015    }
5016    int c = (uint8_t)(*p);
5017    p = skip_regexp(p + 1, c, true);
5018    if (*p != c) {
5019      return NULL;
5020    }
5021
5022    // Truncate the pattern.
5023    if (s != NULL) {
5024      *p = NUL;
5025    }
5026    p++;
5027
5028    // Find the flags
5029    while (*p == 'g' || *p == 'j' || *p == 'f') {
5030      if (flags != NULL) {
5031        if (*p == 'g') {
5032          *flags |= VGR_GLOBAL;
5033        } else if (*p == 'j') {
5034          *flags |= VGR_NOJUMP;
5035        } else {
5036          *flags |= VGR_FUZZY;
5037        }
5038      }
5039      p++;
5040    }
5041  }
5042  return p;
5043}
5044
5045/// `:oldfiles` (sync) and `:browse oldfiles` (async).
5046void ex_oldfiles(exarg_T *eap)
5047{
5048  nlua_call_excmd("vim._core.ex_cmd", "ex_oldfiles", eap, &cmdmod, NULL);
5049}