robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
86.6 KiB2907 linesraw
1// register.c: functions for managing registers
2
3#include "nvim/api/private/helpers.h"
4#include "nvim/autocmd.h"
5#include "nvim/buffer.h"
6#include "nvim/buffer_defs.h"
7#include "nvim/buffer_updates.h"
8#include "nvim/change.h"
9#include "nvim/charset.h"
10#include "nvim/clipboard.h"
11#include "nvim/cursor.h"
12#include "nvim/drawscreen.h"
13#include "nvim/errors.h"
14#include "nvim/eval.h"
15#include "nvim/eval/typval.h"
16#include "nvim/ex_cmds2.h"
17#include "nvim/ex_docmd.h"
18#include "nvim/ex_getln.h"
19#include "nvim/extmark.h"
20#include "nvim/file_search.h"
21#include "nvim/fold.h"
22#include "nvim/garray.h"
23#include "nvim/globals.h"
24#include "nvim/indent.h"
25#include "nvim/input.h"
26#include "nvim/insert.h"
27#include "nvim/insexpand.h"
28#include "nvim/keycodes.h"
29#include "nvim/mark.h"
30#include "nvim/mbyte.h"
31#include "nvim/mcursor.h"
32#include "nvim/memline.h"
33#include "nvim/message.h"
34#include "nvim/move.h"
35#include "nvim/normal.h"
36#include "nvim/ops.h"
37#include "nvim/option.h"
38#include "nvim/option_vars.h"
39#include "nvim/os/input.h"
40#include "nvim/os/time.h"
41#include "nvim/plines.h"
42#include "nvim/register.h"
43#include "nvim/search.h"
44#include "nvim/strings.h"
45#include "nvim/terminal.h"
46#include "nvim/types_defs.h"
47#include "nvim/ui.h"
48#include "nvim/undo.h"
49
50#include "register.c.generated.h"
51
52// Keep the last expression line here, for repeating.
53static char *expr_line = NULL;
54
55static int execreg_lastc = NUL;
56
57static yankreg_T y_regs[NUM_REGISTERS] = { 0 };
58
59static yankreg_T *y_previous = NULL;  // ptr to last written yankreg
60
61static const char e_register_char_cannot_contain_multiple_lines[]
62  = N_("E883: Register '%c' cannot contain multiple lines");
63
64/// @return the index of the register "" points to.
65int get_unname_register(void)
66{
67  return y_previous == NULL ? -1 : (int)(y_previous - &y_regs[0]);
68}
69
70yankreg_T *get_y_register(int reg)
71{
72  return &y_regs[reg];
73}
74
75/// What `p` pastes: the last-written register (x: -, yy: 0, "+yy: +, :let @"=…: 0).
76///
77/// Exception: with clipboard=unnamed/unnamedplus, `p` tries the provider first.
78yankreg_T *get_y_previous(void)
79  FUNC_ATTR_PURE
80{
81  return y_previous;
82}
83
84/// Get an expression for the "\"=expr1" or "CTRL-R =expr1"
85///
86/// @return  '=' when OK, NUL otherwise.
87int get_expr_register(void)
88{
89  char *new_line = getcmdline('=', 0, 0, true);
90  if (new_line == NULL) {
91    return NUL;
92  }
93  if (*new_line == NUL) {  // use previous line
94    xfree(new_line);
95  } else {
96    set_expr_line(new_line);
97  }
98  return '=';
99}
100
101/// Set the expression for the '=' register.
102/// Argument must be an allocated string.
103void set_expr_line(char *new_line)
104{
105  xfree(expr_line);
106  expr_line = new_line;
107}
108
109/// Get the result of the '=' register expression.
110///
111/// @return  a pointer to allocated memory, or NULL for failure.
112char *get_expr_line(void)
113{
114  static int nested = 0;
115
116  if (expr_line == NULL) {
117    return NULL;
118  }
119
120  // Make a copy of the expression, because evaluating it may cause it to be
121  // changed.
122  char *expr_copy = xstrdup(expr_line);
123
124  // When we are invoked recursively limit the evaluation to 10 levels.
125  // Then return the string as-is.
126  if (nested >= 10) {
127    return expr_copy;
128  }
129
130  nested++;
131  char *rv = eval_to_string(expr_copy, true, false);
132  nested--;
133  xfree(expr_copy);
134  return rv;
135}
136
137/// Get the '=' register expression itself, without evaluating it.
138char *get_expr_line_src(void)
139{
140  if (expr_line == NULL) {
141    return NULL;
142  }
143  return xstrdup(expr_line);
144}
145
146/// @return  whether `regname` is a valid name of a yank register.
147///
148/// @note: There is no check for 0 (default register), caller should do this.
149/// The black hole register '_' is regarded as valid.
150///
151/// @param regname name of register
152/// @param writing allow only writable registers
153bool valid_yank_reg(int regname, bool writing)
154{
155  if ((regname > 0 && ASCII_ISALNUM(regname))
156      || (!writing && vim_strchr("/#.%:=", regname) != NULL)
157      || regname == '"'
158      || regname == '-'
159      || regname == '_'
160      || regname == '*'
161      || regname == '+') {
162    return true;
163  }
164  return false;
165}
166
167/// Check if the default register (used in an unnamed paste) should be a
168/// clipboard register. This happens when `clipboard=unnamed[plus]` is set
169/// and a provider is available.
170///
171/// @returns the name of a clipboard register that should be used, or `NUL` if none.
172int get_default_register_name(void)
173{
174  int name = NUL;
175  adjust_clipboard_name(&name, true, false);
176  return name;
177}
178
179/// Iterate over registers `regs` (only NUM_SAVED_REGISTERS, not clipboard "*"/"+").
180///
181/// @param[in]   iter      Iterator. Pass NULL to start iteration.
182/// @param[in]   regs      Registers list to be iterated.
183/// @param[out]  name      Register name.
184/// @param[out]  reg       Register contents.
185///
186/// @return Pointer that must be passed to next `op_register_iter` call or
187///         NULL if iteration is over.
188const void *op_reg_iter(const void *const iter, const yankreg_T *const regs, char *const name,
189                        yankreg_T *const reg, bool *is_unnamed)
190  FUNC_ATTR_NONNULL_ARG(3, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT
191{
192  *name = NUL;
193  const yankreg_T *iter_reg = (iter == NULL
194                               ? &(regs[0])
195                               : (const yankreg_T *const)iter);
196  while (iter_reg - &(regs[0]) < NUM_SAVED_REGISTERS && reg_empty(iter_reg)) {
197    iter_reg++;
198  }
199  if (iter_reg - &(regs[0]) == NUM_SAVED_REGISTERS || reg_empty(iter_reg)) {
200    return NULL;
201  }
202  int iter_off = (int)(iter_reg - &(regs[0]));
203  *name = (char)get_register_name(iter_off);
204  *reg = *iter_reg;
205  *is_unnamed = (iter_reg == y_previous);
206  while (++iter_reg - &(regs[0]) < NUM_SAVED_REGISTERS) {
207    if (!reg_empty(iter_reg)) {
208      return (void *)iter_reg;
209    }
210  }
211  return NULL;
212}
213
214/// Iterate over global registers (only NUM_SAVED_REGISTERS, not clipboard "*"/"+").
215///
216/// @see op_register_iter
217const void *op_global_reg_iter(const void *const iter, char *const name, yankreg_T *const reg,
218                               bool *is_unnamed)
219  FUNC_ATTR_NONNULL_ARG(2, 3, 4) FUNC_ATTR_WARN_UNUSED_RESULT
220{
221  return op_reg_iter(iter, y_regs, name, reg, is_unnamed);
222}
223
224/// Gets the most-recent timestamp (nanoseconds) of all registers, or 0 if all are empty. Every
225/// register-write sets its timestamp, so this detects if any register changed (e.g. for caching).
226///
227/// @param clipboard  Include clipboard registers ("*"/"+").
228Timestamp reg_max_ts(bool clipboard)
229{
230  Timestamp max_ts = 0;
231  const void *iter = NULL;
232  do {
233    char name = NUL;
234    yankreg_T reg;
235    bool is_unnamed = false;
236    iter = op_global_reg_iter(iter, &name, &reg, &is_unnamed);
237    if (name == NUL) {
238      break;
239    }
240    max_ts = MAX(max_ts, reg.timestamp);
241  } while (iter != NULL);
242  if (clipboard) {
243    max_ts = MAX(max_ts, get_y_register(op_reg_index('*'))->timestamp);
244    max_ts = MAX(max_ts, get_y_register(op_reg_index('+'))->timestamp);
245  }
246  return max_ts;
247}
248
249/// Get a number of non-empty registers
250size_t op_reg_amount(void)
251  FUNC_ATTR_WARN_UNUSED_RESULT
252{
253  size_t ret = 0;
254  for (size_t i = 0; i < NUM_SAVED_REGISTERS; i++) {
255    if (!reg_empty(y_regs + i)) {
256      ret++;
257    }
258  }
259  return ret;
260}
261
262/// Set register to a given value
263///
264/// @param[in]  name  Register name.
265/// @param[in]  reg  Register value.
266/// @param[in]  is_unnamed  Whether to set the unnamed regiseter to reg
267///
268/// @return true on success, false on failure.
269bool op_reg_set(const char name, const yankreg_T reg, bool is_unnamed)
270{
271  int i = op_reg_index(name);
272  if (i == -1) {
273    return false;
274  }
275  free_register(&y_regs[i]);
276  y_regs[i] = reg;
277
278  if (is_unnamed) {
279    y_previous = &y_regs[i];
280  }
281  return true;
282}
283
284/// Get register with the given name
285///
286/// @param[in]  name  Register name.
287///
288/// @return Pointer to the register contents or NULL.
289const yankreg_T *op_reg_get(const char name)
290{
291  int i = op_reg_index(name);
292  if (i == -1) {
293    return NULL;
294  }
295  return &y_regs[i];
296}
297
298/// Set the previous yank register
299///
300/// @param[in]  name  Register name.
301///
302/// @return true on success, false on failure.
303bool op_reg_set_previous(const char name)
304{
305  int i = op_reg_index(name);
306  if (i == -1) {
307    return false;
308  }
309
310  y_previous = &y_regs[i];
311  return true;
312}
313
314/// Updates the "y_width" of a blockwise register based on its contents.
315/// Do nothing on a non-blockwise register.
316void update_yankreg_width(yankreg_T *reg)
317{
318  if (reg->y_type == kMTBlockWise) {
319    size_t maxlen = 0;
320    for (size_t i = 0; i < reg->y_size; i++) {
321      size_t rowlen = mb_string2cells_len(reg->y_array[i].data, reg->y_array[i].size);
322      maxlen = MAX(maxlen, rowlen);
323    }
324    assert(maxlen <= INT_MAX);
325    reg->y_width = MAX(reg->y_width, (int)maxlen - 1);
326  }
327}
328
329/// @return yankreg_T to use, according to the value of `regname`.
330/// Cannot handle the '_' (black hole) register.
331/// Must only be called with a valid register name!
332///
333/// @param regname The name of the register used or 0 for the unnamed register
334/// @param mode One of the following three flags:
335///
336/// `YREG_PASTE`:
337/// Prepare for pasting the register `regname`. With no regname specified,
338/// read from last written register, or from unnamed clipboard (depending on the
339/// `clipboard=unnamed` option). Queries the clipboard provider if necessary.
340///
341/// `YREG_YANK`:
342/// Preparare for yanking into `regname`. With no regname specified,
343/// yank into `"0` register. Update `y_previous` for next unnamed paste.
344///
345/// `YREG_PUT`:
346/// Obtain the location that would be read when pasting `regname`.
347yankreg_T *get_yank_register(int regname, int mode)
348{
349  yankreg_T *reg;
350
351  if ((mode == YREG_PASTE || mode == YREG_PUT)
352      && get_clipboard(regname, &reg, false)) {
353    // reg is set to clipboard contents.
354    return reg;
355  } else if (mode == YREG_PUT && (regname == '*' || regname == '+')) {
356    // in case clipboard not available and we aren't actually pasting,
357    // return an empty register
358    static yankreg_T empty_reg = { .y_array = NULL };
359    return &empty_reg;
360  } else if (mode != YREG_YANK
361             && (regname == 0 || regname == '"' || regname == '*' || regname == '+')
362             && y_previous != NULL) {
363    // in case clipboard not available, paste from previous used register
364    return y_previous;
365  }
366
367  int i = op_reg_index(regname);
368  // when not 0-9, a-z, A-Z or '-'/'+'/'*': use register 0
369  if (i == -1) {
370    i = 0;
371  }
372  reg = &y_regs[i];
373
374  if (mode == YREG_YANK) {
375    // remember the written register for unnamed paste
376    y_previous = reg;
377  }
378  return reg;
379}
380
381/// Check if the current yank register has kMTLineWise register type
382/// For valid, non-blackhole registers also provides pointer to the register
383/// structure prepared for pasting.
384///
385/// @param regname The name of the register used or 0 for the unnamed register
386/// @param reg Pointer to store yankreg_T* for the requested register. Will be
387///        set to NULL for invalid or blackhole registers.
388bool yank_register_mline(int regname, yankreg_T **reg)
389{
390  *reg = NULL;
391  if (regname != 0 && !valid_yank_reg(regname, false)) {
392    return false;
393  }
394  if (regname == '_') {  // black hole is always empty
395    return false;
396  }
397  *reg = get_yank_register(regname, YREG_PASTE);
398  return (*reg)->y_type == kMTLineWise;
399}
400
401/// @return  a copy of contents in register `name` for use in do_put. Should be
402///          freed by caller.
403yankreg_T *copy_register(int name)
404  FUNC_ATTR_NONNULL_RET
405{
406  yankreg_T *reg = get_yank_register(name, YREG_PASTE);
407
408  yankreg_T *copy = xmalloc(sizeof(yankreg_T));
409  *copy = *reg;
410  if (copy->y_size == 0) {
411    copy->y_array = NULL;
412  } else {
413    copy->y_array = xcalloc(copy->y_size, sizeof(String));
414    for (size_t i = 0; i < copy->y_size; i++) {
415      copy->y_array[i] = copy_string(reg->y_array[i], NULL);
416    }
417  }
418  return copy;
419}
420
421/// Stuff string "p" into yank register "regname" as a single line (append if
422/// uppercase). "p" must have been allocated.
423///
424/// @return  FAIL for failure, OK otherwise
425static int stuff_yank(int regname, char *p)
426{
427  // check for read-only register
428  if (regname != 0 && !valid_yank_reg(regname, true)) {
429    xfree(p);
430    return FAIL;
431  }
432  if (regname == '_') {             // black hole: don't do anything
433    xfree(p);
434    return OK;
435  }
436
437  const size_t plen = strlen(p);
438  yankreg_T *reg = get_yank_register(regname, YREG_YANK);
439  if (is_append_register(regname) && reg->y_array != NULL) {
440    String *pp = &(reg->y_array[reg->y_size - 1]);
441    const size_t tmplen = pp->size + plen;
442    char *tmp = xmalloc(tmplen + 1);
443    memcpy(tmp, pp->data, pp->size);
444    memcpy(tmp + pp->size, p, plen);
445    *(tmp + tmplen) = NUL;
446    xfree(p);
447    xfree(pp->data);
448    *pp = cbuf_as_string(tmp, tmplen);
449  } else {
450    free_register(reg);
451    reg->additional_data = NULL;
452    reg->y_array = xmalloc(sizeof(String));
453    reg->y_array[0] = cbuf_as_string(p, plen);
454    reg->y_size = 1;
455    reg->y_type = kMTCharWise;
456  }
457  reg->timestamp = (Timestamp)os_realtime();
458  return OK;
459}
460
461/// Start or stop recording into a yank register.
462///
463/// @return  FAIL for failure, OK otherwise.
464int do_record(int c)
465{
466  static int regname;
467  int retval;
468
469  if (reg_recording == 0) {
470    // start recording
471    // registers 0-9, a-z and " are allowed
472    if (c < 0 || (!ASCII_ISALNUM(c) && c != '"')) {
473      retval = FAIL;
474    } else {
475      reg_recording = c;
476      // TODO(bfredl): showmode based messaging is currently missing with cmdheight=0
477      showmode();
478      regname = c;
479      retval = OK;
480
481      apply_autocmds(EVENT_RECORDINGENTER, NULL, NULL, false, curbuf);
482    }
483  } else {  // stop recording
484    save_v_event_T save_v_event;
485    // Set the v:event dictionary with information about the recording.
486    dict_T *dict = get_v_event(&save_v_event);
487
488    // The recorded text contents.
489    char *p = get_recorded();
490    if (p != NULL) {
491      // Remove escaping for K_SPECIAL in multi-byte chars.
492      vim_unescape_ks(p);
493      tv_dict_add_str(dict, S_LEN("regcontents"), p);
494    }
495
496    // Name of requested register, or empty string for unnamed operation.
497    char buf[NUMBUFLEN + 2];
498    buf[0] = (char)regname;
499    buf[1] = NUL;
500    tv_dict_add_str(dict, S_LEN("regname"), buf);
501    tv_dict_set_keys_readonly(dict);
502
503    // Get the recorded key hits.  K_SPECIAL will be escaped, this
504    // needs to be removed again to put it in a register.  exec_reg then
505    // adds the escaping back later.
506    apply_autocmds(EVENT_RECORDINGLEAVE, NULL, NULL, false, curbuf);
507    restore_v_event(dict, &save_v_event);
508    reg_recorded = reg_recording;
509    reg_recording = 0;
510    if (p_ch == 0 || ui_has(kUIMessages)) {
511      showmode();
512    } else {
513      msg("", 0);
514    }
515    if (p == NULL) {
516      retval = FAIL;
517    } else {
518      // We don't want to change the default register here, so save and
519      // restore the current register name.
520      yankreg_T *old_y_previous = y_previous;
521
522      retval = stuff_yank(regname, p);
523
524      y_previous = old_y_previous;
525    }
526  }
527  return retval;
528}
529
530/// Insert register contents "s" into the typeahead buffer, so that it will be
531/// executed again.
532///
533/// @param esc    when true then it is to be taken literally: Escape K_SPECIAL
534///               characters and no remapping.
535/// @param colon  add ':' before the line
536static int put_in_typebuf(char *s, bool esc, bool colon, int silent)
537{
538  int retval = OK;
539
540  put_reedit_in_typebuf(silent);
541  if (colon) {
542    retval = ins_typebuf("\n", REMAP_NONE, 0, true, silent);
543  }
544  if (retval == OK) {
545    char *p;
546
547    if (esc) {
548      p = vim_strsave_escape_ks(s);
549    } else {
550      p = s;
551    }
552    if (p == NULL) {
553      retval = FAIL;
554    } else {
555      retval = ins_typebuf(p, esc ? REMAP_NONE : REMAP_YES, 0, true, silent);
556    }
557    if (esc) {
558      xfree(p);
559    }
560  }
561  if (colon && retval == OK) {
562    retval = ins_typebuf(":", REMAP_NONE, 0, true, silent);
563  }
564  return retval;
565}
566
567/// If "restart_edit" is not zero, put it in the typeahead buffer, so that it's
568/// used only after other typeahead has been processed.
569static void put_reedit_in_typebuf(int silent)
570{
571  if (restart_edit == NUL) {
572    return;
573  }
574
575  uint8_t buf[] = { K_SPECIAL, KS_EXTRA, KE_COMMAND,
576                    // :startinsert
577                    's', 't', 'a', 'r', 't', 'i', CAR, NUL };
578  if (restart_edit == 'R') {
579    buf[8] = 'r';  // :startreplace
580  } else if (restart_edit == 'V') {
581    buf[8] = 'g';  // :startgreplace
582  } else if (restart_edit == 'A') {
583    buf[8] = '!';  // :startinsert!
584  }
585  if (ins_typebuf((char *)buf, REMAP_NONE, 0, true, silent) == OK) {
586    restart_edit = NUL;
587  }
588}
589
590/// When executing a register as a series of ex-commands, if the
591/// line-continuation character is used for a line, then join it with one or
592/// more previous lines. Note that lines are processed backwards starting from
593/// the last line in the register.
594///
595/// @param lines list of lines in the register
596/// @param idx   index of the line starting with \ or "\. Join this line with all the immediate
597///              predecessor lines that start with a \ and the first line that doesn't start
598///              with a \. Lines that start with a comment "\ character are ignored.
599/// @returns the concatenated line. The index of the line that should be
600///          processed next is returned in idx.
601static char *execreg_line_continuation(String *lines, size_t *idx)
602{
603  size_t cmd_start = *idx;
604  assert(cmd_start > 0);
605  const size_t cmd_end = cmd_start;
606
607  garray_T ga;
608  ga_init(&ga, (int)sizeof(char), 400);
609
610  // search backwards to find the first line of this command.
611  // Any line not starting with \ or "\ is the start of the
612  // command.
613  while (--cmd_start > 0) {
614    char *p = skipwhite(lines[cmd_start].data);
615    if (*p != '\\' && (p[0] != '"' || p[1] != '\\' || p[2] != ' ')) {
616      break;
617    }
618  }
619
620  // join all the lines
621  String *tmp = &lines[cmd_start];
622  ga_concat_len(&ga, tmp->data, tmp->size);
623  for (size_t j = cmd_start + 1; j <= cmd_end; j++) {
624    tmp = &lines[j];
625    char *p = skipwhite(tmp->data);
626    if (*p == '\\') {
627      // Adjust the growsize to the current length to
628      // speed up concatenating many lines.
629      if (ga.ga_len > 400) {
630        ga_set_growsize(&ga, MIN(ga.ga_len, 8000));
631      }
632      p++;
633      ga_concat_len(&ga, p, (size_t)(tmp->data + tmp->size - p));
634    }
635  }
636  ga_append(&ga, NUL);
637  char *str = xmemdupz(ga.ga_data, (size_t)ga.ga_len);
638  ga_clear(&ga);
639
640  *idx = cmd_start;
641  return str;
642}
643
644/// Execute a yank register: copy it into the stuff buffer
645///
646/// @param colon   insert ':' before each line
647/// @param addcr   always add '\n' to end of line
648/// @param silent  set "silent" flag in typeahead buffer
649///
650/// @return FAIL for failure, OK otherwise
651int do_execreg(int regname, int colon, int addcr, int silent)
652{
653  int retval = OK;
654
655  if (regname == '@') {                 // repeat previous one
656    if (execreg_lastc == NUL) {
657      emsg(_("E748: No previously used register"));
658      return FAIL;
659    }
660    regname = execreg_lastc;
661  }
662  // check for valid regname
663  if (regname == '%' || regname == '#' || !valid_yank_reg(regname, false)) {
664    emsg_invreg(regname);
665    return FAIL;
666  }
667  execreg_lastc = regname;
668
669  if (regname == '_') {                 // black hole: don't stuff anything
670    return OK;
671  }
672
673  if (regname == ':') {                 // use last command line
674    if (last_cmdline == NULL) {
675      emsg(_(e_nolastcmd));
676      return FAIL;
677    }
678    // don't keep the cmdline containing @:
679    XFREE_CLEAR(new_last_cmdline);
680    // Escape all control characters with a CTRL-V
681    char *p = vim_strsave_escaped_ext(last_cmdline,
682                                      "\001\002\003\004\005\006\007"
683                                      "\010\011\012\013\014\015\016\017"
684                                      "\020\021\022\023\024\025\026\027"
685                                      "\030\031\032\033\034\035\036\037",
686                                      Ctrl_V, false);
687    // When in Visual mode "'<,'>" will be prepended to the command.
688    // Remove it when it's already there.
689    if (Visual.active && strncmp(p, "'<,'>", 5) == 0) {
690      retval = put_in_typebuf(p + 5, true, true, silent);
691    } else {
692      retval = put_in_typebuf(p, true, true, silent);
693    }
694    xfree(p);
695  } else if (regname == '=') {
696    char *p = get_expr_line();
697    if (p == NULL) {
698      return FAIL;
699    }
700    retval = put_in_typebuf(p, true, colon, silent);
701    xfree(p);
702  } else if (regname == '.') {        // use last inserted text
703    char *p = get_last_insert_save();
704    if (p == NULL) {
705      emsg(_(e_noinstext));
706      return FAIL;
707    }
708    retval = put_in_typebuf(p, false, colon, silent);
709    xfree(p);
710  } else {
711    yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
712    if (reg->y_array == NULL) {
713      return FAIL;
714    }
715
716    // Disallow remapping for ":@r".
717    int remap = colon ? REMAP_NONE : REMAP_YES;
718
719    // Insert lines into typeahead buffer, from last one to first one.
720    put_reedit_in_typebuf(silent);
721    for (size_t i = reg->y_size; i-- > 0;) {  // from y_size - 1 to 0 included
722      // insert NL between lines and after last line if type is kMTLineWise
723      if (reg->y_type == kMTLineWise || i < reg->y_size - 1 || addcr) {
724        if (ins_typebuf("\n", remap, 0, true, silent) == FAIL) {
725          return FAIL;
726        }
727      }
728
729      // Handle line-continuation for :@<register>
730      char *str = reg->y_array[i].data;
731      bool free_str = false;
732      if (colon && i > 0) {
733        char *p = skipwhite(str);
734        if (*p == '\\' || (p[0] == '"' && p[1] == '\\' && p[2] == ' ')) {
735          str = execreg_line_continuation(reg->y_array, &i);
736          free_str = true;
737        }
738      }
739      char *escaped = vim_strsave_escape_ks(str);
740      if (free_str) {
741        xfree(str);
742      }
743      retval = ins_typebuf(escaped, remap, 0, true, silent);
744      xfree(escaped);
745      if (retval == FAIL) {
746        return FAIL;
747      }
748      if (colon
749          && ins_typebuf(":", remap, 0, true, silent) == FAIL) {
750        return FAIL;
751      }
752    }
753    reg_executing = regname == 0 ? '"' : regname;  // disable the 'q' command
754    pending_end_reg_executing = false;
755  }
756  return retval;
757}
758
759/// Insert a yank register: copy it into the Read buffer.
760/// Used by CTRL-R command and middle mouse button in insert mode.
761///
762/// @param literally_arg  insert literally, not as if typed
763///
764/// @return FAIL for failure, OK otherwise
765int insert_reg(int regname, yankreg_T *reg, bool literally_arg)
766{
767  int retval = OK;
768  bool allocated;
769  const bool literally = literally_arg || is_literal_register(regname);
770
771  // It is possible to get into an endless loop by having CTRL-R a in
772  // register a and then, in insert mode, doing CTRL-R a.
773  // If you hit CTRL-C, the loop will be broken here.
774  os_breakcheck();
775  if (got_int) {
776    return FAIL;
777  }
778
779  // check for valid regname
780  if (regname != NUL && !valid_yank_reg(regname, false)) {
781    return FAIL;
782  }
783
784  char *arg;
785  if (regname == '.') {  // Insert last inserted text.
786    retval = stuff_inserted(NUL, 1, true);
787  } else if (get_spec_reg(regname, &arg, &allocated, true)) {
788    if (arg == NULL) {
789      return FAIL;
790    }
791    stuffescaped(arg, literally);
792    if (allocated) {
793      xfree(arg);
794    }
795  } else {  // Name or number register.
796    if (reg == NULL) {
797      reg = get_yank_register(regname, YREG_PASTE);
798    }
799    if (reg->y_array == NULL) {
800      retval = FAIL;
801    } else {
802      // Put (not stuff). Redo "<C-R>x" instead of the literal text.
803      const bool put = reg->y_type == kMTCharWise
804                       && (regname == '-'
805                           // Multicursor: per-cursor registers.
806                           || (mc_ins_cascading() && reg->y_size == 1
807                               && (ASCII_ISALNUM(regname) || regname == '"')));
808      for (size_t i = 0; i < reg->y_size; i++) {
809        if (put) {
810          Direction dir = BACKWARD;
811          if ((State & REPLACE_FLAG) != 0) {
812            pos_T curpos;
813            if (u_save_cursor() == FAIL) {
814              return FAIL;
815            }
816            del_chars(mb_charlen(reg->y_array[0].data), true);
817            curpos = curwin->w_cursor;
818            if (oneright() == FAIL) {
819              // hit end of line, need to put forward (after the current position)
820              dir = FORWARD;
821            }
822            curwin->w_cursor = curpos;
823          }
824
825          redo_append_char(Ctrl_R);
826          redo_append_char(regname);
827          do_put(regname, NULL, dir, 1, PUT_CURSEND);
828        } else {
829          stuffescaped(reg->y_array[i].data, literally);
830          // Insert a newline between lines and after last line if
831          // y_type is kMTLineWise.
832          if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
833            stuffcharReadbuff('\n');
834          }
835        }
836      }
837    }
838  }
839
840  return retval;
841}
842
843/// If "regname" is a special register, return true and store a pointer to its
844/// value in "argp".
845///
846/// @param allocated  return: true when value was allocated
847/// @param errmsg     give error message when failing
848///
849/// @return  true if "regname" is a special register,
850bool get_spec_reg(int regname, char **argp, bool *allocated, bool errmsg)
851{
852  *argp = NULL;
853  *allocated = false;
854  switch (regname) {
855  case '%':                     // file name
856    if (errmsg) {
857      check_fname();            // will give emsg if not set
858    }
859    *argp = curbuf->b_fname;
860    return true;
861
862  case '#':                       // alternate file name
863    *argp = getaltfname(errmsg);  // may give emsg if not set
864    return true;
865
866  case '=':                     // result of expression
867    *argp = get_expr_line();
868    *allocated = true;
869    return true;
870
871  case ':':                     // last command line
872    if (last_cmdline == NULL && errmsg) {
873      emsg(_(e_nolastcmd));
874    }
875    *argp = last_cmdline;
876    return true;
877
878  case '/':                     // last search-pattern
879    if (last_search_pat() == NULL && errmsg) {
880      emsg(_(e_noprevre));
881    }
882    *argp = last_search_pat();
883    return true;
884
885  case '.':                     // last inserted text
886    *argp = get_last_insert_save();
887    *allocated = true;
888    if (*argp == NULL && errmsg) {
889      emsg(_(e_noinstext));
890    }
891    return true;
892
893  case Ctrl_F:                  // Filename under cursor
894  case Ctrl_P:                  // Path under cursor, expand via "path"
895    if (!errmsg) {
896      return false;
897    }
898    *argp = file_name_at_cursor(FNAME_MESS | FNAME_HYP | (regname == Ctrl_P ? FNAME_EXP : 0),
899                                1, NULL);
900    *allocated = true;
901    return true;
902
903  case Ctrl_W:                  // word under cursor
904  case Ctrl_A:                  // WORD (mnemonic All) under cursor
905    if (!errmsg) {
906      return false;
907    }
908    size_t cnt = find_ident_under_cursor(argp, (regname == Ctrl_W
909                                                ? (FIND_IDENT|FIND_STRING)
910                                                : FIND_STRING), NULL);
911    *argp = cnt ? xmemdupz(*argp, cnt) : NULL;
912    *allocated = true;
913    return true;
914
915  case Ctrl_L:                  // Line under cursor
916    if (!errmsg) {
917      return false;
918    }
919
920    *argp = ml_get_buf(curwin->w_buffer, curwin->w_cursor.lnum);
921    return true;
922
923  case '_':                     // black hole: always empty
924    *argp = "";
925    return true;
926  }
927
928  return false;
929}
930
931/// Paste a yank register into the command line.
932/// Only for non-special registers.
933/// Used by CTRL-R in command-line mode.
934/// insert_reg() can't be used here, because special characters from the
935/// register contents will be interpreted as commands.
936///
937/// @param regname   Register name.
938/// @param literally_arg Insert text literally instead of "as typed".
939/// @param remcr     When true, don't add CR characters.
940///
941/// @returns FAIL for failure, OK otherwise
942bool cmdline_paste_reg(int regname, bool literally_arg, bool remcr)
943{
944  const bool literally = literally_arg || is_literal_register(regname);
945
946  yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
947  if (reg->y_array == NULL) {
948    return FAIL;
949  }
950
951  for (size_t i = 0; i < reg->y_size; i++) {
952    cmdline_paste_str(reg->y_array[i].data, literally);
953
954    // Insert ^M between lines, unless `remcr` is true.
955    if (i < reg->y_size - 1 && !remcr) {
956      cmdline_paste_str("\r", literally);
957    }
958
959    // Check for CTRL-C, in case someone tries to paste a few thousand
960    // lines and gets bored.
961    os_breakcheck();
962    if (got_int) {
963      return FAIL;
964    }
965  }
966  return OK;
967}
968
969/// Shift the delete registers: "9 is cleared, "8 becomes "9, etc.
970void shift_delete_registers(bool y_append)
971{
972  free_register(&y_regs[9]);  // free register "9
973  for (int n = 9; n > 1; n--) {
974    y_regs[n] = y_regs[n - 1];
975  }
976  if (!y_append) {
977    y_previous = &y_regs[1];
978  }
979  y_regs[1].y_array = NULL;  // set register "1 to empty
980}
981
982#ifdef EXITFREE
983void clear_registers(void)
984{
985  for (int i = 0; i < NUM_REGISTERS; i++) {
986    free_register(&y_regs[i]);
987  }
988}
989#endif
990
991/// Free contents of yankreg `reg`.
992/// Called for normal freeing and in case of error.
993///
994/// @param reg  must not be NULL (but `reg->y_array` might be)
995void free_register(yankreg_T *reg)
996  FUNC_ATTR_NONNULL_ALL
997{
998  XFREE_CLEAR(reg->additional_data);
999  if (reg->y_array != NULL) {
1000    for (size_t i = reg->y_size; i-- > 0;) {  // from y_size - 1 to 0 included
1001      API_CLEAR_STRING(reg->y_array[i]);
1002    }
1003    XFREE_CLEAR(reg->y_array);
1004  }
1005  *reg = (yankreg_T){ 0 };
1006}
1007
1008/// Copy a block range into a register.
1009///
1010/// @param exclude_trailing_space  if true, do not copy trailing whitespaces.
1011static void yank_copy_line(yankreg_T *reg, struct block_def *bd, size_t y_idx,
1012                           bool exclude_trailing_space)
1013  FUNC_ATTR_NONNULL_ALL
1014{
1015  if (exclude_trailing_space) {
1016    bd->endspaces = 0;
1017  }
1018  int size = bd->startspaces + bd->endspaces + bd->textlen;
1019  assert(size >= 0);
1020  char *pnew = xmallocz((size_t)size);
1021  reg->y_array[y_idx].data = pnew;
1022  memset(pnew, ' ', (size_t)bd->startspaces);
1023  pnew += bd->startspaces;
1024  memmove(pnew, bd->textstart, (size_t)bd->textlen);
1025  pnew += bd->textlen;
1026  memset(pnew, ' ', (size_t)bd->endspaces);
1027  pnew += bd->endspaces;
1028  if (exclude_trailing_space) {
1029    int s = bd->textlen + bd->endspaces;
1030
1031    while (s > 0 && ascii_iswhite(*(bd->textstart + s - 1))) {
1032      s = s - utf_head_off(bd->textstart, bd->textstart + s - 1) - 1;
1033      pnew--;
1034    }
1035  }
1036  *pnew = NUL;
1037  reg->y_array[y_idx].size = (size_t)(pnew - reg->y_array[y_idx].data);
1038}
1039
1040void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append)
1041{
1042  yankreg_T newreg;  // new yank register when appending
1043  MotionType yank_type = oap->motion_type;
1044  size_t yanklines = (size_t)oap->line_count;
1045  linenr_T yankendlnum = oap->end.lnum;
1046  struct block_def bd;
1047
1048  yankreg_T *curr = reg;  // copy of current register
1049  // append to existing contents
1050  if (append && reg->y_array != NULL) {
1051    reg = &newreg;
1052  } else {
1053    free_register(reg);  // free previously yanked lines
1054  }
1055
1056  // If the cursor was in column 1 before and after the movement, and the
1057  // operator is not inclusive, the yank is always linewise.
1058  if (oap->motion_type == kMTCharWise
1059      && oap->start.col == 0
1060      && !oap->inclusive
1061      && (!oap->is_VIsual || *p_sel == 'o')
1062      && oap->end.col == 0
1063      && yanklines > 1) {
1064    yank_type = kMTLineWise;
1065    yankendlnum--;
1066    yanklines--;
1067  }
1068
1069  reg->y_size = yanklines;
1070  reg->y_type = yank_type;  // set the yank register type
1071  reg->y_width = 0;
1072  reg->y_array = xcalloc(yanklines, sizeof(String));
1073  reg->additional_data = NULL;
1074  reg->timestamp = (Timestamp)os_realtime();
1075
1076  size_t y_idx = 0;  // index in y_array[]
1077  linenr_T lnum = oap->start.lnum;  // current line number
1078
1079  if (yank_type == kMTBlockWise) {
1080    // Visual block mode
1081    reg->y_width = oap->end_vcol - oap->start_vcol;
1082
1083    if (curwin->w_curswant == MAXCOL && reg->y_width > 0) {
1084      reg->y_width--;
1085    }
1086  }
1087
1088  for (; lnum <= yankendlnum; lnum++, y_idx++) {
1089    switch (reg->y_type) {
1090    case kMTBlockWise:
1091      block_prep(oap, &bd, lnum, false);
1092      yank_copy_line(reg, &bd, y_idx, oap->excl_tr_ws);
1093      break;
1094
1095    case kMTLineWise:
1096      reg->y_array[y_idx] = cbuf_to_string(ml_get(lnum), (size_t)ml_get_len(lnum));
1097      break;
1098
1099    case kMTCharWise:
1100      charwise_block_prep(oap->start, oap->end, &bd, lnum, oap->inclusive);
1101      // make sure bd.textlen is not longer than the text
1102      int tmp = (int)strlen(bd.textstart);
1103      if (tmp < bd.textlen) {
1104        bd.textlen = tmp;
1105      }
1106      yank_copy_line(reg, &bd, y_idx, false);
1107      break;
1108
1109    // NOTREACHED
1110    case kMTUnknown:
1111      abort();
1112    }
1113  }
1114
1115  if (curr != reg) {      // append the new block to the old block
1116    size_t j;
1117    String *new_ptr = xmalloc(sizeof(String) * (curr->y_size + reg->y_size));
1118    for (j = 0; j < curr->y_size; j++) {
1119      new_ptr[j] = curr->y_array[j];
1120    }
1121    xfree(curr->y_array);
1122    curr->y_array = new_ptr;
1123
1124    if (yank_type == kMTLineWise) {
1125      // kMTLineWise overrides kMTCharWise and kMTBlockWise
1126      curr->y_type = kMTLineWise;
1127    }
1128
1129    // Concatenate the last line of the old block with the first line of
1130    // the new block, unless being Vi compatible.
1131    if (curr->y_type == kMTCharWise
1132        && vim_strchr(p_cpo, kCpoRegappend) == NULL) {
1133      char *pnew = xmalloc(curr->y_array[curr->y_size - 1].size
1134                           + reg->y_array[0].size + 1);
1135      j--;
1136      STRCPY(pnew, curr->y_array[j].data);
1137      STRCPY(pnew + curr->y_array[j].size, reg->y_array[0].data);
1138      xfree(curr->y_array[j].data);
1139      curr->y_array[j] = cbuf_as_string(pnew,
1140                                        curr->y_array[j].size + reg->y_array[0].size);
1141      j++;
1142      API_CLEAR_STRING(reg->y_array[0]);
1143      y_idx = 1;
1144    } else {
1145      y_idx = 0;
1146    }
1147    while (y_idx < reg->y_size) {
1148      curr->y_array[j++] = reg->y_array[y_idx++];
1149    }
1150    curr->y_size = j;
1151    xfree(reg->y_array);
1152  }
1153
1154  if (message) {  // Display message about yank?
1155    if (yank_type == kMTCharWise && yanklines == 1) {
1156      yanklines = 0;
1157    }
1158    // Some versions of Vi use ">=" here, some don't...
1159    if (yanklines > (size_t)p_report) {
1160      char namebuf[100];
1161
1162      if (oap->regname == NUL) {
1163        *namebuf = NUL;
1164      } else {
1165        vim_snprintf(namebuf, sizeof(namebuf), _(" into \"%c"), oap->regname);
1166      }
1167
1168      // redisplay now, so message is not deleted
1169      update_topline(curwin);
1170      if (must_redraw) {
1171        update_screen();
1172      }
1173      if (yank_type == kMTBlockWise) {
1174        smsg(0, NGETTEXT("block of %" PRId64 " line yanked%s",
1175                         "block of %" PRId64 " lines yanked%s", yanklines),
1176             (int64_t)yanklines, namebuf);
1177      } else {
1178        smsg(0, NGETTEXT("%" PRId64 " line yanked%s",
1179                         "%" PRId64 " lines yanked%s", yanklines),
1180             (int64_t)yanklines, namebuf);
1181      }
1182    }
1183  }
1184
1185  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
1186    // Set "'[" and "']" marks.
1187    curbuf->b_op_start = oap->start;
1188    curbuf->b_op_end = oap->end;
1189    if (yank_type == kMTLineWise) {
1190      curbuf->b_op_start.col = 0;
1191      curbuf->b_op_end.col = MAXCOL;
1192    }
1193    if (yank_type != kMTLineWise && !oap->inclusive) {
1194      // Exclude the end position.
1195      decl(&curbuf->b_op_end);
1196    }
1197  }
1198}
1199
1200/// Format the register type as a string.
1201///
1202/// @param reg_type The register type.
1203/// @param reg_width The width, only used if "reg_type" is kMTBlockWise.
1204/// @param[out] buf Buffer to store formatted string. The allocated size should
1205///                 be at least NUMBUFLEN+2 to always fit the value.
1206/// @param bufsize The allocated size of the buffer.
1207///
1208/// @return The length of the register type string.
1209size_t format_reg_type(MotionType reg_type, colnr_T reg_width, char *buf, size_t bufsize)
1210  FUNC_ATTR_NONNULL_ALL
1211{
1212  assert(bufsize > 1);
1213  switch (reg_type) {
1214  case kMTLineWise:
1215    buf[0] = 'V';
1216    buf[1] = NUL;
1217    return 1;
1218  case kMTCharWise:
1219    buf[0] = 'v';
1220    buf[1] = NUL;
1221    return 1;
1222  case kMTBlockWise:
1223    return vim_snprintf_safelen(buf, bufsize, CTRL_V_STR "%" PRIdCOLNR, reg_width + 1);
1224  case kMTUnknown:
1225    buf[0] = NUL;
1226    return 0;
1227  }
1228  abort();
1229}
1230
1231static void add_regtype_to_dict(yankreg_T *reg, dict_T *dict, char *buf, size_t bufsize)
1232{
1233  // "reg" is NULL when pasting a special register, which is charwise.
1234  size_t len = format_reg_type(reg != NULL ? reg->y_type : kMTCharWise,
1235                               reg != NULL ? reg->y_width : 0, buf, bufsize);
1236  tv_dict_add_str_len(dict, S_LEN("regtype"), buf, (int)len);
1237}
1238
1239/// Execute autocommands for TextYankPost.
1240///
1241/// @param oap Operator arguments.
1242/// @param reg The yank register used.
1243void do_autocmd_textyankpost(oparg_T *oap, yankreg_T *reg)
1244  FUNC_ATTR_NONNULL_ALL
1245{
1246  static bool recursive = false;
1247
1248  if (recursive || !has_event(EVENT_TEXTYANKPOST)) {
1249    // No autocommand was defined, or we yanked from this autocommand.
1250    return;
1251  }
1252
1253  recursive = true;
1254
1255  save_v_event_T save_v_event;
1256  // Set the v:event dictionary with information about the yank.
1257  dict_T *dict = get_v_event(&save_v_event);
1258
1259  // The yanked text contents.
1260  list_T *const list = tv_list_alloc((ptrdiff_t)reg->y_size);
1261  for (size_t i = 0; i < reg->y_size; i++) {
1262    tv_list_append_string(list, reg->y_array[i].data, (int)reg->y_array[i].size);
1263  }
1264  tv_list_set_lock(list, VAR_FIXED);
1265  tv_dict_add_list(dict, S_LEN("regcontents"), list);
1266
1267  // Register type.
1268  char buf[NUMBUFLEN + 2];
1269  add_regtype_to_dict(reg, dict, buf, ARRAY_SIZE(buf));
1270
1271  // Name of requested register, or empty string for unnamed operation.
1272  buf[0] = (char)oap->regname;
1273  buf[1] = NUL;
1274  tv_dict_add_str(dict, S_LEN("regname"), buf);
1275
1276  // Motion type: inclusive or exclusive.
1277  tv_dict_add_bool(dict, S_LEN("inclusive"),
1278                   oap->inclusive ? kBoolVarTrue : kBoolVarFalse);
1279
1280  // Kind of operation: yank, delete, change).
1281  buf[0] = (char)get_op_char(oap->op_type);
1282  buf[1] = NUL;
1283  tv_dict_add_str(dict, S_LEN("operator"), buf);
1284
1285  // Selection type: visual or not.
1286  tv_dict_add_bool(dict, S_LEN("visual"),
1287                   oap->is_VIsual ? kBoolVarTrue : kBoolVarFalse);
1288
1289  tv_dict_set_keys_readonly(dict);
1290  textlock++;
1291  apply_autocmds(EVENT_TEXTYANKPOST, NULL, NULL, false, curbuf);
1292  textlock--;
1293  restore_v_event(dict, &save_v_event);
1294
1295  recursive = false;
1296}
1297
1298/// Trigger TextPutPre or TextPutPost autocommand.
1299///
1300/// @param reg     May be NULL, if special register
1301/// @param insert  Not NULL if special register, except '.'
1302/// @param post    If Post or Pre
1303/// @param dir     BACKWARD for 'P', FORWARD for 'p'
1304static void put_do_autocmd(int regname, yankreg_T *reg, const String *insert, bool post,
1305                           Direction dir)
1306{
1307  static bool recursive = false;
1308
1309  if (recursive || (regname == '_' && reg == NULL)) {
1310    return;
1311  }
1312
1313  if (regname != '.' && insert == NULL && reg == NULL) {
1314    // Can happen when pasting text in normal mode in a terminal buffer
1315    return;
1316  }
1317
1318  save_v_event_T save_v_event;
1319  dict_T *v_event = get_v_event(&save_v_event);
1320
1321  list_T *list = tv_list_alloc(reg != NULL ? (ptrdiff_t)reg->y_size : 1);
1322
1323  if (regname == '.') {
1324    if (last_insert_ga.ga_data != NULL) {
1325      // Get the last inserted text to place in "regcontents"
1326      tv_list_append_string(list, last_insert_ga.ga_data, last_insert_ga.ga_len);
1327    }
1328  } else if (insert != NULL) {
1329    tv_list_append_string(list, insert->data, (ssize_t)insert->size);
1330  } else {
1331    for (size_t n = 0; n < reg->y_size; n++) {
1332      tv_list_append_string(list, reg->y_array[n].data, (ssize_t)reg->y_array[n].size);
1333    }
1334  }
1335
1336  tv_list_set_lock(list, VAR_FIXED);
1337  tv_dict_add_list(v_event, S_LEN("regcontents"), list);
1338
1339  char buf[NUMBUFLEN + 2];
1340
1341  // register name or empty string for unnamed operation
1342  buf[0] = (char)regname;
1343  buf[1] = NUL;
1344  size_t buflen = (buf[0] == NUL) ? 0 : 1;
1345  tv_dict_add_str_len(v_event, S_LEN("regname"), buf, (int)buflen);
1346
1347  // kind of operation (P, p)
1348  buf[0] = dir == BACKWARD ? 'P' : 'p';
1349  buf[1] = NUL;
1350  buflen = 1;
1351  tv_dict_add_str_len(v_event, S_LEN("operator"), buf, (int)buflen);
1352
1353  add_regtype_to_dict(reg, v_event, buf, sizeof(buf));
1354
1355  tv_dict_add_bool(v_event, S_LEN("visual"), Visual.active);
1356
1357  // Lock the dictionary and its keys
1358  tv_dict_set_keys_readonly(v_event);
1359
1360  recursive = true;
1361  textlock++;
1362  if (post) {
1363    apply_autocmds(EVENT_TEXTPUTPOST, NULL, NULL, false, curbuf);
1364  } else {
1365    apply_autocmds(EVENT_TEXTPUTPRE, NULL, NULL, false, curbuf);
1366  }
1367  textlock--;
1368  recursive = false;
1369
1370  // Empty the dictionary, v:event is still valid
1371  restore_v_event(v_event, &save_v_event);
1372}
1373
1374/// Yanks the text between "oap->start" and "oap->end" into a yank register.
1375/// If we are to append (uppercase register), we first yank into a new yank
1376/// register and then concatenate the old and the new one.
1377/// Do not call this from a delete operation. Use op_yank_reg() instead.
1378///
1379/// @param oap operator arguments
1380/// @param message show message when more than `&report` lines are yanked.
1381/// @returns whether the operation register was writable.
1382bool op_yank(oparg_T *oap, bool message)
1383  FUNC_ATTR_NONNULL_ALL
1384{
1385  // check for read-only register
1386  if (oap->regname != 0 && !valid_yank_reg(oap->regname, true)) {
1387    beep_flush();
1388    return false;
1389  }
1390  if (oap->regname == '_') {
1391    return true;  // black hole: nothing to do
1392  }
1393
1394  yankreg_T *reg = get_yank_register(oap->regname, YREG_YANK);
1395  op_yank_reg(oap, message, reg, is_append_register(oap->regname));
1396  set_clipboard(oap->regname, reg);
1397  do_autocmd_textyankpost(oap, reg);
1398  return true;
1399}
1400
1401/// Put contents of register "regname" into the text.
1402/// Caller must check "regname" to be valid!
1403///
1404/// @param flags  PUT_FIXINDENT     make indent look nice
1405///               PUT_CURSEND       leave cursor after end of new text
1406///               PUT_LINE          force linewise put (":put")
1407///               PUT_BLOCK_INNER   in block mode, do not add trailing spaces
1408/// @param dir    BACKWARD for 'P', FORWARD for 'p'
1409void do_put(int regname, yankreg_T *reg, int dir, int count, int flags)
1410{
1411  size_t totlen = 0;  // init for gcc
1412  linenr_T lnum = 0;
1413  MotionType y_type;
1414  size_t y_size;
1415  int y_width = 0;
1416  colnr_T vcol = 0;
1417  String *y_array = NULL;
1418  linenr_T nr_lines = 0;
1419  bool allocated = false;
1420  const pos_T orig_start = curbuf->b_op_start;
1421  const pos_T orig_end = curbuf->b_op_end;
1422  unsigned cur_ve_flags = get_ve_flags(curwin);
1423
1424  // Remove any preinserted text (issue vim/vim#19329)
1425  if (ins_compl_preinsert_effect()) {
1426    ins_compl_delete(false);
1427  }
1428
1429  curbuf->b_op_start = curwin->w_cursor;        // default for '[ mark
1430  curbuf->b_op_end = curwin->w_cursor;          // default for '] mark
1431
1432  // Using inserted text works differently, because the register includes
1433  // special characters (newlines, etc.).
1434  if (regname == '.' && !reg) {
1435    bool non_linewise_vis = (Visual.active && Visual.mode != 'V');
1436
1437    // PUT_LINE has special handling below which means we use 'i' to start.
1438    char command_start_char = non_linewise_vis
1439                              ? 'c'
1440                              : (flags & PUT_LINE ? 'i' : (dir == FORWARD ? 'a' : 'i'));
1441
1442    bool has_textput_events = has_event(EVENT_TEXTPUTPRE) || has_event(EVENT_TEXTPUTPOST);
1443    if (has_textput_events) {
1444      add_last_insert++;
1445    }
1446
1447    // To avoid 'autoindent' on linewise puts, create a new line with `:put _`.
1448    if (flags & PUT_LINE) {
1449      const int save_add_last_insert = add_last_insert;
1450      add_last_insert = 0;
1451      stuffcharReadbuff(K_COMMAND);
1452      if (dir == FORWARD) {
1453        stuffReadbuffLen(S_LEN("put _"));
1454      } else {
1455        stuffReadbuffLen(S_LEN("put! _"));
1456      }
1457      stuffcharReadbuff(CAR);
1458      add_last_insert = save_add_last_insert;
1459    }
1460
1461    // If given a count when putting linewise, we stuff the readbuf with the
1462    // dot register 'count' times split by newlines.
1463    if (flags & PUT_LINE) {
1464      stuffcharReadbuff(command_start_char);
1465      for (; count > 0; count--) {
1466        stuff_inserted(NUL, 1, count != 1);
1467        if (count != 1) {
1468          // To avoid 'autoindent' affecting the text, use Ctrl_U to remove any
1469          // whitespace. Can't just insert Ctrl_U into readbuf1, this would go
1470          // back to the previous line in the case of 'noautoindent' and
1471          // 'backspace' includes "eol". So we insert a dummy space for Ctrl_U
1472          // to consume.
1473          static const char s[] = { '\n', ' ', Ctrl_U, NUL };
1474          stuffReadbuffLen(S_LEN(s));
1475        }
1476      }
1477    } else {
1478      stuff_inserted(command_start_char, count, false);
1479    }
1480
1481    // Since the text is not inserted into the buffer immediately, just call
1482    // TextPutPost after TextPutPre.
1483    if (has_event(EVENT_TEXTPUTPRE)) {
1484      put_do_autocmd('.', NULL, NULL, false, dir);
1485    }
1486    if (has_event(EVENT_TEXTPUTPOST)) {
1487      put_do_autocmd('.', NULL, NULL, true, dir);
1488    }
1489
1490    if (has_textput_events && --add_last_insert == 0) {
1491      ga_clear(&last_insert_ga);
1492    }
1493
1494    // Putting the text is done later, so can't move the cursor to the next
1495    // character.  Simulate it with motion commands after the insert.
1496    if (flags & PUT_CURSEND) {
1497      if (flags & PUT_LINE) {
1498        stuffReadbuff("j0");
1499      } else {
1500        // Avoid ringing the bell from attempting to move into the space after
1501        // the current line. We can stuff the readbuffer with "l" if:
1502        // 1) 'virtualedit' is "all" or "onemore"
1503        // 2) We are not at the end of the line
1504        // 3) We are not  (one past the end of the line && on the last line)
1505        //    This allows a visual put over a selection one past the end of the
1506        //    line joining the current line with the one below.
1507
1508        // curwin->w_cursor.col marks the byte position of the cursor in the
1509        // currunt line. It increases up to a max of
1510        // strlen(ml_get(curwin->w_cursor.lnum)). With 'virtualedit' and the
1511        // cursor past the end of the line, curwin->w_cursor.coladd is
1512        // incremented instead of curwin->w_cursor.col.
1513        char *cursor_pos = get_cursor_pos_ptr();
1514        bool one_past_line = (*cursor_pos == NUL);
1515        bool eol = false;
1516        if (!one_past_line) {
1517          eol = (*(cursor_pos + utfc_ptr2len(cursor_pos)) == NUL);
1518        }
1519
1520        bool ve_allows = (cur_ve_flags == kOptVeFlagAll || cur_ve_flags == kOptVeFlagOnemore);
1521        bool eof = curbuf->b_ml.ml_line_count == curwin->w_cursor.lnum
1522                   && one_past_line;
1523        if (ve_allows || !(eol || eof)) {
1524          stuffcharReadbuff('l');
1525        }
1526      }
1527    } else if (flags & PUT_LINE) {
1528      stuffReadbuff("g'[");
1529    }
1530
1531    // So the 'u' command restores cursor position after ".p, save the cursor
1532    // position now (though not saving any text).
1533    if (command_start_char == 'a') {
1534      if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL) {
1535        return;
1536      }
1537    }
1538
1539    // Execute the stuffed keys here: the put resolves within the current command.
1540    exec_stuffed(NULL);
1541    return;
1542  }
1543
1544  // For special registers '%' (file name), '#' (alternate file name) and
1545  // ':' (last command line), etc. we have to create a fake yank register.
1546  String insert_string = STRING_INIT;
1547  if (!reg && get_spec_reg(regname, &insert_string.data, &allocated, true)) {
1548    if (insert_string.data == NULL) {
1549      return;
1550    }
1551  }
1552
1553  if (!curbuf->terminal) {
1554    // Autocommands may be executed when saving lines for undo.  This might
1555    // make y_array invalid, so we start undo now to avoid that.
1556    if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL) {
1557      return;
1558    }
1559  }
1560
1561  if (insert_string.data != NULL) {
1562    insert_string.size = strlen(insert_string.data);
1563    y_type = kMTCharWise;
1564    if (regname == '=') {
1565      // For the = register we need to split the string at NL
1566      // characters.
1567      // Loop twice: count the number of lines and save them.
1568      while (true) {
1569        y_size = 0;
1570        char *ptr = insert_string.data;
1571        size_t ptrlen = insert_string.size;
1572        while (ptr != NULL) {
1573          if (y_array != NULL) {
1574            y_array[y_size].data = ptr;
1575          }
1576          y_size++;
1577          char *tmp = vim_strchr(ptr, '\n');
1578          if (tmp == NULL) {
1579            if (y_array != NULL) {
1580              y_array[y_size - 1].size = ptrlen;
1581            }
1582          } else {
1583            if (y_array != NULL) {
1584              *tmp = NUL;
1585              y_array[y_size - 1].size = (size_t)(tmp - ptr);
1586              ptrlen -= y_array[y_size - 1].size + 1;
1587            }
1588            tmp++;
1589            // A trailing '\n' makes the register linewise.
1590            if (*tmp == NUL) {
1591              y_type = kMTLineWise;
1592              break;
1593            }
1594          }
1595          ptr = tmp;
1596        }
1597        if (y_array != NULL) {
1598          break;
1599        }
1600        y_array = xmalloc(y_size * sizeof(String));
1601      }
1602    } else {
1603      y_size = 1;               // use fake one-line yank register
1604      y_array = &insert_string;
1605    }
1606    if (has_event(EVENT_TEXTPUTPRE)) {
1607      put_do_autocmd(regname, NULL, &insert_string, false, dir);
1608    }
1609  } else {
1610    if (has_event(EVENT_TEXTPUTPRE)) {
1611      yankreg_T *const save_reg = reg;
1612      if (reg == NULL) {
1613        // Make sure to call this before we set the variables, as setreg()
1614        // may be called and invalidate them.
1615        reg = get_yank_register(regname, YREG_PASTE);
1616      }
1617      put_do_autocmd(regname, reg, NULL, false, dir);
1618      reg = save_reg;
1619    }
1620    // in case of replacing visually selected text
1621    // the yankreg might already have been saved to avoid
1622    // just restoring the deleted text.
1623    if (reg == NULL) {
1624      reg = get_yank_register(regname, YREG_PASTE);
1625    }
1626
1627    y_type = reg->y_type;
1628    y_width = reg->y_width;
1629    y_size = reg->y_size;
1630    y_array = reg->y_array;
1631  }
1632
1633  if (curbuf->terminal) {
1634    terminal_paste(count, y_array, y_size);
1635    goto end;
1636  }
1637
1638  colnr_T split_pos = 0;
1639  if (y_type == kMTLineWise) {
1640    if (flags & PUT_LINE_SPLIT) {
1641      // "p" or "P" in Visual mode: split the lines to put the text in
1642      // between.
1643      if (u_save_cursor() == FAIL) {
1644        goto end;
1645      }
1646      char *curline = get_cursor_line_ptr();
1647      char *p = get_cursor_pos_ptr();
1648      char *const p_orig = p;
1649      const size_t plen = (size_t)get_cursor_pos_len();
1650      if (dir == FORWARD && *p != NUL) {
1651        MB_PTR_ADV(p);
1652      }
1653      // we need this later for the correct extmark_splice() event
1654      split_pos = (colnr_T)(p - curline);
1655
1656      char *ptr = xmemdupz(p, plen - (size_t)(p - p_orig));
1657      ml_append(curwin->w_cursor.lnum, ptr, 0, false);
1658      xfree(ptr);
1659
1660      ptr = xmemdupz(get_cursor_line_ptr(), (size_t)split_pos);
1661      ml_replace(curwin->w_cursor.lnum, ptr, false);
1662      nr_lines++;
1663      dir = FORWARD;
1664
1665      buf_updates_send_changes(curbuf, curwin->w_cursor.lnum, 1, 1);
1666    }
1667    if (flags & PUT_LINE_FORWARD) {
1668      // Must be "p" for a Visual block, put lines below the block.
1669      curwin->w_cursor = curbuf->b_visual.vi_end;
1670      dir = FORWARD;
1671    }
1672    curbuf->b_op_start = curwin->w_cursor;      // default for '[ mark
1673    curbuf->b_op_end = curwin->w_cursor;        // default for '] mark
1674  }
1675
1676  if (flags & PUT_LINE) {  // :put command or "p" in Visual line mode.
1677    y_type = kMTLineWise;
1678  }
1679
1680  if (y_size == 0 || y_array == NULL) {
1681    semsg(_("E353: Nothing in register %s"),
1682          regname == 0 ? "\"" : transchar(regname));
1683    goto end;
1684  }
1685
1686  if (y_type == kMTBlockWise) {
1687    lnum = curwin->w_cursor.lnum + (linenr_T)y_size + 1;
1688    lnum = MIN(lnum, curbuf->b_ml.ml_line_count + 1);
1689    if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL) {
1690      goto end;
1691    }
1692  } else if (y_type == kMTLineWise) {
1693    lnum = curwin->w_cursor.lnum;
1694    // Correct line number for closed fold.  Don't move the cursor yet,
1695    // u_save() uses it.
1696    if (dir == BACKWARD) {
1697      hasFolding(curwin, lnum, &lnum, NULL);
1698    } else {
1699      hasFolding(curwin, lnum, NULL, &lnum);
1700    }
1701    if (dir == FORWARD) {
1702      lnum++;
1703    }
1704    // In an empty buffer the empty line is going to be replaced, include
1705    // it in the saved lines.
1706    if ((buf_is_empty(curbuf)
1707         ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL) {
1708      goto end;
1709    }
1710    if (dir == FORWARD) {
1711      curwin->w_cursor.lnum = lnum - 1;
1712    } else {
1713      curwin->w_cursor.lnum = lnum;
1714    }
1715    curbuf->b_op_start = curwin->w_cursor;      // for mark_adjust()
1716  } else if (u_save_cursor() == FAIL) {
1717    goto end;
1718  }
1719
1720  if (cur_ve_flags == kOptVeFlagAll && y_type == kMTCharWise) {
1721    if (gchar_cursor() == TAB) {
1722      int viscol = getviscol();
1723      OptInt ts = curbuf->b_p_ts;
1724      // Don't need to insert spaces when "p" on the last position of a
1725      // tab or "P" on the first position.
1726      if (dir == FORWARD
1727          ? tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1
1728          : curwin->w_cursor.coladd > 0) {
1729        coladvance_force(viscol);
1730      } else {
1731        curwin->w_cursor.coladd = 0;
1732      }
1733    } else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL) {
1734      coladvance_force(getviscol() + (dir == FORWARD));
1735    }
1736  }
1737
1738  lnum = curwin->w_cursor.lnum;
1739  colnr_T col = curwin->w_cursor.col;
1740
1741  // Block mode
1742  if (y_type == kMTBlockWise) {
1743    int incr = 0;
1744    struct block_def bd;
1745    int c = gchar_cursor();
1746    colnr_T endcol2 = 0;
1747
1748    if (dir == FORWARD && c != NUL) {
1749      if (cur_ve_flags == kOptVeFlagAll) {
1750        getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2, 0);
1751      } else {
1752        getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col, 0);
1753      }
1754
1755      // move to start of next multi-byte character
1756      curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr());
1757      col++;
1758    } else {
1759      getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2, 0);
1760    }
1761
1762    col += curwin->w_cursor.coladd;
1763    if (cur_ve_flags == kOptVeFlagAll
1764        && (curwin->w_cursor.coladd > 0 || endcol2 == curwin->w_cursor.col)) {
1765      if (dir == FORWARD && c == NUL) {
1766        col++;
1767      }
1768      if (dir != FORWARD && c != NUL && curwin->w_cursor.coladd > 0) {
1769        curwin->w_cursor.col++;
1770      }
1771      if (c == TAB) {
1772        if (dir == BACKWARD && curwin->w_cursor.col) {
1773          curwin->w_cursor.col--;
1774        }
1775        if (dir == FORWARD && col - 1 == endcol2) {
1776          curwin->w_cursor.col++;
1777        }
1778      }
1779    }
1780    curwin->w_cursor.coladd = 0;
1781    bd.textcol = 0;
1782    for (size_t i = 0; i < y_size; i++) {
1783      int spaces = 0;
1784      char shortline;
1785      // can just be 0 or 1, needed for blockwise paste beyond the current
1786      // buffer end
1787      int lines_appended = 0;
1788
1789      bd.startspaces = 0;
1790      bd.endspaces = 0;
1791      vcol = 0;
1792      int delcount = 0;
1793
1794      // add a new line
1795      if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) {
1796        if (ml_append(curbuf->b_ml.ml_line_count, "", 1, false) == FAIL) {
1797          break;
1798        }
1799        nr_lines++;
1800        lines_appended = 1;
1801      }
1802      // get the old line and advance to the position to insert at
1803      char *oldp = get_cursor_line_ptr();
1804      colnr_T oldlen = get_cursor_line_len();
1805
1806      CharsizeArg csarg;
1807      CSType cstype = init_charsize_arg(&csarg, curwin, curwin->w_cursor.lnum, oldp);
1808      StrCharInfo ci = utf_ptr2StrCharInfo(oldp);
1809      vcol = 0;
1810      while (vcol < col && *ci.ptr != NUL) {
1811        ClusterInfo cli = utf_ClusterInfo(ci);
1812        incr = win_charsize(cstype, vcol, ci.ptr, ci.chr.value, &csarg, cli.cells).width;
1813        vcol += incr;
1814        ci = cli.next;
1815      }
1816      char *ptr = ci.ptr;
1817      bd.textcol = (colnr_T)(ptr - oldp);
1818
1819      shortline = (vcol < col) || (vcol == col && !*ptr);
1820
1821      if (vcol < col) {     // line too short, pad with spaces
1822        bd.startspaces = col - vcol;
1823      } else if (vcol > col) {
1824        bd.endspaces = vcol - col;
1825        bd.startspaces = incr - bd.endspaces;
1826        bd.textcol--;
1827        delcount = 1;
1828        bd.textcol -= utf_head_off(oldp, oldp + bd.textcol);
1829        if (oldp[bd.textcol] != TAB) {
1830          // Only a Tab can be split into spaces.  Other
1831          // characters will have to be moved to after the
1832          // block, causing misalignment.
1833          delcount = 0;
1834          bd.endspaces = 0;
1835        }
1836      }
1837
1838      const int yanklen = (int)y_array[i].size;
1839
1840      if ((flags & PUT_BLOCK_INNER) == 0) {
1841        // calculate number of spaces required to fill right side of block
1842        spaces = y_width + 1;
1843
1844        cstype = init_charsize_arg(&csarg, curwin, 0, y_array[i].data);
1845        ci = utf_ptr2StrCharInfo(y_array[i].data);
1846        while (*ci.ptr != NUL) {
1847          ClusterInfo cli = utf_ClusterInfo(ci);
1848          spaces -= win_charsize(cstype, 0, ci.ptr, ci.chr.value, &csarg, cli.cells).width;
1849          ci = cli.next;
1850        }
1851        spaces = MAX(spaces, 0);
1852      }
1853
1854      // Insert the new text.
1855      // First check for multiplication overflow.
1856      if (yanklen + spaces != 0
1857          && count > ((INT_MAX - (bd.startspaces + bd.endspaces)) / (yanklen + spaces))) {
1858        emsg(_(e_resulting_text_too_long));
1859        break;
1860      }
1861
1862      totlen = (size_t)count * (size_t)(yanklen + spaces) + (size_t)bd.startspaces +
1863               (size_t)bd.endspaces;
1864      char *newp = xmalloc(totlen + (size_t)oldlen + 1);
1865
1866      // copy part up to cursor to new line
1867      ptr = newp;
1868      memmove(ptr, oldp, (size_t)bd.textcol);
1869      ptr += bd.textcol;
1870
1871      // may insert some spaces before the new text
1872      memset(ptr, ' ', (size_t)bd.startspaces);
1873      ptr += bd.startspaces;
1874
1875      // insert the new text
1876      for (int j = 0; j < count; j++) {
1877        memmove(ptr, y_array[i].data, (size_t)yanklen);
1878        ptr += yanklen;
1879
1880        // insert block's trailing spaces only if there's text behind
1881        if ((j < count - 1 || !shortline) && spaces > 0) {
1882          memset(ptr, ' ', (size_t)spaces);
1883          ptr += spaces;
1884        } else {
1885          totlen -= (size_t)spaces;  // didn't use these spaces
1886        }
1887      }
1888
1889      // may insert some spaces after the new text
1890      memset(ptr, ' ', (size_t)bd.endspaces);
1891      ptr += bd.endspaces;
1892
1893      // move the text after the cursor to the end of the line.
1894      int columns = oldlen - bd.textcol - delcount + 1;
1895      assert(columns >= 0);
1896      memmove(ptr, oldp + bd.textcol + delcount, (size_t)columns);
1897      ml_replace(curwin->w_cursor.lnum, newp, false);
1898      extmark_splice_cols(curbuf, (int)curwin->w_cursor.lnum - 1, bd.textcol,
1899                          delcount, (int)totlen + lines_appended, kExtmarkUndo);
1900
1901      curwin->w_cursor.lnum++;
1902      if (i == 0) {
1903        curwin->w_cursor.col += bd.startspaces;
1904      }
1905    }
1906
1907    changed_lines(curbuf, lnum, 0, curbuf->b_op_start.lnum + (linenr_T)y_size
1908                  - nr_lines, nr_lines, true);
1909
1910    // Set '[ mark.
1911    curbuf->b_op_start = curwin->w_cursor;
1912    curbuf->b_op_start.lnum = lnum;
1913
1914    // adjust '] mark
1915    curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
1916    curbuf->b_op_end.col = MAX(bd.textcol + (colnr_T)totlen - 1, 0);
1917    curbuf->b_op_end.coladd = 0;
1918    if (flags & PUT_CURSEND) {
1919      curwin->w_cursor = curbuf->b_op_end;
1920      curwin->w_cursor.col++;
1921
1922      // in Insert mode we might be after the NUL, correct for that
1923      colnr_T len = get_cursor_line_len();
1924      curwin->w_cursor.col = MIN(curwin->w_cursor.col, len);
1925    } else {
1926      curwin->w_cursor.lnum = lnum;
1927    }
1928  } else {
1929    const int yanklen = (int)y_array[0].size;
1930
1931    // Character or Line mode
1932    if (y_type == kMTCharWise) {
1933      // if type is kMTCharWise, FORWARD is the same as BACKWARD on the next
1934      // char
1935      if (dir == FORWARD && gchar_cursor() != NUL) {
1936        int bytelen = utfc_ptr2len(get_cursor_pos_ptr());
1937
1938        // put it on the next of the multi-byte character.
1939        col += bytelen;
1940        if (yanklen) {
1941          curwin->w_cursor.col += bytelen;
1942          curbuf->b_op_end.col += bytelen;
1943        }
1944      }
1945      curbuf->b_op_start = curwin->w_cursor;
1946    } else if (dir == BACKWARD) {
1947      // Line mode: BACKWARD is the same as FORWARD on the previous line
1948      lnum--;
1949    }
1950    pos_T new_cursor = curwin->w_cursor;
1951
1952    // simple case: insert into one line at a time
1953    if (y_type == kMTCharWise && y_size == 1) {
1954      linenr_T end_lnum = 0;  // init for gcc
1955      linenr_T start_lnum = lnum;
1956      int first_byte_off = 0;
1957
1958      if (Visual.active) {
1959        end_lnum = MAX(curbuf->b_visual.vi_end.lnum, curbuf->b_visual.vi_start.lnum);
1960        if (end_lnum > start_lnum) {
1961          // "col" is valid for the first line, in following lines
1962          // the virtual column needs to be used.  Matters for
1963          // multi-byte characters.
1964          pos_T pos = {
1965            .lnum = lnum,
1966            .col = col,
1967            .coladd = 0,
1968          };
1969          getvcol(curwin, &pos, NULL, &vcol, NULL, 0);
1970        }
1971      }
1972
1973      if (count == 0 || yanklen == 0) {
1974        if (Visual.active) {
1975          lnum = end_lnum;
1976        }
1977      } else if (count > INT_MAX / yanklen) {
1978        // multiplication overflow
1979        emsg(_(e_resulting_text_too_long));
1980      } else {
1981        totlen = (size_t)count * (size_t)yanklen;
1982        do {
1983          char *oldp = ml_get(lnum);
1984          colnr_T oldlen = ml_get_len(lnum);
1985          if (lnum > start_lnum) {
1986            pos_T pos = {
1987              .lnum = lnum,
1988            };
1989            if (getvpos(curwin, &pos, vcol) == OK) {
1990              col = pos.col;
1991            } else {
1992              col = MAXCOL;
1993            }
1994          }
1995          if (Visual.active && col > oldlen) {
1996            lnum++;
1997            continue;
1998          }
1999          char *newp = xmalloc(totlen + (size_t)oldlen + 1);
2000          memmove(newp, oldp, (size_t)col);
2001          char *ptr = newp + col;
2002          for (size_t i = 0; i < (size_t)count; i++) {
2003            memmove(ptr, y_array[0].data, (size_t)yanklen);
2004            ptr += yanklen;
2005          }
2006          memmove(ptr, oldp + col, (size_t)(oldlen - col) + 1);  // +1 for NUL
2007          ml_replace(lnum, newp, false);
2008
2009          // compute the byte offset for the last character
2010          first_byte_off = utf_head_off(newp, ptr - 1);
2011
2012          // Place cursor on last putted char.
2013          if (lnum == curwin->w_cursor.lnum) {
2014            // make sure curwin->w_virtcol is updated
2015            changed_cline_bef_curs(curwin);
2016            invalidate_botline_win(curwin);
2017            curwin->w_cursor.col += (colnr_T)(totlen - 1);
2018          }
2019          changed_bytes(lnum, col);
2020          extmark_splice_cols(curbuf, (int)lnum - 1, col,
2021                              0, (int)totlen, kExtmarkUndo);
2022          if (Visual.active) {
2023            lnum++;
2024          }
2025        } while (Visual.active && lnum <= end_lnum);
2026
2027        if (Visual.active) {  // reset lnum to the last visual line
2028          lnum--;
2029        }
2030      }
2031
2032      // put '] at the first byte of the last character
2033      curbuf->b_op_end = curwin->w_cursor;
2034      curbuf->b_op_end.col -= first_byte_off;
2035
2036      // For "CTRL-O p" in Insert mode, put cursor after last char
2037      if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND))) {
2038        curwin->w_cursor.col++;
2039      } else {
2040        curwin->w_cursor.col -= first_byte_off;
2041      }
2042    } else {
2043      linenr_T new_lnum = new_cursor.lnum;
2044      int indent;
2045      int orig_indent = 0;
2046      int indent_diff = 0;        // init for gcc
2047      bool first_indent = true;
2048      int lendiff = 0;
2049
2050      if (flags & PUT_FIXINDENT) {
2051        orig_indent = get_indent();
2052      }
2053
2054      // Insert at least one line.  When y_type is kMTCharWise, break the first
2055      // line in two.
2056      for (int cnt = 1; cnt <= count; cnt++) {
2057        size_t i = 0;
2058        if (y_type == kMTCharWise) {
2059          // Split the current line in two at the insert position.
2060          // First insert y_array[size - 1] in front of second line.
2061          // Then append y_array[0] to first line.
2062          lnum = new_cursor.lnum;
2063          char *ptr = ml_get(lnum) + col;
2064          size_t ptrlen = (size_t)ml_get_len(lnum) - (size_t)col;
2065          totlen = y_array[y_size - 1].size;
2066          char *newp = xmalloc(ptrlen + totlen + 1);
2067          STRCPY(newp, y_array[y_size - 1].data);
2068          STRCPY(newp + totlen, ptr);
2069          // insert second line
2070          ml_append(lnum, newp, 0, false);
2071          new_lnum++;
2072          xfree(newp);
2073
2074          char *oldp = ml_get(lnum);
2075          newp = xmalloc((size_t)col + (size_t)yanklen + 1);
2076          // copy first part of line
2077          memmove(newp, oldp, (size_t)col);
2078          // append to first line
2079          memmove(newp + col, y_array[0].data, (size_t)yanklen + 1);
2080          ml_replace(lnum, newp, false);
2081
2082          curwin->w_cursor.lnum = lnum;
2083          i = 1;
2084        }
2085
2086        for (; i < y_size; i++) {
2087          if ((y_type != kMTCharWise || i < y_size - 1)) {
2088            if (ml_append(lnum, y_array[i].data, 0, false) == FAIL) {
2089              goto error;
2090            }
2091            new_lnum++;
2092          }
2093          lnum++;
2094          nr_lines++;
2095          if (flags & PUT_FIXINDENT) {
2096            pos_T old_pos = curwin->w_cursor;
2097            curwin->w_cursor.lnum = lnum;
2098            char *ptr = ml_get(lnum);
2099            if (cnt == count && i == y_size - 1) {
2100              lendiff = ml_get_len(lnum);
2101            }
2102            if (*ptr == '#' && preprocs_left()) {
2103              indent = 0;                   // Leave # lines at start
2104            } else if (*ptr == NUL) {
2105              indent = 0;                   // Ignore empty lines
2106            } else if (first_indent) {
2107              indent_diff = orig_indent - get_indent();
2108              indent = orig_indent;
2109              first_indent = false;
2110            } else if ((indent = get_indent() + indent_diff) < 0) {
2111              indent = 0;
2112            }
2113            set_indent(indent, SIN_NOMARK);
2114            curwin->w_cursor = old_pos;
2115            // remember how many chars were removed
2116            if (cnt == count && i == y_size - 1) {
2117              lendiff -= ml_get_len(lnum);
2118            }
2119          }
2120        }
2121
2122        bcount_t totsize = 0;
2123        int lastsize = 0;
2124        if (y_type == kMTCharWise
2125            || (y_type == kMTLineWise && (flags & PUT_LINE_SPLIT))) {
2126          for (i = 0; i < y_size - 1; i++) {
2127            totsize += (bcount_t)y_array[i].size + 1;
2128          }
2129          lastsize = (int)y_array[y_size - 1].size;
2130          totsize += lastsize;
2131        }
2132        if (y_type == kMTCharWise) {
2133          extmark_splice(curbuf, (int)new_cursor.lnum - 1, col, 0, 0, 0,
2134                         (int)y_size - 1, lastsize, totsize,
2135                         kExtmarkUndo);
2136        } else if (y_type == kMTLineWise && (flags & PUT_LINE_SPLIT)) {
2137          // Account for last pasted NL + last NL
2138          extmark_splice(curbuf, (int)new_cursor.lnum - 1, split_pos, 0, 0, 0,
2139                         (int)y_size + 1, 0, totsize + 2, kExtmarkUndo);
2140        }
2141
2142        if (cnt == 1) {
2143          new_lnum = lnum;
2144        }
2145      }
2146
2147error:
2148      // Adjust marks.
2149      if (y_type == kMTLineWise) {
2150        curbuf->b_op_start.col = 0;
2151        if (dir == FORWARD) {
2152          curbuf->b_op_start.lnum++;
2153        }
2154      }
2155
2156      ExtmarkOp kind = (y_type == kMTLineWise && !(flags & PUT_LINE_SPLIT))
2157                       ? kExtmarkUndo : kExtmarkNOOP;
2158      mark_adjust(curbuf->b_op_start.lnum + (y_type == kMTCharWise),
2159                  (linenr_T)MAXLNUM, nr_lines, 0, kind);
2160
2161      // note changed text for displaying and folding
2162      if (y_type == kMTCharWise) {
2163        changed_lines(curbuf, curwin->w_cursor.lnum, col,
2164                      curwin->w_cursor.lnum + 1, nr_lines, true);
2165      } else {
2166        changed_lines(curbuf, curbuf->b_op_start.lnum, 0,
2167                      curbuf->b_op_start.lnum, nr_lines, true);
2168      }
2169
2170      // Put the '] mark on the first byte of the last inserted character.
2171      // Correct the length for change in indent.
2172      curbuf->b_op_end.lnum = new_lnum;
2173      col = MAX(0, (colnr_T)y_array[y_size - 1].size - lendiff);
2174      if (col > 1) {
2175        curbuf->b_op_end.col = col - 1;
2176        if (y_array[y_size - 1].size > 0) {
2177          curbuf->b_op_end.col -= utf_head_off(y_array[y_size - 1].data,
2178                                               y_array[y_size - 1].data
2179                                               + y_array[y_size - 1].size - 1);
2180        }
2181      } else {
2182        curbuf->b_op_end.col = 0;
2183      }
2184
2185      if (flags & PUT_CURSLINE) {
2186        // ":put": put cursor on last inserted line
2187        curwin->w_cursor.lnum = lnum;
2188        beginline(BL_WHITE | BL_FIX);
2189      } else if (flags & PUT_CURSEND) {
2190        // put cursor after inserted text
2191        if (y_type == kMTLineWise) {
2192          if (lnum >= curbuf->b_ml.ml_line_count) {
2193            curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
2194          } else {
2195            curwin->w_cursor.lnum = lnum + 1;
2196          }
2197          curwin->w_cursor.col = 0;
2198        } else {
2199          curwin->w_cursor.lnum = new_lnum;
2200          curwin->w_cursor.col = col;
2201          curbuf->b_op_end = curwin->w_cursor;
2202          if (col > 1) {
2203            curbuf->b_op_end.col = col - 1;
2204          }
2205        }
2206      } else if (y_type == kMTLineWise) {
2207        // put cursor on first non-blank in first inserted line
2208        curwin->w_cursor.col = 0;
2209        if (dir == FORWARD) {
2210          curwin->w_cursor.lnum++;
2211        }
2212        beginline(BL_WHITE | BL_FIX);
2213      } else {  // put cursor on first inserted character
2214        curwin->w_cursor = new_cursor;
2215      }
2216    }
2217  }
2218
2219  msgmore(nr_lines);
2220  curwin->w_set_curswant = true;
2221
2222  // Make sure the cursor is not after the NUL.
2223  int len = get_cursor_line_len();
2224  if (curwin->w_cursor.col > len) {
2225    if (cur_ve_flags == kOptVeFlagAll) {
2226      curwin->w_cursor.coladd = curwin->w_cursor.col - len;
2227    }
2228    curwin->w_cursor.col = len;
2229  }
2230
2231end:
2232  if (cmdmod.cmod_flags & CMOD_LOCKMARKS) {
2233    curbuf->b_op_start = orig_start;
2234    curbuf->b_op_end = orig_end;
2235  }
2236
2237  if (has_event(EVENT_TEXTPUTPOST)) {
2238    if (insert_string.data == NULL) {
2239      put_do_autocmd(regname, reg, NULL, true, dir);
2240    } else {
2241      put_do_autocmd(regname, NULL, &insert_string, true, dir);
2242    }
2243  }
2244
2245  if (allocated) {
2246    xfree(insert_string.data);
2247  }
2248  if (regname == '=') {
2249    xfree(y_array);
2250  }
2251
2252  if (!curbuf->terminal) {  // XXX
2253    Visual.active = false;
2254  }
2255
2256  // If the cursor is past the end of the line put it at the end.
2257  adjust_cursor_eol();
2258}
2259
2260/// display a string for do_dis()
2261/// truncate at end of screen line
2262///
2263/// @param skip_esc  if true, ignore trailing ESC
2264static void dis_msg(const char *p, bool skip_esc)
2265  FUNC_ATTR_NONNULL_ALL
2266{
2267  int n = Columns - 6;
2268  while (*p != NUL
2269         && !(*p == ESC && skip_esc && *(p + 1) == NUL)
2270         && (n -= ptr2cells(p)) >= 0) {
2271    int l;
2272    if ((l = utfc_ptr2len(p)) > 1) {
2273      msg_outtrans_len(p, l, 0, false);
2274      p += l;
2275    } else {
2276      msg_outtrans_len(p++, 1, 0, false);
2277    }
2278  }
2279  os_breakcheck();
2280}
2281
2282/// ":dis" and ":registers": Display the contents of the yank registers.
2283void ex_display(exarg_T *eap)
2284{
2285  char *p;
2286  yankreg_T *yb;
2287  char *arg = eap->arg;
2288  int type;
2289
2290  if (arg != NULL && *arg == NUL) {
2291    arg = NULL;
2292  }
2293  int hl_id = HLF_8;
2294
2295  msg_ext_set_kind("list_cmd");
2296  msg_ext_skip_flush = true;
2297  // Highlight title
2298  msg_puts_title(_("\nType Name Content"));
2299  for (int i = -1; i < NUM_REGISTERS && !got_int; i++) {
2300    int name = get_register_name(i);
2301    if (arg != NULL && vim_strchr(arg, name) == NULL) {
2302      continue;             // did not ask for this register
2303    }
2304
2305    switch (get_reg_type(name, NULL)) {
2306    case kMTLineWise:
2307      type = 'l'; break;
2308    case kMTCharWise:
2309      type = 'c'; break;
2310    default:
2311      type = 'b'; break;
2312    }
2313
2314    if (i == -1) {
2315      if (y_previous != NULL) {
2316        yb = y_previous;
2317      } else {
2318        yb = &(y_regs[0]);
2319      }
2320    } else {
2321      yb = &(y_regs[i]);
2322    }
2323
2324    get_clipboard(name, &yb, true);
2325
2326    if (name == mb_tolower(redir_reg)
2327        || (redir_reg == '"' && yb == y_previous)) {
2328      continue;  // do not list register being written to, the
2329                 // pointer can be freed
2330    }
2331
2332    if (yb->y_array != NULL) {
2333      bool do_show = false;
2334
2335      for (size_t j = 0; !do_show && j < yb->y_size; j++) {
2336        do_show = !message_filtered(yb->y_array[j].data);
2337      }
2338
2339      if (do_show || yb->y_size == 0) {
2340        msg_putchar('\n');
2341        msg_puts("  ");
2342        msg_putchar(type);
2343        msg_puts("  ");
2344        msg_putchar('"');
2345        msg_putchar(name);
2346        msg_puts("   ");
2347
2348        int n = Columns - 11;
2349        for (size_t j = 0; j < yb->y_size && n > 1; j++) {
2350          if (j) {
2351            msg_puts_hl("^J", hl_id, false);
2352            n -= 2;
2353          }
2354          for (p = yb->y_array[j].data;
2355               *p != NUL && (n -= ptr2cells(p)) >= 0; p++) {
2356            int clen = utfc_ptr2len(p);
2357            msg_outtrans_len(p, clen, 0, false);
2358            p += clen - 1;
2359          }
2360        }
2361        if (n > 1 && yb->y_type == kMTLineWise) {
2362          msg_puts_hl("^J", hl_id, false);
2363        }
2364      }
2365      os_breakcheck();
2366    }
2367  }
2368
2369  // display last inserted text
2370  String insert = get_last_insert();
2371  if ((p = insert.data) != NULL
2372      && (arg == NULL || vim_strchr(arg, '.') != NULL) && !got_int
2373      && !message_filtered(p)) {
2374    msg_puts("\n  c  \".   ");
2375    dis_msg(p, true);
2376  }
2377
2378  // display last command line
2379  if (last_cmdline != NULL && (arg == NULL || vim_strchr(arg, ':') != NULL)
2380      && !got_int && !message_filtered(last_cmdline)) {
2381    msg_puts("\n  c  \":   ");
2382    dis_msg(last_cmdline, false);
2383  }
2384
2385  // display current file name
2386  if (curbuf->b_fname != NULL
2387      && (arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int
2388      && !message_filtered(curbuf->b_fname)) {
2389    msg_puts("\n  c  \"%   ");
2390    dis_msg(curbuf->b_fname, false);
2391  }
2392
2393  // display alternate file name
2394  if ((arg == NULL || vim_strchr(arg, '#') != NULL) && !got_int) {
2395    char *fname;
2396    linenr_T dummy;
2397
2398    if (buflist_name_nr(0, &fname, &dummy) != FAIL && !message_filtered(fname)) {
2399      msg_puts("\n  c  \"#   ");
2400      dis_msg(fname, false);
2401    }
2402  }
2403
2404  // display last search pattern
2405  if (last_search_pat() != NULL
2406      && (arg == NULL || vim_strchr(arg, '/') != NULL) && !got_int
2407      && !message_filtered(last_search_pat())) {
2408    msg_puts("\n  c  \"/   ");
2409    dis_msg(last_search_pat(), false);
2410  }
2411
2412  // display last used expression
2413  if (expr_line != NULL && (arg == NULL || vim_strchr(arg, '=') != NULL)
2414      && !got_int && !message_filtered(expr_line)) {
2415    msg_puts("\n  c  \"=   ");
2416    dis_msg(expr_line, false);
2417  }
2418  msg_ext_skip_flush = false;
2419}
2420
2421/// Used for getregtype()
2422///
2423/// @return  the type of a register or
2424///          kMTUnknown for error.
2425MotionType get_reg_type(int regname, colnr_T *reg_width)
2426{
2427  switch (regname) {
2428  case '%':     // file name
2429  case '#':     // alternate file name
2430  case '=':     // expression
2431  case ':':     // last command line
2432  case '/':     // last search-pattern
2433  case '.':     // last inserted text
2434  case Ctrl_F:  // Filename under cursor
2435  case Ctrl_P:  // Path under cursor, expand via "path"
2436  case Ctrl_W:  // word under cursor
2437  case Ctrl_A:  // WORD (mnemonic All) under cursor
2438  case '_':     // black hole: always empty
2439    return kMTCharWise;
2440  }
2441
2442  if (regname != NUL && !valid_yank_reg(regname, false)) {
2443    return kMTUnknown;
2444  }
2445
2446  yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
2447
2448  if (reg->y_array != NULL) {
2449    if (reg_width != NULL && reg->y_type == kMTBlockWise) {
2450      *reg_width = reg->y_width;
2451    }
2452    return reg->y_type;
2453  }
2454  return kMTUnknown;
2455}
2456
2457/// When `flags` has `kGRegList` return a list with text `s`.
2458/// Otherwise just return `s`.
2459///
2460/// @return  a void * for use in get_reg_contents().
2461static void *get_reg_wrap_one_line(char *s, int flags)
2462{
2463  if (!(flags & kGRegList)) {
2464    return s;
2465  }
2466  list_T *const list = tv_list_alloc(1);
2467  tv_list_append_allocated_string(list, s);
2468  return list;
2469}
2470
2471/// Gets the contents of a register.
2472/// @remark Used for `@r` in expressions and for `getreg()`.
2473///
2474/// @param regname  The register.
2475/// @param flags    see @ref GRegFlags
2476///
2477/// @returns The contents of the register as an allocated string.
2478/// @returns A linked list when `flags` contains @ref kGRegList.
2479/// @returns NULL for error.
2480void *get_reg_contents(int regname, int flags)
2481{
2482  // Don't allow using an expression register inside an expression.
2483  if (regname == '=') {
2484    if (flags & kGRegNoExpr) {
2485      return NULL;
2486    }
2487    if (flags & kGRegExprSrc) {
2488      return get_reg_wrap_one_line(get_expr_line_src(), flags);
2489    }
2490    return get_reg_wrap_one_line(get_expr_line(), flags);
2491  }
2492
2493  if (regname == '@') {     // "@@" is used for unnamed register
2494    regname = '"';
2495  }
2496
2497  // check for valid regname
2498  if (regname != NUL && !valid_yank_reg(regname, false)) {
2499    return NULL;
2500  }
2501
2502  char *retval;
2503  bool allocated;
2504  if (get_spec_reg(regname, &retval, &allocated, false)) {
2505    if (retval == NULL) {
2506      return NULL;
2507    }
2508    if (allocated) {
2509      return get_reg_wrap_one_line(retval, flags);
2510    }
2511    return get_reg_wrap_one_line(xstrdup(retval), flags);
2512  }
2513
2514  yankreg_T *reg = get_yank_register(regname, YREG_PUT);
2515  if (reg->y_array == NULL) {
2516    return NULL;
2517  }
2518
2519  if (flags & kGRegList) {
2520    list_T *const list = tv_list_alloc((ptrdiff_t)reg->y_size);
2521    for (size_t i = 0; i < reg->y_size; i++) {
2522      tv_list_append_string(list, reg->y_array[i].data, (int)reg->y_array[i].size);
2523    }
2524
2525    return list;
2526  }
2527
2528  // Compute length of resulting string.
2529  size_t len = 0;
2530  for (size_t i = 0; i < reg->y_size; i++) {
2531    len += reg->y_array[i].size;
2532    // Insert a newline between lines and after last line if y_type is kMTLineWise.
2533    if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
2534      len++;
2535    }
2536  }
2537
2538  retval = xmalloc(len + 1);
2539
2540  // Copy the lines of the yank register into the string.
2541  len = 0;
2542  for (size_t i = 0; i < reg->y_size; i++) {
2543    STRCPY(retval + len, reg->y_array[i].data);
2544    len += reg->y_array[i].size;
2545
2546    // Insert a newline between lines and after the last line if y_type is kMTLineWise.
2547    if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
2548      retval[len++] = '\n';
2549    }
2550  }
2551  retval[len] = NUL;
2552
2553  return retval;
2554}
2555
2556static yankreg_T *init_write_reg(int name, yankreg_T **old_y_previous, bool must_append)
2557{
2558  if (!valid_yank_reg(name, true)) {  // check for valid reg name
2559    emsg_invreg(name);
2560    return NULL;
2561  }
2562
2563  // Don't want to change the current (unnamed) register.
2564  *old_y_previous = y_previous;
2565
2566  yankreg_T *reg = get_yank_register(name, YREG_YANK);
2567  if (!is_append_register(name) && !must_append) {
2568    free_register(reg);
2569  }
2570  return reg;
2571}
2572
2573/// str_to_reg - Put a string into a register.
2574///
2575/// When the register is not empty, the string is appended.
2576///
2577/// @param y_ptr pointer to yank register
2578/// @param yank_type The motion type (kMTUnknown to auto detect)
2579/// @param str string or list of strings to put in register
2580/// @param len length of the string (Ignored when str_list=true.)
2581/// @param blocklen width of visual block, or -1 for "I don't know."
2582/// @param str_list True if str is `char **`.
2583static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type, const char *str, size_t len,
2584                       colnr_T blocklen, bool str_list)
2585  FUNC_ATTR_NONNULL_ALL
2586{
2587  if (y_ptr->y_array == NULL) {  // NULL means empty register
2588    y_ptr->y_size = 0;
2589  }
2590
2591  if (yank_type == kMTUnknown) {
2592    yank_type = ((str_list
2593                  || (len > 0 && (str[len - 1] == NL || str[len - 1] == CAR)))
2594                 ? kMTLineWise : kMTCharWise);
2595  }
2596
2597  size_t newlines = 0;
2598  bool extraline = false;  // extra line at the end
2599  bool append = false;     // append to last line in register
2600
2601  // Count the number of lines within the string
2602  if (str_list) {
2603    for (char **ss = (char **)str; *ss != NULL; ss++) {
2604      newlines++;
2605    }
2606  } else {
2607    newlines = memcnt(str, '\n', len);
2608    if (yank_type == kMTCharWise || len == 0 || str[len - 1] != '\n') {
2609      extraline = 1;
2610      newlines++;         // count extra newline at the end
2611    }
2612    if (y_ptr->y_size > 0 && y_ptr->y_type == kMTCharWise) {
2613      append = true;
2614      newlines--;         // uncount newline when appending first line
2615    }
2616  }
2617
2618  // Without any lines make the register empty.
2619  if (y_ptr->y_size + newlines == 0) {
2620    XFREE_CLEAR(y_ptr->y_array);
2621    return;
2622  }
2623
2624  // Grow the register array to hold the pointers to the new lines.
2625  String *pp = xrealloc(y_ptr->y_array, (y_ptr->y_size + newlines) * sizeof(String));
2626  y_ptr->y_array = pp;
2627
2628  size_t lnum = y_ptr->y_size;  // The current line number.
2629
2630  // If called with `blocklen < 0`, we have to update the yank reg's width.
2631  size_t maxlen = 0;
2632
2633  // Find the end of each line and save it into the array.
2634  if (str_list) {
2635    for (char **ss = (char **)str; *ss != NULL; ss++, lnum++) {
2636      pp[lnum] = cstr_to_string(*ss);
2637      if (yank_type == kMTBlockWise) {
2638        size_t charlen = mb_string2cells(*ss);
2639        maxlen = MAX(maxlen, charlen);
2640      }
2641    }
2642  } else {
2643    size_t line_len;
2644    for (const char *start = str, *end = str + len;
2645         start < end + extraline;
2646         start += line_len + 1, lnum++) {
2647      int charlen = 0;
2648
2649      const char *line_end = start;
2650      while (line_end < end) {  // find the end of the line
2651        if (*line_end == '\n') {
2652          break;
2653        }
2654        if (yank_type == kMTBlockWise) {
2655          charlen += utf_ptr2cells_len(line_end, (int)(end - line_end));
2656        }
2657
2658        if (*line_end == NUL) {
2659          line_end++;  // registers can have NUL chars
2660        } else {
2661          line_end += utfc_ptr2len_len(line_end, (int)(end - line_end));
2662        }
2663      }
2664      assert(line_end - start >= 0);
2665      line_len = (size_t)(line_end - start);
2666      maxlen = MAX(maxlen, (size_t)charlen);
2667
2668      // When appending, copy the previous line and free it after.
2669      size_t extra = append ? pp[--lnum].size : 0;
2670      char *s = xmallocz(line_len + extra);
2671      if (extra > 0) {
2672        memcpy(s, pp[lnum].data, extra);
2673      }
2674      if (line_len > 0) {
2675        memcpy(s + extra, start, line_len);
2676      }
2677      size_t s_len = extra + line_len;
2678
2679      if (append) {
2680        xfree(pp[lnum].data);
2681        append = false;  // only first line is appended
2682      }
2683      pp[lnum] = cbuf_as_string(s, s_len);
2684
2685      // Convert NULs to '\n' to prevent truncation.
2686      memchrsub(pp[lnum].data, NUL, '\n', s_len);
2687    }
2688  }
2689  y_ptr->y_type = yank_type;
2690  y_ptr->y_size = lnum;
2691  XFREE_CLEAR(y_ptr->additional_data);
2692  y_ptr->timestamp = (Timestamp)os_realtime();
2693  if (yank_type == kMTBlockWise) {
2694    y_ptr->y_width = (blocklen == -1 ? (colnr_T)maxlen - 1 : blocklen);
2695  } else {
2696    y_ptr->y_width = 0;
2697  }
2698}
2699
2700static void finish_write_reg(int name, yankreg_T *reg, yankreg_T *old_y_previous)
2701{
2702  // Send text of clipboard register to the clipboard.
2703  set_clipboard(name, reg);
2704
2705  // ':let @" = "val"' should change the meaning of the "" register
2706  if (name != '"') {
2707    y_previous = old_y_previous;
2708  }
2709}
2710
2711/// store `str` in register `name`
2712///
2713/// @see write_reg_contents_ex
2714void write_reg_contents(int name, const char *str, ssize_t len, int must_append)
2715{
2716  write_reg_contents_ex(name, str, len, must_append, kMTUnknown, 0);
2717}
2718
2719void write_reg_contents_lst(int name, char **strings, bool must_append, MotionType yank_type,
2720                            colnr_T block_len)
2721{
2722  if (name == '/' || name == '=' || name == '#') {
2723    char *s = strings[0];
2724    if (strings[0] == NULL) {
2725      s = "";
2726    } else if (strings[1] != NULL) {
2727      semsg(_(e_register_char_cannot_contain_multiple_lines), name);
2728      return;
2729    }
2730    write_reg_contents_ex(name, s, -1, must_append, yank_type, block_len);
2731    return;
2732  }
2733
2734  // black hole: nothing to do
2735  if (name == '_') {
2736    return;
2737  }
2738
2739  yankreg_T *old_y_previous, *reg;
2740  if (!(reg = init_write_reg(name, &old_y_previous, must_append))) {
2741    return;
2742  }
2743
2744  str_to_reg(reg, yank_type, (char *)strings, strlen((char *)strings),
2745             block_len, true);
2746  finish_write_reg(name, reg, old_y_previous);
2747}
2748
2749/// write_reg_contents_ex - store `str` in register `name`
2750///
2751/// If `str` ends in '\n' or '\r', use linewise, otherwise use charwise.
2752///
2753/// @warning when `name` is '/', `len` and `must_append` are ignored. This
2754///          means that `str` MUST be NUL-terminated.
2755///
2756/// @param name The name of the register
2757/// @param str The contents to write
2758/// @param len If >= 0, write `len` bytes of `str`. Otherwise, write
2759///               `strlen(str)` bytes. If `len` is larger than the
2760///               allocated size of `src`, the behaviour is undefined.
2761/// @param must_append If true, append the contents of `str` to the current
2762///                    contents of the register. Note that regardless of
2763///                    `must_append`, this function will append when `name`
2764///                    is an uppercase letter.
2765/// @param yank_type The motion type (kMTUnknown to auto detect)
2766/// @param block_len width of visual block
2767void write_reg_contents_ex(int name, const char *str, ssize_t len, bool must_append,
2768                           MotionType yank_type, colnr_T block_len)
2769{
2770  if (len < 0) {
2771    len = (ssize_t)strlen(str);
2772  }
2773
2774  // Special case: '/' search pattern
2775  if (name == '/') {
2776    set_last_search_pat(str, RE_SEARCH, true, true);
2777    return;
2778  }
2779
2780  if (name == '#') {
2781    if (len == 0) {
2782      curwin->w_alt_fnum = 0;  // clear altfile
2783      return;
2784    }
2785
2786    buf_T *buf;
2787
2788    if (ascii_isdigit(*str)) {
2789      int num = atoi(str);
2790
2791      buf = buflist_findnr(num);
2792      if (buf == NULL) {
2793        semsg(_(e_nobufnr), (int64_t)num);
2794      }
2795    } else {
2796      buf = buflist_findnr(buflist_findpat(str, str + len, true, false, false));
2797    }
2798    if (buf == NULL) {
2799      return;
2800    }
2801    curwin->w_alt_fnum = buf->b_fnum;
2802    return;
2803  }
2804
2805  if (name == '=') {
2806    size_t offset = 0;
2807    size_t totlen = (size_t)len;
2808
2809    if (must_append && expr_line) {
2810      // append has been specified and expr_line already exists, so we'll
2811      // append the new string to expr_line.
2812      size_t exprlen = strlen(expr_line);
2813
2814      totlen += exprlen;
2815      offset = exprlen;
2816    }
2817
2818    // modify the global expr_line, extend/shrink it if necessary (realloc).
2819    // Copy the input string into the adjusted memory at the specified
2820    // offset.
2821    expr_line = xrealloc(expr_line, totlen + 1);
2822    memcpy(expr_line + offset, str, (size_t)len);
2823    expr_line[totlen] = NUL;
2824
2825    return;
2826  }
2827
2828  if (name == '_') {        // black hole: nothing to do
2829    return;
2830  }
2831
2832  yankreg_T *old_y_previous, *reg;
2833  if (!(reg = init_write_reg(name, &old_y_previous, must_append))) {
2834    return;
2835  }
2836  str_to_reg(reg, yank_type, str, (size_t)len, block_len, false);
2837  finish_write_reg(name, reg, old_y_previous);
2838}
2839
2840/// @param[out] reg Expected to be empty
2841bool prepare_yankreg_from_object(yankreg_T *reg, String regtype, size_t lines)
2842{
2843  char type = regtype.data ? regtype.data[0] : NUL;
2844
2845  switch (type) {
2846  case 0:
2847    reg->y_type = kMTUnknown;
2848    break;
2849  case 'v':
2850  case 'c':
2851    reg->y_type = kMTCharWise;
2852    break;
2853  case 'V':
2854  case 'l':
2855    reg->y_type = kMTLineWise;
2856    break;
2857  case 'b':
2858  case Ctrl_V:
2859    reg->y_type = kMTBlockWise;
2860    break;
2861  default:
2862    return false;
2863  }
2864
2865  reg->y_width = 0;
2866  if (regtype.size > 1) {
2867    if (reg->y_type != kMTBlockWise) {
2868      return false;
2869    }
2870
2871    // allow "b7" for a block at least 7 spaces wide
2872    if (!ascii_isdigit(regtype.data[1])) {
2873      return false;
2874    }
2875    const char *p = regtype.data + 1;
2876    reg->y_width = getdigits_int((char **)&p, false, 1) - 1;
2877    if (regtype.size > (size_t)(p - regtype.data)) {
2878      return false;
2879    }
2880  }
2881
2882  reg->additional_data = NULL;
2883  reg->timestamp = 0;
2884  return true;
2885}
2886
2887void finish_yankreg_from_object(yankreg_T *reg, bool clipboard_adjust)
2888{
2889  if (reg->y_size > 0 && reg->y_array[reg->y_size - 1].size == 0) {
2890    // a known-to-be charwise yank might have a final linebreak
2891    // but otherwise there is no line after the final newline
2892    if (reg->y_type != kMTCharWise) {
2893      if (reg->y_type == kMTUnknown || clipboard_adjust) {
2894        reg->y_size--;
2895      }
2896      if (reg->y_type == kMTUnknown) {
2897        reg->y_type = kMTLineWise;
2898      }
2899    }
2900  } else {
2901    if (reg->y_type == kMTUnknown) {
2902      reg->y_type = kMTCharWise;
2903    }
2904  }
2905
2906  update_yankreg_width(reg);
2907}