1// This is an open source non-commercial project. Dear PVS-Studio, please check
2// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
3
4/*
5 * ops.c: implementation of various operators: op_shift, op_delete, op_tilde,
6 * op_change, op_yank, do_put, do_join
7 */
8
9#include <assert.h>
10#include <inttypes.h>
11#include <stdbool.h>
12#include <string.h>
13
14#include "nvim/vim.h"
15#include "nvim/ascii.h"
16#include "nvim/ops.h"
17#include "nvim/buffer.h"
18#include "nvim/change.h"
19#include "nvim/charset.h"
20#include "nvim/cursor.h"
21#include "nvim/assert.h"
22#include "nvim/edit.h"
23#include "nvim/eval.h"
24#include "nvim/eval/typval.h"
25#include "nvim/ex_cmds.h"
26#include "nvim/ex_cmds2.h"
27#include "nvim/ex_getln.h"
28#include "nvim/fileio.h"
29#include "nvim/fold.h"
30#include "nvim/getchar.h"
31#include "nvim/indent.h"
32#include "nvim/log.h"
33#include "nvim/mark.h"
34#include "nvim/mbyte.h"
35#include "nvim/memline.h"
36#include "nvim/memory.h"
37#include "nvim/message.h"
38#include "nvim/misc1.h"
39#include "nvim/move.h"
40#include "nvim/normal.h"
41#include "nvim/option.h"
42#include "nvim/path.h"
43#include "nvim/screen.h"
44#include "nvim/search.h"
45#include "nvim/state.h"
46#include "nvim/strings.h"
47#include "nvim/terminal.h"
48#include "nvim/ui.h"
49#include "nvim/undo.h"
50#include "nvim/macros.h"
51#include "nvim/window.h"
52#include "nvim/os/input.h"
53#include "nvim/os/time.h"
54
55static yankreg_T y_regs[NUM_REGISTERS];
56
57static yankreg_T *y_previous = NULL; /* ptr to last written yankreg */
58
59// for behavior between start_batch_changes() and end_batch_changes())
60static int batch_change_count = 0; // inside a script
61static bool clipboard_delay_update = false; // delay clipboard update
62static bool clipboard_needs_update = false; // clipboard was updated
63static bool clipboard_didwarn = false;
64
65/*
66 * structure used by block_prep, op_delete and op_yank for blockwise operators
67 * also op_change, op_shift, op_insert, op_replace - AKelly
68 */
69struct block_def {
70 int startspaces; /* 'extra' cols before first char */
71 int endspaces; /* 'extra' cols after last char */
72 int textlen; /* chars in block */
73 char_u *textstart; /* pointer to 1st char (partially) in block */
74 colnr_T textcol; /* index of chars (partially) in block */
75 colnr_T start_vcol; /* start col of 1st char wholly inside block */
76 colnr_T end_vcol; /* start col of 1st char wholly after block */
77 int is_short; /* TRUE if line is too short to fit in block */
78 int is_MAX; /* TRUE if curswant==MAXCOL when starting */
79 int is_oneChar; /* TRUE if block within one character */
80 int pre_whitesp; /* screen cols of ws before block */
81 int pre_whitesp_c; /* chars of ws before block */
82 colnr_T end_char_vcols; /* number of vcols of post-block char */
83 colnr_T start_char_vcols; /* number of vcols of pre-block char */
84};
85
86#ifdef INCLUDE_GENERATED_DECLARATIONS
87# include "ops.c.generated.h"
88#endif
89
90/*
91 * The names of operators.
92 * IMPORTANT: Index must correspond with defines in vim.h!!!
93 * The third field indicates whether the operator always works on lines.
94 */
95static char opchars[][3] =
96{
97 { NUL, NUL, false }, // OP_NOP
98 { 'd', NUL, false }, // OP_DELETE
99 { 'y', NUL, false }, // OP_YANK
100 { 'c', NUL, false }, // OP_CHANGE
101 { '<', NUL, true }, // OP_LSHIFT
102 { '>', NUL, true }, // OP_RSHIFT
103 { '!', NUL, true }, // OP_FILTER
104 { 'g', '~', false }, // OP_TILDE
105 { '=', NUL, true }, // OP_INDENT
106 { 'g', 'q', true }, // OP_FORMAT
107 { ':', NUL, true }, // OP_COLON
108 { 'g', 'U', false }, // OP_UPPER
109 { 'g', 'u', false }, // OP_LOWER
110 { 'J', NUL, true }, // DO_JOIN
111 { 'g', 'J', true }, // DO_JOIN_NS
112 { 'g', '?', false }, // OP_ROT13
113 { 'r', NUL, false }, // OP_REPLACE
114 { 'I', NUL, false }, // OP_INSERT
115 { 'A', NUL, false }, // OP_APPEND
116 { 'z', 'f', true }, // OP_FOLD
117 { 'z', 'o', true }, // OP_FOLDOPEN
118 { 'z', 'O', true }, // OP_FOLDOPENREC
119 { 'z', 'c', true }, // OP_FOLDCLOSE
120 { 'z', 'C', true }, // OP_FOLDCLOSEREC
121 { 'z', 'd', true }, // OP_FOLDDEL
122 { 'z', 'D', true }, // OP_FOLDDELREC
123 { 'g', 'w', true }, // OP_FORMAT2
124 { 'g', '@', false }, // OP_FUNCTION
125 { Ctrl_A, NUL, false }, // OP_NR_ADD
126 { Ctrl_X, NUL, false }, // OP_NR_SUB
127};
128
129/*
130 * Translate a command name into an operator type.
131 * Must only be called with a valid operator name!
132 */
133int get_op_type(int char1, int char2)
134{
135 int i;
136
137 if (char1 == 'r') {
138 // ignore second character
139 return OP_REPLACE;
140 }
141 if (char1 == '~') {
142 // when tilde is an operator
143 return OP_TILDE;
144 }
145 if (char1 == 'g' && char2 == Ctrl_A) {
146 // add
147 return OP_NR_ADD;
148 }
149 if (char1 == 'g' && char2 == Ctrl_X) {
150 // subtract
151 return OP_NR_SUB;
152 }
153 for (i = 0;; i++) {
154 if (opchars[i][0] == char1 && opchars[i][1] == char2) {
155 break;
156 }
157 if (i == (int)(ARRAY_SIZE(opchars) - 1)) {
158 internal_error("get_op_type()");
159 break;
160 }
161 }
162 return i;
163}
164
165/*
166 * Return TRUE if operator "op" always works on whole lines.
167 */
168int op_on_lines(int op)
169{
170 return opchars[op][2];
171}
172
173/*
174 * Get first operator command character.
175 * Returns 'g' or 'z' if there is another command character.
176 */
177int get_op_char(int optype)
178{
179 return opchars[optype][0];
180}
181
182/*
183 * Get second operator command character.
184 */
185int get_extra_op_char(int optype)
186{
187 return opchars[optype][1];
188}
189
190/*
191 * op_shift - handle a shift operation
192 */
193void op_shift(oparg_T *oap, int curs_top, int amount)
194{
195 long i;
196 int first_char;
197 char_u *s;
198 int block_col = 0;
199
200 if (u_save((linenr_T)(oap->start.lnum - 1),
201 (linenr_T)(oap->end.lnum + 1)) == FAIL)
202 return;
203
204 if (oap->motion_type == kMTBlockWise) {
205 block_col = curwin->w_cursor.col;
206 }
207
208 for (i = oap->line_count - 1; i >= 0; i--) {
209 first_char = *get_cursor_line_ptr();
210 if (first_char == NUL) { // empty line
211 curwin->w_cursor.col = 0;
212 } else if (oap->motion_type == kMTBlockWise) {
213 shift_block(oap, amount);
214 } else if (first_char != '#' || !preprocs_left()) {
215 // Move the line right if it doesn't start with '#', 'smartindent'
216 // isn't set or 'cindent' isn't set or '#' isn't in 'cino'.
217 shift_line(oap->op_type == OP_LSHIFT, p_sr, amount, false);
218 }
219 ++curwin->w_cursor.lnum;
220 }
221
222 changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L, true);
223
224 if (oap->motion_type == kMTBlockWise) {
225 curwin->w_cursor.lnum = oap->start.lnum;
226 curwin->w_cursor.col = block_col;
227 } else if (curs_top) { /* put cursor on first line, for ">>" */
228 curwin->w_cursor.lnum = oap->start.lnum;
229 beginline(BL_SOL | BL_FIX); /* shift_line() may have set cursor.col */
230 } else
231 --curwin->w_cursor.lnum; /* put cursor on last line, for ":>" */
232
233 // The cursor line is not in a closed fold
234 foldOpenCursor();
235
236 if (oap->line_count > p_report) {
237 if (oap->op_type == OP_RSHIFT)
238 s = (char_u *)">";
239 else
240 s = (char_u *)"<";
241 if (oap->line_count == 1) {
242 if (amount == 1)
243 sprintf((char *)IObuff, _("1 line %sed 1 time"), s);
244 else
245 sprintf((char *)IObuff, _("1 line %sed %d times"), s, amount);
246 } else {
247 if (amount == 1)
248 sprintf((char *)IObuff, _("%" PRId64 " lines %sed 1 time"),
249 (int64_t)oap->line_count, s);
250 else
251 sprintf((char *)IObuff, _("%" PRId64 " lines %sed %d times"),
252 (int64_t)oap->line_count, s, amount);
253 }
254 msg(IObuff);
255 }
256
257 /*
258 * Set "'[" and "']" marks.
259 */
260 curbuf->b_op_start = oap->start;
261 curbuf->b_op_end.lnum = oap->end.lnum;
262 curbuf->b_op_end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
263 if (curbuf->b_op_end.col > 0)
264 --curbuf->b_op_end.col;
265}
266
267// Shift the current line one shiftwidth left (if left != 0) or right
268// leaves cursor on first blank in the line.
269void shift_line(
270 int left,
271 int round,
272 int amount,
273 int call_changed_bytes /* call changed_bytes() */
274)
275{
276 int count;
277 int i, j;
278 int p_sw = get_sw_value(curbuf);
279
280 count = get_indent(); /* get current indent */
281
282 if (round) { /* round off indent */
283 i = count / p_sw; /* number of p_sw rounded down */
284 j = count % p_sw; /* extra spaces */
285 if (j && left) /* first remove extra spaces */
286 --amount;
287 if (left) {
288 i -= amount;
289 if (i < 0)
290 i = 0;
291 } else
292 i += amount;
293 count = i * p_sw;
294 } else { /* original vi indent */
295 if (left) {
296 count -= p_sw * amount;
297 if (count < 0)
298 count = 0;
299 } else
300 count += p_sw * amount;
301 }
302
303 /* Set new indent */
304 if (State & VREPLACE_FLAG)
305 change_indent(INDENT_SET, count, FALSE, NUL, call_changed_bytes);
306 else
307 (void)set_indent(count, call_changed_bytes ? SIN_CHANGED : 0);
308}
309
310/*
311 * Shift one line of the current block one shiftwidth right or left.
312 * Leaves cursor on first character in block.
313 */
314static void shift_block(oparg_T *oap, int amount)
315{
316 const bool left = (oap->op_type == OP_LSHIFT);
317 const int oldstate = State;
318 char_u *newp;
319 const int oldcol = curwin->w_cursor.col;
320 const int p_sw = get_sw_value(curbuf);
321 const int p_ts = (int)curbuf->b_p_ts;
322 struct block_def bd;
323 int incr;
324 int i = 0, j = 0;
325 const int old_p_ri = p_ri;
326
327 p_ri = 0; /* don't want revins in indent */
328
329 State = INSERT; // don't want REPLACE for State
330 block_prep(oap, &bd, curwin->w_cursor.lnum, true);
331 if (bd.is_short) {
332 return;
333 }
334
335 // total is number of screen columns to be inserted/removed
336 int total = (int)((unsigned)amount * (unsigned)p_sw);
337 if ((total / p_sw) != amount) {
338 return; // multiplication overflow
339 }
340
341 char_u *const oldp = get_cursor_line_ptr();
342
343 if (!left) {
344 /*
345 * 1. Get start vcol
346 * 2. Total ws vcols
347 * 3. Divvy into TABs & spp
348 * 4. Construct new string
349 */
350 total += bd.pre_whitesp; // all virtual WS up to & incl a split TAB
351 colnr_T ws_vcol = bd.start_vcol - bd.pre_whitesp;
352 if (bd.startspaces) {
353 if (has_mbyte) {
354 if ((*mb_ptr2len)(bd.textstart) == 1) {
355 bd.textstart++;
356 } else {
357 ws_vcol = 0;
358 bd.startspaces = 0;
359 }
360 } else {
361 bd.textstart++;
362 }
363 }
364 for (; ascii_iswhite(*bd.textstart); ) {
365 // TODO: is passing bd.textstart for start of the line OK?
366 incr = lbr_chartabsize_adv(bd.textstart, &bd.textstart, (colnr_T)(bd.start_vcol));
367 total += incr;
368 bd.start_vcol += incr;
369 }
370 /* OK, now total=all the VWS reqd, and textstart points at the 1st
371 * non-ws char in the block. */
372 if (!curbuf->b_p_et)
373 i = ((ws_vcol % p_ts) + total) / p_ts; /* number of tabs */
374 if (i)
375 j = ((ws_vcol % p_ts) + total) % p_ts; /* number of spp */
376 else
377 j = total;
378 /* if we're splitting a TAB, allow for it */
379 bd.textcol -= bd.pre_whitesp_c - (bd.startspaces != 0);
380 const int len = (int)STRLEN(bd.textstart) + 1;
381 int col = bd.textcol + i +j + len;
382 assert(col >= 0);
383 newp = (char_u *)xmalloc((size_t)col);
384 memset(newp, NUL, (size_t)col);
385 memmove(newp, oldp, (size_t)bd.textcol);
386 memset(newp + bd.textcol, TAB, (size_t)i);
387 memset(newp + bd.textcol + i, ' ', (size_t)j);
388 /* the end */
389 memmove(newp + bd.textcol + i + j, bd.textstart, (size_t)len);
390 } else { // left
391 colnr_T destination_col; // column to which text in block will
392 // be shifted
393 char_u *verbatim_copy_end; // end of the part of the line which is
394 // copied verbatim
395 colnr_T verbatim_copy_width; // the (displayed) width of this part
396 // of line
397 size_t fill; // nr of spaces that replace a TAB
398 size_t new_line_len; // the length of the line after the
399 // block shift
400 char_u *non_white = bd.textstart;
401
402 /*
403 * Firstly, let's find the first non-whitespace character that is
404 * displayed after the block's start column and the character's column
405 * number. Also, let's calculate the width of all the whitespace
406 * characters that are displayed in the block and precede the searched
407 * non-whitespace character.
408 */
409
410 /* If "bd.startspaces" is set, "bd.textstart" points to the character,
411 * the part of which is displayed at the block's beginning. Let's start
412 * searching from the next character. */
413 if (bd.startspaces) {
414 MB_PTR_ADV(non_white);
415 }
416
417 // The character's column is in "bd.start_vcol".
418 colnr_T non_white_col = bd.start_vcol;
419
420 while (ascii_iswhite(*non_white)) {
421 incr = lbr_chartabsize_adv(bd.textstart, &non_white, non_white_col);
422 non_white_col += incr;
423 }
424
425
426 const colnr_T block_space_width = non_white_col - oap->start_vcol;
427 // We will shift by "total" or "block_space_width", whichever is less.
428 const colnr_T shift_amount = block_space_width < total
429 ? block_space_width
430 : total;
431 // The column to which we will shift the text.
432 destination_col = non_white_col - shift_amount;
433
434 /* Now let's find out how much of the beginning of the line we can
435 * reuse without modification. */
436 verbatim_copy_end = bd.textstart;
437 verbatim_copy_width = bd.start_vcol;
438
439 /* If "bd.startspaces" is set, "bd.textstart" points to the character
440 * preceding the block. We have to subtract its width to obtain its
441 * column number. */
442 if (bd.startspaces)
443 verbatim_copy_width -= bd.start_char_vcols;
444 while (verbatim_copy_width < destination_col) {
445 char_u *line = verbatim_copy_end;
446
447 // TODO: is passing verbatim_copy_end for start of the line OK?
448 incr = lbr_chartabsize(line, verbatim_copy_end, verbatim_copy_width);
449 if (verbatim_copy_width + incr > destination_col)
450 break;
451 verbatim_copy_width += incr;
452 MB_PTR_ADV(verbatim_copy_end);
453 }
454
455 /* If "destination_col" is different from the width of the initial
456 * part of the line that will be copied, it means we encountered a tab
457 * character, which we will have to partly replace with spaces. */
458 assert(destination_col - verbatim_copy_width >= 0);
459 fill = (size_t)(destination_col - verbatim_copy_width);
460
461 assert(verbatim_copy_end - oldp >= 0);
462 const size_t verbatim_diff = (size_t)(verbatim_copy_end - oldp);
463 // The replacement line will consist of:
464 // - the beginning of the original line up to "verbatim_copy_end",
465 // - "fill" number of spaces,
466 // - the rest of the line, pointed to by non_white.
467 new_line_len = verbatim_diff + fill + STRLEN(non_white) + 1;
468
469 newp = (char_u *) xmalloc(new_line_len);
470 memmove(newp, oldp, verbatim_diff);
471 memset(newp + verbatim_diff, ' ', fill);
472 STRMOVE(newp + verbatim_diff + fill, non_white);
473 }
474 // replace the line
475 ml_replace(curwin->w_cursor.lnum, newp, false);
476 changed_bytes(curwin->w_cursor.lnum, (colnr_T)bd.textcol);
477 State = oldstate;
478 curwin->w_cursor.col = oldcol;
479 p_ri = old_p_ri;
480}
481
482/*
483 * Insert string "s" (b_insert ? before : after) block :AKelly
484 * Caller must prepare for undo.
485 */
486static void block_insert(oparg_T *oap, char_u *s, int b_insert, struct block_def *bdp)
487{
488 int p_ts;
489 int count = 0; // extra spaces to replace a cut TAB
490 int spaces = 0; // non-zero if cutting a TAB
491 colnr_T offset; // pointer along new line
492 size_t s_len = STRLEN(s);
493 char_u *newp, *oldp; // new, old lines
494 linenr_T lnum; // loop var
495 int oldstate = State;
496 State = INSERT; // don't want REPLACE for State
497
498 for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++) {
499 block_prep(oap, bdp, lnum, true);
500 if (bdp->is_short && b_insert) {
501 continue; // OP_INSERT, line ends before block start
502 }
503
504 oldp = ml_get(lnum);
505
506 if (b_insert) {
507 p_ts = bdp->start_char_vcols;
508 spaces = bdp->startspaces;
509 if (spaces != 0)
510 count = p_ts - 1; /* we're cutting a TAB */
511 offset = bdp->textcol;
512 } else { /* append */
513 p_ts = bdp->end_char_vcols;
514 if (!bdp->is_short) { /* spaces = padding after block */
515 spaces = (bdp->endspaces ? p_ts - bdp->endspaces : 0);
516 if (spaces != 0)
517 count = p_ts - 1; /* we're cutting a TAB */
518 offset = bdp->textcol + bdp->textlen - (spaces != 0);
519 } else { /* spaces = padding to block edge */
520 /* if $ used, just append to EOL (ie spaces==0) */
521 if (!bdp->is_MAX)
522 spaces = (oap->end_vcol - bdp->end_vcol) + 1;
523 count = spaces;
524 offset = bdp->textcol + bdp->textlen;
525 }
526 }
527
528 if (spaces > 0) {
529 int off;
530
531 // Avoid starting halfway through a multi-byte character.
532 if (b_insert) {
533 off = utf_head_off(oldp, oldp + offset + spaces);
534 } else {
535 off = (*mb_off_next)(oldp, oldp + offset);
536 offset += off;
537 }
538 spaces -= off;
539 count -= off;
540 }
541
542 assert(count >= 0);
543 newp = (char_u *)xmalloc(STRLEN(oldp) + s_len + (size_t)count + 1);
544
545 // copy up to shifted part
546 memmove(newp, oldp, (size_t)offset);
547 oldp += offset;
548
549 // insert pre-padding
550 memset(newp + offset, ' ', (size_t)spaces);
551
552 // copy the new text
553 memmove(newp + offset + spaces, s, s_len);
554 offset += (int)s_len;
555
556 if (spaces && !bdp->is_short) {
557 // insert post-padding
558 memset(newp + offset + spaces, ' ', (size_t)(p_ts - spaces));
559 // We're splitting a TAB, don't copy it.
560 oldp++;
561 // We allowed for that TAB, remember this now
562 count++;
563 }
564
565 if (spaces > 0)
566 offset += count;
567 STRMOVE(newp + offset, oldp);
568
569 ml_replace(lnum, newp, false);
570
571 if (lnum == oap->end.lnum) {
572 /* Set "']" mark to the end of the block instead of the end of
573 * the insert in the first line. */
574 curbuf->b_op_end.lnum = oap->end.lnum;
575 curbuf->b_op_end.col = offset;
576 }
577 } /* for all lnum */
578
579 changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L, true);
580
581 State = oldstate;
582}
583
584/*
585 * op_reindent - handle reindenting a block of lines.
586 */
587void op_reindent(oparg_T *oap, Indenter how)
588{
589 long i;
590 char_u *l;
591 int amount;
592 linenr_T first_changed = 0;
593 linenr_T last_changed = 0;
594 linenr_T start_lnum = curwin->w_cursor.lnum;
595
596 /* Don't even try when 'modifiable' is off. */
597 if (!MODIFIABLE(curbuf)) {
598 EMSG(_(e_modifiable));
599 return;
600 }
601
602 for (i = oap->line_count - 1; i >= 0 && !got_int; i--) {
603 /* it's a slow thing to do, so give feedback so there's no worry that
604 * the computer's just hung. */
605
606 if (i > 1
607 && (i % 50 == 0 || i == oap->line_count - 1)
608 && oap->line_count > p_report)
609 smsg(_("%" PRId64 " lines to indent... "), (int64_t)i);
610
611 /*
612 * Be vi-compatible: For lisp indenting the first line is not
613 * indented, unless there is only one line.
614 */
615 if (i != oap->line_count - 1 || oap->line_count == 1
616 || how != get_lisp_indent) {
617 l = skipwhite(get_cursor_line_ptr());
618 if (*l == NUL) /* empty or blank line */
619 amount = 0;
620 else
621 amount = how(); /* get the indent for this line */
622
623 if (amount >= 0 && set_indent(amount, SIN_UNDO)) {
624 /* did change the indent, call changed_lines() later */
625 if (first_changed == 0)
626 first_changed = curwin->w_cursor.lnum;
627 last_changed = curwin->w_cursor.lnum;
628 }
629 }
630 ++curwin->w_cursor.lnum;
631 curwin->w_cursor.col = 0; /* make sure it's valid */
632 }
633
634 /* put cursor on first non-blank of indented line */
635 curwin->w_cursor.lnum = start_lnum;
636 beginline(BL_SOL | BL_FIX);
637
638 /* Mark changed lines so that they will be redrawn. When Visual
639 * highlighting was present, need to continue until the last line. When
640 * there is no change still need to remove the Visual highlighting. */
641 if (last_changed != 0) {
642 changed_lines(first_changed, 0,
643 oap->is_VIsual ? start_lnum + oap->line_count :
644 last_changed + 1, 0L, true);
645 } else if (oap->is_VIsual) {
646 redraw_curbuf_later(INVERTED);
647 }
648
649 if (oap->line_count > p_report) {
650 i = oap->line_count - (i + 1);
651 if (i == 1)
652 MSG(_("1 line indented "));
653 else
654 smsg(_("%" PRId64 " lines indented "), (int64_t)i);
655 }
656 /* set '[ and '] marks */
657 curbuf->b_op_start = oap->start;
658 curbuf->b_op_end = oap->end;
659}
660
661/*
662 * Keep the last expression line here, for repeating.
663 */
664static char_u *expr_line = NULL;
665
666/*
667 * Get an expression for the "\"=expr1" or "CTRL-R =expr1"
668 * Returns '=' when OK, NUL otherwise.
669 */
670int get_expr_register(void)
671{
672 char_u *new_line;
673
674 new_line = getcmdline('=', 0L, 0);
675 if (new_line == NULL)
676 return NUL;
677 if (*new_line == NUL) /* use previous line */
678 xfree(new_line);
679 else
680 set_expr_line(new_line);
681 return '=';
682}
683
684/*
685 * Set the expression for the '=' register.
686 * Argument must be an allocated string.
687 */
688void set_expr_line(char_u *new_line)
689{
690 xfree(expr_line);
691 expr_line = new_line;
692}
693
694/*
695 * Get the result of the '=' register expression.
696 * Returns a pointer to allocated memory, or NULL for failure.
697 */
698char_u *get_expr_line(void)
699{
700 char_u *expr_copy;
701 char_u *rv;
702 static int nested = 0;
703
704 if (expr_line == NULL)
705 return NULL;
706
707 /* Make a copy of the expression, because evaluating it may cause it to be
708 * changed. */
709 expr_copy = vim_strsave(expr_line);
710
711 /* When we are invoked recursively limit the evaluation to 10 levels.
712 * Then return the string as-is. */
713 if (nested >= 10)
714 return expr_copy;
715
716 ++nested;
717 rv = eval_to_string(expr_copy, NULL, TRUE);
718 --nested;
719 xfree(expr_copy);
720 return rv;
721}
722
723/*
724 * Get the '=' register expression itself, without evaluating it.
725 */
726char_u *get_expr_line_src(void)
727{
728 if (expr_line == NULL)
729 return NULL;
730 return vim_strsave(expr_line);
731}
732
733/// Returns whether `regname` is a valid name of a yank register.
734/// Note: There is no check for 0 (default register), caller should do this.
735/// The black hole register '_' is regarded as valid.
736///
737/// @param regname name of register
738/// @param writing allow only writable registers
739bool valid_yank_reg(int regname, bool writing)
740{
741 if ((regname > 0 && ASCII_ISALNUM(regname))
742 || (!writing && vim_strchr((char_u *) "/.%:=" , regname) != NULL)
743 || regname == '#'
744 || regname == '"'
745 || regname == '-'
746 || regname == '_'
747 || regname == '*'
748 || regname == '+') {
749 return true;
750 }
751 return false;
752}
753
754typedef enum {
755 YREG_PASTE,
756 YREG_YANK,
757 YREG_PUT,
758} yreg_mode_t;
759
760/// Return yankreg_T to use, according to the value of `regname`.
761/// Cannot handle the '_' (black hole) register.
762/// Must only be called with a valid register name!
763///
764/// @param regname The name of the register used or 0 for the unnamed register
765/// @param mode One of the following three flags:
766///
767/// `YREG_PASTE`:
768/// Prepare for pasting the register `regname`. With no regname specified,
769/// read from last written register, or from unnamed clipboard (depending on the
770/// `clipboard=unnamed` option). Queries the clipboard provider if necessary.
771///
772/// `YREG_YANK`:
773/// Preparare for yanking into `regname`. With no regname specified,
774/// yank into `"0` register. Update `y_previous` for next unnamed paste.
775///
776/// `YREG_PUT`:
777/// Obtain the location that would be read when pasting `regname`.
778yankreg_T *get_yank_register(int regname, int mode)
779{
780 yankreg_T *reg;
781
782 if (mode == YREG_PASTE && get_clipboard(regname, &reg, false)) {
783 // reg is set to clipboard contents.
784 return reg;
785 } else if (mode != YREG_YANK
786 && (regname == 0 || regname == '"' || regname == '*' || regname == '+')
787 && y_previous != NULL) {
788 // in case clipboard not available, paste from previous used register
789 return y_previous;
790 }
791
792 int i = op_reg_index(regname);
793 // when not 0-9, a-z, A-Z or '-'/'+'/'*': use register 0
794 if (i == -1) {
795 i = 0;
796 }
797 reg = &y_regs[i];
798
799 if (mode == YREG_YANK) {
800 // remember the written register for unnamed paste
801 y_previous = reg;
802 }
803 return reg;
804}
805
806static bool is_append_register(int regname)
807{
808 return ASCII_ISUPPER(regname);
809}
810
811/// Returns a copy of contents in register `name`
812/// for use in do_put. Should be freed by caller.
813yankreg_T *copy_register(int name)
814 FUNC_ATTR_NONNULL_RET
815{
816 yankreg_T *reg = get_yank_register(name, YREG_PASTE);
817
818 yankreg_T *copy = xmalloc(sizeof(yankreg_T));
819 *copy = *reg;
820 if (copy->y_size == 0) {
821 copy->y_array = NULL;
822 } else {
823 copy->y_array = xcalloc(copy->y_size, sizeof(char_u *));
824 for (size_t i = 0; i < copy->y_size; i++) {
825 copy->y_array[i] = vim_strsave(reg->y_array[i]);
826 }
827 }
828 return copy;
829}
830
831/// check if the current yank register has kMTLineWise register type
832bool yank_register_mline(int regname)
833{
834 if (regname != 0 && !valid_yank_reg(regname, false)) {
835 return false;
836 }
837 if (regname == '_') { // black hole is always empty
838 return false;
839 }
840 yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
841 return reg->y_type == kMTLineWise;
842}
843
844/*
845 * Start or stop recording into a yank register.
846 *
847 * Return FAIL for failure, OK otherwise.
848 */
849int do_record(int c)
850{
851 char_u *p;
852 static int regname;
853 yankreg_T *old_y_previous;
854 int retval;
855
856 if (reg_recording == 0) {
857 // start recording
858 // registers 0-9, a-z and " are allowed
859 if (c < 0 || (!ASCII_ISALNUM(c) && c != '"')) {
860 retval = FAIL;
861 } else {
862 reg_recording = c;
863 showmode();
864 regname = c;
865 retval = OK;
866 }
867 } else { /* stop recording */
868 /*
869 * Get the recorded key hits. K_SPECIAL and CSI will be escaped, this
870 * needs to be removed again to put it in a register. exec_reg then
871 * adds the escaping back later.
872 */
873 reg_recording = 0;
874 if (ui_has(kUIMessages)) {
875 showmode();
876 } else {
877 MSG("");
878 }
879 p = get_recorded();
880 if (p == NULL)
881 retval = FAIL;
882 else {
883 /* Remove escaping for CSI and K_SPECIAL in multi-byte chars. */
884 vim_unescape_csi(p);
885
886 /*
887 * We don't want to change the default register here, so save and
888 * restore the current register name.
889 */
890 old_y_previous = y_previous;
891
892 retval = stuff_yank(regname, p);
893
894 y_previous = old_y_previous;
895 }
896 }
897 return retval;
898}
899
900static void set_yreg_additional_data(yankreg_T *reg, dict_T *additional_data)
901 FUNC_ATTR_NONNULL_ARG(1)
902{
903 if (reg->additional_data == additional_data) {
904 return;
905 }
906 tv_dict_unref(reg->additional_data);
907 reg->additional_data = additional_data;
908}
909
910/*
911 * Stuff string "p" into yank register "regname" as a single line (append if
912 * uppercase). "p" must have been alloced.
913 *
914 * return FAIL for failure, OK otherwise
915 */
916static int stuff_yank(int regname, char_u *p)
917{
918 /* check for read-only register */
919 if (regname != 0 && !valid_yank_reg(regname, true)) {
920 xfree(p);
921 return FAIL;
922 }
923 if (regname == '_') { /* black hole: don't do anything */
924 xfree(p);
925 return OK;
926 }
927 yankreg_T *reg = get_yank_register(regname, YREG_YANK);
928 if (is_append_register(regname) && reg->y_array != NULL) {
929 char_u **pp = &(reg->y_array[reg->y_size - 1]);
930 char_u *lp = xmalloc(STRLEN(*pp) + STRLEN(p) + 1);
931 STRCPY(lp, *pp);
932 // TODO(philix): use xstpcpy() in stuff_yank()
933 STRCAT(lp, p);
934 xfree(p);
935 xfree(*pp);
936 *pp = lp;
937 } else {
938 free_register(reg);
939 set_yreg_additional_data(reg, NULL);
940 reg->y_array = (char_u **)xmalloc(sizeof(char_u *));
941 reg->y_array[0] = p;
942 reg->y_size = 1;
943 reg->y_type = kMTCharWise;
944 }
945 reg->timestamp = os_time();
946 return OK;
947}
948
949static int execreg_lastc = NUL;
950
951/// Execute a yank register: copy it into the stuff buffer
952///
953/// Return FAIL for failure, OK otherwise
954int
955do_execreg(
956 int regname,
957 int colon, /* insert ':' before each line */
958 int addcr, /* always add '\n' to end of line */
959 int silent /* set "silent" flag in typeahead buffer */
960)
961{
962 char_u *p;
963 int retval = OK;
964
965 if (regname == '@') { /* repeat previous one */
966 if (execreg_lastc == NUL) {
967 EMSG(_("E748: No previously used register"));
968 return FAIL;
969 }
970 regname = execreg_lastc;
971 }
972 /* check for valid regname */
973 if (regname == '%' || regname == '#' || !valid_yank_reg(regname, false)) {
974 emsg_invreg(regname);
975 return FAIL;
976 }
977 execreg_lastc = regname;
978
979 if (regname == '_') /* black hole: don't stuff anything */
980 return OK;
981
982 if (regname == ':') { /* use last command line */
983 if (last_cmdline == NULL) {
984 EMSG(_(e_nolastcmd));
985 return FAIL;
986 }
987 // don't keep the cmdline containing @:
988 XFREE_CLEAR(new_last_cmdline);
989 // Escape all control characters with a CTRL-V
990 p = vim_strsave_escaped_ext(
991 last_cmdline,
992 (char_u *)"\001\002\003\004\005\006\007"
993 "\010\011\012\013\014\015\016\017"
994 "\020\021\022\023\024\025\026\027"
995 "\030\031\032\033\034\035\036\037",
996 Ctrl_V, false);
997 // When in Visual mode "'<,'>" will be prepended to the command.
998 // Remove it when it's already there.
999 if (VIsual_active && STRNCMP(p, "'<,'>", 5) == 0) {
1000 retval = put_in_typebuf(p + 5, true, true, silent);
1001 } else {
1002 retval = put_in_typebuf(p, true, true, silent);
1003 }
1004 xfree(p);
1005 } else if (regname == '=') {
1006 p = get_expr_line();
1007 if (p == NULL)
1008 return FAIL;
1009 retval = put_in_typebuf(p, true, colon, silent);
1010 xfree(p);
1011 } else if (regname == '.') { /* use last inserted text */
1012 p = get_last_insert_save();
1013 if (p == NULL) {
1014 EMSG(_(e_noinstext));
1015 return FAIL;
1016 }
1017 retval = put_in_typebuf(p, false, colon, silent);
1018 xfree(p);
1019 } else {
1020 yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
1021 if (reg->y_array == NULL)
1022 return FAIL;
1023
1024 // Disallow remaping for ":@r".
1025 int remap = colon ? REMAP_NONE : REMAP_YES;
1026
1027 /*
1028 * Insert lines into typeahead buffer, from last one to first one.
1029 */
1030 put_reedit_in_typebuf(silent);
1031 char_u *escaped;
1032 for (size_t i = reg->y_size; i-- > 0;) { // from y_size - 1 to 0 included
1033 // insert NL between lines and after last line if type is kMTLineWise
1034 if (reg->y_type == kMTLineWise || i < reg->y_size - 1 || addcr) {
1035 if (ins_typebuf((char_u *)"\n", remap, 0, true, silent) == FAIL) {
1036 return FAIL;
1037 }
1038 }
1039 escaped = vim_strsave_escape_csi(reg->y_array[i]);
1040 retval = ins_typebuf(escaped, remap, 0, TRUE, silent);
1041 xfree(escaped);
1042 if (retval == FAIL)
1043 return FAIL;
1044 if (colon && ins_typebuf((char_u *)":", remap, 0, TRUE, silent)
1045 == FAIL)
1046 return FAIL;
1047 }
1048 reg_executing = regname == 0 ? '"' : regname; // disable the 'q' command
1049 }
1050 return retval;
1051}
1052
1053/*
1054 * If "restart_edit" is not zero, put it in the typeahead buffer, so that it's
1055 * used only after other typeahead has been processed.
1056 */
1057static void put_reedit_in_typebuf(int silent)
1058{
1059 char_u buf[3];
1060
1061 if (restart_edit != NUL) {
1062 if (restart_edit == 'V') {
1063 buf[0] = 'g';
1064 buf[1] = 'R';
1065 buf[2] = NUL;
1066 } else {
1067 buf[0] = (char_u)(restart_edit == 'I' ? 'i' : restart_edit);
1068 buf[1] = NUL;
1069 }
1070 if (ins_typebuf(buf, REMAP_NONE, 0, TRUE, silent) == OK)
1071 restart_edit = NUL;
1072 }
1073}
1074
1075/*
1076 * Insert register contents "s" into the typeahead buffer, so that it will be
1077 * executed again.
1078 * When "esc" is TRUE it is to be taken literally: Escape CSI characters and
1079 * no remapping.
1080 */
1081static int put_in_typebuf(
1082 char_u *s,
1083 bool esc,
1084 bool colon, // add ':' before the line
1085 int silent
1086)
1087{
1088 int retval = OK;
1089
1090 put_reedit_in_typebuf(silent);
1091 if (colon)
1092 retval = ins_typebuf((char_u *)"\n", REMAP_NONE, 0, TRUE, silent);
1093 if (retval == OK) {
1094 char_u *p;
1095
1096 if (esc)
1097 p = vim_strsave_escape_csi(s);
1098 else
1099 p = s;
1100 if (p == NULL)
1101 retval = FAIL;
1102 else
1103 retval = ins_typebuf(p, esc ? REMAP_NONE : REMAP_YES,
1104 0, TRUE, silent);
1105 if (esc)
1106 xfree(p);
1107 }
1108 if (colon && retval == OK)
1109 retval = ins_typebuf((char_u *)":", REMAP_NONE, 0, TRUE, silent);
1110 return retval;
1111}
1112
1113/*
1114 * Insert a yank register: copy it into the Read buffer.
1115 * Used by CTRL-R command and middle mouse button in insert mode.
1116 *
1117 * return FAIL for failure, OK otherwise
1118 */
1119int insert_reg(
1120 int regname,
1121 int literally /* insert literally, not as if typed */
1122)
1123{
1124 int retval = OK;
1125 bool allocated;
1126
1127 /*
1128 * It is possible to get into an endless loop by having CTRL-R a in
1129 * register a and then, in insert mode, doing CTRL-R a.
1130 * If you hit CTRL-C, the loop will be broken here.
1131 */
1132 os_breakcheck();
1133 if (got_int)
1134 return FAIL;
1135
1136 /* check for valid regname */
1137 if (regname != NUL && !valid_yank_reg(regname, false))
1138 return FAIL;
1139
1140 char_u *arg;
1141 if (regname == '.') { // Insert last inserted text.
1142 retval = stuff_inserted(NUL, 1L, true);
1143 } else if (get_spec_reg(regname, &arg, &allocated, true)) {
1144 if (arg == NULL) {
1145 return FAIL;
1146 }
1147 stuffescaped((const char *)arg, literally);
1148 if (allocated) {
1149 xfree(arg);
1150 }
1151 } else { // Name or number register.
1152 yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
1153 if (reg->y_array == NULL) {
1154 retval = FAIL;
1155 } else {
1156 for (size_t i = 0; i < reg->y_size; i++) {
1157 stuffescaped((const char *)reg->y_array[i], literally);
1158 // Insert a newline between lines and after last line if
1159 // y_type is kMTLineWise.
1160 if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
1161 stuffcharReadbuff('\n');
1162 }
1163 }
1164 }
1165 }
1166
1167 return retval;
1168}
1169
1170/*
1171 * Stuff a string into the typeahead buffer, such that edit() will insert it
1172 * literally ("literally" TRUE) or interpret is as typed characters.
1173 */
1174static void stuffescaped(const char *arg, int literally)
1175{
1176 while (*arg != NUL) {
1177 // Stuff a sequence of normal ASCII characters, that's fast. Also
1178 // stuff K_SPECIAL to get the effect of a special key when "literally"
1179 // is TRUE.
1180 const char *const start = arg;
1181 while ((*arg >= ' ' && *arg < DEL) || ((uint8_t)(*arg) == K_SPECIAL
1182 && !literally)) {
1183 arg++;
1184 }
1185 if (arg > start) {
1186 stuffReadbuffLen(start, (long)(arg - start));
1187 }
1188
1189 /* stuff a single special character */
1190 if (*arg != NUL) {
1191 const int c = (has_mbyte
1192 ? mb_cptr2char_adv((const char_u **)&arg)
1193 : (uint8_t)(*arg++));
1194 if (literally && ((c < ' ' && c != TAB) || c == DEL)) {
1195 stuffcharReadbuff(Ctrl_V);
1196 }
1197 stuffcharReadbuff(c);
1198 }
1199 }
1200}
1201
1202// If "regname" is a special register, return true and store a pointer to its
1203// value in "argp".
1204bool get_spec_reg(
1205 int regname,
1206 char_u **argp,
1207 bool *allocated, // return: true when value was allocated
1208 bool errmsg // give error message when failing
1209)
1210{
1211 size_t cnt;
1212
1213 *argp = NULL;
1214 *allocated = false;
1215 switch (regname) {
1216 case '%': /* file name */
1217 if (errmsg)
1218 check_fname(); /* will give emsg if not set */
1219 *argp = curbuf->b_fname;
1220 return true;
1221
1222 case '#': // alternate file name
1223 *argp = getaltfname(errmsg); // may give emsg if not set
1224 return true;
1225
1226 case '=': /* result of expression */
1227 *argp = get_expr_line();
1228 *allocated = true;
1229 return true;
1230
1231 case ':': /* last command line */
1232 if (last_cmdline == NULL && errmsg)
1233 EMSG(_(e_nolastcmd));
1234 *argp = last_cmdline;
1235 return true;
1236
1237 case '/': /* last search-pattern */
1238 if (last_search_pat() == NULL && errmsg)
1239 EMSG(_(e_noprevre));
1240 *argp = last_search_pat();
1241 return true;
1242
1243 case '.': /* last inserted text */
1244 *argp = get_last_insert_save();
1245 *allocated = true;
1246 if (*argp == NULL && errmsg) {
1247 EMSG(_(e_noinstext));
1248 }
1249 return true;
1250
1251 case Ctrl_F: // Filename under cursor
1252 case Ctrl_P: // Path under cursor, expand via "path"
1253 if (!errmsg) {
1254 return false;
1255 }
1256 *argp = file_name_at_cursor(
1257 FNAME_MESS | FNAME_HYP | (regname == Ctrl_P ? FNAME_EXP : 0),
1258 1L, NULL);
1259 *allocated = true;
1260 return true;
1261
1262 case Ctrl_W: // word under cursor
1263 case Ctrl_A: // WORD (mnemonic All) under cursor
1264 if (!errmsg) {
1265 return false;
1266 }
1267 cnt = find_ident_under_cursor(argp, (regname == Ctrl_W
1268 ? (FIND_IDENT|FIND_STRING)
1269 : FIND_STRING));
1270 *argp = cnt ? vim_strnsave(*argp, cnt) : NULL;
1271 *allocated = true;
1272 return true;
1273
1274 case Ctrl_L: // Line under cursor
1275 if (!errmsg) {
1276 return false;
1277 }
1278
1279 *argp = ml_get_buf(curwin->w_buffer, curwin->w_cursor.lnum, false);
1280 return true;
1281
1282 case '_': /* black hole: always empty */
1283 *argp = (char_u *)"";
1284 return true;
1285 }
1286
1287 return false;
1288}
1289
1290/// Paste a yank register into the command line.
1291/// Only for non-special registers.
1292/// Used by CTRL-R in command-line mode.
1293/// insert_reg() can't be used here, because special characters from the
1294/// register contents will be interpreted as commands.
1295///
1296/// @param regname Register name.
1297/// @param literally Insert text literally instead of "as typed".
1298/// @param remcr When true, don't add CR characters.
1299///
1300/// @returns FAIL for failure, OK otherwise
1301bool cmdline_paste_reg(int regname, bool literally, bool remcr)
1302{
1303 yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
1304 if (reg->y_array == NULL)
1305 return FAIL;
1306
1307 for (size_t i = 0; i < reg->y_size; i++) {
1308 cmdline_paste_str(reg->y_array[i], literally);
1309
1310 // Insert ^M between lines, unless `remcr` is true.
1311 if (i < reg->y_size - 1 && !remcr) {
1312 cmdline_paste_str((char_u *)"\r", literally);
1313 }
1314
1315 /* Check for CTRL-C, in case someone tries to paste a few thousand
1316 * lines and gets bored. */
1317 os_breakcheck();
1318 if (got_int)
1319 return FAIL;
1320 }
1321 return OK;
1322}
1323
1324// Shift the delete registers: "9 is cleared, "8 becomes "9, etc.
1325static void shift_delete_registers(bool y_append)
1326{
1327 free_register(&y_regs[9]); // free register "9
1328 for (int n = 9; n > 1; n--) {
1329 y_regs[n] = y_regs[n - 1];
1330 }
1331 if (!y_append) {
1332 y_previous = &y_regs[1];
1333 }
1334 y_regs[1].y_array = NULL; // set register "1 to empty
1335}
1336
1337/*
1338 * Handle a delete operation.
1339 *
1340 * Return FAIL if undo failed, OK otherwise.
1341 */
1342int op_delete(oparg_T *oap)
1343{
1344 int n;
1345 linenr_T lnum;
1346 char_u *ptr;
1347 char_u *newp, *oldp;
1348 struct block_def bd;
1349 linenr_T old_lcount = curbuf->b_ml.ml_line_count;
1350
1351 if (curbuf->b_ml.ml_flags & ML_EMPTY) { // nothing to do
1352 return OK;
1353 }
1354
1355 // Nothing to delete, return here. Do prepare undo, for op_change().
1356 if (oap->empty) {
1357 return u_save_cursor();
1358 }
1359
1360 if (!MODIFIABLE(curbuf)) {
1361 EMSG(_(e_modifiable));
1362 return FAIL;
1363 }
1364
1365 if (has_mbyte)
1366 mb_adjust_opend(oap);
1367
1368 /*
1369 * Imitate the strange Vi behaviour: If the delete spans more than one
1370 * line and motion_type == kMTCharWise and the result is a blank line, make the
1371 * delete linewise. Don't do this for the change command or Visual mode.
1372 */
1373 if (oap->motion_type == kMTCharWise
1374 && !oap->is_VIsual
1375 && oap->line_count > 1
1376 && oap->motion_force == NUL
1377 && oap->op_type == OP_DELETE) {
1378 ptr = ml_get(oap->end.lnum) + oap->end.col;
1379 if (*ptr != NUL)
1380 ptr += oap->inclusive;
1381 ptr = skipwhite(ptr);
1382 if (*ptr == NUL && inindent(0)) {
1383 oap->motion_type = kMTLineWise;
1384 }
1385 }
1386
1387 /*
1388 * Check for trying to delete (e.g. "D") in an empty line.
1389 * Note: For the change operator it is ok.
1390 */
1391 if (oap->motion_type != kMTLineWise
1392 && oap->line_count == 1
1393 && oap->op_type == OP_DELETE
1394 && *ml_get(oap->start.lnum) == NUL) {
1395 // It's an error to operate on an empty region, when 'E' included in
1396 // 'cpoptions' (Vi compatible).
1397 if (virtual_op) {
1398 // Virtual editing: Nothing gets deleted, but we set the '[ and ']
1399 // marks as if it happened.
1400 goto setmarks;
1401 }
1402 if (vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL) {
1403 beep_flush();
1404 }
1405 return OK;
1406 }
1407
1408 /*
1409 * Do a yank of whatever we're about to delete.
1410 * If a yank register was specified, put the deleted text into that
1411 * register. For the black hole register '_' don't yank anything.
1412 */
1413 if (oap->regname != '_') {
1414 yankreg_T *reg = NULL;
1415 int did_yank = false;
1416 if (oap->regname != 0) {
1417 // yank without message
1418 did_yank = op_yank(oap, false, true);
1419 if (!did_yank) {
1420 // op_yank failed, don't do anything
1421 return OK;
1422 }
1423 }
1424
1425 /*
1426 * Put deleted text into register 1 and shift number registers if the
1427 * delete contains a line break, or when a regname has been specified.
1428 */
1429 if (oap->regname != 0 || oap->motion_type == kMTLineWise
1430 || oap->line_count > 1 || oap->use_reg_one) {
1431 shift_delete_registers(is_append_register(oap->regname));
1432 reg = &y_regs[1];
1433 op_yank_reg(oap, false, reg, false);
1434 did_yank = true;
1435 }
1436
1437 /* Yank into small delete register when no named register specified
1438 * and the delete is within one line. */
1439 if (oap->regname == 0 && oap->motion_type != kMTLineWise
1440 && oap->line_count == 1) {
1441 reg = get_yank_register('-', YREG_YANK);
1442 op_yank_reg(oap, false, reg, false);
1443 did_yank = true;
1444 }
1445
1446 if (did_yank || oap->regname == 0) {
1447 if (reg == NULL) {
1448 abort();
1449 }
1450 set_clipboard(oap->regname, reg);
1451 do_autocmd_textyankpost(oap, reg);
1452 }
1453
1454 }
1455
1456 /*
1457 * block mode delete
1458 */
1459 if (oap->motion_type == kMTBlockWise) {
1460 if (u_save((linenr_T)(oap->start.lnum - 1),
1461 (linenr_T)(oap->end.lnum + 1)) == FAIL) {
1462 return FAIL;
1463 }
1464
1465 for (lnum = curwin->w_cursor.lnum; lnum <= oap->end.lnum; lnum++) {
1466 block_prep(oap, &bd, lnum, true);
1467 if (bd.textlen == 0) { // nothing to delete
1468 continue;
1469 }
1470
1471 /* Adjust cursor position for tab replaced by spaces and 'lbr'. */
1472 if (lnum == curwin->w_cursor.lnum) {
1473 curwin->w_cursor.col = bd.textcol + bd.startspaces;
1474 curwin->w_cursor.coladd = 0;
1475 }
1476
1477 // n == number of chars deleted
1478 // If we delete a TAB, it may be replaced by several characters.
1479 // Thus the number of characters may increase!
1480 n = bd.textlen - bd.startspaces - bd.endspaces;
1481 oldp = ml_get(lnum);
1482 newp = (char_u *)xmalloc(STRLEN(oldp) - (size_t)n + 1);
1483 // copy up to deleted part
1484 memmove(newp, oldp, (size_t)bd.textcol);
1485 // insert spaces
1486 memset(newp + bd.textcol, ' ', (size_t)bd.startspaces +
1487 (size_t)bd.endspaces);
1488 // copy the part after the deleted part
1489 oldp += bd.textcol + bd.textlen;
1490 STRMOVE(newp + bd.textcol + bd.startspaces + bd.endspaces, oldp);
1491 // replace the line
1492 ml_replace(lnum, newp, false);
1493 }
1494
1495 check_cursor_col();
1496 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1497 oap->end.lnum + 1, 0L, true);
1498 oap->line_count = 0; // no lines deleted
1499 } else if (oap->motion_type == kMTLineWise) {
1500 if (oap->op_type == OP_CHANGE) {
1501 /* Delete the lines except the first one. Temporarily move the
1502 * cursor to the next line. Save the current line number, if the
1503 * last line is deleted it may be changed.
1504 */
1505 if (oap->line_count > 1) {
1506 lnum = curwin->w_cursor.lnum;
1507 ++curwin->w_cursor.lnum;
1508 del_lines(oap->line_count - 1, TRUE);
1509 curwin->w_cursor.lnum = lnum;
1510 }
1511 if (u_save_cursor() == FAIL)
1512 return FAIL;
1513 if (curbuf->b_p_ai) { // don't delete indent
1514 beginline(BL_WHITE); // cursor on first non-white
1515 did_ai = true; // delete the indent when ESC hit
1516 ai_col = curwin->w_cursor.col;
1517 } else
1518 beginline(0); /* cursor in column 0 */
1519 truncate_line(FALSE); /* delete the rest of the line */
1520 /* leave cursor past last char in line */
1521 if (oap->line_count > 1)
1522 u_clearline(); /* "U" command not possible after "2cc" */
1523 } else {
1524 del_lines(oap->line_count, TRUE);
1525 beginline(BL_WHITE | BL_FIX);
1526 u_clearline(); /* "U" command not possible after "dd" */
1527 }
1528 } else {
1529 if (virtual_op) {
1530 int endcol = 0;
1531
1532 /* For virtualedit: break the tabs that are partly included. */
1533 if (gchar_pos(&oap->start) == '\t') {
1534 if (u_save_cursor() == FAIL) /* save first line for undo */
1535 return FAIL;
1536 if (oap->line_count == 1)
1537 endcol = getviscol2(oap->end.col, oap->end.coladd);
1538 coladvance_force(getviscol2(oap->start.col, oap->start.coladd));
1539 oap->start = curwin->w_cursor;
1540 if (oap->line_count == 1) {
1541 coladvance(endcol);
1542 oap->end.col = curwin->w_cursor.col;
1543 oap->end.coladd = curwin->w_cursor.coladd;
1544 curwin->w_cursor = oap->start;
1545 }
1546 }
1547
1548 /* Break a tab only when it's included in the area. */
1549 if (gchar_pos(&oap->end) == '\t'
1550 && oap->end.coladd == 0
1551 && oap->inclusive) {
1552 /* save last line for undo */
1553 if (u_save((linenr_T)(oap->end.lnum - 1),
1554 (linenr_T)(oap->end.lnum + 1)) == FAIL)
1555 return FAIL;
1556 curwin->w_cursor = oap->end;
1557 coladvance_force(getviscol2(oap->end.col, oap->end.coladd));
1558 oap->end = curwin->w_cursor;
1559 curwin->w_cursor = oap->start;
1560 }
1561 }
1562
1563 if (oap->line_count == 1) { /* delete characters within one line */
1564 if (u_save_cursor() == FAIL) /* save line for undo */
1565 return FAIL;
1566
1567 /* if 'cpoptions' contains '$', display '$' at end of change */
1568 if ( vim_strchr(p_cpo, CPO_DOLLAR) != NULL
1569 && oap->op_type == OP_CHANGE
1570 && oap->end.lnum == curwin->w_cursor.lnum
1571 && !oap->is_VIsual
1572 )
1573 display_dollar(oap->end.col - !oap->inclusive);
1574
1575 n = oap->end.col - oap->start.col + 1 - !oap->inclusive;
1576
1577 if (virtual_op) {
1578 /* fix up things for virtualedit-delete:
1579 * break the tabs which are going to get in our way
1580 */
1581 char_u *curline = get_cursor_line_ptr();
1582 int len = (int)STRLEN(curline);
1583
1584 if (oap->end.coladd != 0
1585 && (int)oap->end.col >= len - 1
1586 && !(oap->start.coladd && (int)oap->end.col >= len - 1))
1587 n++;
1588 /* Delete at least one char (e.g, when on a control char). */
1589 if (n == 0 && oap->start.coladd != oap->end.coladd)
1590 n = 1;
1591
1592 /* When deleted a char in the line, reset coladd. */
1593 if (gchar_cursor() != NUL)
1594 curwin->w_cursor.coladd = 0;
1595 }
1596
1597 (void)del_bytes((colnr_T)n, !virtual_op,
1598 oap->op_type == OP_DELETE && !oap->is_VIsual);
1599 } else {
1600 // delete characters between lines
1601 pos_T curpos;
1602
1603 /* save deleted and changed lines for undo */
1604 if (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
1605 (linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL)
1606 return FAIL;
1607
1608 truncate_line(true); // delete from cursor to end of line
1609
1610 curpos = curwin->w_cursor; // remember curwin->w_cursor
1611 curwin->w_cursor.lnum++;
1612 del_lines(oap->line_count - 2, false);
1613
1614 // delete from start of line until op_end
1615 n = (oap->end.col + 1 - !oap->inclusive);
1616 curwin->w_cursor.col = 0;
1617 (void)del_bytes((colnr_T)n, !virtual_op,
1618 oap->op_type == OP_DELETE && !oap->is_VIsual);
1619 curwin->w_cursor = curpos; // restore curwin->w_cursor
1620 (void)do_join(2, false, false, false, false);
1621 }
1622 }
1623
1624 msgmore(curbuf->b_ml.ml_line_count - old_lcount);
1625
1626setmarks:
1627 if (oap->motion_type == kMTBlockWise) {
1628 curbuf->b_op_end.lnum = oap->end.lnum;
1629 curbuf->b_op_end.col = oap->start.col;
1630 } else
1631 curbuf->b_op_end = oap->start;
1632 curbuf->b_op_start = oap->start;
1633
1634 return OK;
1635}
1636
1637/*
1638 * Adjust end of operating area for ending on a multi-byte character.
1639 * Used for deletion.
1640 */
1641static void mb_adjust_opend(oparg_T *oap)
1642{
1643 char_u *p;
1644
1645 if (oap->inclusive) {
1646 p = ml_get(oap->end.lnum);
1647 oap->end.col += mb_tail_off(p, p + oap->end.col);
1648 }
1649}
1650
1651/*
1652 * Put character 'c' at position 'lp'
1653 */
1654static inline void pbyte(pos_T lp, int c)
1655{
1656 assert(c <= UCHAR_MAX);
1657 *(ml_get_buf(curbuf, lp.lnum, true) + lp.col) = (char_u)c;
1658}
1659
1660// Replace the character under the cursor with "c".
1661// This takes care of multi-byte characters.
1662static void replace_character(int c)
1663{
1664 const int n = State;
1665
1666 State = REPLACE;
1667 ins_char(c);
1668 State = n;
1669 // Backup to the replaced character.
1670 dec_cursor();
1671}
1672
1673/*
1674 * Replace a whole area with one character.
1675 */
1676int op_replace(oparg_T *oap, int c)
1677{
1678 int n, numc;
1679 int num_chars;
1680 char_u *newp, *oldp;
1681 colnr_T oldlen;
1682 struct block_def bd;
1683 char_u *after_p = NULL;
1684 int had_ctrl_v_cr = false;
1685
1686 if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty)
1687 return OK; /* nothing to do */
1688
1689 if (c == REPLACE_CR_NCHAR) {
1690 had_ctrl_v_cr = true;
1691 c = CAR;
1692 } else if (c == REPLACE_NL_NCHAR) {
1693 had_ctrl_v_cr = true;
1694 c = NL;
1695 }
1696
1697 if (has_mbyte)
1698 mb_adjust_opend(oap);
1699
1700 if (u_save((linenr_T)(oap->start.lnum - 1),
1701 (linenr_T)(oap->end.lnum + 1)) == FAIL)
1702 return FAIL;
1703
1704 /*
1705 * block mode replace
1706 */
1707 if (oap->motion_type == kMTBlockWise) {
1708 bd.is_MAX = (curwin->w_curswant == MAXCOL);
1709 for (; curwin->w_cursor.lnum <= oap->end.lnum; curwin->w_cursor.lnum++) {
1710 curwin->w_cursor.col = 0; // make sure cursor position is valid
1711 block_prep(oap, &bd, curwin->w_cursor.lnum, true);
1712 if (bd.textlen == 0 && (!virtual_op || bd.is_MAX)) {
1713 continue; // nothing to replace
1714 }
1715
1716 /* n == number of extra chars required
1717 * If we split a TAB, it may be replaced by several characters.
1718 * Thus the number of characters may increase!
1719 */
1720 /* If the range starts in virtual space, count the initial
1721 * coladd offset as part of "startspaces" */
1722 if (virtual_op && bd.is_short && *bd.textstart == NUL) {
1723 pos_T vpos;
1724
1725 vpos.lnum = curwin->w_cursor.lnum;
1726 getvpos(&vpos, oap->start_vcol);
1727 bd.startspaces += vpos.coladd;
1728 n = bd.startspaces;
1729 } else
1730 /* allow for pre spaces */
1731 n = (bd.startspaces ? bd.start_char_vcols - 1 : 0);
1732
1733 /* allow for post spp */
1734 n += (bd.endspaces
1735 && !bd.is_oneChar
1736 && bd.end_char_vcols > 0) ? bd.end_char_vcols - 1 : 0;
1737 /* Figure out how many characters to replace. */
1738 numc = oap->end_vcol - oap->start_vcol + 1;
1739 if (bd.is_short && (!virtual_op || bd.is_MAX))
1740 numc -= (oap->end_vcol - bd.end_vcol) + 1;
1741
1742 /* A double-wide character can be replaced only up to half the
1743 * times. */
1744 if ((*mb_char2cells)(c) > 1) {
1745 if ((numc & 1) && !bd.is_short) {
1746 ++bd.endspaces;
1747 ++n;
1748 }
1749 numc = numc / 2;
1750 }
1751
1752 /* Compute bytes needed, move character count to num_chars. */
1753 num_chars = numc;
1754 numc *= (*mb_char2len)(c);
1755
1756 oldp = get_cursor_line_ptr();
1757 oldlen = (int)STRLEN(oldp);
1758
1759 size_t newp_size = (size_t)bd.textcol + (size_t)bd.startspaces;
1760 if (had_ctrl_v_cr || (c != '\r' && c != '\n')) {
1761 newp_size += (size_t)numc;
1762 if (!bd.is_short) {
1763 newp_size += (size_t)(bd.endspaces + oldlen
1764 - bd.textcol - bd.textlen);
1765 }
1766 }
1767 newp = xmallocz(newp_size);
1768 // copy up to deleted part
1769 memmove(newp, oldp, (size_t)bd.textcol);
1770 oldp += bd.textcol + bd.textlen;
1771 // insert pre-spaces
1772 memset(newp + bd.textcol, ' ', (size_t)bd.startspaces);
1773 // insert replacement chars CHECK FOR ALLOCATED SPACE
1774 // REPLACE_CR_NCHAR/REPLACE_NL_NCHAR is used for entering CR literally.
1775 size_t after_p_len = 0;
1776 int col = oldlen - bd.textcol - bd.textlen + 1;
1777 assert(col >= 0);
1778 if (had_ctrl_v_cr || (c != '\r' && c != '\n')) {
1779 // strlen(newp) at this point
1780 int newp_len = bd.textcol + bd.startspaces;
1781 while (--num_chars >= 0) {
1782 newp_len += utf_char2bytes(c, newp + newp_len);
1783 }
1784 if (!bd.is_short) {
1785 // insert post-spaces
1786 memset(newp + newp_len, ' ', (size_t)bd.endspaces);
1787 newp_len += bd.endspaces;
1788 // copy the part after the changed part
1789 memmove(newp + newp_len, oldp, (size_t)col);
1790 }
1791 } else {
1792 // Replacing with \r or \n means splitting the line.
1793 after_p_len = (size_t)col;
1794 after_p = (char_u *)xmalloc(after_p_len);
1795 memmove(after_p, oldp, after_p_len);
1796 }
1797 // replace the line
1798 ml_replace(curwin->w_cursor.lnum, newp, false);
1799 if (after_p != NULL) {
1800 ml_append(curwin->w_cursor.lnum++, after_p, (int)after_p_len, false);
1801 appended_lines_mark(curwin->w_cursor.lnum, 1L);
1802 oap->end.lnum++;
1803 xfree(after_p);
1804 }
1805 }
1806 } else {
1807 // Characterwise or linewise motion replace.
1808 if (oap->motion_type == kMTLineWise) {
1809 oap->start.col = 0;
1810 curwin->w_cursor.col = 0;
1811 oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
1812 if (oap->end.col)
1813 --oap->end.col;
1814 } else if (!oap->inclusive)
1815 dec(&(oap->end));
1816
1817 while (ltoreq(curwin->w_cursor, oap->end)) {
1818 n = gchar_cursor();
1819 if (n != NUL) {
1820 if ((*mb_char2len)(c) > 1 || (*mb_char2len)(n) > 1) {
1821 /* This is slow, but it handles replacing a single-byte
1822 * with a multi-byte and the other way around. */
1823 if (curwin->w_cursor.lnum == oap->end.lnum)
1824 oap->end.col += (*mb_char2len)(c) - (*mb_char2len)(n);
1825 replace_character(c);
1826 } else {
1827 if (n == TAB) {
1828 int end_vcol = 0;
1829
1830 if (curwin->w_cursor.lnum == oap->end.lnum) {
1831 /* oap->end has to be recalculated when
1832 * the tab breaks */
1833 end_vcol = getviscol2(oap->end.col,
1834 oap->end.coladd);
1835 }
1836 coladvance_force(getviscol());
1837 if (curwin->w_cursor.lnum == oap->end.lnum)
1838 getvpos(&oap->end, end_vcol);
1839 }
1840 pbyte(curwin->w_cursor, c);
1841 }
1842 } else if (virtual_op && curwin->w_cursor.lnum == oap->end.lnum) {
1843 int virtcols = oap->end.coladd;
1844
1845 if (curwin->w_cursor.lnum == oap->start.lnum
1846 && oap->start.col == oap->end.col && oap->start.coladd)
1847 virtcols -= oap->start.coladd;
1848
1849 /* oap->end has been trimmed so it's effectively inclusive;
1850 * as a result an extra +1 must be counted so we don't
1851 * trample the NUL byte. */
1852 coladvance_force(getviscol2(oap->end.col, oap->end.coladd) + 1);
1853 curwin->w_cursor.col -= (virtcols + 1);
1854 for (; virtcols >= 0; virtcols--) {
1855 if (utf_char2len(c) > 1) {
1856 replace_character(c);
1857 } else {
1858 pbyte(curwin->w_cursor, c);
1859 }
1860 if (inc(&curwin->w_cursor) == -1) {
1861 break;
1862 }
1863 }
1864 }
1865
1866 /* Advance to next character, stop at the end of the file. */
1867 if (inc_cursor() == -1)
1868 break;
1869 }
1870 }
1871
1872 curwin->w_cursor = oap->start;
1873 check_cursor();
1874 changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L, true);
1875
1876 /* Set "'[" and "']" marks. */
1877 curbuf->b_op_start = oap->start;
1878 curbuf->b_op_end = oap->end;
1879
1880 return OK;
1881}
1882
1883
1884/*
1885 * Handle the (non-standard vi) tilde operator. Also for "gu", "gU" and "g?".
1886 */
1887void op_tilde(oparg_T *oap)
1888{
1889 pos_T pos;
1890 struct block_def bd;
1891 int did_change = FALSE;
1892
1893 if (u_save((linenr_T)(oap->start.lnum - 1),
1894 (linenr_T)(oap->end.lnum + 1)) == FAIL)
1895 return;
1896
1897 pos = oap->start;
1898 if (oap->motion_type == kMTBlockWise) { // Visual block mode
1899 for (; pos.lnum <= oap->end.lnum; pos.lnum++) {
1900 int one_change;
1901
1902 block_prep(oap, &bd, pos.lnum, false);
1903 pos.col = bd.textcol;
1904 one_change = swapchars(oap->op_type, &pos, bd.textlen);
1905 did_change |= one_change;
1906
1907 }
1908 if (did_change) {
1909 changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L, true);
1910 }
1911 } else { // not block mode
1912 if (oap->motion_type == kMTLineWise) {
1913 oap->start.col = 0;
1914 pos.col = 0;
1915 oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
1916 if (oap->end.col)
1917 --oap->end.col;
1918 } else if (!oap->inclusive)
1919 dec(&(oap->end));
1920
1921 if (pos.lnum == oap->end.lnum)
1922 did_change = swapchars(oap->op_type, &pos,
1923 oap->end.col - pos.col + 1);
1924 else
1925 for (;; ) {
1926 did_change |= swapchars(oap->op_type, &pos,
1927 pos.lnum == oap->end.lnum ? oap->end.col + 1 :
1928 (int)STRLEN(ml_get_pos(&pos)));
1929 if (ltoreq(oap->end, pos) || inc(&pos) == -1)
1930 break;
1931 }
1932 if (did_change) {
1933 changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1,
1934 0L, true);
1935 }
1936 }
1937
1938 if (!did_change && oap->is_VIsual)
1939 /* No change: need to remove the Visual selection */
1940 redraw_curbuf_later(INVERTED);
1941
1942 /*
1943 * Set '[ and '] marks.
1944 */
1945 curbuf->b_op_start = oap->start;
1946 curbuf->b_op_end = oap->end;
1947
1948 if (oap->line_count > p_report) {
1949 if (oap->line_count == 1)
1950 MSG(_("1 line changed"));
1951 else
1952 smsg(_("%" PRId64 " lines changed"), (int64_t)oap->line_count);
1953 }
1954}
1955
1956/*
1957 * Invoke swapchar() on "length" bytes at position "pos".
1958 * "pos" is advanced to just after the changed characters.
1959 * "length" is rounded up to include the whole last multi-byte character.
1960 * Also works correctly when the number of bytes changes.
1961 * Returns TRUE if some character was changed.
1962 */
1963static int swapchars(int op_type, pos_T *pos, int length)
1964{
1965 int todo;
1966 int did_change = 0;
1967
1968 for (todo = length; todo > 0; --todo) {
1969 if (has_mbyte) {
1970 int len = (*mb_ptr2len)(ml_get_pos(pos));
1971
1972 /* we're counting bytes, not characters */
1973 if (len > 0)
1974 todo -= len - 1;
1975 }
1976 did_change |= swapchar(op_type, pos);
1977 if (inc(pos) == -1) /* at end of file */
1978 break;
1979 }
1980 return did_change;
1981}
1982
1983// If op_type == OP_UPPER: make uppercase,
1984// if op_type == OP_LOWER: make lowercase,
1985// if op_type == OP_ROT13: do rot13 encoding,
1986// else swap case of character at 'pos'
1987// returns true when something actually changed.
1988bool swapchar(int op_type, pos_T *pos)
1989 FUNC_ATTR_NONNULL_ARG(2)
1990{
1991 const int c = gchar_pos(pos);
1992
1993 // Only do rot13 encoding for ASCII characters.
1994 if (c >= 0x80 && op_type == OP_ROT13) {
1995 return false;
1996 }
1997
1998 if (op_type == OP_UPPER && c == 0xdf) {
1999 pos_T sp = curwin->w_cursor;
2000
2001 /* Special handling of German sharp s: change to "SS". */
2002 curwin->w_cursor = *pos;
2003 del_char(false);
2004 ins_char('S');
2005 ins_char('S');
2006 curwin->w_cursor = sp;
2007 inc(pos);
2008 }
2009
2010 int nc = c;
2011 if (mb_islower(c)) {
2012 if (op_type == OP_ROT13) {
2013 nc = ROT13(c, 'a');
2014 } else if (op_type != OP_LOWER) {
2015 nc = mb_toupper(c);
2016 }
2017 } else if (mb_isupper(c)) {
2018 if (op_type == OP_ROT13) {
2019 nc = ROT13(c, 'A');
2020 } else if (op_type != OP_UPPER) {
2021 nc = mb_tolower(c);
2022 }
2023 }
2024 if (nc != c) {
2025 if (c >= 0x80 || nc >= 0x80) {
2026 pos_T sp = curwin->w_cursor;
2027
2028 curwin->w_cursor = *pos;
2029 /* don't use del_char(), it also removes composing chars */
2030 del_bytes(utf_ptr2len(get_cursor_pos_ptr()), FALSE, FALSE);
2031 ins_char(nc);
2032 curwin->w_cursor = sp;
2033 } else {
2034 pbyte(*pos, nc);
2035 }
2036 return true;
2037 }
2038 return false;
2039}
2040
2041/*
2042 * op_insert - Insert and append operators for Visual mode.
2043 */
2044void op_insert(oparg_T *oap, long count1)
2045{
2046 long ins_len, pre_textlen = 0;
2047 char_u *firstline, *ins_text;
2048 colnr_T ind_pre = 0;
2049 struct block_def bd;
2050 int i;
2051 pos_T t1;
2052
2053 /* edit() changes this - record it for OP_APPEND */
2054 bd.is_MAX = (curwin->w_curswant == MAXCOL);
2055
2056 /* vis block is still marked. Get rid of it now. */
2057 curwin->w_cursor.lnum = oap->start.lnum;
2058 update_screen(INVERTED);
2059
2060 if (oap->motion_type == kMTBlockWise) {
2061 // When 'virtualedit' is used, need to insert the extra spaces before
2062 // doing block_prep(). When only "block" is used, virtual edit is
2063 // already disabled, but still need it when calling
2064 // coladvance_force().
2065 if (curwin->w_cursor.coladd > 0) {
2066 unsigned old_ve_flags = ve_flags;
2067
2068 ve_flags = VE_ALL;
2069 if (u_save_cursor() == FAIL)
2070 return;
2071 coladvance_force(oap->op_type == OP_APPEND
2072 ? oap->end_vcol + 1 : getviscol());
2073 if (oap->op_type == OP_APPEND)
2074 --curwin->w_cursor.col;
2075 ve_flags = old_ve_flags;
2076 }
2077 // Get the info about the block before entering the text
2078 block_prep(oap, &bd, oap->start.lnum, true);
2079 // Get indent information
2080 ind_pre = (colnr_T)getwhitecols_curline();
2081 firstline = ml_get(oap->start.lnum) + bd.textcol;
2082
2083 if (oap->op_type == OP_APPEND) {
2084 firstline += bd.textlen;
2085 }
2086 pre_textlen = (long)STRLEN(firstline);
2087 }
2088
2089 if (oap->op_type == OP_APPEND) {
2090 if (oap->motion_type == kMTBlockWise
2091 && curwin->w_cursor.coladd == 0
2092 ) {
2093 /* Move the cursor to the character right of the block. */
2094 curwin->w_set_curswant = TRUE;
2095 while (*get_cursor_pos_ptr() != NUL
2096 && (curwin->w_cursor.col < bd.textcol + bd.textlen))
2097 ++curwin->w_cursor.col;
2098 if (bd.is_short && !bd.is_MAX) {
2099 /* First line was too short, make it longer and adjust the
2100 * values in "bd". */
2101 if (u_save_cursor() == FAIL)
2102 return;
2103 for (i = 0; i < bd.endspaces; i++)
2104 ins_char(' ');
2105 bd.textlen += bd.endspaces;
2106 }
2107 } else {
2108 curwin->w_cursor = oap->end;
2109 check_cursor_col();
2110
2111 // Works just like an 'i'nsert on the next character.
2112 if (!LINEEMPTY(curwin->w_cursor.lnum)
2113 && oap->start_vcol != oap->end_vcol) {
2114 inc_cursor();
2115 }
2116 }
2117 }
2118
2119 t1 = oap->start;
2120 (void)edit(NUL, false, (linenr_T)count1);
2121
2122 // When a tab was inserted, and the characters in front of the tab
2123 // have been converted to a tab as well, the column of the cursor
2124 // might have actually been reduced, so need to adjust here. */
2125 if (t1.lnum == curbuf->b_op_start_orig.lnum
2126 && lt(curbuf->b_op_start_orig, t1)) {
2127 oap->start = curbuf->b_op_start_orig;
2128 }
2129
2130 /* If user has moved off this line, we don't know what to do, so do
2131 * nothing.
2132 * Also don't repeat the insert when Insert mode ended with CTRL-C. */
2133 if (curwin->w_cursor.lnum != oap->start.lnum || got_int)
2134 return;
2135
2136 if (oap->motion_type == kMTBlockWise) {
2137 struct block_def bd2;
2138 bool did_indent = false;
2139
2140 // if indent kicked in, the firstline might have changed
2141 // but only do that, if the indent actually increased
2142 const colnr_T ind_post = (colnr_T)getwhitecols_curline();
2143 if (curbuf->b_op_start.col > ind_pre && ind_post > ind_pre) {
2144 bd.textcol += ind_post - ind_pre;
2145 bd.start_vcol += ind_post - ind_pre;
2146 did_indent = true;
2147 }
2148
2149 // The user may have moved the cursor before inserting something, try
2150 // to adjust the block for that. But only do it, if the difference
2151 // does not come from indent kicking in.
2152 if (oap->start.lnum == curbuf->b_op_start_orig.lnum
2153 && !bd.is_MAX
2154 && !did_indent) {
2155 if (oap->op_type == OP_INSERT
2156 && oap->start.col + oap->start.coladd
2157 != curbuf->b_op_start_orig.col + curbuf->b_op_start_orig.coladd) {
2158 int t = getviscol2(curbuf->b_op_start_orig.col,
2159 curbuf->b_op_start_orig.coladd);
2160 oap->start.col = curbuf->b_op_start_orig.col;
2161 pre_textlen -= t - oap->start_vcol;
2162 oap->start_vcol = t;
2163 } else if (oap->op_type == OP_APPEND
2164 && oap->end.col + oap->end.coladd
2165 >= curbuf->b_op_start_orig.col
2166 + curbuf->b_op_start_orig.coladd) {
2167 int t = getviscol2(curbuf->b_op_start_orig.col,
2168 curbuf->b_op_start_orig.coladd);
2169 oap->start.col = curbuf->b_op_start_orig.col;
2170 /* reset pre_textlen to the value of OP_INSERT */
2171 pre_textlen += bd.textlen;
2172 pre_textlen -= t - oap->start_vcol;
2173 oap->start_vcol = t;
2174 oap->op_type = OP_INSERT;
2175 }
2176 }
2177
2178 /*
2179 * Spaces and tabs in the indent may have changed to other spaces and
2180 * tabs. Get the starting column again and correct the length.
2181 * Don't do this when "$" used, end-of-line will have changed.
2182 */
2183 block_prep(oap, &bd2, oap->start.lnum, true);
2184 if (!bd.is_MAX || bd2.textlen < bd.textlen) {
2185 if (oap->op_type == OP_APPEND) {
2186 pre_textlen += bd2.textlen - bd.textlen;
2187 if (bd2.endspaces)
2188 --bd2.textlen;
2189 }
2190 bd.textcol = bd2.textcol;
2191 bd.textlen = bd2.textlen;
2192 }
2193
2194 /*
2195 * Subsequent calls to ml_get() flush the firstline data - take a
2196 * copy of the required string.
2197 */
2198 firstline = ml_get(oap->start.lnum);
2199 const size_t len = STRLEN(firstline);
2200 colnr_T add = bd.textcol;
2201 if (oap->op_type == OP_APPEND) {
2202 add += bd.textlen;
2203 }
2204 if ((size_t)add > len) {
2205 firstline += len; // short line, point to the NUL
2206 } else {
2207 firstline += add;
2208 }
2209 ins_len = (long)STRLEN(firstline) - pre_textlen;
2210 if (pre_textlen >= 0 && ins_len > 0) {
2211 ins_text = vim_strnsave(firstline, (size_t)ins_len);
2212 // block handled here
2213 if (u_save(oap->start.lnum, (linenr_T)(oap->end.lnum + 1)) == OK) {
2214 block_insert(oap, ins_text, (oap->op_type == OP_INSERT), &bd);
2215 }
2216
2217 curwin->w_cursor.col = oap->start.col;
2218 check_cursor();
2219 xfree(ins_text);
2220 }
2221 }
2222}
2223
2224/*
2225 * op_change - handle a change operation
2226 *
2227 * return TRUE if edit() returns because of a CTRL-O command
2228 */
2229int op_change(oparg_T *oap)
2230{
2231 colnr_T l;
2232 int retval;
2233 long offset;
2234 linenr_T linenr;
2235 long ins_len;
2236 long pre_textlen = 0;
2237 long pre_indent = 0;
2238 char_u *newp;
2239 char_u *firstline;
2240 char_u *ins_text;
2241 char_u *oldp;
2242 struct block_def bd;
2243
2244 l = oap->start.col;
2245 if (oap->motion_type == kMTLineWise) {
2246 l = 0;
2247 if (!p_paste && curbuf->b_p_si
2248 && !curbuf->b_p_cin
2249 )
2250 can_si = true; // It's like opening a new line, do si
2251 }
2252
2253 /* First delete the text in the region. In an empty buffer only need to
2254 * save for undo */
2255 if (curbuf->b_ml.ml_flags & ML_EMPTY) {
2256 if (u_save_cursor() == FAIL)
2257 return FALSE;
2258 } else if (op_delete(oap) == FAIL)
2259 return FALSE;
2260
2261 if ((l > curwin->w_cursor.col) && !LINEEMPTY(curwin->w_cursor.lnum)
2262 && !virtual_op) {
2263 inc_cursor();
2264 }
2265
2266 // check for still on same line (<CR> in inserted text meaningless)
2267 // skip blank lines too
2268 if (oap->motion_type == kMTBlockWise) {
2269 // Add spaces before getting the current line length.
2270 if (virtual_op && (curwin->w_cursor.coladd > 0
2271 || gchar_cursor() == NUL)) {
2272 coladvance_force(getviscol());
2273 }
2274 firstline = ml_get(oap->start.lnum);
2275 pre_textlen = (long)STRLEN(firstline);
2276 pre_indent = (long)getwhitecols(firstline);
2277 bd.textcol = curwin->w_cursor.col;
2278 }
2279
2280 if (oap->motion_type == kMTLineWise) {
2281 fix_indent();
2282 }
2283
2284 retval = edit(NUL, FALSE, (linenr_T)1);
2285
2286 /*
2287 * In Visual block mode, handle copying the new text to all lines of the
2288 * block.
2289 * Don't repeat the insert when Insert mode ended with CTRL-C.
2290 */
2291 if (oap->motion_type == kMTBlockWise
2292 && oap->start.lnum != oap->end.lnum && !got_int) {
2293 // Auto-indenting may have changed the indent. If the cursor was past
2294 // the indent, exclude that indent change from the inserted text.
2295 firstline = ml_get(oap->start.lnum);
2296 if (bd.textcol > (colnr_T)pre_indent) {
2297 long new_indent = (long)getwhitecols(firstline);
2298
2299 pre_textlen += new_indent - pre_indent;
2300 bd.textcol += (colnr_T)(new_indent - pre_indent);
2301 }
2302
2303 ins_len = (long)STRLEN(firstline) - pre_textlen;
2304 if (ins_len > 0) {
2305 /* Subsequent calls to ml_get() flush the firstline data - take a
2306 * copy of the inserted text. */
2307 ins_text = (char_u *)xmalloc((size_t)(ins_len + 1));
2308 STRLCPY(ins_text, firstline + bd.textcol, ins_len + 1);
2309 for (linenr = oap->start.lnum + 1; linenr <= oap->end.lnum;
2310 linenr++) {
2311 block_prep(oap, &bd, linenr, true);
2312 if (!bd.is_short || virtual_op) {
2313 pos_T vpos;
2314
2315 /* If the block starts in virtual space, count the
2316 * initial coladd offset as part of "startspaces" */
2317 if (bd.is_short) {
2318 vpos.lnum = linenr;
2319 (void)getvpos(&vpos, oap->start_vcol);
2320 } else {
2321 vpos.coladd = 0;
2322 }
2323 oldp = ml_get(linenr);
2324 newp = xmalloc(STRLEN(oldp) + (size_t)vpos.coladd
2325 + (size_t)ins_len + 1);
2326 // copy up to block start
2327 memmove(newp, oldp, (size_t)bd.textcol);
2328 offset = bd.textcol;
2329 memset(newp + offset, ' ', (size_t)vpos.coladd);
2330 offset += vpos.coladd;
2331 memmove(newp + offset, ins_text, (size_t)ins_len);
2332 offset += ins_len;
2333 oldp += bd.textcol;
2334 STRMOVE(newp + offset, oldp);
2335 ml_replace(linenr, newp, false);
2336 }
2337 }
2338 check_cursor();
2339 changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L, true);
2340 xfree(ins_text);
2341 }
2342 }
2343
2344 return retval;
2345}
2346
2347/*
2348 * set all the yank registers to empty (called from main())
2349 */
2350void init_yank(void)
2351{
2352 memset(&(y_regs[0]), 0, sizeof(y_regs));
2353}
2354
2355#if defined(EXITFREE)
2356void clear_registers(void)
2357{
2358 int i;
2359
2360 for (i = 0; i < NUM_REGISTERS; i++) {
2361 free_register(&y_regs[i]);
2362 }
2363}
2364
2365#endif
2366
2367
2368 /// Free contents of yankreg `reg`.
2369 /// Called for normal freeing and in case of error.
2370 /// `reg` must not be NULL (but `reg->y_array` might be)
2371void free_register(yankreg_T *reg)
2372 FUNC_ATTR_NONNULL_ALL
2373{
2374 set_yreg_additional_data(reg, NULL);
2375 if (reg->y_array != NULL) {
2376 for (size_t i = reg->y_size; i-- > 0;) { // from y_size - 1 to 0 included
2377 xfree(reg->y_array[i]);
2378 }
2379 XFREE_CLEAR(reg->y_array);
2380 }
2381}
2382
2383/// Yanks the text between "oap->start" and "oap->end" into a yank register.
2384/// If we are to append (uppercase register), we first yank into a new yank
2385/// register and then concatenate the old and the new one.
2386///
2387/// @param oap operator arguments
2388/// @param message show message when more than `&report` lines are yanked.
2389/// @param deleting whether the function was called from a delete operation.
2390/// @returns whether the operation register was writable.
2391bool op_yank(oparg_T *oap, bool message, int deleting)
2392 FUNC_ATTR_NONNULL_ALL
2393{
2394 // check for read-only register
2395 if (oap->regname != 0 && !valid_yank_reg(oap->regname, true)) {
2396 beep_flush();
2397 return false;
2398 }
2399 if (oap->regname == '_') {
2400 return true; // black hole: nothing to do
2401 }
2402
2403 yankreg_T *reg = get_yank_register(oap->regname, YREG_YANK);
2404 op_yank_reg(oap, message, reg, is_append_register(oap->regname));
2405 // op_delete will set_clipboard and do_autocmd
2406 if (!deleting) {
2407 set_clipboard(oap->regname, reg);
2408 do_autocmd_textyankpost(oap, reg);
2409 }
2410
2411 return true;
2412}
2413
2414static void op_yank_reg(oparg_T *oap, bool message, yankreg_T *reg, bool append)
2415{
2416 yankreg_T newreg; // new yank register when appending
2417 char_u **new_ptr;
2418 linenr_T lnum; // current line number
2419 size_t j;
2420 MotionType yank_type = oap->motion_type;
2421 size_t yanklines = (size_t)oap->line_count;
2422 linenr_T yankendlnum = oap->end.lnum;
2423 char_u *p;
2424 char_u *pnew;
2425 struct block_def bd;
2426
2427 yankreg_T *curr = reg; // copy of current register
2428 // append to existing contents
2429 if (append && reg->y_array != NULL) {
2430 reg = &newreg;
2431 } else {
2432 free_register(reg); // free previously yanked lines
2433 }
2434
2435 // If the cursor was in column 1 before and after the movement, and the
2436 // operator is not inclusive, the yank is always linewise.
2437 if (oap->motion_type == kMTCharWise
2438 && oap->start.col == 0
2439 && !oap->inclusive
2440 && (!oap->is_VIsual || *p_sel == 'o')
2441 && oap->end.col == 0
2442 && yanklines > 1) {
2443 yank_type = kMTLineWise;
2444 yankendlnum--;
2445 yanklines--;
2446 }
2447
2448 reg->y_size = yanklines;
2449 reg->y_type = yank_type; // set the yank register type
2450 reg->y_width = 0;
2451 reg->y_array = xcalloc(yanklines, sizeof(char_u *));
2452 reg->additional_data = NULL;
2453 reg->timestamp = os_time();
2454
2455 size_t y_idx = 0; // index in y_array[]
2456 lnum = oap->start.lnum;
2457
2458 if (yank_type == kMTBlockWise) {
2459 // Visual block mode
2460 reg->y_width = oap->end_vcol - oap->start_vcol;
2461
2462 if (curwin->w_curswant == MAXCOL && reg->y_width > 0)
2463 reg->y_width--;
2464 }
2465
2466 for (; lnum <= yankendlnum; lnum++, y_idx++) {
2467 switch (reg->y_type) {
2468 case kMTBlockWise:
2469 block_prep(oap, &bd, lnum, false);
2470 yank_copy_line(reg, &bd, y_idx);
2471 break;
2472
2473 case kMTLineWise:
2474 reg->y_array[y_idx] = vim_strsave(ml_get(lnum));
2475 break;
2476
2477 case kMTCharWise:
2478 {
2479 colnr_T startcol = 0, endcol = MAXCOL;
2480 int is_oneChar = FALSE;
2481 colnr_T cs, ce;
2482 p = ml_get(lnum);
2483 bd.startspaces = 0;
2484 bd.endspaces = 0;
2485
2486 if (lnum == oap->start.lnum) {
2487 startcol = oap->start.col;
2488 if (virtual_op) {
2489 getvcol(curwin, &oap->start, &cs, NULL, &ce);
2490 if (ce != cs && oap->start.coladd > 0) {
2491 /* Part of a tab selected -- but don't
2492 * double-count it. */
2493 bd.startspaces = (ce - cs + 1)
2494 - oap->start.coladd;
2495 startcol++;
2496 }
2497 }
2498 }
2499
2500 if (lnum == oap->end.lnum) {
2501 endcol = oap->end.col;
2502 if (virtual_op) {
2503 getvcol(curwin, &oap->end, &cs, NULL, &ce);
2504 if (p[endcol] == NUL || (cs + oap->end.coladd < ce
2505 // Don't add space for double-wide
2506 // char; endcol will be on last byte
2507 // of multi-byte char.
2508 && utf_head_off(p, p + endcol) == 0)) {
2509 if (oap->start.lnum == oap->end.lnum
2510 && oap->start.col == oap->end.col) {
2511 /* Special case: inside a single char */
2512 is_oneChar = TRUE;
2513 bd.startspaces = oap->end.coladd
2514 - oap->start.coladd + oap->inclusive;
2515 endcol = startcol;
2516 } else {
2517 bd.endspaces = oap->end.coladd
2518 + oap->inclusive;
2519 endcol -= oap->inclusive;
2520 }
2521 }
2522 }
2523 }
2524 if (endcol == MAXCOL)
2525 endcol = (colnr_T)STRLEN(p);
2526 if (startcol > endcol
2527 || is_oneChar
2528 ) {
2529 bd.textlen = 0;
2530 } else {
2531 bd.textlen = endcol - startcol + oap->inclusive;
2532 }
2533 bd.textstart = p + startcol;
2534 yank_copy_line(reg, &bd, y_idx);
2535 break;
2536 }
2537 // NOTREACHED
2538 case kMTUnknown:
2539 assert(false);
2540 }
2541 }
2542
2543 if (curr != reg) { /* append the new block to the old block */
2544 new_ptr = xmalloc(sizeof(char_u *) * (curr->y_size + reg->y_size));
2545 for (j = 0; j < curr->y_size; ++j)
2546 new_ptr[j] = curr->y_array[j];
2547 xfree(curr->y_array);
2548 curr->y_array = new_ptr;
2549
2550 if (yank_type == kMTLineWise) {
2551 // kMTLineWise overrides kMTCharWise and kMTBlockWise
2552 curr->y_type = kMTLineWise;
2553 }
2554
2555 // Concatenate the last line of the old block with the first line of
2556 // the new block, unless being Vi compatible.
2557 if (curr->y_type == kMTCharWise
2558 && vim_strchr(p_cpo, CPO_REGAPPEND) == NULL) {
2559 pnew = xmalloc(STRLEN(curr->y_array[curr->y_size - 1])
2560 + STRLEN(reg->y_array[0]) + 1);
2561 STRCPY(pnew, curr->y_array[--j]);
2562 STRCAT(pnew, reg->y_array[0]);
2563 xfree(curr->y_array[j]);
2564 xfree(reg->y_array[0]);
2565 curr->y_array[j++] = pnew;
2566 y_idx = 1;
2567 } else
2568 y_idx = 0;
2569 while (y_idx < reg->y_size)
2570 curr->y_array[j++] = reg->y_array[y_idx++];
2571 curr->y_size = j;
2572 xfree(reg->y_array);
2573 }
2574 if (curwin->w_p_rnu) {
2575 redraw_later(SOME_VALID); // cursor moved to start
2576 }
2577 if (message) { // Display message about yank?
2578 if (yank_type == kMTCharWise && yanklines == 1) {
2579 yanklines = 0;
2580 }
2581 // Some versions of Vi use ">=" here, some don't...
2582 if (yanklines > (size_t)p_report) {
2583 char namebuf[100];
2584
2585 if (oap->regname == NUL) {
2586 *namebuf = NUL;
2587 } else {
2588 vim_snprintf(namebuf, sizeof(namebuf), _(" into \"%c"), oap->regname);
2589 }
2590
2591 // redisplay now, so message is not deleted
2592 update_topline_redraw();
2593 if (yanklines == 1) {
2594 if (yank_type == kMTBlockWise) {
2595 smsg(_("block of 1 line yanked%s"), namebuf);
2596 } else {
2597 smsg(_("1 line yanked%s"), namebuf);
2598 }
2599 } else if (yank_type == kMTBlockWise) {
2600 smsg(_("block of %" PRId64 " lines yanked%s"),
2601 (int64_t)yanklines, namebuf);
2602 } else {
2603 smsg(_("%" PRId64 " lines yanked%s"), (int64_t)yanklines, namebuf);
2604 }
2605 }
2606 }
2607
2608 /*
2609 * Set "'[" and "']" marks.
2610 */
2611 curbuf->b_op_start = oap->start;
2612 curbuf->b_op_end = oap->end;
2613 if (yank_type == kMTLineWise) {
2614 curbuf->b_op_start.col = 0;
2615 curbuf->b_op_end.col = MAXCOL;
2616 }
2617
2618 return;
2619}
2620
2621static void yank_copy_line(yankreg_T *reg, struct block_def *bd, size_t y_idx)
2622{
2623 int size = bd->startspaces + bd->endspaces + bd->textlen;
2624 assert(size >= 0);
2625 char_u *pnew = xmallocz((size_t)size);
2626 reg->y_array[y_idx] = pnew;
2627 memset(pnew, ' ', (size_t)bd->startspaces);
2628 pnew += bd->startspaces;
2629 memmove(pnew, bd->textstart, (size_t)bd->textlen);
2630 pnew += bd->textlen;
2631 memset(pnew, ' ', (size_t)bd->endspaces);
2632 pnew += bd->endspaces;
2633 *pnew = NUL;
2634}
2635
2636/// Execute autocommands for TextYankPost.
2637///
2638/// @param oap Operator arguments.
2639/// @param reg The yank register used.
2640static void do_autocmd_textyankpost(oparg_T *oap, yankreg_T *reg)
2641 FUNC_ATTR_NONNULL_ALL
2642{
2643 static bool recursive = false;
2644
2645 if (recursive || !has_event(EVENT_TEXTYANKPOST)) {
2646 // No autocommand was defined, or we yanked from this autocommand.
2647 return;
2648 }
2649
2650 recursive = true;
2651
2652 // Set the v:event dictionary with information about the yank.
2653 dict_T *dict = get_vim_var_dict(VV_EVENT);
2654
2655 // The yanked text contents.
2656 list_T *const list = tv_list_alloc((ptrdiff_t)reg->y_size);
2657 for (size_t i = 0; i < reg->y_size; i++) {
2658 tv_list_append_string(list, (const char *)reg->y_array[i], -1);
2659 }
2660 tv_list_set_lock(list, VAR_FIXED);
2661 tv_dict_add_list(dict, S_LEN("regcontents"), list);
2662
2663 // Register type.
2664 char buf[NUMBUFLEN+2];
2665 format_reg_type(reg->y_type, reg->y_width, buf, ARRAY_SIZE(buf));
2666 tv_dict_add_str(dict, S_LEN("regtype"), buf);
2667
2668 // Name of requested register, or empty string for unnamed operation.
2669 buf[0] = (char)oap->regname;
2670 buf[1] = NUL;
2671 tv_dict_add_str(dict, S_LEN("regname"), buf);
2672
2673 // Motion type: inclusive or exclusive.
2674 tv_dict_add_special(dict, S_LEN("inclusive"),
2675 oap->inclusive ? kSpecialVarTrue : kSpecialVarFalse);
2676
2677 // Kind of operation: yank, delete, change).
2678 buf[0] = (char)get_op_char(oap->op_type);
2679 buf[1] = NUL;
2680 tv_dict_add_str(dict, S_LEN("operator"), buf);
2681
2682 tv_dict_set_keys_readonly(dict);
2683 textlock++;
2684 apply_autocmds(EVENT_TEXTYANKPOST, NULL, NULL, false, curbuf);
2685 textlock--;
2686 tv_dict_clear(dict);
2687
2688 recursive = false;
2689}
2690
2691
2692/*
2693 * Put contents of register "regname" into the text.
2694 * Caller must check "regname" to be valid!
2695 * "flags": PUT_FIXINDENT make indent look nice
2696 * PUT_CURSEND leave cursor after end of new text
2697 * PUT_LINE force linewise put (":put")
2698 dir: BACKWARD for 'P', FORWARD for 'p' */
2699void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
2700{
2701 char_u *ptr;
2702 char_u *newp;
2703 char_u *oldp;
2704 int yanklen;
2705 size_t totlen = 0; // init for gcc
2706 linenr_T lnum;
2707 colnr_T col;
2708 size_t i; // index in y_array[]
2709 MotionType y_type;
2710 size_t y_size;
2711 size_t oldlen;
2712 int y_width = 0;
2713 colnr_T vcol;
2714 int delcount;
2715 int incr = 0;
2716 struct block_def bd;
2717 char_u **y_array = NULL;
2718 long nr_lines = 0;
2719 pos_T new_cursor;
2720 int indent;
2721 int orig_indent = 0; /* init for gcc */
2722 int indent_diff = 0; /* init for gcc */
2723 int first_indent = TRUE;
2724 int lendiff = 0;
2725 pos_T old_pos;
2726 char_u *insert_string = NULL;
2727 bool allocated = false;
2728 long cnt;
2729
2730 if (flags & PUT_FIXINDENT)
2731 orig_indent = get_indent();
2732
2733 curbuf->b_op_start = curwin->w_cursor; /* default for '[ mark */
2734 curbuf->b_op_end = curwin->w_cursor; /* default for '] mark */
2735
2736 /*
2737 * Using inserted text works differently, because the register includes
2738 * special characters (newlines, etc.).
2739 */
2740 if (regname == '.' && !reg) {
2741 bool non_linewise_vis = (VIsual_active && VIsual_mode != 'V');
2742
2743 // PUT_LINE has special handling below which means we use 'i' to start.
2744 char command_start_char = non_linewise_vis ? 'c' :
2745 (flags & PUT_LINE ? 'i' : (dir == FORWARD ? 'a' : 'i'));
2746
2747 // To avoid 'autoindent' on linewise puts, create a new line with `:put _`.
2748 if (flags & PUT_LINE) {
2749 do_put('_', NULL, dir, 1, PUT_LINE);
2750 }
2751
2752 // If given a count when putting linewise, we stuff the readbuf with the
2753 // dot register 'count' times split by newlines.
2754 if (flags & PUT_LINE) {
2755 stuffcharReadbuff(command_start_char);
2756 for (; count > 0; count--) {
2757 (void)stuff_inserted(NUL, 1, count != 1);
2758 if (count != 1) {
2759 // To avoid 'autoindent' affecting the text, use Ctrl_U to remove any
2760 // whitespace. Can't just insert Ctrl_U into readbuf1, this would go
2761 // back to the previous line in the case of 'noautoindent' and
2762 // 'backspace' includes "eol". So we insert a dummy space for Ctrl_U
2763 // to consume.
2764 stuffReadbuff("\n ");
2765 stuffcharReadbuff(Ctrl_U);
2766 }
2767 }
2768 } else {
2769 (void)stuff_inserted(command_start_char, count, false);
2770 }
2771
2772 // Putting the text is done later, so can't move the cursor to the next
2773 // character. Simulate it with motion commands after the insert.
2774 if (flags & PUT_CURSEND) {
2775 if (flags & PUT_LINE) {
2776 stuffReadbuff("j0");
2777 } else {
2778 // Avoid ringing the bell from attempting to move into the space after
2779 // the current line. We can stuff the readbuffer with "l" if:
2780 // 1) 'virtualedit' is "all" or "onemore"
2781 // 2) We are not at the end of the line
2782 // 3) We are not (one past the end of the line && on the last line)
2783 // This allows a visual put over a selection one past the end of the
2784 // line joining the current line with the one below.
2785
2786 // curwin->w_cursor.col marks the byte position of the cursor in the
2787 // currunt line. It increases up to a max of
2788 // STRLEN(ml_get(curwin->w_cursor.lnum)). With 'virtualedit' and the
2789 // cursor past the end of the line, curwin->w_cursor.coladd is
2790 // incremented instead of curwin->w_cursor.col.
2791 char_u *cursor_pos = get_cursor_pos_ptr();
2792 bool one_past_line = (*cursor_pos == NUL);
2793 bool eol = false;
2794 if (!one_past_line) {
2795 eol = (*(cursor_pos + mb_ptr2len(cursor_pos)) == NUL);
2796 }
2797
2798 bool ve_allows = (ve_flags == VE_ALL || ve_flags == VE_ONEMORE);
2799 bool eof = curbuf->b_ml.ml_line_count == curwin->w_cursor.lnum
2800 && one_past_line;
2801 if (ve_allows || !(eol || eof)) {
2802 stuffcharReadbuff('l');
2803 }
2804 }
2805 } else if (flags & PUT_LINE) {
2806 stuffReadbuff("g'[");
2807 }
2808
2809 // So the 'u' command restores cursor position after ".p, save the cursor
2810 // position now (though not saving any text).
2811 if (command_start_char == 'a') {
2812 if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL) {
2813 return;
2814 }
2815 }
2816 return;
2817 }
2818
2819 /*
2820 * For special registers '%' (file name), '#' (alternate file name) and
2821 * ':' (last command line), etc. we have to create a fake yank register.
2822 */
2823 if (!reg && get_spec_reg(regname, &insert_string, &allocated, true)) {
2824 if (insert_string == NULL) {
2825 return;
2826 }
2827 }
2828
2829 if (!curbuf->terminal) {
2830 // Autocommands may be executed when saving lines for undo. This might
2831 // make y_array invalid, so we start undo now to avoid that.
2832 if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL) {
2833 return;
2834 }
2835 }
2836
2837 if (insert_string != NULL) {
2838 y_type = kMTCharWise;
2839 if (regname == '=') {
2840 /* For the = register we need to split the string at NL
2841 * characters.
2842 * Loop twice: count the number of lines and save them. */
2843 for (;; ) {
2844 y_size = 0;
2845 ptr = insert_string;
2846 while (ptr != NULL) {
2847 if (y_array != NULL)
2848 y_array[y_size] = ptr;
2849 ++y_size;
2850 ptr = vim_strchr(ptr, '\n');
2851 if (ptr != NULL) {
2852 if (y_array != NULL)
2853 *ptr = NUL;
2854 ++ptr;
2855 /* A trailing '\n' makes the register linewise. */
2856 if (*ptr == NUL) {
2857 y_type = kMTLineWise;
2858 break;
2859 }
2860 }
2861 }
2862 if (y_array != NULL)
2863 break;
2864 y_array = (char_u **)xmalloc(y_size * sizeof(char_u *));
2865 }
2866 } else {
2867 y_size = 1; /* use fake one-line yank register */
2868 y_array = &insert_string;
2869 }
2870 } else {
2871 // in case of replacing visually selected text
2872 // the yankreg might already have been saved to avoid
2873 // just restoring the deleted text.
2874 if (reg == NULL) {
2875 reg = get_yank_register(regname, YREG_PASTE);
2876 }
2877
2878 y_type = reg->y_type;
2879 y_width = reg->y_width;
2880 y_size = reg->y_size;
2881 y_array = reg->y_array;
2882 }
2883
2884 if (curbuf->terminal) {
2885 terminal_paste(count, y_array, y_size);
2886 return;
2887 }
2888
2889 if (y_type == kMTLineWise) {
2890 if (flags & PUT_LINE_SPLIT) {
2891 // "p" or "P" in Visual mode: split the lines to put the text in
2892 // between.
2893 if (u_save_cursor() == FAIL) {
2894 goto end;
2895 }
2896 char_u *p = get_cursor_pos_ptr();
2897 if (dir == FORWARD && *p != NUL) {
2898 MB_PTR_ADV(p);
2899 }
2900 ptr = vim_strsave(p);
2901 ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, false);
2902 xfree(ptr);
2903
2904 oldp = get_cursor_line_ptr();
2905 p = oldp + curwin->w_cursor.col;
2906 if (dir == FORWARD && *p != NUL) {
2907 MB_PTR_ADV(p);
2908 }
2909 ptr = vim_strnsave(oldp, (size_t)(p - oldp));
2910 ml_replace(curwin->w_cursor.lnum, ptr, false);
2911 nr_lines++;
2912 dir = FORWARD;
2913 }
2914 if (flags & PUT_LINE_FORWARD) {
2915 /* Must be "p" for a Visual block, put lines below the block. */
2916 curwin->w_cursor = curbuf->b_visual.vi_end;
2917 dir = FORWARD;
2918 }
2919 curbuf->b_op_start = curwin->w_cursor; /* default for '[ mark */
2920 curbuf->b_op_end = curwin->w_cursor; /* default for '] mark */
2921 }
2922
2923 if (flags & PUT_LINE) { // :put command or "p" in Visual line mode.
2924 y_type = kMTLineWise;
2925 }
2926
2927 if (y_size == 0 || y_array == NULL) {
2928 EMSG2(_("E353: Nothing in register %s"),
2929 regname == 0 ? (char_u *)"\"" : transchar(regname));
2930 goto end;
2931 }
2932
2933 if (y_type == kMTBlockWise) {
2934 lnum = curwin->w_cursor.lnum + (linenr_T)y_size + 1;
2935 if (lnum > curbuf->b_ml.ml_line_count) {
2936 lnum = curbuf->b_ml.ml_line_count + 1;
2937 }
2938 if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL) {
2939 goto end;
2940 }
2941 } else if (y_type == kMTLineWise) {
2942 lnum = curwin->w_cursor.lnum;
2943 // Correct line number for closed fold. Don't move the cursor yet,
2944 // u_save() uses it.
2945 if (dir == BACKWARD) {
2946 (void)hasFolding(lnum, &lnum, NULL);
2947 } else {
2948 (void)hasFolding(lnum, NULL, &lnum);
2949 }
2950 if (dir == FORWARD) {
2951 lnum++;
2952 }
2953 // In an empty buffer the empty line is going to be replaced, include
2954 // it in the saved lines.
2955 if ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL) {
2956 goto end;
2957 }
2958 if (dir == FORWARD) {
2959 curwin->w_cursor.lnum = lnum - 1;
2960 } else {
2961 curwin->w_cursor.lnum = lnum;
2962 }
2963 curbuf->b_op_start = curwin->w_cursor; // for mark_adjust()
2964 } else if (u_save_cursor() == FAIL) {
2965 goto end;
2966 }
2967
2968 yanklen = (int)STRLEN(y_array[0]);
2969
2970 if (ve_flags == VE_ALL && y_type == kMTCharWise) {
2971 if (gchar_cursor() == TAB) {
2972 /* Don't need to insert spaces when "p" on the last position of a
2973 * tab or "P" on the first position. */
2974 if (dir == FORWARD
2975 ? (int)curwin->w_cursor.coladd < curbuf->b_p_ts - 1
2976 : curwin->w_cursor.coladd > 0)
2977 coladvance_force(getviscol());
2978 else
2979 curwin->w_cursor.coladd = 0;
2980 } else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)
2981 coladvance_force(getviscol() + (dir == FORWARD));
2982 }
2983
2984 lnum = curwin->w_cursor.lnum;
2985 col = curwin->w_cursor.col;
2986
2987 /*
2988 * Block mode
2989 */
2990 if (y_type == kMTBlockWise) {
2991 int c = gchar_cursor();
2992 colnr_T endcol2 = 0;
2993
2994 if (dir == FORWARD && c != NUL) {
2995 if (ve_flags == VE_ALL)
2996 getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
2997 else
2998 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
2999
3000 // move to start of next multi-byte character
3001 curwin->w_cursor.col += (*mb_ptr2len)(get_cursor_pos_ptr());
3002 col++;
3003 } else {
3004 getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
3005 }
3006
3007 col += curwin->w_cursor.coladd;
3008 if (ve_flags == VE_ALL
3009 && (curwin->w_cursor.coladd > 0
3010 || endcol2 == curwin->w_cursor.col)) {
3011 if (dir == FORWARD && c == NUL)
3012 ++col;
3013 if (dir != FORWARD && c != NUL)
3014 ++curwin->w_cursor.col;
3015 if (c == TAB) {
3016 if (dir == BACKWARD && curwin->w_cursor.col)
3017 curwin->w_cursor.col--;
3018 if (dir == FORWARD && col - 1 == endcol2)
3019 curwin->w_cursor.col++;
3020 }
3021 }
3022 curwin->w_cursor.coladd = 0;
3023 bd.textcol = 0;
3024 for (i = 0; i < y_size; i++) {
3025 int spaces;
3026 char shortline;
3027
3028 bd.startspaces = 0;
3029 bd.endspaces = 0;
3030 vcol = 0;
3031 delcount = 0;
3032
3033 /* add a new line */
3034 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) {
3035 if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"",
3036 (colnr_T)1, false) == FAIL) {
3037 break;
3038 }
3039 nr_lines++;
3040 }
3041 /* get the old line and advance to the position to insert at */
3042 oldp = get_cursor_line_ptr();
3043 oldlen = STRLEN(oldp);
3044 for (ptr = oldp; vcol < col && *ptr; ) {
3045 /* Count a tab for what it's worth (if list mode not on) */
3046 incr = lbr_chartabsize_adv(oldp, &ptr, (colnr_T)vcol);
3047 vcol += incr;
3048 }
3049 bd.textcol = (colnr_T)(ptr - oldp);
3050
3051 shortline = (vcol < col) || (vcol == col && !*ptr);
3052
3053 if (vcol < col) /* line too short, padd with spaces */
3054 bd.startspaces = col - vcol;
3055 else if (vcol > col) {
3056 bd.endspaces = vcol - col;
3057 bd.startspaces = incr - bd.endspaces;
3058 --bd.textcol;
3059 delcount = 1;
3060 bd.textcol -= utf_head_off(oldp, oldp + bd.textcol);
3061 if (oldp[bd.textcol] != TAB) {
3062 /* Only a Tab can be split into spaces. Other
3063 * characters will have to be moved to after the
3064 * block, causing misalignment. */
3065 delcount = 0;
3066 bd.endspaces = 0;
3067 }
3068 }
3069
3070 yanklen = (int)STRLEN(y_array[i]);
3071
3072 // calculate number of spaces required to fill right side of block
3073 spaces = y_width + 1;
3074 for (long j = 0; j < yanklen; j++) {
3075 spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);
3076 }
3077 if (spaces < 0) {
3078 spaces = 0;
3079 }
3080
3081 // insert the new text
3082 totlen = (size_t)(count * (yanklen + spaces)
3083 + bd.startspaces + bd.endspaces);
3084 newp = (char_u *) xmalloc(totlen + oldlen + 1);
3085 // copy part up to cursor to new line
3086 ptr = newp;
3087 memmove(ptr, oldp, (size_t)bd.textcol);
3088 ptr += bd.textcol;
3089 // may insert some spaces before the new text
3090 memset(ptr, ' ', (size_t)bd.startspaces);
3091 ptr += bd.startspaces;
3092 // insert the new text
3093 for (long j = 0; j < count; j++) {
3094 memmove(ptr, y_array[i], (size_t)yanklen);
3095 ptr += yanklen;
3096
3097 // insert block's trailing spaces only if there's text behind
3098 if ((j < count - 1 || !shortline) && spaces) {
3099 memset(ptr, ' ', (size_t)spaces);
3100 ptr += spaces;
3101 }
3102 }
3103 // may insert some spaces after the new text
3104 memset(ptr, ' ', (size_t)bd.endspaces);
3105 ptr += bd.endspaces;
3106 // move the text after the cursor to the end of the line.
3107 int columns = (int)oldlen - bd.textcol - delcount + 1;
3108 assert(columns >= 0);
3109 memmove(ptr, oldp + bd.textcol + delcount, (size_t)columns);
3110 ml_replace(curwin->w_cursor.lnum, newp, false);
3111
3112 ++curwin->w_cursor.lnum;
3113 if (i == 0)
3114 curwin->w_cursor.col += bd.startspaces;
3115 }
3116
3117 changed_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines, true);
3118
3119 /* Set '[ mark. */
3120 curbuf->b_op_start = curwin->w_cursor;
3121 curbuf->b_op_start.lnum = lnum;
3122
3123 /* adjust '] mark */
3124 curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
3125 curbuf->b_op_end.col = bd.textcol + (colnr_T)totlen - 1;
3126 curbuf->b_op_end.coladd = 0;
3127 if (flags & PUT_CURSEND) {
3128 colnr_T len;
3129
3130 curwin->w_cursor = curbuf->b_op_end;
3131 curwin->w_cursor.col++;
3132
3133 /* in Insert mode we might be after the NUL, correct for that */
3134 len = (colnr_T)STRLEN(get_cursor_line_ptr());
3135 if (curwin->w_cursor.col > len)
3136 curwin->w_cursor.col = len;
3137 } else
3138 curwin->w_cursor.lnum = lnum;
3139 } else {
3140 // Character or Line mode
3141 if (y_type == kMTCharWise) {
3142 // if type is kMTCharWise, FORWARD is the same as BACKWARD on the next
3143 // char
3144 if (dir == FORWARD && gchar_cursor() != NUL) {
3145 int bytelen = (*mb_ptr2len)(get_cursor_pos_ptr());
3146
3147 // put it on the next of the multi-byte character.
3148 col += bytelen;
3149 if (yanklen) {
3150 curwin->w_cursor.col += bytelen;
3151 curbuf->b_op_end.col += bytelen;
3152 }
3153 }
3154 curbuf->b_op_start = curwin->w_cursor;
3155 }
3156 /*
3157 * Line mode: BACKWARD is the same as FORWARD on the previous line
3158 */
3159 else if (dir == BACKWARD)
3160 --lnum;
3161 new_cursor = curwin->w_cursor;
3162
3163 // simple case: insert into current line
3164 if (y_type == kMTCharWise && y_size == 1) {
3165 linenr_T end_lnum = 0; // init for gcc
3166
3167 if (VIsual_active) {
3168 end_lnum = curbuf->b_visual.vi_end.lnum;
3169 if (end_lnum < curbuf->b_visual.vi_start.lnum) {
3170 end_lnum = curbuf->b_visual.vi_start.lnum;
3171 }
3172 }
3173
3174 do {
3175 totlen = (size_t)(count * yanklen);
3176 if (totlen > 0) {
3177 oldp = ml_get(lnum);
3178 if (VIsual_active && col > (int)STRLEN(oldp)) {
3179 lnum++;
3180 continue;
3181 }
3182 newp = (char_u *)xmalloc((size_t)(STRLEN(oldp) + totlen + 1));
3183 memmove(newp, oldp, (size_t)col);
3184 ptr = newp + col;
3185 for (i = 0; i < (size_t)count; i++) {
3186 memmove(ptr, y_array[0], (size_t)yanklen);
3187 ptr += yanklen;
3188 }
3189 STRMOVE(ptr, oldp + col);
3190 ml_replace(lnum, newp, false);
3191 // Place cursor on last putted char.
3192 if (lnum == curwin->w_cursor.lnum) {
3193 // make sure curwin->w_virtcol is updated
3194 changed_cline_bef_curs();
3195 curwin->w_cursor.col += (colnr_T)(totlen - 1);
3196 }
3197 }
3198 if (VIsual_active) {
3199 lnum++;
3200 }
3201 } while (VIsual_active && lnum <= end_lnum);
3202
3203 if (VIsual_active) { /* reset lnum to the last visual line */
3204 lnum--;
3205 }
3206
3207 curbuf->b_op_end = curwin->w_cursor;
3208 /* For "CTRL-O p" in Insert mode, put cursor after last char */
3209 if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))
3210 ++curwin->w_cursor.col;
3211 changed_bytes(lnum, col);
3212 } else {
3213 // Insert at least one line. When y_type is kMTCharWise, break the first
3214 // line in two.
3215 for (cnt = 1; cnt <= count; cnt++) {
3216 i = 0;
3217 if (y_type == kMTCharWise) {
3218 // Split the current line in two at the insert position.
3219 // First insert y_array[size - 1] in front of second line.
3220 // Then append y_array[0] to first line.
3221 lnum = new_cursor.lnum;
3222 ptr = ml_get(lnum) + col;
3223 totlen = STRLEN(y_array[y_size - 1]);
3224 newp = (char_u *) xmalloc((size_t)(STRLEN(ptr) + totlen + 1));
3225 STRCPY(newp, y_array[y_size - 1]);
3226 STRCAT(newp, ptr);
3227 // insert second line
3228 ml_append(lnum, newp, (colnr_T)0, false);
3229 xfree(newp);
3230
3231 oldp = ml_get(lnum);
3232 newp = (char_u *)xmalloc((size_t)col + (size_t)yanklen + 1);
3233 // copy first part of line
3234 memmove(newp, oldp, (size_t)col);
3235 // append to first line
3236 memmove(newp + col, y_array[0], (size_t)yanklen + 1);
3237 ml_replace(lnum, newp, false);
3238
3239 curwin->w_cursor.lnum = lnum;
3240 i = 1;
3241 }
3242
3243 for (; i < y_size; i++) {
3244 if ((y_type != kMTCharWise || i < y_size - 1)
3245 && ml_append(lnum, y_array[i], (colnr_T)0, false)
3246 == FAIL) {
3247 goto error;
3248 }
3249 lnum++;
3250 ++nr_lines;
3251 if (flags & PUT_FIXINDENT) {
3252 old_pos = curwin->w_cursor;
3253 curwin->w_cursor.lnum = lnum;
3254 ptr = ml_get(lnum);
3255 if (cnt == count && i == y_size - 1)
3256 lendiff = (int)STRLEN(ptr);
3257 if (*ptr == '#' && preprocs_left())
3258 indent = 0; /* Leave # lines at start */
3259 else if (*ptr == NUL)
3260 indent = 0; /* Ignore empty lines */
3261 else if (first_indent) {
3262 indent_diff = orig_indent - get_indent();
3263 indent = orig_indent;
3264 first_indent = FALSE;
3265 } else if ((indent = get_indent() + indent_diff) < 0)
3266 indent = 0;
3267 (void)set_indent(indent, 0);
3268 curwin->w_cursor = old_pos;
3269 /* remember how many chars were removed */
3270 if (cnt == count && i == y_size - 1)
3271 lendiff -= (int)STRLEN(ml_get(lnum));
3272 }
3273 }
3274 }
3275
3276error:
3277 // Adjust marks.
3278 if (y_type == kMTLineWise) {
3279 curbuf->b_op_start.col = 0;
3280 if (dir == FORWARD)
3281 curbuf->b_op_start.lnum++;
3282 }
3283 // Skip mark_adjust when adding lines after the last one, there
3284 // can't be marks there. But still needed in diff mode.
3285 if (curbuf->b_op_start.lnum + (y_type == kMTCharWise) - 1 + nr_lines
3286 < curbuf->b_ml.ml_line_count || curwin->w_p_diff) {
3287 mark_adjust(curbuf->b_op_start.lnum + (y_type == kMTCharWise),
3288 (linenr_T)MAXLNUM, nr_lines, 0L, false);
3289 }
3290
3291 // note changed text for displaying and folding
3292 if (y_type == kMTCharWise) {
3293 changed_lines(curwin->w_cursor.lnum, col,
3294 curwin->w_cursor.lnum + 1, nr_lines, true);
3295 } else {
3296 changed_lines(curbuf->b_op_start.lnum, 0,
3297 curbuf->b_op_start.lnum, nr_lines, true);
3298 }
3299
3300 /* put '] mark at last inserted character */
3301 curbuf->b_op_end.lnum = lnum;
3302 /* correct length for change in indent */
3303 col = (colnr_T)STRLEN(y_array[y_size - 1]) - lendiff;
3304 if (col > 1)
3305 curbuf->b_op_end.col = col - 1;
3306 else
3307 curbuf->b_op_end.col = 0;
3308
3309 if (flags & PUT_CURSLINE) {
3310 /* ":put": put cursor on last inserted line */
3311 curwin->w_cursor.lnum = lnum;
3312 beginline(BL_WHITE | BL_FIX);
3313 } else if (flags & PUT_CURSEND) {
3314 // put cursor after inserted text
3315 if (y_type == kMTLineWise) {
3316 if (lnum >= curbuf->b_ml.ml_line_count) {
3317 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3318 } else {
3319 curwin->w_cursor.lnum = lnum + 1;
3320 }
3321 curwin->w_cursor.col = 0;
3322 } else {
3323 curwin->w_cursor.lnum = lnum;
3324 curwin->w_cursor.col = col;
3325 }
3326 } else if (y_type == kMTLineWise) {
3327 // put cursor on first non-blank in first inserted line
3328 curwin->w_cursor.col = 0;
3329 if (dir == FORWARD)
3330 ++curwin->w_cursor.lnum;
3331 beginline(BL_WHITE | BL_FIX);
3332 } else /* put cursor on first inserted character */
3333 curwin->w_cursor = new_cursor;
3334 }
3335 }
3336
3337 msgmore(nr_lines);
3338 curwin->w_set_curswant = TRUE;
3339
3340end:
3341 if (allocated)
3342 xfree(insert_string);
3343 if (regname == '=')
3344 xfree(y_array);
3345
3346 VIsual_active = FALSE;
3347
3348 /* If the cursor is past the end of the line put it at the end. */
3349 adjust_cursor_eol();
3350}
3351
3352/*
3353 * When the cursor is on the NUL past the end of the line and it should not be
3354 * there move it left.
3355 */
3356void adjust_cursor_eol(void)
3357{
3358 if (curwin->w_cursor.col > 0
3359 && gchar_cursor() == NUL
3360 && (ve_flags & VE_ONEMORE) == 0
3361 && !(restart_edit || (State & INSERT))) {
3362 /* Put the cursor on the last character in the line. */
3363 dec_cursor();
3364
3365 if (ve_flags == VE_ALL) {
3366 colnr_T scol, ecol;
3367
3368 /* Coladd is set to the width of the last character. */
3369 getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
3370 curwin->w_cursor.coladd = ecol - scol + 1;
3371 }
3372 }
3373}
3374
3375/*
3376 * Return TRUE if lines starting with '#' should be left aligned.
3377 */
3378int preprocs_left(void)
3379{
3380 return ((curbuf->b_p_si && !curbuf->b_p_cin)
3381 || (curbuf->b_p_cin && in_cinkeys('#', ' ', true)
3382 && curbuf->b_ind_hash_comment == 0));
3383}
3384
3385/* Return the character name of the register with the given number */
3386int get_register_name(int num)
3387{
3388 if (num == -1)
3389 return '"';
3390 else if (num < 10)
3391 return num + '0';
3392 else if (num == DELETION_REGISTER)
3393 return '-';
3394 else if (num == STAR_REGISTER)
3395 return '*';
3396 else if (num == PLUS_REGISTER)
3397 return '+';
3398 else {
3399 return num + 'a' - 10;
3400 }
3401}
3402
3403/*
3404 * ":dis" and ":registers": Display the contents of the yank registers.
3405 */
3406void ex_display(exarg_T *eap)
3407{
3408 char_u *p;
3409 yankreg_T *yb;
3410 int name;
3411 char_u *arg = eap->arg;
3412 int clen;
3413
3414 if (arg != NULL && *arg == NUL)
3415 arg = NULL;
3416 int attr = HL_ATTR(HLF_8);
3417
3418 /* Highlight title */
3419 MSG_PUTS_TITLE(_("\n--- Registers ---"));
3420 for (int i = -1; i < NUM_REGISTERS && !got_int; i++) {
3421 name = get_register_name(i);
3422
3423 if (arg != NULL && vim_strchr(arg, name) == NULL) {
3424 continue; /* did not ask for this register */
3425 }
3426
3427
3428 if (i == -1) {
3429 if (y_previous != NULL)
3430 yb = y_previous;
3431 else
3432 yb = &(y_regs[0]);
3433 } else
3434 yb = &(y_regs[i]);
3435
3436 get_clipboard(name, &yb, true);
3437
3438 if (name == mb_tolower(redir_reg)
3439 || (redir_reg == '"' && yb == y_previous)) {
3440 continue; // do not list register being written to, the
3441 // pointer can be freed
3442 }
3443
3444 if (yb->y_array != NULL) {
3445 msg_putchar('\n');
3446 msg_putchar('"');
3447 msg_putchar(name);
3448 MSG_PUTS(" ");
3449
3450 int n = Columns - 6;
3451 for (size_t j = 0; j < yb->y_size && n > 1; j++) {
3452 if (j) {
3453 MSG_PUTS_ATTR("^J", attr);
3454 n -= 2;
3455 }
3456 for (p = yb->y_array[j]; *p && (n -= ptr2cells(p)) >= 0; p++) { // -V1019 NOLINT(whitespace/line_length)
3457 clen = (*mb_ptr2len)(p);
3458 msg_outtrans_len(p, clen);
3459 p += clen - 1;
3460 }
3461 }
3462 if (n > 1 && yb->y_type == kMTLineWise) {
3463 MSG_PUTS_ATTR("^J", attr);
3464 }
3465 ui_flush(); // show one line at a time
3466 }
3467 os_breakcheck();
3468 }
3469
3470 /*
3471 * display last inserted text
3472 */
3473 if ((p = get_last_insert()) != NULL
3474 && (arg == NULL || vim_strchr(arg, '.') != NULL) && !got_int) {
3475 MSG_PUTS("\n\". ");
3476 dis_msg(p, TRUE);
3477 }
3478
3479 /*
3480 * display last command line
3481 */
3482 if (last_cmdline != NULL && (arg == NULL || vim_strchr(arg, ':') != NULL)
3483 && !got_int) {
3484 MSG_PUTS("\n\": ");
3485 dis_msg(last_cmdline, FALSE);
3486 }
3487
3488 /*
3489 * display current file name
3490 */
3491 if (curbuf->b_fname != NULL
3492 && (arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int) {
3493 MSG_PUTS("\n\"% ");
3494 dis_msg(curbuf->b_fname, FALSE);
3495 }
3496
3497 /*
3498 * display alternate file name
3499 */
3500 if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int) {
3501 char_u *fname;
3502 linenr_T dummy;
3503
3504 if (buflist_name_nr(0, &fname, &dummy) != FAIL) {
3505 MSG_PUTS("\n\"# ");
3506 dis_msg(fname, FALSE);
3507 }
3508 }
3509
3510 /*
3511 * display last search pattern
3512 */
3513 if (last_search_pat() != NULL
3514 && (arg == NULL || vim_strchr(arg, '/') != NULL) && !got_int) {
3515 MSG_PUTS("\n\"/ ");
3516 dis_msg(last_search_pat(), FALSE);
3517 }
3518
3519 /*
3520 * display last used expression
3521 */
3522 if (expr_line != NULL && (arg == NULL || vim_strchr(arg, '=') != NULL)
3523 && !got_int) {
3524 MSG_PUTS("\n\"= ");
3525 dis_msg(expr_line, FALSE);
3526 }
3527}
3528
3529/*
3530 * display a string for do_dis()
3531 * truncate at end of screen line
3532 */
3533static void
3534dis_msg(
3535 char_u *p,
3536 int skip_esc /* if TRUE, ignore trailing ESC */
3537)
3538{
3539 int n;
3540 int l;
3541
3542 n = Columns - 6;
3543 while (*p != NUL
3544 && !(*p == ESC && skip_esc && *(p + 1) == NUL)
3545 && (n -= ptr2cells(p)) >= 0) {
3546 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1) {
3547 msg_outtrans_len(p, l);
3548 p += l;
3549 } else
3550 msg_outtrans_len(p++, 1);
3551 }
3552 os_breakcheck();
3553}
3554
3555/// If \p "process" is true and the line begins with a comment leader (possibly
3556/// after some white space), return a pointer to the text after it.
3557/// Put a boolean value indicating whether the line ends with an unclosed
3558/// comment in "is_comment".
3559///
3560/// @param line - line to be processed
3561/// @param process - if false, will only check whether the line ends
3562/// with an unclosed comment,
3563/// @param include_space - whether to skip space following the comment leader
3564/// @param[out] is_comment - whether the current line ends with an unclosed
3565/// comment.
3566char_u *skip_comment(
3567 char_u *line, bool process, bool include_space, bool *is_comment
3568)
3569{
3570 char_u *comment_flags = NULL;
3571 int lead_len;
3572 int leader_offset = get_last_leader_offset(line, &comment_flags);
3573
3574 *is_comment = false;
3575 if (leader_offset != -1) {
3576 /* Let's check whether the line ends with an unclosed comment.
3577 * If the last comment leader has COM_END in flags, there's no comment.
3578 */
3579 while (*comment_flags) {
3580 if (*comment_flags == COM_END
3581 || *comment_flags == ':') {
3582 break;
3583 }
3584 comment_flags++;
3585 }
3586 if (*comment_flags != COM_END) {
3587 *is_comment = true;
3588 }
3589 }
3590
3591 if (process == false) {
3592 return line;
3593 }
3594
3595 lead_len = get_leader_len(line, &comment_flags, false, include_space);
3596
3597 if (lead_len == 0)
3598 return line;
3599
3600 /* Find:
3601 * - COM_END,
3602 * - colon,
3603 * whichever comes first.
3604 */
3605 while (*comment_flags) {
3606 if (*comment_flags == COM_END
3607 || *comment_flags == ':') {
3608 break;
3609 }
3610 ++comment_flags;
3611 }
3612
3613 /* If we found a colon, it means that we are not processing a line
3614 * starting with a closing part of a three-part comment. That's good,
3615 * because we don't want to remove those as this would be annoying.
3616 */
3617 if (*comment_flags == ':' || *comment_flags == NUL) {
3618 line += lead_len;
3619 }
3620
3621 return line;
3622}
3623
3624// Join 'count' lines (minimal 2) at cursor position.
3625// When "save_undo" is TRUE save lines for undo first.
3626// Set "use_formatoptions" to FALSE when e.g. processing backspace and comment
3627// leaders should not be removed.
3628// When setmark is true, sets the '[ and '] mark, else, the caller is expected
3629// to set those marks.
3630//
3631// return FAIL for failure, OK otherwise
3632int do_join(size_t count,
3633 int insert_space,
3634 int save_undo,
3635 int use_formatoptions,
3636 bool setmark)
3637{
3638 char_u *curr = NULL;
3639 char_u *curr_start = NULL;
3640 char_u *cend;
3641 char_u *newp;
3642 char_u *spaces; /* number of spaces inserted before a line */
3643 int endcurr1 = NUL;
3644 int endcurr2 = NUL;
3645 int currsize = 0; /* size of the current line */
3646 int sumsize = 0; /* size of the long new line */
3647 linenr_T t;
3648 colnr_T col = 0;
3649 int ret = OK;
3650 int *comments = NULL;
3651 int remove_comments = (use_formatoptions == TRUE)
3652 && has_format_option(FO_REMOVE_COMS);
3653 bool prev_was_comment = false;
3654 assert(count >= 1);
3655
3656 if (save_undo && u_save(curwin->w_cursor.lnum - 1,
3657 curwin->w_cursor.lnum + (linenr_T)count) == FAIL) {
3658 return FAIL;
3659 }
3660 // Allocate an array to store the number of spaces inserted before each
3661 // line. We will use it to pre-compute the length of the new line and the
3662 // proper placement of each original line in the new one.
3663 spaces = xcalloc(count, 1);
3664 if (remove_comments) {
3665 comments = xcalloc(count, sizeof(*comments));
3666 }
3667
3668 // Don't move anything, just compute the final line length
3669 // and setup the array of space strings lengths
3670 for (t = 0; t < (linenr_T)count; t++) {
3671 curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t));
3672 if (t == 0 && setmark) {
3673 // Set the '[ mark.
3674 curwin->w_buffer->b_op_start.lnum = curwin->w_cursor.lnum;
3675 curwin->w_buffer->b_op_start.col = (colnr_T)STRLEN(curr);
3676 }
3677 if (remove_comments) {
3678 // We don't want to remove the comment leader if the
3679 // previous line is not a comment.
3680 if (t > 0 && prev_was_comment) {
3681 char_u *new_curr = skip_comment(curr, true, insert_space,
3682 &prev_was_comment);
3683 comments[t] = (int)(new_curr - curr);
3684 curr = new_curr;
3685 } else {
3686 curr = skip_comment(curr, false, insert_space, &prev_was_comment);
3687 }
3688 }
3689
3690 if (insert_space && t > 0) {
3691 curr = skipwhite(curr);
3692 if (*curr != ')' && currsize != 0 && endcurr1 != TAB
3693 && (!has_format_option(FO_MBYTE_JOIN)
3694 || (utf_ptr2char(curr) < 0x100 && endcurr1 < 0x100))
3695 && (!has_format_option(FO_MBYTE_JOIN2)
3696 || utf_ptr2char(curr) < 0x100 || endcurr1 < 0x100)
3697 ) {
3698 /* don't add a space if the line is ending in a space */
3699 if (endcurr1 == ' ')
3700 endcurr1 = endcurr2;
3701 else
3702 ++spaces[t];
3703 // Extra space when 'joinspaces' set and line ends in '.', '?', or '!'.
3704 if (p_js && (endcurr1 == '.' || endcurr1 == '?' || endcurr1 == '!')) {
3705 ++spaces[t];
3706 }
3707 }
3708 }
3709 currsize = (int)STRLEN(curr);
3710 sumsize += currsize + spaces[t];
3711 endcurr1 = endcurr2 = NUL;
3712 if (insert_space && currsize > 0) {
3713 cend = curr + currsize;
3714 MB_PTR_BACK(curr, cend);
3715 endcurr1 = utf_ptr2char(cend);
3716 if (cend > curr) {
3717 MB_PTR_BACK(curr, cend);
3718 endcurr2 = utf_ptr2char(cend);
3719 }
3720 }
3721 line_breakcheck();
3722 if (got_int) {
3723 ret = FAIL;
3724 goto theend;
3725 }
3726 }
3727
3728 // store the column position before last line
3729 col = sumsize - currsize - spaces[count - 1];
3730
3731 // allocate the space for the new line
3732 newp = (char_u *)xmalloc((size_t)sumsize + 1);
3733 cend = newp + sumsize;
3734 *cend = 0;
3735
3736 /*
3737 * Move affected lines to the new long one.
3738 *
3739 * Move marks from each deleted line to the joined line, adjusting the
3740 * column. This is not Vi compatible, but Vi deletes the marks, thus that
3741 * should not really be a problem.
3742 */
3743 for (t = (linenr_T)count - 1;; t--) {
3744 cend -= currsize;
3745 memmove(cend, curr, (size_t)currsize);
3746 if (spaces[t] > 0) {
3747 cend -= spaces[t];
3748 memset(cend, ' ', (size_t)(spaces[t]));
3749 }
3750
3751 // If deleting more spaces than adding, the cursor moves no more than
3752 // what is added if it is inside these spaces.
3753 const int spaces_removed = (int)((curr - curr_start) - spaces[t]);
3754
3755 mark_col_adjust(curwin->w_cursor.lnum + t, (colnr_T)0, (linenr_T)-t,
3756 (long)(cend - newp - spaces_removed), spaces_removed);
3757 if (t == 0) {
3758 break;
3759 }
3760 curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1));
3761 if (remove_comments)
3762 curr += comments[t - 1];
3763 if (insert_space && t > 1)
3764 curr = skipwhite(curr);
3765 currsize = (int)STRLEN(curr);
3766 }
3767 ml_replace(curwin->w_cursor.lnum, newp, false);
3768
3769 if (setmark) {
3770 // Set the '] mark.
3771 curwin->w_buffer->b_op_end.lnum = curwin->w_cursor.lnum;
3772 curwin->w_buffer->b_op_end.col = sumsize;
3773 }
3774
3775 /* Only report the change in the first line here, del_lines() will report
3776 * the deleted line. */
3777 changed_lines(curwin->w_cursor.lnum, currsize,
3778 curwin->w_cursor.lnum + 1, 0L, true);
3779
3780 /*
3781 * Delete following lines. To do this we move the cursor there
3782 * briefly, and then move it back. After del_lines() the cursor may
3783 * have moved up (last line deleted), so the current lnum is kept in t.
3784 */
3785 t = curwin->w_cursor.lnum;
3786 curwin->w_cursor.lnum++;
3787 del_lines((long)count - 1, false);
3788 curwin->w_cursor.lnum = t;
3789
3790 /*
3791 * Set the cursor column:
3792 * Vi compatible: use the column of the first join
3793 * vim: use the column of the last join
3794 */
3795 curwin->w_cursor.col =
3796 (vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col);
3797 check_cursor_col();
3798
3799 curwin->w_cursor.coladd = 0;
3800 curwin->w_set_curswant = TRUE;
3801
3802theend:
3803 xfree(spaces);
3804 if (remove_comments)
3805 xfree(comments);
3806 return ret;
3807}
3808
3809/*
3810 * Return TRUE if the two comment leaders given are the same. "lnum" is
3811 * the first line. White-space is ignored. Note that the whole of
3812 * 'leader1' must match 'leader2_len' characters from 'leader2' -- webb
3813 */
3814static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, int leader2_len, char_u *leader2_flags)
3815{
3816 int idx1 = 0, idx2 = 0;
3817 char_u *p;
3818 char_u *line1;
3819 char_u *line2;
3820
3821 if (leader1_len == 0)
3822 return leader2_len == 0;
3823
3824 /*
3825 * If first leader has 'f' flag, the lines can be joined only if the
3826 * second line does not have a leader.
3827 * If first leader has 'e' flag, the lines can never be joined.
3828 * If fist leader has 's' flag, the lines can only be joined if there is
3829 * some text after it and the second line has the 'm' flag.
3830 */
3831 if (leader1_flags != NULL) {
3832 for (p = leader1_flags; *p && *p != ':'; ++p) {
3833 if (*p == COM_FIRST)
3834 return leader2_len == 0;
3835 if (*p == COM_END)
3836 return FALSE;
3837 if (*p == COM_START) {
3838 if (*(ml_get(lnum) + leader1_len) == NUL)
3839 return FALSE;
3840 if (leader2_flags == NULL || leader2_len == 0)
3841 return FALSE;
3842 for (p = leader2_flags; *p && *p != ':'; ++p)
3843 if (*p == COM_MIDDLE)
3844 return TRUE;
3845 return FALSE;
3846 }
3847 }
3848 }
3849
3850 /*
3851 * Get current line and next line, compare the leaders.
3852 * The first line has to be saved, only one line can be locked at a time.
3853 */
3854 line1 = vim_strsave(ml_get(lnum));
3855 for (idx1 = 0; ascii_iswhite(line1[idx1]); ++idx1)
3856 ;
3857 line2 = ml_get(lnum + 1);
3858 for (idx2 = 0; idx2 < leader2_len; ++idx2) {
3859 if (!ascii_iswhite(line2[idx2])) {
3860 if (line1[idx1++] != line2[idx2])
3861 break;
3862 } else
3863 while (ascii_iswhite(line1[idx1]))
3864 ++idx1;
3865 }
3866 xfree(line1);
3867
3868 return idx2 == leader2_len && idx1 == leader1_len;
3869}
3870
3871/*
3872 * Implementation of the format operator 'gq'.
3873 */
3874void
3875op_format(
3876 oparg_T *oap,
3877 int keep_cursor /* keep cursor on same text char */
3878)
3879{
3880 long old_line_count = curbuf->b_ml.ml_line_count;
3881
3882 /* Place the cursor where the "gq" or "gw" command was given, so that "u"
3883 * can put it back there. */
3884 curwin->w_cursor = oap->cursor_start;
3885
3886 if (u_save((linenr_T)(oap->start.lnum - 1),
3887 (linenr_T)(oap->end.lnum + 1)) == FAIL)
3888 return;
3889 curwin->w_cursor = oap->start;
3890
3891 if (oap->is_VIsual)
3892 /* When there is no change: need to remove the Visual selection */
3893 redraw_curbuf_later(INVERTED);
3894
3895 /* Set '[ mark at the start of the formatted area */
3896 curbuf->b_op_start = oap->start;
3897
3898 /* For "gw" remember the cursor position and put it back below (adjusted
3899 * for joined and split lines). */
3900 if (keep_cursor)
3901 saved_cursor = oap->cursor_start;
3902
3903 format_lines(oap->line_count, keep_cursor);
3904
3905 /*
3906 * Leave the cursor at the first non-blank of the last formatted line.
3907 * If the cursor was moved one line back (e.g. with "Q}") go to the next
3908 * line, so "." will do the next lines.
3909 */
3910 if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
3911 ++curwin->w_cursor.lnum;
3912 beginline(BL_WHITE | BL_FIX);
3913 old_line_count = curbuf->b_ml.ml_line_count - old_line_count;
3914 msgmore(old_line_count);
3915
3916 /* put '] mark on the end of the formatted area */
3917 curbuf->b_op_end = curwin->w_cursor;
3918
3919 if (keep_cursor) {
3920 curwin->w_cursor = saved_cursor;
3921 saved_cursor.lnum = 0;
3922 }
3923
3924 if (oap->is_VIsual) {
3925 FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
3926 if (wp->w_old_cursor_lnum != 0) {
3927 /* When lines have been inserted or deleted, adjust the end of
3928 * the Visual area to be redrawn. */
3929 if (wp->w_old_cursor_lnum > wp->w_old_visual_lnum) {
3930 wp->w_old_cursor_lnum += old_line_count;
3931 } else {
3932 wp->w_old_visual_lnum += old_line_count;
3933 }
3934 }
3935 }
3936 }
3937}
3938
3939/*
3940 * Implementation of the format operator 'gq' for when using 'formatexpr'.
3941 */
3942void op_formatexpr(oparg_T *oap)
3943{
3944 if (oap->is_VIsual)
3945 /* When there is no change: need to remove the Visual selection */
3946 redraw_curbuf_later(INVERTED);
3947
3948 if (fex_format(oap->start.lnum, oap->line_count, NUL) != 0)
3949 /* As documented: when 'formatexpr' returns non-zero fall back to
3950 * internal formatting. */
3951 op_format(oap, FALSE);
3952}
3953
3954int
3955fex_format(
3956 linenr_T lnum,
3957 long count,
3958 int c /* character to be inserted */
3959)
3960{
3961 int use_sandbox = was_set_insecurely((char_u *)"formatexpr",
3962 OPT_LOCAL);
3963 int r;
3964 char_u *fex;
3965
3966 /*
3967 * Set v:lnum to the first line number and v:count to the number of lines.
3968 * Set v:char to the character to be inserted (can be NUL).
3969 */
3970 set_vim_var_nr(VV_LNUM, (varnumber_T)lnum);
3971 set_vim_var_nr(VV_COUNT, (varnumber_T)count);
3972 set_vim_var_char(c);
3973
3974 // Make a copy, the option could be changed while calling it.
3975 fex = vim_strsave(curbuf->b_p_fex);
3976 // Evaluate the function.
3977 if (use_sandbox) {
3978 sandbox++;
3979 }
3980 r = (int)eval_to_number(fex);
3981 if (use_sandbox) {
3982 sandbox--;
3983 }
3984
3985 set_vim_var_string(VV_CHAR, NULL, -1);
3986 xfree(fex);
3987
3988 return r;
3989}
3990
3991/*
3992 * Format "line_count" lines, starting at the cursor position.
3993 * When "line_count" is negative, format until the end of the paragraph.
3994 * Lines after the cursor line are saved for undo, caller must have saved the
3995 * first line.
3996 */
3997void
3998format_lines(
3999 linenr_T line_count,
4000 int avoid_fex /* don't use 'formatexpr' */
4001)
4002{
4003 int max_len;
4004 int is_not_par; /* current line not part of parag. */
4005 int next_is_not_par; /* next line not part of paragraph */
4006 int is_end_par; /* at end of paragraph */
4007 int prev_is_end_par = FALSE; /* prev. line not part of parag. */
4008 int next_is_start_par = FALSE;
4009 int leader_len = 0; /* leader len of current line */
4010 int next_leader_len; /* leader len of next line */
4011 char_u *leader_flags = NULL; /* flags for leader of current line */
4012 char_u *next_leader_flags; /* flags for leader of next line */
4013 int do_comments; /* format comments */
4014 int do_comments_list = 0; /* format comments with 'n' or '2' */
4015 int advance = TRUE;
4016 int second_indent = -1; /* indent for second line (comment
4017 * aware) */
4018 int do_second_indent;
4019 int do_number_indent;
4020 int do_trail_white;
4021 int first_par_line = TRUE;
4022 int smd_save;
4023 long count;
4024 int need_set_indent = TRUE; /* set indent of next paragraph */
4025 int force_format = FALSE;
4026 int old_State = State;
4027
4028 /* length of a line to force formatting: 3 * 'tw' */
4029 max_len = comp_textwidth(TRUE) * 3;
4030
4031 /* check for 'q', '2' and '1' in 'formatoptions' */
4032 do_comments = has_format_option(FO_Q_COMS);
4033 do_second_indent = has_format_option(FO_Q_SECOND);
4034 do_number_indent = has_format_option(FO_Q_NUMBER);
4035 do_trail_white = has_format_option(FO_WHITE_PAR);
4036
4037 /*
4038 * Get info about the previous and current line.
4039 */
4040 if (curwin->w_cursor.lnum > 1)
4041 is_not_par = fmt_check_par(curwin->w_cursor.lnum - 1
4042 , &leader_len, &leader_flags, do_comments
4043 );
4044 else
4045 is_not_par = TRUE;
4046 next_is_not_par = fmt_check_par(curwin->w_cursor.lnum
4047 , &next_leader_len, &next_leader_flags, do_comments
4048 );
4049 is_end_par = (is_not_par || next_is_not_par);
4050 if (!is_end_par && do_trail_white)
4051 is_end_par = !ends_in_white(curwin->w_cursor.lnum - 1);
4052
4053 curwin->w_cursor.lnum--;
4054 for (count = line_count; count != 0 && !got_int; --count) {
4055 /*
4056 * Advance to next paragraph.
4057 */
4058 if (advance) {
4059 curwin->w_cursor.lnum++;
4060 prev_is_end_par = is_end_par;
4061 is_not_par = next_is_not_par;
4062 leader_len = next_leader_len;
4063 leader_flags = next_leader_flags;
4064 }
4065
4066 /*
4067 * The last line to be formatted.
4068 */
4069 if (count == 1 || curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) {
4070 next_is_not_par = TRUE;
4071 next_leader_len = 0;
4072 next_leader_flags = NULL;
4073 } else {
4074 next_is_not_par = fmt_check_par(curwin->w_cursor.lnum + 1
4075 , &next_leader_len, &next_leader_flags, do_comments
4076 );
4077 if (do_number_indent)
4078 next_is_start_par =
4079 (get_number_indent(curwin->w_cursor.lnum + 1) > 0);
4080 }
4081 advance = TRUE;
4082 is_end_par = (is_not_par || next_is_not_par || next_is_start_par);
4083 if (!is_end_par && do_trail_white)
4084 is_end_par = !ends_in_white(curwin->w_cursor.lnum);
4085
4086 /*
4087 * Skip lines that are not in a paragraph.
4088 */
4089 if (is_not_par) {
4090 if (line_count < 0)
4091 break;
4092 } else {
4093 /*
4094 * For the first line of a paragraph, check indent of second line.
4095 * Don't do this for comments and empty lines.
4096 */
4097 if (first_par_line
4098 && (do_second_indent || do_number_indent)
4099 && prev_is_end_par
4100 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
4101 if (do_second_indent && !LINEEMPTY(curwin->w_cursor.lnum + 1)) {
4102 if (leader_len == 0 && next_leader_len == 0) {
4103 /* no comment found */
4104 second_indent =
4105 get_indent_lnum(curwin->w_cursor.lnum + 1);
4106 } else {
4107 second_indent = next_leader_len;
4108 do_comments_list = 1;
4109 }
4110 } else if (do_number_indent) {
4111 if (leader_len == 0 && next_leader_len == 0) {
4112 /* no comment found */
4113 second_indent =
4114 get_number_indent(curwin->w_cursor.lnum);
4115 } else {
4116 /* get_number_indent() is now "comment aware"... */
4117 second_indent =
4118 get_number_indent(curwin->w_cursor.lnum);
4119 do_comments_list = 1;
4120 }
4121 }
4122 }
4123
4124 /*
4125 * When the comment leader changes, it's the end of the paragraph.
4126 */
4127 if (curwin->w_cursor.lnum >= curbuf->b_ml.ml_line_count
4128 || !same_leader(curwin->w_cursor.lnum,
4129 leader_len, leader_flags,
4130 next_leader_len, next_leader_flags)
4131 )
4132 is_end_par = TRUE;
4133
4134 /*
4135 * If we have got to the end of a paragraph, or the line is
4136 * getting long, format it.
4137 */
4138 if (is_end_par || force_format) {
4139 if (need_set_indent)
4140 /* replace indent in first line with minimal number of
4141 * tabs and spaces, according to current options */
4142 (void)set_indent(get_indent(), SIN_CHANGED);
4143
4144 /* put cursor on last non-space */
4145 State = NORMAL; /* don't go past end-of-line */
4146 coladvance((colnr_T)MAXCOL);
4147 while (curwin->w_cursor.col && ascii_isspace(gchar_cursor()))
4148 dec_cursor();
4149
4150 /* do the formatting, without 'showmode' */
4151 State = INSERT; /* for open_line() */
4152 smd_save = p_smd;
4153 p_smd = FALSE;
4154 insertchar(NUL, INSCHAR_FORMAT
4155 + (do_comments ? INSCHAR_DO_COM : 0)
4156 + (do_comments && do_comments_list
4157 ? INSCHAR_COM_LIST : 0)
4158 + (avoid_fex ? INSCHAR_NO_FEX : 0), second_indent);
4159 State = old_State;
4160 p_smd = smd_save;
4161 second_indent = -1;
4162 /* at end of par.: need to set indent of next par. */
4163 need_set_indent = is_end_par;
4164 if (is_end_par) {
4165 /* When called with a negative line count, break at the
4166 * end of the paragraph. */
4167 if (line_count < 0)
4168 break;
4169 first_par_line = TRUE;
4170 }
4171 force_format = FALSE;
4172 }
4173
4174 /*
4175 * When still in same paragraph, join the lines together. But
4176 * first delete the leader from the second line.
4177 */
4178 if (!is_end_par) {
4179 advance = FALSE;
4180 curwin->w_cursor.lnum++;
4181 curwin->w_cursor.col = 0;
4182 if (line_count < 0 && u_save_cursor() == FAIL)
4183 break;
4184 if (next_leader_len > 0) {
4185 (void)del_bytes(next_leader_len, false, false);
4186 mark_col_adjust(curwin->w_cursor.lnum, (colnr_T)0, 0L,
4187 (long)-next_leader_len, 0);
4188 } else if (second_indent > 0) { // the "leader" for FO_Q_SECOND
4189 int indent = (int)getwhitecols_curline();
4190
4191 if (indent > 0) {
4192 (void)del_bytes(indent, FALSE, FALSE);
4193 mark_col_adjust(curwin->w_cursor.lnum,
4194 (colnr_T)0, 0L, (long)-indent, 0);
4195 }
4196 }
4197 curwin->w_cursor.lnum--;
4198 if (do_join(2, TRUE, FALSE, FALSE, false) == FAIL) {
4199 beep_flush();
4200 break;
4201 }
4202 first_par_line = FALSE;
4203 /* If the line is getting long, format it next time */
4204 if (STRLEN(get_cursor_line_ptr()) > (size_t)max_len)
4205 force_format = TRUE;
4206 else
4207 force_format = FALSE;
4208 }
4209 }
4210 line_breakcheck();
4211 }
4212}
4213
4214/*
4215 * Return TRUE if line "lnum" ends in a white character.
4216 */
4217static int ends_in_white(linenr_T lnum)
4218{
4219 char_u *s = ml_get(lnum);
4220 size_t l;
4221
4222 if (*s == NUL)
4223 return FALSE;
4224 l = STRLEN(s) - 1;
4225 return ascii_iswhite(s[l]);
4226}
4227
4228/*
4229 * Blank lines, and lines containing only the comment leader, are left
4230 * untouched by the formatting. The function returns TRUE in this
4231 * case. It also returns TRUE when a line starts with the end of a comment
4232 * ('e' in comment flags), so that this line is skipped, and not joined to the
4233 * previous line. A new paragraph starts after a blank line, or when the
4234 * comment leader changes -- webb.
4235 */
4236static int fmt_check_par(linenr_T lnum, int *leader_len, char_u **leader_flags, int do_comments)
4237{
4238 char_u *flags = NULL; /* init for GCC */
4239 char_u *ptr;
4240
4241 ptr = ml_get(lnum);
4242 if (do_comments)
4243 *leader_len = get_leader_len(ptr, leader_flags, FALSE, TRUE);
4244 else
4245 *leader_len = 0;
4246
4247 if (*leader_len > 0) {
4248 /*
4249 * Search for 'e' flag in comment leader flags.
4250 */
4251 flags = *leader_flags;
4252 while (*flags && *flags != ':' && *flags != COM_END)
4253 ++flags;
4254 }
4255
4256 return *skipwhite(ptr + *leader_len) == NUL
4257 || (*leader_len > 0 && *flags == COM_END)
4258 || startPS(lnum, NUL, FALSE);
4259}
4260
4261/*
4262 * Return TRUE when a paragraph starts in line "lnum". Return FALSE when the
4263 * previous line is in the same paragraph. Used for auto-formatting.
4264 */
4265int paragraph_start(linenr_T lnum)
4266{
4267 char_u *p;
4268 int leader_len = 0; /* leader len of current line */
4269 char_u *leader_flags = NULL; /* flags for leader of current line */
4270 int next_leader_len = 0; /* leader len of next line */
4271 char_u *next_leader_flags = NULL; /* flags for leader of next line */
4272 int do_comments; /* format comments */
4273
4274 if (lnum <= 1)
4275 return TRUE; /* start of the file */
4276
4277 p = ml_get(lnum - 1);
4278 if (*p == NUL)
4279 return TRUE; /* after empty line */
4280
4281 do_comments = has_format_option(FO_Q_COMS);
4282 if (fmt_check_par(lnum - 1
4283 , &leader_len, &leader_flags, do_comments
4284 ))
4285 return TRUE; /* after non-paragraph line */
4286
4287 if (fmt_check_par(lnum
4288 , &next_leader_len, &next_leader_flags, do_comments
4289 ))
4290 return TRUE; /* "lnum" is not a paragraph line */
4291
4292 if (has_format_option(FO_WHITE_PAR) && !ends_in_white(lnum - 1))
4293 return TRUE; /* missing trailing space in previous line. */
4294
4295 if (has_format_option(FO_Q_NUMBER) && (get_number_indent(lnum) > 0))
4296 return TRUE; /* numbered item starts in "lnum". */
4297
4298 if (!same_leader(lnum - 1, leader_len, leader_flags,
4299 next_leader_len, next_leader_flags))
4300 return TRUE; /* change of comment leader. */
4301
4302 return FALSE;
4303}
4304
4305/*
4306 * prepare a few things for block mode yank/delete/tilde
4307 *
4308 * for delete:
4309 * - textlen includes the first/last char to be (partly) deleted
4310 * - start/endspaces is the number of columns that are taken by the
4311 * first/last deleted char minus the number of columns that have to be
4312 * deleted.
4313 * for yank and tilde:
4314 * - textlen includes the first/last char to be wholly yanked
4315 * - start/endspaces is the number of columns of the first/last yanked char
4316 * that are to be yanked.
4317 */
4318static void block_prep(oparg_T *oap, struct block_def *bdp, linenr_T lnum,
4319 bool is_del)
4320{
4321 int incr = 0;
4322 char_u *pend;
4323 char_u *pstart;
4324 char_u *line;
4325 char_u *prev_pstart;
4326 char_u *prev_pend;
4327
4328 bdp->startspaces = 0;
4329 bdp->endspaces = 0;
4330 bdp->textlen = 0;
4331 bdp->start_vcol = 0;
4332 bdp->end_vcol = 0;
4333 bdp->is_short = FALSE;
4334 bdp->is_oneChar = FALSE;
4335 bdp->pre_whitesp = 0;
4336 bdp->pre_whitesp_c = 0;
4337 bdp->end_char_vcols = 0;
4338 bdp->start_char_vcols = 0;
4339
4340 line = ml_get(lnum);
4341 pstart = line;
4342 prev_pstart = line;
4343 while (bdp->start_vcol < oap->start_vcol && *pstart) {
4344 /* Count a tab for what it's worth (if list mode not on) */
4345 incr = lbr_chartabsize(line, pstart, (colnr_T)bdp->start_vcol);
4346 bdp->start_vcol += incr;
4347 if (ascii_iswhite(*pstart)) {
4348 bdp->pre_whitesp += incr;
4349 bdp->pre_whitesp_c++;
4350 } else {
4351 bdp->pre_whitesp = 0;
4352 bdp->pre_whitesp_c = 0;
4353 }
4354 prev_pstart = pstart;
4355 MB_PTR_ADV(pstart);
4356 }
4357 bdp->start_char_vcols = incr;
4358 if (bdp->start_vcol < oap->start_vcol) { /* line too short */
4359 bdp->end_vcol = bdp->start_vcol;
4360 bdp->is_short = TRUE;
4361 if (!is_del || oap->op_type == OP_APPEND)
4362 bdp->endspaces = oap->end_vcol - oap->start_vcol + 1;
4363 } else {
4364 /* notice: this converts partly selected Multibyte characters to
4365 * spaces, too. */
4366 bdp->startspaces = bdp->start_vcol - oap->start_vcol;
4367 if (is_del && bdp->startspaces)
4368 bdp->startspaces = bdp->start_char_vcols - bdp->startspaces;
4369 pend = pstart;
4370 bdp->end_vcol = bdp->start_vcol;
4371 if (bdp->end_vcol > oap->end_vcol) { /* it's all in one character */
4372 bdp->is_oneChar = TRUE;
4373 if (oap->op_type == OP_INSERT)
4374 bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
4375 else if (oap->op_type == OP_APPEND) {
4376 bdp->startspaces += oap->end_vcol - oap->start_vcol + 1;
4377 bdp->endspaces = bdp->start_char_vcols - bdp->startspaces;
4378 } else {
4379 bdp->startspaces = oap->end_vcol - oap->start_vcol + 1;
4380 if (is_del && oap->op_type != OP_LSHIFT) {
4381 /* just putting the sum of those two into
4382 * bdp->startspaces doesn't work for Visual replace,
4383 * so we have to split the tab in two */
4384 bdp->startspaces = bdp->start_char_vcols
4385 - (bdp->start_vcol - oap->start_vcol);
4386 bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
4387 }
4388 }
4389 } else {
4390 prev_pend = pend;
4391 while (bdp->end_vcol <= oap->end_vcol && *pend != NUL) {
4392 /* Count a tab for what it's worth (if list mode not on) */
4393 prev_pend = pend;
4394 incr = lbr_chartabsize_adv(line, &pend, (colnr_T)bdp->end_vcol);
4395 bdp->end_vcol += incr;
4396 }
4397 if (bdp->end_vcol <= oap->end_vcol
4398 && (!is_del
4399 || oap->op_type == OP_APPEND
4400 || oap->op_type == OP_REPLACE)) { /* line too short */
4401 bdp->is_short = TRUE;
4402 /* Alternative: include spaces to fill up the block.
4403 * Disadvantage: can lead to trailing spaces when the line is
4404 * short where the text is put */
4405 /* if (!is_del || oap->op_type == OP_APPEND) */
4406 if (oap->op_type == OP_APPEND || virtual_op)
4407 bdp->endspaces = oap->end_vcol - bdp->end_vcol
4408 + oap->inclusive;
4409 else
4410 bdp->endspaces = 0; /* replace doesn't add characters */
4411 } else if (bdp->end_vcol > oap->end_vcol) {
4412 bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1;
4413 if (!is_del && bdp->endspaces) {
4414 bdp->endspaces = incr - bdp->endspaces;
4415 if (pend != pstart)
4416 pend = prev_pend;
4417 }
4418 }
4419 }
4420 bdp->end_char_vcols = incr;
4421 if (is_del && bdp->startspaces)
4422 pstart = prev_pstart;
4423 bdp->textlen = (int)(pend - pstart);
4424 }
4425 bdp->textcol = (colnr_T) (pstart - line);
4426 bdp->textstart = pstart;
4427}
4428
4429/// Handle the add/subtract operator.
4430///
4431/// @param[in] oap Arguments of operator.
4432/// @param[in] Prenum1 Amount of addition or subtraction.
4433/// @param[in] g_cmd Prefixed with `g`.
4434void op_addsub(oparg_T *oap, linenr_T Prenum1, bool g_cmd)
4435{
4436 pos_T pos;
4437 struct block_def bd;
4438 ssize_t change_cnt = 0;
4439 linenr_T amount = Prenum1;
4440
4441 if (!VIsual_active) {
4442 pos = curwin->w_cursor;
4443 if (u_save_cursor() == FAIL) {
4444 return;
4445 }
4446 change_cnt = do_addsub(oap->op_type, &pos, 0, amount);
4447 if (change_cnt) {
4448 changed_lines(pos.lnum, 0, pos.lnum + 1, 0L, true);
4449 }
4450 } else {
4451 int one_change;
4452 int length;
4453 pos_T startpos;
4454
4455 if (u_save((linenr_T)(oap->start.lnum - 1),
4456 (linenr_T)(oap->end.lnum + 1)) == FAIL) {
4457 return;
4458 }
4459
4460 pos = oap->start;
4461 for (; pos.lnum <= oap->end.lnum; pos.lnum++) {
4462 if (oap->motion_type == kMTBlockWise) {
4463 // Visual block mode
4464 block_prep(oap, &bd, pos.lnum, false);
4465 pos.col = bd.textcol;
4466 length = bd.textlen;
4467 } else if (oap->motion_type == kMTLineWise) {
4468 curwin->w_cursor.col = 0;
4469 pos.col = 0;
4470 length = (colnr_T)STRLEN(ml_get(pos.lnum));
4471 } else {
4472 // oap->motion_type == kMTCharWise
4473 if (pos.lnum == oap->start.lnum && !oap->inclusive) {
4474 dec(&(oap->end));
4475 }
4476 length = (colnr_T)STRLEN(ml_get(pos.lnum));
4477 pos.col = 0;
4478 if (pos.lnum == oap->start.lnum) {
4479 pos.col += oap->start.col;
4480 length -= oap->start.col;
4481 }
4482 if (pos.lnum == oap->end.lnum) {
4483 length = (int)STRLEN(ml_get(oap->end.lnum));
4484 if (oap->end.col >= length) {
4485 oap->end.col = length - 1;
4486 }
4487 length = oap->end.col - pos.col + 1;
4488 }
4489 }
4490 one_change = do_addsub(oap->op_type, &pos, length, amount);
4491 if (one_change) {
4492 // Remember the start position of the first change.
4493 if (change_cnt == 0) {
4494 startpos = curbuf->b_op_start;
4495 }
4496 change_cnt++;
4497 }
4498
4499 if (g_cmd && one_change) {
4500 amount += Prenum1;
4501 }
4502 }
4503 if (change_cnt) {
4504 changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L, true);
4505 }
4506
4507 if (!change_cnt && oap->is_VIsual) {
4508 // No change: need to remove the Visual selection
4509 redraw_curbuf_later(INVERTED);
4510 }
4511
4512 // Set '[ mark if something changed. Keep the last end
4513 // position from do_addsub().
4514 if (change_cnt > 0) {
4515 curbuf->b_op_start = startpos;
4516 }
4517
4518 if (change_cnt > p_report) {
4519 if (change_cnt == 1) {
4520 MSG(_("1 line changed"));
4521 } else {
4522 smsg((char *)_("%" PRId64 " lines changed"), (int64_t)change_cnt);
4523 }
4524 }
4525 }
4526}
4527
4528/// Add or subtract from a number in a line.
4529///
4530/// @param op_type OP_NR_ADD or OP_NR_SUB.
4531/// @param pos Cursor position.
4532/// @param length Target number length.
4533/// @param Prenum1 Amount of addition or subtraction.
4534///
4535/// @return true if some character was changed.
4536int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1)
4537{
4538 int col;
4539 char_u *buf1;
4540 char_u buf2[NUMBUFLEN];
4541 int pre; // 'X' or 'x': hex; '0': octal; 'B' or 'b': bin
4542 static bool hexupper = false; // 0xABC
4543 uvarnumber_T n;
4544 uvarnumber_T oldn;
4545 char_u *ptr;
4546 int c;
4547 int todel;
4548 bool dohex;
4549 bool dooct;
4550 bool dobin;
4551 bool doalp;
4552 int firstdigit;
4553 bool subtract;
4554 bool negative = false;
4555 bool was_positive = true;
4556 bool visual = VIsual_active;
4557 bool did_change = false;
4558 pos_T save_cursor = curwin->w_cursor;
4559 int maxlen = 0;
4560 pos_T startpos;
4561 pos_T endpos;
4562
4563 dohex = (vim_strchr(curbuf->b_p_nf, 'x') != NULL); // "heX"
4564 dooct = (vim_strchr(curbuf->b_p_nf, 'o') != NULL); // "Octal"
4565 dobin = (vim_strchr(curbuf->b_p_nf, 'b') != NULL); // "Bin"
4566 doalp = (vim_strchr(curbuf->b_p_nf, 'p') != NULL); // "alPha"
4567
4568 curwin->w_cursor = *pos;
4569 ptr = ml_get(pos->lnum);
4570 col = pos->col;
4571
4572 if (*ptr == NUL) {
4573 goto theend;
4574 }
4575
4576 // First check if we are on a hexadecimal number, after the "0x".
4577 if (!VIsual_active) {
4578 if (dobin) {
4579 while (col > 0 && ascii_isbdigit(ptr[col])) {
4580 col--;
4581 col -= utf_head_off(ptr, ptr + col);
4582 }
4583 }
4584
4585 if (dohex) {
4586 while (col > 0 && ascii_isxdigit(ptr[col])) {
4587 col--;
4588 col -= utf_head_off(ptr, ptr + col);
4589 }
4590 }
4591 if (dobin
4592 && dohex
4593 && !((col > 0
4594 && (ptr[col] == 'X' || ptr[col] == 'x')
4595 && ptr[col - 1] == '0'
4596 && !utf_head_off(ptr, ptr + col - 1)
4597 && ascii_isxdigit(ptr[col + 1])))) {
4598 // In case of binary/hexadecimal pattern overlap match, rescan
4599
4600 col = curwin->w_cursor.col;
4601
4602 while (col > 0 && ascii_isdigit(ptr[col])) {
4603 col--;
4604 col -= utf_head_off(ptr, ptr + col);
4605 }
4606 }
4607
4608 if ((dohex
4609 && col > 0
4610 && (ptr[col] == 'X' || ptr[col] == 'x')
4611 && ptr[col - 1] == '0'
4612 && !utf_head_off(ptr, ptr + col - 1)
4613 && ascii_isxdigit(ptr[col + 1]))
4614 || (dobin
4615 && col > 0
4616 && (ptr[col] == 'B' || ptr[col] == 'b')
4617 && ptr[col - 1] == '0'
4618 && !utf_head_off(ptr, ptr + col - 1)
4619 && ascii_isbdigit(ptr[col + 1]))) {
4620 // Found hexadecimal or binary number, move to its start.
4621 col--;
4622 col -= utf_head_off(ptr, ptr + col);
4623 } else {
4624 // Search forward and then backward to find the start of number.
4625 col = pos->col;
4626
4627 while (ptr[col] != NUL
4628 && !ascii_isdigit(ptr[col])
4629 && !(doalp && ASCII_ISALPHA(ptr[col]))) {
4630 col++;
4631 }
4632
4633 while (col > 0
4634 && ascii_isdigit(ptr[col - 1])
4635 && !(doalp && ASCII_ISALPHA(ptr[col]))) {
4636 col--;
4637 }
4638 }
4639 }
4640
4641 if (visual) {
4642 while (ptr[col] != NUL && length > 0 && !ascii_isdigit(ptr[col])
4643 && !(doalp && ASCII_ISALPHA(ptr[col]))) {
4644 int mb_len = MB_PTR2LEN(ptr + col);
4645
4646 col += mb_len;
4647 length -= mb_len;
4648 }
4649
4650 if (length == 0) {
4651 goto theend;
4652 }
4653
4654 if (col > pos->col && ptr[col - 1] == '-'
4655 && !utf_head_off(ptr, ptr + col - 1)) {
4656 negative = true;
4657 was_positive = false;
4658 }
4659 }
4660
4661 // If a number was found, and saving for undo works, replace the number.
4662 firstdigit = ptr[col];
4663 if (!ascii_isdigit(firstdigit) && !(doalp && ASCII_ISALPHA(firstdigit))) {
4664 beep_flush();
4665 goto theend;
4666 }
4667
4668 if (doalp && ASCII_ISALPHA(firstdigit)) {
4669 // decrement or increment alphabetic character
4670 if (op_type == OP_NR_SUB) {
4671 if (CharOrd(firstdigit) < Prenum1) {
4672 if (isupper(firstdigit)) {
4673 firstdigit = 'A';
4674 } else {
4675 firstdigit = 'a';
4676 }
4677 } else {
4678 firstdigit -= (int)Prenum1;
4679 }
4680 } else {
4681 if (26 - CharOrd(firstdigit) - 1 < Prenum1) {
4682 if (isupper(firstdigit)) {
4683 firstdigit = 'Z';
4684 } else {
4685 firstdigit = 'z';
4686 }
4687 } else {
4688 firstdigit += (int)Prenum1;
4689 }
4690 }
4691 curwin->w_cursor.col = col;
4692 startpos = curwin->w_cursor;
4693 did_change = true;
4694 (void)del_char(false);
4695 ins_char(firstdigit);
4696 endpos = curwin->w_cursor;
4697 curwin->w_cursor.col = col;
4698 } else {
4699 if (col > 0 && ptr[col - 1] == '-'
4700 && !utf_head_off(ptr, ptr + col - 1) && !visual) {
4701 // negative number
4702 col--;
4703 negative = true;
4704 }
4705
4706 // get the number value (unsigned)
4707 if (visual && VIsual_mode != 'V') {
4708 maxlen = (curbuf->b_visual.vi_curswant == MAXCOL
4709 ? (int)STRLEN(ptr) - col
4710 : length);
4711 }
4712
4713 vim_str2nr(ptr + col, &pre, &length,
4714 0 + (dobin ? STR2NR_BIN : 0)
4715 + (dooct ? STR2NR_OCT : 0)
4716 + (dohex ? STR2NR_HEX : 0),
4717 NULL, &n, maxlen);
4718
4719 // ignore leading '-' for hex, octal and bin numbers
4720 if (pre && negative) {
4721 col++;
4722 length--;
4723 negative = false;
4724 }
4725
4726 // add or subtract
4727 subtract = false;
4728 if (op_type == OP_NR_SUB) {
4729 subtract ^= true;
4730 }
4731 if (negative) {
4732 subtract ^= true;
4733 }
4734
4735 oldn = n;
4736
4737 n = subtract ? n - (uvarnumber_T)Prenum1
4738 : n + (uvarnumber_T)Prenum1;
4739
4740 // handle wraparound for decimal numbers
4741 if (!pre) {
4742 if (subtract) {
4743 if (n > oldn) {
4744 n = 1 + (n ^ (uvarnumber_T)-1);
4745 negative ^= true;
4746 }
4747 } else {
4748 // add
4749 if (n < oldn) {
4750 n = (n ^ (uvarnumber_T)-1);
4751 negative ^= true;
4752 }
4753 }
4754 if (n == 0) {
4755 negative = false;
4756 }
4757 }
4758
4759 if (visual && !was_positive && !negative && col > 0) {
4760 // need to remove the '-'
4761 col--;
4762 length++;
4763 }
4764
4765 // Delete the old number.
4766 curwin->w_cursor.col = col;
4767 startpos = curwin->w_cursor;
4768 did_change = true;
4769 todel = length;
4770 c = gchar_cursor();
4771
4772 // Don't include the '-' in the length, only the length of the part
4773 // after it is kept the same.
4774 if (c == '-') {
4775 length--;
4776 }
4777 while (todel-- > 0) {
4778 if (c < 0x100 && isalpha(c)) {
4779 if (isupper(c)) {
4780 hexupper = true;
4781 } else {
4782 hexupper = false;
4783 }
4784 }
4785 // del_char() will mark line needing displaying
4786 (void)del_char(false);
4787 c = gchar_cursor();
4788 }
4789
4790 // Prepare the leading characters in buf1[].
4791 // When there are many leading zeros it could be very long.
4792 // Allocate a bit too much.
4793 buf1 = xmalloc((size_t)length + NUMBUFLEN);
4794 ptr = buf1;
4795 if (negative && (!visual || was_positive)) {
4796 *ptr++ = '-';
4797 }
4798 if (pre) {
4799 *ptr++ = '0';
4800 length--;
4801 }
4802 if (pre == 'b' || pre == 'B' || pre == 'x' || pre == 'X') {
4803 *ptr++ = (char_u)pre;
4804 length--;
4805 }
4806
4807 // Put the number characters in buf2[].
4808 if (pre == 'b' || pre == 'B') {
4809 size_t bits = 0;
4810 size_t i = 0;
4811
4812 // leading zeros
4813 for (bits = 8 * sizeof(n); bits > 0; bits--) {
4814 if ((n >> (bits - 1)) & 0x1) {
4815 break;
4816 }
4817 }
4818
4819 while (bits > 0) {
4820 buf2[i++] = ((n >> --bits) & 0x1) ? '1' : '0';
4821 }
4822
4823 buf2[i] = '\0';
4824
4825 } else if (pre == 0) {
4826 vim_snprintf((char *)buf2, ARRAY_SIZE(buf2), "%" PRIu64, (uint64_t)n);
4827 } else if (pre == '0') {
4828 vim_snprintf((char *)buf2, ARRAY_SIZE(buf2), "%" PRIo64, (uint64_t)n);
4829 } else if (hexupper) {
4830 vim_snprintf((char *)buf2, ARRAY_SIZE(buf2), "%" PRIX64, (uint64_t)n);
4831 } else {
4832 vim_snprintf((char *)buf2, ARRAY_SIZE(buf2), "%" PRIx64, (uint64_t)n);
4833 }
4834 length -= (int)STRLEN(buf2);
4835
4836 // Adjust number of zeros to the new number of digits, so the
4837 // total length of the number remains the same.
4838 // Don't do this when
4839 // the result may look like an octal number.
4840 if (firstdigit == '0' && !(dooct && pre == 0)) {
4841 while (length-- > 0) {
4842 *ptr++ = '0';
4843 }
4844 }
4845 *ptr = NUL;
4846 STRCAT(buf1, buf2);
4847 ins_str(buf1); // insert the new number
4848 xfree(buf1);
4849 endpos = curwin->w_cursor;
4850 if (curwin->w_cursor.col) {
4851 curwin->w_cursor.col--;
4852 }
4853 }
4854
4855 // set the '[ and '] marks
4856 curbuf->b_op_start = startpos;
4857 curbuf->b_op_end = endpos;
4858 if (curbuf->b_op_end.col > 0) {
4859 curbuf->b_op_end.col--;
4860 }
4861
4862theend:
4863 if (visual) {
4864 curwin->w_cursor = save_cursor;
4865 } else if (did_change) {
4866 curwin->w_set_curswant = true;
4867 }
4868
4869 return did_change;
4870}
4871
4872/*
4873 * Return the type of a register.
4874 * Used for getregtype()
4875 * Returns kMTUnknown for error.
4876 */
4877MotionType get_reg_type(int regname, colnr_T *reg_width)
4878{
4879 switch (regname) {
4880 case '%': // file name
4881 case '#': // alternate file name
4882 case '=': // expression
4883 case ':': // last command line
4884 case '/': // last search-pattern
4885 case '.': // last inserted text
4886 case Ctrl_F: // Filename under cursor
4887 case Ctrl_P: // Path under cursor, expand via "path"
4888 case Ctrl_W: // word under cursor
4889 case Ctrl_A: // WORD (mnemonic All) under cursor
4890 case '_': // black hole: always empty
4891 return kMTCharWise;
4892 }
4893
4894 if (regname != NUL && !valid_yank_reg(regname, false)) {
4895 return kMTUnknown;
4896 }
4897
4898 yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
4899
4900 if (reg->y_array != NULL) {
4901 if (reg_width != NULL && reg->y_type == kMTBlockWise) {
4902 *reg_width = reg->y_width;
4903 }
4904 return reg->y_type;
4905 }
4906 return kMTUnknown;
4907}
4908
4909/// Format the register type as a string.
4910///
4911/// @param reg_type The register type.
4912/// @param reg_width The width, only used if "reg_type" is kMTBlockWise.
4913/// @param[out] buf Buffer to store formatted string. The allocated size should
4914/// be at least NUMBUFLEN+2 to always fit the value.
4915/// @param buf_len The allocated size of the buffer.
4916void format_reg_type(MotionType reg_type, colnr_T reg_width,
4917 char *buf, size_t buf_len)
4918 FUNC_ATTR_NONNULL_ALL
4919{
4920 assert(buf_len > 1);
4921 switch (reg_type) {
4922 case kMTLineWise:
4923 buf[0] = 'V';
4924 buf[1] = NUL;
4925 break;
4926 case kMTCharWise:
4927 buf[0] = 'v';
4928 buf[1] = NUL;
4929 break;
4930 case kMTBlockWise:
4931 snprintf(buf, buf_len, CTRL_V_STR "%" PRIdCOLNR, reg_width + 1);
4932 break;
4933 case kMTUnknown:
4934 buf[0] = NUL;
4935 break;
4936 }
4937}
4938
4939
4940/// When `flags` has `kGRegList` return a list with text `s`.
4941/// Otherwise just return `s`.
4942///
4943/// Returns a void * for use in get_reg_contents().
4944static void *get_reg_wrap_one_line(char_u *s, int flags)
4945{
4946 if (!(flags & kGRegList)) {
4947 return s;
4948 }
4949 list_T *const list = tv_list_alloc(1);
4950 tv_list_append_allocated_string(list, (char *)s);
4951 return list;
4952}
4953
4954/// Gets the contents of a register.
4955/// @remark Used for `@r` in expressions and for `getreg()`.
4956///
4957/// @param regname The register.
4958/// @param flags see @ref GRegFlags
4959///
4960/// @returns The contents of the register as an allocated string.
4961/// @returns A linked list when `flags` contains @ref kGRegList.
4962/// @returns NULL for error.
4963void *get_reg_contents(int regname, int flags)
4964{
4965 // Don't allow using an expression register inside an expression.
4966 if (regname == '=') {
4967 if (flags & kGRegNoExpr) {
4968 return NULL;
4969 }
4970 if (flags & kGRegExprSrc) {
4971 return get_reg_wrap_one_line(get_expr_line_src(), flags);
4972 }
4973 return get_reg_wrap_one_line(get_expr_line(), flags);
4974 }
4975
4976 if (regname == '@') /* "@@" is used for unnamed register */
4977 regname = '"';
4978
4979 /* check for valid regname */
4980 if (regname != NUL && !valid_yank_reg(regname, false))
4981 return NULL;
4982
4983 char_u *retval;
4984 bool allocated;
4985 if (get_spec_reg(regname, &retval, &allocated, false)) {
4986 if (retval == NULL) {
4987 return NULL;
4988 }
4989 if (allocated) {
4990 return get_reg_wrap_one_line(retval, flags);
4991 }
4992 return get_reg_wrap_one_line(vim_strsave(retval), flags);
4993 }
4994
4995 yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
4996 if (reg->y_array == NULL)
4997 return NULL;
4998
4999 if (flags & kGRegList) {
5000 list_T *const list = tv_list_alloc((ptrdiff_t)reg->y_size);
5001 for (size_t i = 0; i < reg->y_size; i++) {
5002 tv_list_append_string(list, (const char *)reg->y_array[i], -1);
5003 }
5004
5005 return list;
5006 }
5007
5008 /*
5009 * Compute length of resulting string.
5010 */
5011 size_t len = 0;
5012 for (size_t i = 0; i < reg->y_size; i++) {
5013 len += STRLEN(reg->y_array[i]);
5014 /*
5015 * Insert a newline between lines and after last line if
5016 * y_type is kMTLineWise.
5017 */
5018 if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
5019 len++;
5020 }
5021 }
5022
5023 retval = xmalloc(len + 1);
5024
5025 /*
5026 * Copy the lines of the yank register into the string.
5027 */
5028 len = 0;
5029 for (size_t i = 0; i < reg->y_size; i++) {
5030 STRCPY(retval + len, reg->y_array[i]);
5031 len += STRLEN(retval + len);
5032
5033 /*
5034 * Insert a NL between lines and after the last line if y_type is
5035 * kMTLineWise.
5036 */
5037 if (reg->y_type == kMTLineWise || i < reg->y_size - 1) {
5038 retval[len++] = '\n';
5039 }
5040 }
5041 retval[len] = NUL;
5042
5043 return retval;
5044}
5045
5046static yankreg_T *init_write_reg(int name, yankreg_T **old_y_previous, bool must_append)
5047{
5048 if (!valid_yank_reg(name, true)) { // check for valid reg name
5049 emsg_invreg(name);
5050 return NULL;
5051 }
5052
5053 // Don't want to change the current (unnamed) register.
5054 *old_y_previous = y_previous;
5055
5056 yankreg_T *reg = get_yank_register(name, YREG_YANK);
5057 if (!is_append_register(name) && !must_append) {
5058 free_register(reg);
5059 }
5060 return reg;
5061}
5062
5063static void finish_write_reg(int name, yankreg_T *reg, yankreg_T *old_y_previous)
5064{
5065 // Send text of clipboard register to the clipboard.
5066 set_clipboard(name, reg);
5067
5068 // ':let @" = "val"' should change the meaning of the "" register
5069 if (name != '"') {
5070 y_previous = old_y_previous;
5071 }
5072}
5073
5074/// write_reg_contents - store `str` in register `name`
5075///
5076/// @see write_reg_contents_ex
5077void write_reg_contents(int name, const char_u *str, ssize_t len,
5078 int must_append)
5079{
5080 write_reg_contents_ex(name, str, len, must_append, kMTUnknown, 0L);
5081}
5082
5083void write_reg_contents_lst(int name, char_u **strings,
5084 bool must_append, MotionType yank_type,
5085 colnr_T block_len)
5086{
5087 if (name == '/' || name == '=') {
5088 char_u *s = strings[0];
5089 if (strings[0] == NULL) {
5090 s = (char_u *)"";
5091 } else if (strings[1] != NULL) {
5092 EMSG(_("E883: search pattern and expression register may not "
5093 "contain two or more lines"));
5094 return;
5095 }
5096 write_reg_contents_ex(name, s, -1, must_append, yank_type, block_len);
5097 return;
5098 }
5099
5100 // black hole: nothing to do
5101 if (name == '_') {
5102 return;
5103 }
5104
5105 yankreg_T *old_y_previous, *reg;
5106 if (!(reg = init_write_reg(name, &old_y_previous, must_append))) {
5107 return;
5108 }
5109
5110 str_to_reg(reg, yank_type, (char_u *)strings, STRLEN((char_u *)strings),
5111 block_len, true);
5112 finish_write_reg(name, reg, old_y_previous);
5113}
5114
5115/// write_reg_contents_ex - store `str` in register `name`
5116///
5117/// If `str` ends in '\n' or '\r', use linewise, otherwise use
5118/// characterwise.
5119///
5120/// @warning when `name` is '/', `len` and `must_append` are ignored. This
5121/// means that `str` MUST be NUL-terminated.
5122///
5123/// @param name The name of the register
5124/// @param str The contents to write
5125/// @param len If >= 0, write `len` bytes of `str`. Otherwise, write
5126/// `strlen(str)` bytes. If `len` is larger than the
5127/// allocated size of `src`, the behaviour is undefined.
5128/// @param must_append If true, append the contents of `str` to the current
5129/// contents of the register. Note that regardless of
5130/// `must_append`, this function will append when `name`
5131/// is an uppercase letter.
5132/// @param yank_type The motion type (kMTUnknown to auto detect)
5133/// @param block_len width of visual block
5134void write_reg_contents_ex(int name,
5135 const char_u *str,
5136 ssize_t len,
5137 bool must_append,
5138 MotionType yank_type,
5139 colnr_T block_len)
5140{
5141 if (len < 0) {
5142 len = (ssize_t) STRLEN(str);
5143 }
5144
5145 /* Special case: '/' search pattern */
5146 if (name == '/') {
5147 set_last_search_pat(str, RE_SEARCH, TRUE, TRUE);
5148 return;
5149 }
5150
5151 if (name == '#') {
5152 buf_T *buf;
5153
5154 if (ascii_isdigit(*str)) {
5155 int num = atoi((char *)str);
5156
5157 buf = buflist_findnr(num);
5158 if (buf == NULL) {
5159 EMSGN(_(e_nobufnr), (long)num);
5160 }
5161 } else {
5162 buf = buflist_findnr(buflist_findpat(str, str + STRLEN(str),
5163 true, false, false));
5164 }
5165 if (buf == NULL) {
5166 return;
5167 }
5168 curwin->w_alt_fnum = buf->b_fnum;
5169 return;
5170 }
5171
5172 if (name == '=') {
5173 size_t offset = 0;
5174 size_t totlen = (size_t) len;
5175
5176 if (must_append && expr_line) {
5177 // append has been specified and expr_line already exists, so we'll
5178 // append the new string to expr_line.
5179 size_t exprlen = STRLEN(expr_line);
5180
5181 totlen += exprlen;
5182 offset = exprlen;
5183 }
5184
5185 // modify the global expr_line, extend/shrink it if necessary (realloc).
5186 // Copy the input string into the adjusted memory at the specified
5187 // offset.
5188 expr_line = xrealloc(expr_line, totlen + 1);
5189 memcpy(expr_line + offset, str, (size_t)len);
5190 expr_line[totlen] = NUL;
5191
5192 return;
5193 }
5194
5195 if (name == '_') { // black hole: nothing to do
5196 return;
5197 }
5198
5199 yankreg_T *old_y_previous, *reg;
5200 if (!(reg = init_write_reg(name, &old_y_previous, must_append))) {
5201 return;
5202 }
5203 str_to_reg(reg, yank_type, str, (size_t)len, block_len, false);
5204 finish_write_reg(name, reg, old_y_previous);
5205}
5206
5207/// str_to_reg - Put a string into a register.
5208///
5209/// When the register is not empty, the string is appended.
5210///
5211/// @param y_ptr pointer to yank register
5212/// @param yank_type The motion type (kMTUnknown to auto detect)
5213/// @param str string or list of strings to put in register
5214/// @param len length of the string (Ignored when str_list=true.)
5215/// @param blocklen width of visual block, or -1 for "I don't know."
5216/// @param str_list True if str is `char_u **`.
5217static void str_to_reg(yankreg_T *y_ptr, MotionType yank_type,
5218 const char_u *str, size_t len, colnr_T blocklen,
5219 bool str_list)
5220 FUNC_ATTR_NONNULL_ALL
5221{
5222 if (y_ptr->y_array == NULL) { // NULL means empty register
5223 y_ptr->y_size = 0;
5224 }
5225
5226 if (yank_type == kMTUnknown) {
5227 yank_type = ((str_list
5228 || (len > 0 && (str[len - 1] == NL || str[len - 1] == CAR)))
5229 ? kMTLineWise : kMTCharWise);
5230 }
5231
5232 size_t newlines = 0;
5233 bool extraline = false; // extra line at the end
5234 bool append = false; // append to last line in register
5235
5236 // Count the number of lines within the string
5237 if (str_list) {
5238 for (char_u **ss = (char_u **) str; *ss != NULL; ++ss) {
5239 newlines++;
5240 }
5241 } else {
5242 newlines = memcnt(str, '\n', len);
5243 if (yank_type == kMTCharWise || len == 0 || str[len - 1] != '\n') {
5244 extraline = 1;
5245 ++newlines; // count extra newline at the end
5246 }
5247 if (y_ptr->y_size > 0 && y_ptr->y_type == kMTCharWise) {
5248 append = true;
5249 --newlines; // uncount newline when appending first line
5250 }
5251 }
5252
5253
5254 // Grow the register array to hold the pointers to the new lines.
5255 char_u **pp = xrealloc(y_ptr->y_array,
5256 (y_ptr->y_size + newlines) * sizeof(char_u *));
5257 y_ptr->y_array = pp;
5258
5259 size_t lnum = y_ptr->y_size; // The current line number.
5260
5261 // If called with `blocklen < 0`, we have to update the yank reg's width.
5262 size_t maxlen = 0;
5263
5264 // Find the end of each line and save it into the array.
5265 if (str_list) {
5266 for (char_u **ss = (char_u **) str; *ss != NULL; ++ss, ++lnum) {
5267 size_t ss_len = STRLEN(*ss);
5268 pp[lnum] = xmemdupz(*ss, ss_len);
5269 if (ss_len > maxlen) {
5270 maxlen = ss_len;
5271 }
5272 }
5273 } else {
5274 size_t line_len;
5275 for (const char_u *start = str, *end = str + len;
5276 start < end + extraline;
5277 start += line_len + 1, lnum++) {
5278 assert(end - start >= 0);
5279 line_len = (size_t)((char_u *)xmemscan(start, '\n',
5280 (size_t)(end - start)) - start);
5281 if (line_len > maxlen) {
5282 maxlen = line_len;
5283 }
5284
5285 // When appending, copy the previous line and free it after.
5286 size_t extra = append ? STRLEN(pp[--lnum]) : 0;
5287 char_u *s = xmallocz(line_len + extra);
5288 memcpy(s, pp[lnum], extra);
5289 memcpy(s + extra, start, line_len);
5290 size_t s_len = extra + line_len;
5291
5292 if (append) {
5293 xfree(pp[lnum]);
5294 append = false; // only first line is appended
5295 }
5296 pp[lnum] = s;
5297
5298 // Convert NULs to '\n' to prevent truncation.
5299 memchrsub(pp[lnum], NUL, '\n', s_len);
5300 }
5301 }
5302 y_ptr->y_type = yank_type;
5303 y_ptr->y_size = lnum;
5304 set_yreg_additional_data(y_ptr, NULL);
5305 y_ptr->timestamp = os_time();
5306 if (yank_type == kMTBlockWise) {
5307 y_ptr->y_width = (blocklen == -1 ? (colnr_T) maxlen - 1 : blocklen);
5308 } else {
5309 y_ptr->y_width = 0;
5310 }
5311}
5312
5313void clear_oparg(oparg_T *oap)
5314{
5315 memset(oap, 0, sizeof(oparg_T));
5316}
5317
5318
5319/*
5320 * Count the number of bytes, characters and "words" in a line.
5321 *
5322 * "Words" are counted by looking for boundaries between non-space and
5323 * space characters. (it seems to produce results that match 'wc'.)
5324 *
5325 * Return value is byte count; word count for the line is added to "*wc".
5326 * Char count is added to "*cc".
5327 *
5328 * The function will only examine the first "limit" characters in the
5329 * line, stopping if it encounters an end-of-line (NUL byte). In that
5330 * case, eol_size will be added to the character count to account for
5331 * the size of the EOL character.
5332 */
5333static varnumber_T line_count_info(char_u *line, varnumber_T *wc,
5334 varnumber_T *cc, varnumber_T limit,
5335 int eol_size)
5336{
5337 varnumber_T i;
5338 varnumber_T words = 0;
5339 varnumber_T chars = 0;
5340 int is_word = 0;
5341
5342 for (i = 0; i < limit && line[i] != NUL; ) {
5343 if (is_word) {
5344 if (ascii_isspace(line[i])) {
5345 words++;
5346 is_word = 0;
5347 }
5348 } else if (!ascii_isspace(line[i]))
5349 is_word = 1;
5350 ++chars;
5351 i += (*mb_ptr2len)(line + i);
5352 }
5353
5354 if (is_word)
5355 words++;
5356 *wc += words;
5357
5358 /* Add eol_size if the end of line was reached before hitting limit. */
5359 if (i < limit && line[i] == NUL) {
5360 i += eol_size;
5361 chars += eol_size;
5362 }
5363 *cc += chars;
5364 return i;
5365}
5366
5367/// Give some info about the position of the cursor (for "g CTRL-G").
5368/// In Visual mode, give some info about the selected region. (In this case,
5369/// the *_count_cursor variables store running totals for the selection.)
5370/// When "dict" is not NULL store the info there instead of showing it.
5371void cursor_pos_info(dict_T *dict)
5372{
5373 char_u *p;
5374 char_u buf1[50];
5375 char_u buf2[40];
5376 linenr_T lnum;
5377 varnumber_T byte_count = 0;
5378 varnumber_T bom_count = 0;
5379 varnumber_T byte_count_cursor = 0;
5380 varnumber_T char_count = 0;
5381 varnumber_T char_count_cursor = 0;
5382 varnumber_T word_count = 0;
5383 varnumber_T word_count_cursor = 0;
5384 int eol_size;
5385 varnumber_T last_check = 100000L;
5386 long line_count_selected = 0;
5387 pos_T min_pos, max_pos;
5388 oparg_T oparg;
5389 struct block_def bd;
5390 const int l_VIsual_active = VIsual_active;
5391 const int l_VIsual_mode = VIsual_mode;
5392
5393 // Compute the length of the file in characters.
5394 if (curbuf->b_ml.ml_flags & ML_EMPTY) {
5395 if (dict == NULL) {
5396 MSG(_(no_lines_msg));
5397 return;
5398 }
5399 } else {
5400 if (get_fileformat(curbuf) == EOL_DOS)
5401 eol_size = 2;
5402 else
5403 eol_size = 1;
5404
5405 if (l_VIsual_active) {
5406 if (lt(VIsual, curwin->w_cursor)) {
5407 min_pos = VIsual;
5408 max_pos = curwin->w_cursor;
5409 } else {
5410 min_pos = curwin->w_cursor;
5411 max_pos = VIsual;
5412 }
5413 if (*p_sel == 'e' && max_pos.col > 0)
5414 --max_pos.col;
5415
5416 if (l_VIsual_mode == Ctrl_V) {
5417 char_u * saved_sbr = p_sbr;
5418
5419 /* Make 'sbr' empty for a moment to get the correct size. */
5420 p_sbr = empty_option;
5421 oparg.is_VIsual = true;
5422 oparg.motion_type = kMTBlockWise;
5423 oparg.op_type = OP_NOP;
5424 getvcols(curwin, &min_pos, &max_pos,
5425 &oparg.start_vcol, &oparg.end_vcol);
5426 p_sbr = saved_sbr;
5427 if (curwin->w_curswant == MAXCOL)
5428 oparg.end_vcol = MAXCOL;
5429 /* Swap the start, end vcol if needed */
5430 if (oparg.end_vcol < oparg.start_vcol) {
5431 oparg.end_vcol += oparg.start_vcol;
5432 oparg.start_vcol = oparg.end_vcol - oparg.start_vcol;
5433 oparg.end_vcol -= oparg.start_vcol;
5434 }
5435 }
5436 line_count_selected = max_pos.lnum - min_pos.lnum + 1;
5437 }
5438
5439 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) {
5440 /* Check for a CTRL-C every 100000 characters. */
5441 if (byte_count > last_check) {
5442 os_breakcheck();
5443 if (got_int)
5444 return;
5445 last_check = byte_count + 100000L;
5446 }
5447
5448 /* Do extra processing for VIsual mode. */
5449 if (l_VIsual_active
5450 && lnum >= min_pos.lnum && lnum <= max_pos.lnum) {
5451 char_u *s = NULL;
5452 long len = 0L;
5453
5454 switch (l_VIsual_mode) {
5455 case Ctrl_V:
5456 virtual_op = virtual_active();
5457 block_prep(&oparg, &bd, lnum, false);
5458 virtual_op = kNone;
5459 s = bd.textstart;
5460 len = (long)bd.textlen;
5461 break;
5462 case 'V':
5463 s = ml_get(lnum);
5464 len = MAXCOL;
5465 break;
5466 case 'v':
5467 {
5468 colnr_T start_col = (lnum == min_pos.lnum)
5469 ? min_pos.col : 0;
5470 colnr_T end_col = (lnum == max_pos.lnum)
5471 ? max_pos.col - start_col + 1 : MAXCOL;
5472
5473 s = ml_get(lnum) + start_col;
5474 len = end_col;
5475 }
5476 break;
5477 }
5478 if (s != NULL) {
5479 byte_count_cursor += line_count_info(s, &word_count_cursor,
5480 &char_count_cursor, len, eol_size);
5481 if (lnum == curbuf->b_ml.ml_line_count
5482 && !curbuf->b_p_eol
5483 && (curbuf->b_p_bin || !curbuf->b_p_fixeol)
5484 && (long)STRLEN(s) < len)
5485 byte_count_cursor -= eol_size;
5486 }
5487 } else {
5488 /* In non-visual mode, check for the line the cursor is on */
5489 if (lnum == curwin->w_cursor.lnum) {
5490 word_count_cursor += word_count;
5491 char_count_cursor += char_count;
5492 byte_count_cursor = byte_count
5493 + line_count_info(ml_get(lnum), &word_count_cursor,
5494 &char_count_cursor,
5495 (varnumber_T)curwin->w_cursor.col + 1,
5496 eol_size);
5497 }
5498 }
5499 // Add to the running totals
5500 byte_count += line_count_info(ml_get(lnum), &word_count, &char_count,
5501 (varnumber_T)MAXCOL, eol_size);
5502 }
5503
5504 // Correction for when last line doesn't have an EOL.
5505 if (!curbuf->b_p_eol && (curbuf->b_p_bin || !curbuf->b_p_fixeol)) {
5506 byte_count -= eol_size;
5507 }
5508
5509 if (dict == NULL) {
5510 if (l_VIsual_active) {
5511 if (l_VIsual_mode == Ctrl_V && curwin->w_curswant < MAXCOL) {
5512 getvcols(curwin, &min_pos, &max_pos, &min_pos.col, &max_pos.col);
5513 int64_t cols;
5514 STRICT_SUB(oparg.end_vcol + 1, oparg.start_vcol, &cols, int64_t);
5515 vim_snprintf((char *)buf1, sizeof(buf1), _("%" PRId64 " Cols; "),
5516 cols);
5517 } else {
5518 buf1[0] = NUL;
5519 }
5520
5521 if (char_count_cursor == byte_count_cursor
5522 && char_count == byte_count) {
5523 vim_snprintf((char *)IObuff, IOSIZE,
5524 _("Selected %s%" PRId64 " of %" PRId64 " Lines;"
5525 " %" PRId64 " of %" PRId64 " Words;"
5526 " %" PRId64 " of %" PRId64 " Bytes"),
5527 buf1, (int64_t)line_count_selected,
5528 (int64_t)curbuf->b_ml.ml_line_count,
5529 (int64_t)word_count_cursor, (int64_t)word_count,
5530 (int64_t)byte_count_cursor, (int64_t)byte_count);
5531 } else {
5532 vim_snprintf((char *)IObuff, IOSIZE,
5533 _("Selected %s%" PRId64 " of %" PRId64 " Lines;"
5534 " %" PRId64 " of %" PRId64 " Words;"
5535 " %" PRId64 " of %" PRId64 " Chars;"
5536 " %" PRId64 " of %" PRId64 " Bytes"),
5537 buf1, (int64_t)line_count_selected,
5538 (int64_t)curbuf->b_ml.ml_line_count,
5539 (int64_t)word_count_cursor, (int64_t)word_count,
5540 (int64_t)char_count_cursor, (int64_t)char_count,
5541 (int64_t)byte_count_cursor, (int64_t)byte_count);
5542 }
5543 } else {
5544 p = get_cursor_line_ptr();
5545 validate_virtcol();
5546 col_print(buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1,
5547 (int)curwin->w_virtcol + 1);
5548 col_print(buf2, sizeof(buf2), (int)STRLEN(p), linetabsize(p));
5549
5550 if (char_count_cursor == byte_count_cursor
5551 && char_count == byte_count) {
5552 vim_snprintf((char *)IObuff, IOSIZE,
5553 _("Col %s of %s; Line %" PRId64 " of %" PRId64 ";"
5554 " Word %" PRId64 " of %" PRId64 ";"
5555 " Byte %" PRId64 " of %" PRId64 ""),
5556 (char *)buf1, (char *)buf2,
5557 (int64_t)curwin->w_cursor.lnum,
5558 (int64_t)curbuf->b_ml.ml_line_count,
5559 (int64_t)word_count_cursor, (int64_t)word_count,
5560 (int64_t)byte_count_cursor, (int64_t)byte_count);
5561 } else {
5562 vim_snprintf((char *)IObuff, IOSIZE,
5563 _("Col %s of %s; Line %" PRId64 " of %" PRId64 ";"
5564 " Word %" PRId64 " of %" PRId64 ";"
5565 " Char %" PRId64 " of %" PRId64 ";"
5566 " Byte %" PRId64 " of %" PRId64 ""),
5567 (char *)buf1, (char *)buf2,
5568 (int64_t)curwin->w_cursor.lnum,
5569 (int64_t)curbuf->b_ml.ml_line_count,
5570 (int64_t)word_count_cursor, (int64_t)word_count,
5571 (int64_t)char_count_cursor, (int64_t)char_count,
5572 (int64_t)byte_count_cursor, (int64_t)byte_count);
5573 }
5574 }
5575 }
5576
5577 bom_count = bomb_size();
5578 if (dict == NULL && bom_count > 0) {
5579 vim_snprintf((char *)IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff),
5580 _("(+%" PRId64 " for BOM)"), (int64_t)bom_count);
5581 }
5582 if (dict == NULL) {
5583 // Don't shorten this message, the user asked for it.
5584 p = p_shm;
5585 p_shm = (char_u *)"";
5586 msg(IObuff);
5587 p_shm = p;
5588 }
5589 }
5590
5591 if (dict != NULL) {
5592 // Don't shorten this message, the user asked for it.
5593 tv_dict_add_nr(dict, S_LEN("words"), (varnumber_T)word_count);
5594 tv_dict_add_nr(dict, S_LEN("chars"), (varnumber_T)char_count);
5595 tv_dict_add_nr(dict, S_LEN("bytes"), (varnumber_T)(byte_count + bom_count));
5596
5597 STATIC_ASSERT(sizeof("visual") == sizeof("cursor"),
5598 "key_len argument in tv_dict_add_nr is wrong");
5599 tv_dict_add_nr(dict, l_VIsual_active ? "visual_bytes" : "cursor_bytes",
5600 sizeof("visual_bytes") - 1, (varnumber_T)byte_count_cursor);
5601 tv_dict_add_nr(dict, l_VIsual_active ? "visual_chars" : "cursor_chars",
5602 sizeof("visual_chars") - 1, (varnumber_T)char_count_cursor);
5603 tv_dict_add_nr(dict, l_VIsual_active ? "visual_words" : "cursor_words",
5604 sizeof("visual_words") - 1, (varnumber_T)word_count_cursor);
5605 }
5606}
5607
5608/// Check if the default register (used in an unnamed paste) should be a
5609/// clipboard register. This happens when `clipboard=unnamed[plus]` is set
5610/// and a provider is available.
5611///
5612/// @returns the name of of a clipboard register that should be used, or `NUL` if none.
5613int get_default_register_name(void)
5614{
5615 int name = NUL;
5616 adjust_clipboard_name(&name, true, false);
5617 return name;
5618}
5619
5620/// Determine if register `*name` should be used as a clipboard.
5621/// In an unnamed operation, `*name` is `NUL` and will be adjusted to */+ if
5622/// `clipboard=unnamed[plus]` is set.
5623///
5624/// @param name The name of register, or `NUL` if unnamed.
5625/// @param quiet Suppress error messages
5626/// @param writing if we're setting the contents of the clipboard
5627///
5628/// @returns the yankreg that should be written into, or `NULL`
5629/// if the register isn't a clipboard or provider isn't available.
5630static yankreg_T *adjust_clipboard_name(int *name, bool quiet, bool writing)
5631{
5632#define MSG_NO_CLIP "clipboard: No provider. " \
5633 "Try \":checkhealth\" or \":h clipboard\"."
5634
5635 yankreg_T *target = NULL;
5636 bool explicit_cb_reg = (*name == '*' || *name == '+');
5637 bool implicit_cb_reg = (*name == NUL) && (cb_flags & CB_UNNAMEDMASK);
5638 if (!explicit_cb_reg && !implicit_cb_reg) {
5639 goto end;
5640 }
5641
5642 if (!eval_has_provider("clipboard")) {
5643 if (batch_change_count == 1 && !quiet
5644 && (!clipboard_didwarn || (explicit_cb_reg && !redirecting()))) {
5645 clipboard_didwarn = true;
5646 // Do NOT error (emsg()) here--if it interrupts :redir we get into
5647 // a weird state, stuck in "redirect mode".
5648 msg((char_u *)MSG_NO_CLIP);
5649 }
5650 // ... else, be silent (don't flood during :while, :redir, etc.).
5651 goto end;
5652 }
5653
5654 if (explicit_cb_reg) {
5655 target = &y_regs[*name == '*' ? STAR_REGISTER : PLUS_REGISTER];
5656 if (writing && (cb_flags & (*name == '*' ? CB_UNNAMED : CB_UNNAMEDPLUS))) {
5657 clipboard_needs_update = false;
5658 }
5659 goto end;
5660 } else { // unnamed register: "implicit" clipboard
5661 if (writing && clipboard_delay_update) {
5662 // For "set" (copy), defer the clipboard call.
5663 clipboard_needs_update = true;
5664 goto end;
5665 } else if (!writing && clipboard_needs_update) {
5666 // For "get" (paste), use the internal value.
5667 goto end;
5668 }
5669
5670 if (cb_flags & CB_UNNAMEDPLUS) {
5671 *name = (cb_flags & CB_UNNAMED && writing) ? '"': '+';
5672 target = &y_regs[PLUS_REGISTER];
5673 } else {
5674 *name = '*';
5675 target = &y_regs[STAR_REGISTER];
5676 }
5677 goto end;
5678 }
5679
5680end:
5681 return target;
5682}
5683
5684/// @param[out] reg Expected to be empty
5685bool prepare_yankreg_from_object(yankreg_T *reg, String regtype, size_t lines)
5686{
5687 char type = regtype.data ? regtype.data[0] : NUL;
5688
5689 switch (type) {
5690 case 0:
5691 reg->y_type = kMTUnknown;
5692 break;
5693 case 'v': case 'c':
5694 reg->y_type = kMTCharWise;
5695 break;
5696 case 'V': case 'l':
5697 reg->y_type = kMTLineWise;
5698 break;
5699 case 'b': case Ctrl_V:
5700 reg->y_type = kMTBlockWise;
5701 break;
5702 default:
5703 return false;
5704 }
5705
5706 reg->y_width = 0;
5707 if (regtype.size > 1) {
5708 if (reg->y_type != kMTBlockWise) {
5709 return false;
5710 }
5711
5712 // allow "b7" for a block at least 7 spaces wide
5713 if (!ascii_isdigit(regtype.data[1])) {
5714 return false;
5715 }
5716 const char *p = regtype.data+1;
5717 reg->y_width = getdigits_int((char_u **)&p, false, 1) - 1;
5718 if (regtype.size > (size_t)(p-regtype.data)) {
5719 return false;
5720 }
5721 }
5722
5723 reg->y_array = xcalloc(lines, sizeof(uint8_t *));
5724 reg->y_size = lines;
5725 reg->additional_data = NULL;
5726 reg->timestamp = 0;
5727 return true;
5728}
5729
5730void finish_yankreg_from_object(yankreg_T *reg, bool clipboard_adjust)
5731{
5732 if (reg->y_size > 0 && strlen((char *)reg->y_array[reg->y_size-1]) == 0) {
5733 // a known-to-be charwise yank might have a final linebreak
5734 // but otherwise there is no line after the final newline
5735 if (reg->y_type != kMTCharWise) {
5736 if (reg->y_type == kMTUnknown || clipboard_adjust) {
5737 xfree(reg->y_array[reg->y_size-1]);
5738 reg->y_size--;
5739 }
5740 if (reg->y_type == kMTUnknown) {
5741 reg->y_type = kMTLineWise;
5742 }
5743 }
5744 } else {
5745 if (reg->y_type == kMTUnknown) {
5746 reg->y_type = kMTCharWise;
5747 }
5748 }
5749
5750 if (reg->y_type == kMTBlockWise) {
5751 size_t maxlen = 0;
5752 for (size_t i = 0; i < reg->y_size; i++) {
5753 size_t rowlen = STRLEN(reg->y_array[i]);
5754 if (rowlen > maxlen) {
5755 maxlen = rowlen;
5756 }
5757 }
5758 assert(maxlen <= INT_MAX);
5759 reg->y_width = MAX(reg->y_width, (int)maxlen - 1);
5760 }
5761}
5762
5763static bool get_clipboard(int name, yankreg_T **target, bool quiet)
5764{
5765 // show message on error
5766 bool errmsg = true;
5767
5768 yankreg_T *reg = adjust_clipboard_name(&name, quiet, false);
5769 if (reg == NULL) {
5770 return false;
5771 }
5772 free_register(reg);
5773
5774 list_T *const args = tv_list_alloc(1);
5775 const char regname = (char)name;
5776 tv_list_append_string(args, &regname, 1);
5777
5778 typval_T result = eval_call_provider("clipboard", "get", args);
5779
5780 if (result.v_type != VAR_LIST) {
5781 if (result.v_type == VAR_NUMBER && result.vval.v_number == 0) {
5782 // failure has already been indicated by provider
5783 errmsg = false;
5784 }
5785 goto err;
5786 }
5787
5788 list_T *res = result.vval.v_list;
5789 list_T *lines = NULL;
5790 if (tv_list_len(res) == 2
5791 && TV_LIST_ITEM_TV(tv_list_first(res))->v_type == VAR_LIST) {
5792 lines = TV_LIST_ITEM_TV(tv_list_first(res))->vval.v_list;
5793 if (TV_LIST_ITEM_TV(tv_list_last(res))->v_type != VAR_STRING) {
5794 goto err;
5795 }
5796 char_u *regtype = TV_LIST_ITEM_TV(tv_list_last(res))->vval.v_string;
5797 if (regtype == NULL || strlen((char *)regtype) > 1) {
5798 goto err;
5799 }
5800 switch (regtype[0]) {
5801 case 0:
5802 reg->y_type = kMTUnknown;
5803 break;
5804 case 'v': case 'c':
5805 reg->y_type = kMTCharWise;
5806 break;
5807 case 'V': case 'l':
5808 reg->y_type = kMTLineWise;
5809 break;
5810 case 'b': case Ctrl_V:
5811 reg->y_type = kMTBlockWise;
5812 break;
5813 default:
5814 goto err;
5815 }
5816 } else {
5817 lines = res;
5818 // provider did not specify regtype, calculate it below
5819 reg->y_type = kMTUnknown;
5820 }
5821
5822 reg->y_array = xcalloc((size_t)tv_list_len(lines), sizeof(char_u *));
5823 reg->y_size = (size_t)tv_list_len(lines);
5824 reg->additional_data = NULL;
5825 reg->timestamp = 0;
5826 // Timestamp is not saved for clipboard registers because clipboard registers
5827 // are not saved in the ShaDa file.
5828
5829 size_t tv_idx = 0;
5830 TV_LIST_ITER_CONST(lines, li, {
5831 if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING) {
5832 goto err;
5833 }
5834 reg->y_array[tv_idx++] = (char_u *)xstrdupnul(
5835 (const char *)TV_LIST_ITEM_TV(li)->vval.v_string);
5836 });
5837
5838 if (reg->y_size > 0 && strlen((char*)reg->y_array[reg->y_size-1]) == 0) {
5839 // a known-to-be charwise yank might have a final linebreak
5840 // but otherwise there is no line after the final newline
5841 if (reg->y_type != kMTCharWise) {
5842 xfree(reg->y_array[reg->y_size-1]);
5843 reg->y_size--;
5844 if (reg->y_type == kMTUnknown) {
5845 reg->y_type = kMTLineWise;
5846 }
5847 }
5848 } else {
5849 if (reg->y_type == kMTUnknown) {
5850 reg->y_type = kMTCharWise;
5851 }
5852 }
5853
5854 if (reg->y_type == kMTBlockWise) {
5855 size_t maxlen = 0;
5856 for (size_t i = 0; i < reg->y_size; i++) {
5857 size_t rowlen = STRLEN(reg->y_array[i]);
5858 if (rowlen > maxlen) {
5859 maxlen = rowlen;
5860 }
5861 }
5862 assert(maxlen <= INT_MAX);
5863 reg->y_width = (int)maxlen - 1;
5864 }
5865
5866 *target = reg;
5867 return true;
5868
5869err:
5870 if (reg->y_array) {
5871 for (size_t i = 0; i < reg->y_size; i++) {
5872 xfree(reg->y_array[i]);
5873 }
5874 xfree(reg->y_array);
5875 }
5876 reg->y_array = NULL;
5877 reg->y_size = 0;
5878 reg->additional_data = NULL;
5879 reg->timestamp = 0;
5880 if (errmsg) {
5881 EMSG("clipboard: provider returned invalid data");
5882 }
5883 *target = reg;
5884 return false;
5885}
5886
5887static void set_clipboard(int name, yankreg_T *reg)
5888{
5889 if (!adjust_clipboard_name(&name, false, true)) {
5890 return;
5891 }
5892
5893 list_T *const lines = tv_list_alloc(
5894 (ptrdiff_t)reg->y_size + (reg->y_type != kMTCharWise));
5895
5896 for (size_t i = 0; i < reg->y_size; i++) {
5897 tv_list_append_string(lines, (const char *)reg->y_array[i], -1);
5898 }
5899
5900 char regtype;
5901 switch (reg->y_type) {
5902 case kMTLineWise: {
5903 regtype = 'V';
5904 tv_list_append_string(lines, NULL, 0);
5905 break;
5906 }
5907 case kMTCharWise: {
5908 regtype = 'v';
5909 break;
5910 }
5911 case kMTBlockWise: {
5912 regtype = 'b';
5913 tv_list_append_string(lines, NULL, 0);
5914 break;
5915 }
5916 case kMTUnknown: {
5917 assert(false);
5918 }
5919 }
5920
5921 list_T *args = tv_list_alloc(3);
5922 tv_list_append_list(args, lines);
5923 tv_list_append_string(args, &regtype, 1); // -V614
5924 tv_list_append_string(args, ((char[]) { (char)name }), 1);
5925
5926 (void)eval_call_provider("clipboard", "set", args);
5927}
5928
5929/// Avoid slow things (clipboard) during batch operations (while/for-loops).
5930void start_batch_changes(void)
5931{
5932 if (++batch_change_count > 1) {
5933 return;
5934 }
5935 clipboard_delay_update = true;
5936}
5937
5938/// Counterpart to start_batch_changes().
5939void end_batch_changes(void)
5940{
5941 if (--batch_change_count > 0) {
5942 // recursive
5943 return;
5944 }
5945 clipboard_delay_update = false;
5946 if (clipboard_needs_update) {
5947 // must be before, as set_clipboard will invoke
5948 // start/end_batch_changes recursively
5949 clipboard_needs_update = false;
5950 // unnamed ("implicit" clipboard)
5951 set_clipboard(NUL, y_previous);
5952 }
5953}
5954
5955int save_batch_count(void)
5956{
5957 int save_count = batch_change_count;
5958 batch_change_count = 0;
5959 clipboard_delay_update = false;
5960 if (clipboard_needs_update) {
5961 clipboard_needs_update = false;
5962 // unnamed ("implicit" clipboard)
5963 set_clipboard(NUL, y_previous);
5964 }
5965 return save_count;
5966}
5967
5968void restore_batch_count(int save_count)
5969{
5970 assert(batch_change_count == 0);
5971 batch_change_count = save_count;
5972 if (batch_change_count > 0) {
5973 clipboard_delay_update = true;
5974 }
5975}
5976
5977
5978/// Check whether register is empty
5979static inline bool reg_empty(const yankreg_T *const reg)
5980 FUNC_ATTR_PURE
5981{
5982 return (reg->y_array == NULL
5983 || reg->y_size == 0
5984 || (reg->y_size == 1
5985 && reg->y_type == kMTCharWise
5986 && *(reg->y_array[0]) == NUL));
5987}
5988
5989/// Iterate over global registers.
5990///
5991/// @see op_register_iter
5992const void *op_global_reg_iter(const void *const iter, char *const name,
5993 yankreg_T *const reg, bool *is_unnamed)
5994 FUNC_ATTR_NONNULL_ARG(2, 3, 4) FUNC_ATTR_WARN_UNUSED_RESULT
5995{
5996 return op_reg_iter(iter, y_regs, name, reg, is_unnamed);
5997}
5998
5999/// Iterate over registers `regs`.
6000///
6001/// @param[in] iter Iterator. Pass NULL to start iteration.
6002/// @param[in] regs Registers list to be iterated.
6003/// @param[out] name Register name.
6004/// @param[out] reg Register contents.
6005///
6006/// @return Pointer that must be passed to next `op_register_iter` call or
6007/// NULL if iteration is over.
6008const void *op_reg_iter(const void *const iter, const yankreg_T *const regs,
6009 char *const name, yankreg_T *const reg,
6010 bool *is_unnamed)
6011 FUNC_ATTR_NONNULL_ARG(3, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT
6012{
6013 *name = NUL;
6014 const yankreg_T *iter_reg = (iter == NULL
6015 ? &(regs[0])
6016 : (const yankreg_T *const)iter);
6017 while (iter_reg - &(regs[0]) < NUM_SAVED_REGISTERS && reg_empty(iter_reg)) {
6018 iter_reg++;
6019 }
6020 if (iter_reg - &(regs[0]) == NUM_SAVED_REGISTERS || reg_empty(iter_reg)) {
6021 return NULL;
6022 }
6023 int iter_off = (int)(iter_reg - &(regs[0]));
6024 *name = (char)get_register_name(iter_off);
6025 *reg = *iter_reg;
6026 *is_unnamed = (iter_reg == y_previous);
6027 while (++iter_reg - &(regs[0]) < NUM_SAVED_REGISTERS) {
6028 if (!reg_empty(iter_reg)) {
6029 return (void *) iter_reg;
6030 }
6031 }
6032 return NULL;
6033}
6034
6035/// Get a number of non-empty registers
6036size_t op_reg_amount(void)
6037 FUNC_ATTR_WARN_UNUSED_RESULT
6038{
6039 size_t ret = 0;
6040 for (size_t i = 0; i < NUM_SAVED_REGISTERS; i++) {
6041 if (!reg_empty(y_regs + i)) {
6042 ret++;
6043 }
6044 }
6045 return ret;
6046}
6047
6048/// Set register to a given value
6049///
6050/// @param[in] name Register name.
6051/// @param[in] reg Register value.
6052/// @param[in] is_unnamed Whether to set the unnamed regiseter to reg
6053///
6054/// @return true on success, false on failure.
6055bool op_reg_set(const char name, const yankreg_T reg, bool is_unnamed)
6056{
6057 int i = op_reg_index(name);
6058 if (i == -1) {
6059 return false;
6060 }
6061 free_register(&y_regs[i]);
6062 y_regs[i] = reg;
6063
6064 if (is_unnamed) {
6065 y_previous = &y_regs[i];
6066 }
6067 return true;
6068}
6069
6070/// Get register with the given name
6071///
6072/// @param[in] name Register name.
6073///
6074/// @return Pointer to the register contents or NULL.
6075const yankreg_T *op_reg_get(const char name)
6076{
6077 int i = op_reg_index(name);
6078 if (i == -1) {
6079 return NULL;
6080 }
6081 return &y_regs[i];
6082}
6083
6084/// Set the previous yank register
6085///
6086/// @param[in] name Register name.
6087///
6088/// @return true on success, false on failure.
6089bool op_reg_set_previous(const char name)
6090 FUNC_ATTR_WARN_UNUSED_RESULT
6091{
6092 int i = op_reg_index(name);
6093 if (i == -1) {
6094 return false;
6095 }
6096
6097 y_previous = &y_regs[i];
6098 return true;
6099}
6100