robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
131.4 KiB4450 linesraw
1// insert.c: functions for Insert mode
2
3#include <assert.h>
4#include <ctype.h>
5#include <inttypes.h>
6#include <stdbool.h>
7#include <stddef.h>
8#include <string.h>
9#include <uv.h>
10
11#include "klib/kvec.h"
12#include "nvim/api/private/defs.h"
13#include "nvim/ascii_defs.h"
14#include "nvim/autocmd.h"
15#include "nvim/autocmd_defs.h"
16#include "nvim/buffer.h"
17#include "nvim/buffer_defs.h"
18#include "nvim/change.h"
19#include "nvim/charset.h"
20#include "nvim/context.h"
21#include "nvim/cursor.h"
22#include "nvim/decoration.h"
23#include "nvim/digraph.h"
24#include "nvim/drawscreen.h"
25#include "nvim/errors.h"
26#include "nvim/eval/buffer.h"
27#include "nvim/eval/typval_defs.h"
28#include "nvim/eval/vars.h"
29#include "nvim/ex_cmds_defs.h"
30#include "nvim/ex_docmd.h"
31#include "nvim/ex_getln.h"
32#include "nvim/extmark.h"
33#include "nvim/extmark_defs.h"
34#include "nvim/fileio.h"
35#include "nvim/fold.h"
36#include "nvim/gettext_defs.h"
37#include "nvim/globals.h"
38#include "nvim/grid.h"
39#include "nvim/grid_defs.h"
40#include "nvim/highlight.h"
41#include "nvim/highlight_defs.h"
42#include "nvim/highlight_group.h"
43#include "nvim/indent.h"
44#include "nvim/indent_c.h"
45#include "nvim/input.h"
46#include "nvim/insert.h"
47#include "nvim/insexpand.h"
48#include "nvim/keycodes.h"
49#include "nvim/macros_defs.h"
50#include "nvim/mapping.h"
51#include "nvim/mark.h"
52#include "nvim/mark_defs.h"
53#include "nvim/marktree_defs.h"
54#include "nvim/mbyte.h"
55#include "nvim/mbyte_defs.h"
56#include "nvim/mcursor.h"
57#include "nvim/memline.h"
58#include "nvim/memline_defs.h"
59#include "nvim/memory.h"
60#include "nvim/message.h"
61#include "nvim/mouse.h"
62#include "nvim/move.h"
63#include "nvim/normal.h"
64#include "nvim/normal_defs.h"
65#include "nvim/ops.h"
66#include "nvim/option.h"
67#include "nvim/option_vars.h"
68#include "nvim/os/input.h"
69#include "nvim/plines.h"
70#include "nvim/popupmenu.h"
71#include "nvim/pos_defs.h"
72#include "nvim/register.h"
73#include "nvim/search.h"
74#include "nvim/state.h"
75#include "nvim/state_defs.h"
76#include "nvim/strings.h"
77#include "nvim/syntax.h"
78#include "nvim/terminal.h"
79#include "nvim/textformat.h"
80#include "nvim/textobject.h"
81#include "nvim/types_defs.h"
82#include "nvim/ui.h"
83#include "nvim/ui_defs.h"
84#include "nvim/undo.h"
85#include "nvim/vim_defs.h"
86#include "nvim/window.h"
87
88typedef struct {
89  VimState state;
90  cmdarg_T *ca;
91  int mincol;
92  int cmdchar;
93  int cmdchar_todo;                  // cmdchar to handle once in init_prompt
94  bool ins_just_started;
95  int startln;
96  int count;
97  int c;
98  int lastc;
99  int i;
100  bool did_backspace;                // previous char was backspace
101  bool line_is_white;                // line is empty before insert
102  linenr_T old_topline;              // topline before insertion
103  int old_topfill;
104  int inserted_space;                // just inserted a space
105  int replaceState;
106  int did_restart_edit;              // remember if insert mode was restarted
107                                     // after a ctrl+o
108  bool nomove;
109} InsertState;
110
111#include "insert.c.generated.h"
112enum {
113  BACKSPACE_CHAR = 1,
114  BACKSPACE_WORD = 2,
115  BACKSPACE_WORD_NOT_SPACE = 3,
116  BACKSPACE_LINE = 4,
117};
118
119/// Set when doing something for completion that may call edit() recursively,
120/// which is not allowed.
121static bool compl_busy = false;
122
123/// the text of the previous insert, K_SPECIAL is escaped
124static String last_insert = STRING_INIT;
125static int last_insert_skip;            // nr of chars in front of previous insert
126
127static kvec_t(char) replace_stack = KV_INITIAL_VALUE;
128
129// With 'autocompletedelay' set, arm the delay and let the main loop fire
130// Insert-mode autocommands; the popup is shown later on K_COMPLETE_DELAY.
131// Otherwise trigger completion right away.
132#define TRIGGER_AUTOCOMPLETE() \
133  do { \
134    mc_ins_cascade();  /* Multicursor: replay pending keys, since compl refused edit(). #41605 */ \
135    redraw_later(curwin, UPD_VALID); \
136    update_screen();  /* Show char deletion immediately */ \
137    ui_flush(); \
138    ins_compl_enable_autocomplete(); \
139    ins_compl_arm_autostart(); \
140    if (!ins_compl_arm_autocomplete_delay()) { \
141      insert_do_complete(s); \
142      break; \
143    } \
144  } while (0)
145
146#define MAY_TRIGGER_AUTOCOMPLETE(c) \
147  do { \
148    if (ins_compl_has_autocomplete() && !char_avail() && curwin->w_cursor.col > 0) { \
149      (c) = char_before_cursor(); \
150      if (vim_isprintc(c)) { \
151        TRIGGER_AUTOCOMPLETE(); \
152      } \
153    } \
154  } while (0)
155
156static void insert_enter(InsertState *s)
157{
158  s->did_backspace = true;
159  s->old_topfill = -1;
160  s->replaceState = MODE_REPLACE;
161  s->cmdchar_todo = s->cmdchar;
162  s->ins_just_started = true;
163  // Remember whether editing was restarted after CTRL-O
164  Ins.did_restart_edit = restart_edit;
165  // sleep before redrawing, needed for "CTRL-O :" that results in an
166  // error message
167  msg_check_for_delay(true);
168  // set Ins.start_orig to Ins.start
169  Ins.update_start_orig = true;
170
171  ins_compl_clear();        // clear stuff for CTRL-X mode
172
173  // Trigger InsertEnter autocommands.  Do not do this for "r<CR>" or "grx".
174  if (s->cmdchar != 'r' && s->cmdchar != 'v') {
175    pos_T save_cursor = curwin->w_cursor;
176
177    const char *const ptr = s->cmdchar == 'R' ? "r" : s->cmdchar == 'V' ? "v" : "i";
178    set_vim_var_string(VV_INSERTMODE, ptr, 1);
179    set_vim_var_string(VV_CHAR, NULL, -1);
180    ins_apply_autocmds(EVENT_INSERTENTER);
181
182    // Check for changed highlighting, e.g. for ModeMsg.
183    if (need_highlight_changed) {
184      highlight_changed();
185    }
186
187    // Make sure the cursor didn't move.  Do call check_cursor_col() in
188    // case the text was modified.  Since Insert mode was not started yet
189    // a call to check_cursor_col() may move the cursor, especially with
190    // the "A" command, thus set State to avoid that. Also check that the
191    // line number is still valid (lines may have been deleted).
192    // Do not restore if v:char was set to a non-empty string.
193    if (!equalpos(curwin->w_cursor, save_cursor)
194        && *get_vim_var_str(VV_CHAR) == NUL
195        && save_cursor.lnum <= curbuf->b_ml.ml_line_count) {
196      int save_state = State;
197
198      curwin->w_cursor = save_cursor;
199      State = MODE_INSERT;
200      check_cursor_col(curwin);
201      State = save_state;
202    }
203  }
204
205  // When doing a paste with the middle mouse button, Ins.start is set to
206  // where the paste started.
207  if (where_paste_started.lnum != 0) {
208    Ins.start = where_paste_started;
209  } else {
210    Ins.start = curwin->w_cursor;
211    if (s->startln) {
212      Ins.start.col = 0;
213    }
214  }
215
216  Ins.start_textlen = linetabsize_str(get_cursor_line_ptr());
217  Ins.start_blank_vcol = MAXCOL;
218
219  if (!Ins.did_ai) {
220    Ins.ai_col = 0;
221  }
222
223  if (s->cmdchar != NUL && restart_edit == 0) {
224    if (s->cmdchar == 'V' || s->cmdchar == 'v') {
225      // "gR" or "gr" command
226      prep_redo(false, false, (CmdSpec){ .count = s->count, .cmd = 'g',
227                                         .cmd2 = (s->cmdchar == 'v') ? 'r' : 'R' });
228    } else {
229      prep_redo(false, false, (CmdSpec){ .count = s->count, .cmd = s->cmdchar,
230                                         .cmd2 = (s->cmdchar == 'g') ? 'I' : NUL });
231      if (s->cmdchar == 'r') {  // "r<CR>" command
232        s->count = 1;           // insert only one <CR>
233      }
234    }
235  }
236
237  if (s->cmdchar == 'R') {
238    State = MODE_REPLACE;
239  } else if (s->cmdchar == 'V' || s->cmdchar == 'v') {
240    State = MODE_VREPLACE;
241    s->replaceState = MODE_VREPLACE;
242    orig_line_count = curbuf->b_ml.ml_line_count;
243    vr_lines_changed = 1;
244  } else {
245    State = MODE_INSERT;
246  }
247
248  may_trigger_modechanged();
249  Ins.stop_insert_mode = false;
250
251  // need to position cursor again when on a TAB and
252  // when on a char with inline virtual text
253  if (gchar_cursor() == TAB || buf_meta_total(curbuf, kMTMetaInline) > 0) {
254    curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL);
255  }
256
257  // Enable langmap or IME, indicated by 'iminsert'.
258  // Note that IME may enabled/disabled without us noticing here, thus the
259  // 'iminsert' value may not reflect what is actually used.  It is updated
260  // when hitting <Esc>.
261  if (curbuf->b_p_iminsert == B_IMODE_LMAP) {
262    State |= MODE_LANGMAP;
263  }
264
265  setmouse();
266  clear_showcmd();
267  // there is no reverse replace mode
268  Ins.revins_on = (State == MODE_INSERT && p_ri);
269  if (Ins.revins_on) {
270    undisplay_dollar();
271  }
272  Ins.revins_chars = 0;
273  Ins.revins_legal = 0;
274  Ins.revins_scol = -1;
275
276  // Handle restarting Insert mode.
277  // Don't do this for "CTRL-O ." (repeat an insert): we get here with
278  // restart_edit non-zero, and something in the stuff buffer.
279  if (restart_edit != 0 && stuff_empty()) {
280    // After a paste we consider text typed to be part of the insert for
281    // the pasted text. You can backspace over the pasted text too.
282    Ins.moved = where_paste_started.lnum == 0 ? kInsJump : kInsNone;
283    restart_edit = 0;
284
285    // If the cursor was after the end-of-line before the CTRL-O and it is
286    // now at the end-of-line, put it after the end-of-line (this is not
287    // correct in very rare cases).
288    // Also do this if curswant is greater than the current virtual
289    // column.  Eg after "^O$" or "^O80|".
290    validate_virtcol(curwin);
291    update_curswant();
292    const char *ptr;
293    if (((ins_at_eol && curwin->w_cursor.lnum == Ins.o_lnum)
294         || curwin->w_curswant > curwin->w_virtcol)
295        && *(ptr = get_cursor_line_ptr() + curwin->w_cursor.col) != NUL) {
296      if (ptr[1] == NUL) {
297        curwin->w_cursor.col++;
298      } else {
299        s->i = utfc_ptr2len(ptr);
300        if (ptr[s->i] == NUL) {
301          curwin->w_cursor.col += s->i;
302        }
303      }
304    }
305    ins_at_eol = false;
306  } else {
307    Ins.moved = kInsNone;
308  }
309
310  // we are in insert mode now, don't need to start it anymore
311  need_start_insertmode = false;
312
313  // Need to save the line for undo before inserting the first char.
314  Ins.need_undo = true;
315
316  where_paste_started.lnum = 0;
317  Ins.can_cindent = true;
318  // The cursor line is not in a closed fold, unless restarting.
319  if (Ins.did_restart_edit == 0) {
320    foldOpenCursor();
321  }
322
323  // If 'showmode' is set, show the current (insert/replace/..) mode.
324  // A warning message for changing a readonly file is given here, before
325  // actually changing anything.  It's put after the mode, if any.
326  s->i = 0;
327  if (p_smd && msg_silent == 0) {
328    s->i = showmode();
329  }
330
331  if (Ins.did_restart_edit == 0) {
332    change_warning(curbuf, s->i == 0 ? 0 : s->i + 1);
333  }
334
335  ui_cursor_shape();            // may show different cursor shape
336  do_digraph(-1);               // clear digraphs
337
338  // Get the current length of the redo buffer, those characters have to be
339  // skipped if we want to get to the inserted characters.
340  String redo = redo_keys(NULL);
341  Ins.new_insert_skip = (int)redo.size;
342  if (redo.data != NULL) {
343    xfree(redo.data);
344  }
345
346  old_indent = 0;
347
348  do {
349    state_enter(&s->state);
350    // If s->count != 0, `ins_esc` will prepare the redo buffer for reprocessing
351    // and return false, causing `state_enter` to be called again.
352  } while (!ins_esc(&s->count, s->cmdchar, s->nomove));
353
354  // Drop a pending autocomplete so it does not outlive Insert mode.
355  ins_compl_clear_autocomplete_delay();
356  // Always update Ins.o_lnum, so that a "CTRL-O ." that adds a line
357  // still puts the cursor back after the inserted text.
358  if (ins_at_eol) {
359    Ins.o_lnum = curwin->w_cursor.lnum;
360  }
361
362  pum_check_clear();
363
364  foldUpdateAfterInsert();
365  // When CTRL-C was typed got_int will be set, with the result
366  // that the autocommands won't be executed. When mapped got_int
367  // is not set, but let's keep the behavior the same.
368  if (s->cmdchar != 'r' && s->cmdchar != 'v' && s->c != Ctrl_C) {
369    ins_apply_autocmds(EVENT_INSERTLEAVE);
370  }
371  did_cursorhold = false;
372
373  // ins_redraw() triggers TextChangedI only when no characters
374  // are in the typeahead buffer, so reset curbuf->b_last_changedtick
375  // if the TextChangedI was not blocked by char_avail() (e.g. using :norm!)
376  // and the TextChangedI autocommand has been triggered.
377  if (!char_avail() && curbuf->b_last_changedtick_i == buf_get_changedtick(curbuf)) {
378    curbuf->b_last_changedtick = buf_get_changedtick(curbuf);
379  }
380}
381
382static int insert_check(VimState *state)
383{
384  InsertState *s = (InsertState *)state;
385
386  // Multicursor: insert-cascade, before entry ("A"/"o"/"cw"/…), and after every executed key.
387  mc_ins_cascade();
388
389  if (!Ins.revins_legal) {
390    Ins.revins_scol = -1;     // reset on illegal motions
391  } else {
392    Ins.revins_legal = 0;
393  }
394
395  if (Ins.moved != kInsNone) {  // don't repeat insert when arrow key used
396    s->count = 0;
397  }
398
399  if (Ins.update_start_orig) {
400    Ins.start_orig = Ins.start;
401  }
402
403  if (curbuf->terminal && !Ins.stop_insert_mode) {
404    // Exit Insert mode and go to Terminal mode.
405    Ins.stop_insert_mode = true;
406    restart_edit = 'I';
407    stuffcharReadbuff(K_NOP);
408  }
409
410  if (Ins.stop_insert_mode && !ins_compl_active()) {
411    // ":stopinsert" used
412    s->count = 0;
413    return 0;  // exit insert mode
414  }
415
416  // set curwin->w_curswant for next K_DOWN or K_UP
417  if (Ins.moved == kInsNone) {
418    curwin->w_set_curswant = true;
419  }
420
421  // If there is no typeahead may check for timestamps (e.g., for when a
422  // menu invoked a shell command).
423  if (stuff_empty()) {
424    did_check_timestamps = false;
425    if (need_check_timestamps) {
426      check_timestamps(false);
427    }
428  }
429
430  // When emsg() was called msg_scroll will have been set.
431  msg_scroll = false;
432
433  // Open fold at the cursor line, according to 'foldopen'.
434  if (fdo_flags & kOptFdoFlagInsert) {
435    foldOpenCursor();
436  }
437
438  // Close folds where the cursor isn't, according to 'foldclose'
439  if (!char_avail()) {
440    foldCheckClose();
441  }
442
443  if (bt_prompt(curbuf)) {
444    init_prompt(s->cmdchar_todo);
445    s->cmdchar_todo = NUL;
446  }
447
448  // If we inserted a character at the last position of the last line in the
449  // window, scroll the window one line up. This avoids an extra redraw.  This
450  // is detected when the cursor column is smaller after inserting something.
451  // Don't do this when the topline changed already, it has already been
452  // adjusted (by insertchar() calling open_line())).
453  // Also don't do this when 'smoothscroll' is set, as the window should then
454  // be scrolled by screen lines.
455  if (curbuf->b_mod_set
456      && curwin->w_p_wrap
457      && !curwin->w_p_sms
458      && !s->did_backspace
459      && curwin->w_topline == s->old_topline
460      && curwin->w_topfill == s->old_topfill
461      && s->count <= 1) {
462    s->mincol = curwin->w_wcol;
463    validate_cursor_col(curwin);
464
465    if (curwin->w_wcol < s->mincol - tabstop_at(get_nolist_virtcol(),
466                                                curbuf->b_p_ts,
467                                                curbuf->b_p_vts_array,
468                                                false)
469        && curwin->w_wrow == curwin->w_view_height - 1 - get_scrolloff_value(curwin)
470        && (curwin->w_cursor.lnum != curwin->w_topline
471            || curwin->w_topfill > 0)) {
472      if (curwin->w_topfill > 0) {
473        curwin->w_topfill--;
474      } else if (hasFolding(curwin, curwin->w_topline, NULL, &s->old_topline)) {
475        set_topline(curwin, s->old_topline + 1);
476      } else {
477        set_topline(curwin, curwin->w_topline + 1);
478      }
479    }
480  }
481
482  // May need to adjust w_topline to show the cursor.
483  if (s->count <= 1) {
484    update_topline(curwin);
485  }
486
487  s->did_backspace = false;
488
489  if (s->count <= 1) {
490    validate_cursor(curwin);  // may set must_redraw
491  }
492
493  // Redraw the display when no characters are waiting.
494  // Also shows mode, ruler and positions cursor.
495  ins_redraw(true);
496
497  if (curwin->w_p_scb) {
498    do_check_scrollbind(true);
499  }
500
501  if (curwin->w_p_crb) {
502    do_check_cursorbind();
503  }
504
505  if (s->count <= 1) {
506    update_curswant();
507  }
508  s->old_topline = curwin->w_topline;
509  s->old_topfill = curwin->w_topfill;
510
511  if (s->c != K_EVENT && s->c != K_COMPLETE_DELAY) {
512    s->lastc = s->c;  // remember the previous char for CTRL-D
513  }
514
515  // After using CTRL-G U the next cursor key will not break undo.
516  if (Ins.dont_sync_undo == kNone) {
517    Ins.dont_sync_undo = kTrue;
518  } else {
519    Ins.dont_sync_undo = kFalse;
520  }
521
522  // Trigger autocomplete when entering Insert mode, either directly
523  // or via change commands like 'ciw', 'cw', etc., before the first
524  // character is typed.
525  if (s->ins_just_started) {
526    s->ins_just_started = false;
527    if (ins_compl_has_autocomplete() && !char_avail() && curwin->w_cursor.col > 0) {
528      s->c = char_before_cursor();
529      if (vim_isprintc(s->c)) {
530        ins_compl_enable_autocomplete();
531        ins_compl_arm_autostart();
532        ins_compl_init_get_longest();
533        // Defer until the delay expires (K_COMPLETE_DELAY), or
534        // trigger now when no delay is in effect.
535        if (!ins_compl_arm_autocomplete_delay()) {
536          insert_do_complete(s);
537          insert_handle_key_post(s);
538          return 1;
539        }
540      }
541    }
542  }
543
544  return 1;
545}
546
547static int insert_execute(VimState *state, int key)
548{
549  InsertState *const s = (InsertState *)state;
550  if (Ins.stop_insert_mode) {
551    // Insert mode ended, possibly from a callback.
552    if (key != K_IGNORE && key != K_NOP) {
553      vungetc(key);
554    }
555    s->count = 0;
556    s->nomove = true;
557    ins_compl_prep(ESC);
558    return 0;
559  }
560
561  if (key == K_IGNORE || key == K_NOP) {
562    return -1;  // get another key
563  }
564  s->c = key;
565
566  // Don't want K_EVENT with cursorhold for the second key, e.g., after CTRL-V.
567  if (key != K_EVENT) {
568    did_cursorhold = true;
569  }
570  if (key != K_EVENT && key != K_COMPLETE_DELAY) {
571    // Don't want delayed autocompletion from the previous key either.
572    ins_compl_clear_autocomplete_delay();
573    ins_compl_disarm_autostart();
574    // A completion already on screen goes on being what it was.
575    if (!ins_compl_active()) {
576      ins_compl_disable_autocomplete();
577    }
578  }
579
580  // Special handling of keys while the popup menu is visible or wanted
581  // and the cursor is still in the completed word.  Only when there is
582  // a match, skip this when no matches were found.
583  if (ins_compl_active() && curwin->w_cursor.col >= ins_compl_col()
584      && ins_compl_has_shown_match() && pum_wanted()) {
585    // BS: Delete one character from "compl_leader".
586    if ((s->c == K_BS || s->c == Ctrl_H)
587        && curwin->w_cursor.col > ins_compl_col()
588        && (s->c = ins_compl_bs()) == NUL) {
589      return 1;  // continue
590    }
591
592    // When no match was selected or it was edited.
593    if (!ins_compl_used_match()) {
594      // CTRL-L: Add one character from the current match to
595      // "compl_leader".  Except when at the original match and
596      // there is nothing to add, CTRL-L works like CTRL-P then.
597      if (s->c == Ctrl_L
598          && (!ctrl_x_mode_line_or_eval()
599              || ins_compl_long_shown_match())) {
600        ins_compl_addfrommatch();
601        return 1;  // continue
602      }
603
604      const bool is_commit = ins_compl_commit_char(s->c);
605      // A non-white character that fits in with the current
606      // completion: Add to "compl_leader".
607      if (!is_commit && ins_compl_accept_char(s->c)) {
608        // Trigger InsertCharPre.
609        char *str = do_insert_char_pre(s->c);
610
611        if (str != NULL) {
612          for (char *p = str; *p != NUL; MB_PTR_ADV(p)) {
613            ins_compl_addleader(utf_ptr2char(p));
614          }
615          xfree(str);
616        } else {
617          ins_compl_addleader(s->c);
618        }
619        return 1;  // continue
620      }
621
622      // Pressing CTRL-Y selects the current match.  When
623      // compl_enter_selects is set the Enter key does the same.
624      if ((s->c == Ctrl_Y || is_commit
625           || (ins_compl_enter_selects()
626               && (s->c == CAR || s->c == K_KENTER || s->c == NL)))
627          && stop_arrow() == OK) {
628        ins_compl_delete(false);
629        if (ins_compl_preinsert_longest() && !ins_compl_is_match_selected()) {
630          ins_compl_insert(false, true);
631          ins_compl_init_get_longest();
632          return 1;  // continue
633        } else {
634          ins_compl_insert(false, false);
635        }
636      } else if (ascii_iswhite_nl_or_nul(s->c) && ins_compl_preinsert_effect()) {
637        // Delete preinserted text when typing special chars
638        ins_compl_delete(false);
639      }
640    }
641  }
642
643  // Prepare for or stop CTRL-X mode. This doesn't do completion, but it does
644  // fix up the text when finishing completion.
645  ins_compl_init_get_longest();
646  if (ins_compl_prep(s->c)) {
647    return 1;  // continue
648  }
649
650  // CTRL-\ CTRL-N goes to Normal mode,
651  // CTRL-\ CTRL-O is like CTRL-O but without moving the cursor
652  if (s->c == Ctrl_BSL) {
653    // may need to redraw when no more chars available now
654    ins_redraw(false);
655    no_mapping++;
656    allow_keys++;
657    s->c = plain_vgetc();
658    no_mapping--;
659    allow_keys--;
660    if (s->c != Ctrl_N && s->c != Ctrl_G && s->c != Ctrl_O) {
661      // it's something else
662      vungetc(s->c);
663      s->c = Ctrl_BSL;
664    } else {
665      if (s->c == Ctrl_O) {
666        ins_ctrl_o();
667        ins_at_eol = false;  // cursor keeps its column
668        s->nomove = true;
669      }
670      s->count = 0;
671      return 0;
672    }
673  }
674
675  if (s->c != K_EVENT) {
676    s->c = do_digraph(s->c);
677  }
678
679  if ((s->c == Ctrl_V || s->c == Ctrl_Q) && ctrl_x_mode_cmdline()) {
680    insert_do_complete(s);
681    insert_handle_key_post(s);
682    return 1;
683  }
684
685  if (s->c == Ctrl_V || s->c == Ctrl_Q) {
686    ins_ctrl_v();
687    s->c = Ctrl_V;       // pretend CTRL-V is last typed character
688    return 1;  // continue
689  }
690
691  if (cindent_on() && ctrl_x_mode_none()) {
692    s->line_is_white = inindent(0);
693    // A key name preceded by a bang means this key is not to be
694    // inserted.  Skip ahead to the re-indenting below.
695    if (in_cinkeys(s->c, '!', s->line_is_white)
696        && stop_arrow() == OK) {
697      do_c_expr_indent();
698      return 1;  // continue
699    }
700    // A key name preceded by a star means that indenting has to be
701    // done before inserting the key.
702    if (Ins.can_cindent && in_cinkeys(s->c, '*', s->line_is_white)
703        && stop_arrow() == OK) {
704      do_c_expr_indent();
705    }
706  }
707
708  if (curwin->w_p_rl) {
709    switch (s->c) {
710    case K_LEFT:
711      s->c = K_RIGHT; break;
712    case K_S_LEFT:
713      s->c = K_S_RIGHT; break;
714    case K_C_LEFT:
715      s->c = K_C_RIGHT; break;
716    case K_RIGHT:
717      s->c = K_LEFT; break;
718    case K_S_RIGHT:
719      s->c = K_S_LEFT; break;
720    case K_C_RIGHT:
721      s->c = K_C_LEFT; break;
722    }
723  }
724
725  // If 'keymodel' contains "startsel", may start selection.  If it
726  // does, a CTRL-O and c will be stuffed, we need to get these
727  // characters.
728  if (ins_start_select(s->c)) {
729    return 1;  // continue
730  }
731
732  return insert_handle_key(s);
733}
734
735static int insert_handle_key(InsertState *s)
736{
737  // The big switch to handle a character in insert mode.
738  switch (s->c) {
739  case ESC:           // End input mode
740    if (echeck_abbr(ESC + ABBR_OFF)) {
741      break;
742    }
743    FALLTHROUGH;
744
745  case Ctrl_C:        // End input mode
746    if (s->c == Ctrl_C && bt_cmdwin(curbuf)) {
747      got_int = false;  // Don't interrupt autocmds etc.
748      cmdwin_do_action("cancel");  // cmdwin: CTRL-C closes cmdwin, pre-fills cmdline.
749      return 0;  // exit insert mode
750    }
751    if (s->c == Ctrl_C && bt_prompt(curbuf)) {
752      if (invoke_prompt_interrupt()) {
753        if (!bt_prompt(curbuf)) {
754          // buffer changed to a non-prompt buffer, get out of
755          // Insert mode
756          return 0;
757        }
758        break;
759      }
760    }
761
762    return 0;  // exit insert mode
763
764  case Ctrl_Z:
765    goto normalchar;                // insert CTRL-Z as normal char
766
767  case Ctrl_O:        // execute one command
768    if (ctrl_x_mode_omni()) {
769      insert_do_complete(s);
770      break;
771    }
772
773    if (echeck_abbr(Ctrl_O + ABBR_OFF)) {
774      break;
775    }
776
777    ins_ctrl_o();
778
779    // don't move the cursor left when 'virtualedit' has "onemore".
780    if (get_ve_flags(curwin) & kOptVeFlagOnemore) {
781      ins_at_eol = false;
782      s->nomove = true;
783    }
784
785    s->count = 0;
786    return 0;  // exit insert mode
787
788  case K_INS:         // toggle insert/replace mode
789  case K_KINS:
790    ins_insert(s->replaceState);
791    break;
792
793  case K_SELECT:      // end of Select mode mapping - ignore
794    break;
795
796  case K_HELP:        // Help key works like <ESC> <Help>
797  case K_F1:
798  case K_XF1:
799    stuffcharReadbuff(K_HELP);
800    return 0;  // exit insert mode
801
802  case ' ':
803    if (mod_mask != MOD_MASK_CTRL) {
804      goto normalchar;
805    }
806    FALLTHROUGH;
807  case K_ZERO:        // Insert the previously inserted text.
808  case NUL:
809  case Ctrl_A:
810    // For ^@ the trailing ESC will end the insert, unless there is an
811    // error.
812    if (stuff_inserted(NUL, 1, (s->c == Ctrl_A)) == FAIL
813        && s->c != Ctrl_A) {
814      return 0;  // exit insert mode
815    }
816    s->inserted_space = false;
817    break;
818
819  case Ctrl_R:        // insert the contents of a register
820    if (ctrl_x_mode_register() && !ins_compl_active()) {
821      insert_do_complete(s);
822      break;
823    }
824    ins_reg();
825    auto_format(false, true);
826    s->inserted_space = false;
827    break;
828
829  case Ctrl_G:        // commands starting with CTRL-G
830    ins_ctrl_g();
831    break;
832
833  case Ctrl_HAT:      // switch input mode and/or langmap
834    ins_ctrl_hat();
835    break;
836
837  case Ctrl__:        // switch between languages
838    if (!p_ari) {
839      goto normalchar;
840    }
841    ins_ctrl_();
842    break;
843
844  case Ctrl_D:        // Make indent one shiftwidth smaller.
845    if (ctrl_x_mode_path_defines()) {
846      insert_do_complete(s);
847      break;
848    }
849    FALLTHROUGH;
850
851  case Ctrl_T:        // Make indent one shiftwidth greater.
852    if (s->c == Ctrl_T && ctrl_x_mode_thesaurus()) {
853      if (check_compl_option(false)) {
854        insert_do_complete(s);
855      }
856      break;
857    }
858    ins_shift(s->c, s->lastc);
859    auto_format(false, true);
860    s->inserted_space = false;
861    break;
862
863  case K_DEL:         // delete character under the cursor
864  case K_KDEL:
865    ins_del();
866    auto_format(false, true);
867    break;
868
869  case K_BS:          // delete character before the cursor
870  case Ctrl_H:
871    s->did_backspace = ins_bs(s->c, BACKSPACE_CHAR, &s->inserted_space);
872    auto_format(false, true);
873    if (s->did_backspace) {
874      MAY_TRIGGER_AUTOCOMPLETE(s->c);
875    }
876    break;
877
878  case Ctrl_W:        // delete word before the cursor
879    if (bt_prompt(curbuf) && (mod_mask & MOD_MASK_SHIFT) == 0) {
880      // In a prompt window CTRL-W is used for window commands.
881      // Use Shift-CTRL-W to delete a word.
882      stuffcharReadbuff(Ctrl_W);
883      restart_edit = 'A';
884      s->nomove = true;
885      s->count = 0;
886      return 0;
887    }
888    s->did_backspace = ins_bs(s->c, BACKSPACE_WORD, &s->inserted_space);
889    auto_format(false, true);
890    if (s->did_backspace) {
891      MAY_TRIGGER_AUTOCOMPLETE(s->c);
892    }
893    break;
894
895  case Ctrl_U:        // delete all inserted text in current line
896    // CTRL-X CTRL-U completes with 'completefunc'.
897    if (ctrl_x_mode_function()) {
898      insert_do_complete(s);
899    } else {
900      s->did_backspace = ins_bs(s->c, BACKSPACE_LINE, &s->inserted_space);
901      auto_format(false, true);
902      s->inserted_space = false;
903      if (s->did_backspace) {
904        MAY_TRIGGER_AUTOCOMPLETE(s->c);
905      }
906    }
907    break;
908
909  case K_LEFTMOUSE:     // mouse keys
910  case K_LEFTMOUSE_NM:
911  case K_LEFTDRAG:
912  case K_LEFTRELEASE:
913  case K_LEFTRELEASE_NM:
914  case K_MOUSEMOVE:
915  case K_MIDDLEMOUSE:
916  case K_MIDDLEDRAG:
917  case K_MIDDLERELEASE:
918  case K_RIGHTMOUSE:
919  case K_RIGHTDRAG:
920  case K_RIGHTRELEASE:
921  case K_X1MOUSE:
922  case K_X1DRAG:
923  case K_X1RELEASE:
924  case K_X2MOUSE:
925  case K_X2DRAG:
926  case K_X2RELEASE:
927    ins_mouse(s->c);
928    break;
929
930  case K_MOUSEDOWN:   // Default action for scroll wheel up: scroll up
931    ins_mousescroll(MSCR_DOWN);
932    break;
933
934  case K_MOUSEUP:     // Default action for scroll wheel down: scroll down
935    ins_mousescroll(MSCR_UP);
936    break;
937
938  case K_MOUSELEFT:   // Scroll wheel left
939    ins_mousescroll(MSCR_LEFT);
940    break;
941
942  case K_MOUSERIGHT:  // Scroll wheel right
943    ins_mousescroll(MSCR_RIGHT);
944    break;
945
946  case K_IGNORE:      // Something mapped to nothing
947    break;
948
949  case K_PASTE_START:
950  case K_EVENT:       // some event
951  case K_COMMAND:     // <Cmd>command<CR>
952  case K_LUA: {
953    bufref_T save_curbuf;
954    const varnumber_T tick = buf_get_changedtick(curbuf);
955    set_bufref(&save_curbuf, curbuf);
956
957    if (s->c == K_PASTE_START) {
958      paste_repeat(1);
959    } else if (s->c == K_EVENT) {
960      state_handle_k_event();
961      // If CTRL-G U was used apply it to the next typed key.
962      if (Ins.dont_sync_undo == kTrue) {
963        Ins.dont_sync_undo = kNone;
964      }
965    } else if (s->c == K_COMMAND) {
966      do_cmdline(NULL, getcmdkeycmd, NULL, 0);
967    } else {
968      map_execute_lua(false, false);
969    }
970
971    // nvim_select_popupmenu_item() can be called from the handling of
972    // K_EVENT, K_COMMAND, or K_LUA.
973    // TODO(bfredl): Not entirely sure this indirection is necessary
974    // but doing like this ensures using nvim_select_popupmenu_item is
975    // equivalent to selecting the item with a typed key.
976    if (pum_want.active) {
977      if (pum_visible()) {
978        // Set this to NULL so that ins_complete() will update the message.
979        edit_submode_extra = NULL;
980        insert_do_complete(s);
981        if (pum_want.finish) {
982          // accept the item and stop completion
983          ins_compl_prep(Ctrl_Y);
984        }
985      }
986      pum_want.active = false;
987    }
988
989    if (curbuf->b_u_synced
990        || (bufref_valid(&save_curbuf)
991            && curbuf == save_curbuf.br_buf
992            && tick != buf_get_changedtick(curbuf))) {
993      // The K_EVENT, K_COMMAND, or K_LUA synced undo or changed this buffer.
994      // Save the cursor line before the next typed edit.
995      Ins.need_undo = true;
996    }
997    break;
998  }
999
1000  case K_COMPLETE_DELAY:  // 'autocompletedelay' expired
1001    // If CTRL-G U was used apply it to the next typed key.
1002    if (Ins.dont_sync_undo == kTrue) {
1003      Ins.dont_sync_undo = kNone;
1004    }
1005    ins_compl_clear_autocomplete_delay();
1006    if (!ins_compl_has_autocomplete() || char_avail() || curwin->w_cursor.col == 0) {
1007      break;
1008    }
1009    s->c = char_before_cursor();
1010    if (!vim_isprintc(s->c)) {
1011      break;
1012    }
1013    // The completion may have been cleared while waiting, so re-enable
1014    // autocomplete to match a zero delay.
1015    ins_compl_enable_autocomplete();
1016    ins_compl_arm_autostart();
1017    insert_do_complete(s);
1018    break;
1019
1020  case K_HOME:        // <Home>
1021  case K_KHOME:
1022  case K_S_HOME:
1023  case K_C_HOME:
1024    ins_home(s->c);
1025    break;
1026
1027  case K_END:         // <End>
1028  case K_KEND:
1029  case K_S_END:
1030  case K_C_END:
1031    ins_end(s->c);
1032    break;
1033
1034  case K_LEFT:        // <Left>
1035    if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)) {
1036      ins_s_left();
1037    } else {
1038      ins_left();
1039    }
1040    break;
1041
1042  case K_S_LEFT:      // <S-Left>
1043  case K_C_LEFT:
1044    ins_s_left();
1045    break;
1046
1047  case K_RIGHT:       // <Right>
1048    if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)) {
1049      ins_s_right();
1050    } else {
1051      ins_right();
1052    }
1053    break;
1054
1055  case K_S_RIGHT:     // <S-Right>
1056  case K_C_RIGHT:
1057    ins_s_right();
1058    break;
1059
1060  case K_UP:          // <Up>
1061    if (pum_visible()) {
1062      insert_do_complete(s);
1063    } else if (mod_mask & MOD_MASK_SHIFT) {
1064      ins_pageup();
1065    } else {
1066      ins_up(false);
1067    }
1068    break;
1069
1070  case K_S_UP:        // <S-Up>
1071  case K_PAGEUP:
1072  case K_KPAGEUP:
1073    if (pum_visible()) {
1074      insert_do_complete(s);
1075    } else {
1076      ins_pageup();
1077    }
1078    break;
1079
1080  case K_DOWN:        // <Down>
1081    if (pum_visible()) {
1082      insert_do_complete(s);
1083    } else if (mod_mask & MOD_MASK_SHIFT) {
1084      ins_pagedown();
1085    } else {
1086      ins_down(false);
1087    }
1088    break;
1089
1090  case K_S_DOWN:      // <S-Down>
1091  case K_PAGEDOWN:
1092  case K_KPAGEDOWN:
1093    if (pum_visible()) {
1094      insert_do_complete(s);
1095    } else {
1096      ins_pagedown();
1097    }
1098    break;
1099
1100  case K_S_TAB:       // When not mapped, use like a normal TAB
1101    s->c = TAB;
1102    FALLTHROUGH;
1103
1104  case TAB:           // TAB or Complete patterns along path
1105    if (ctrl_x_mode_path_patterns()) {
1106      insert_do_complete(s);
1107      break;
1108    }
1109    s->inserted_space = false;
1110    if (ins_tab()) {
1111      goto normalchar;                // insert TAB as a normal char
1112    }
1113    auto_format(false, true);
1114    break;
1115
1116  case K_KENTER:      // <Enter>
1117    s->c = CAR;
1118    FALLTHROUGH;
1119  case CAR:
1120  case NL:
1121    // In a quickfix window a <CR> jumps to the error under the
1122    // cursor.
1123    if (bt_quickfix(curbuf) && s->c == CAR) {
1124      if (curwin->w_llist_ref == NULL) {          // quickfix window
1125        do_cmdline_cmd(".cc");
1126      } else {                                    // location list window
1127        do_cmdline_cmd(".ll");
1128      }
1129      break;
1130    }
1131    if (s->c == CAR && bt_cmdwin(curbuf)) {
1132      cmdwin_do_action("confirm");  // cmdwin: <CR> executes the command under the cursor.
1133      return 0;  // exit insert mode
1134    }
1135    if ((mod_mask & MOD_MASK_SHIFT) == 0 && bt_prompt(curbuf)) {
1136      prompt_invoke_callback();
1137      if (!bt_prompt(curbuf)) {
1138        // buffer changed to a non-prompt buffer, get out of
1139        // Insert mode
1140        return 0;
1141      }
1142      break;
1143    }
1144    if (!ins_eol(s->c)) {
1145      return 0;  // out of memory
1146    }
1147    auto_format(false, false);
1148    s->inserted_space = false;
1149    break;
1150
1151  case Ctrl_K:        // digraph or keyword completion
1152    if (ctrl_x_mode_dictionary()) {
1153      if (check_compl_option(true)) {
1154        insert_do_complete(s);
1155      }
1156      break;
1157    }
1158
1159    s->c = ins_digraph();
1160    if (s->c == NUL) {
1161      break;
1162    }
1163    goto normalchar;
1164
1165  case Ctrl_X:        // Enter CTRL-X mode
1166    ins_ctrl_x();
1167    break;
1168
1169  case Ctrl_RSB:      // Tag name completion after ^X
1170    if (!ctrl_x_mode_tags()) {
1171      goto normalchar;
1172    } else {
1173      insert_do_complete(s);
1174    }
1175    break;
1176
1177  case Ctrl_F:        // File name completion after ^X
1178    if (!ctrl_x_mode_files()) {
1179      goto normalchar;
1180    } else {
1181      insert_do_complete(s);
1182    }
1183    break;
1184
1185  case 's':           // Spelling completion after ^X
1186  case Ctrl_S:
1187    if (!ctrl_x_mode_spell()) {
1188      goto normalchar;
1189    } else {
1190      insert_do_complete(s);
1191    }
1192    break;
1193
1194  case Ctrl_L:        // Whole line completion after ^X
1195    if (!ctrl_x_mode_whole_line()) {
1196      goto normalchar;
1197    }
1198    FALLTHROUGH;
1199
1200  case Ctrl_P:        // Do previous/next pattern completion
1201  case Ctrl_N:
1202    // if 'complete' is empty then plain ^P is no longer special,
1203    // but it is under other ^X modes
1204    if (*curbuf->b_p_cpt == NUL
1205        && (ctrl_x_mode_normal() || ctrl_x_mode_whole_line())
1206        && !compl_status_local()) {
1207      goto normalchar;
1208    }
1209
1210    insert_do_complete(s);
1211    break;
1212
1213  case Ctrl_Y:        // copy from previous line or scroll down
1214  case Ctrl_E:        // copy from next line or scroll up
1215    s->c = ins_ctrl_ey(s->c);
1216    break;
1217
1218  default:
1219
1220normalchar:
1221    // Insert a normal character.
1222
1223    if (!p_paste) {
1224      // Trigger InsertCharPre.
1225      char *str = do_insert_char_pre(s->c);
1226
1227      if (str != NULL) {
1228        if (*str != NUL && stop_arrow() != FAIL) {
1229          // Insert the new value of v:char literally.
1230          for (char *p = str; *p != NUL; MB_PTR_ADV(p)) {
1231            s->c = utf_ptr2char(p);
1232            if (s->c == CAR || s->c == K_KENTER || s->c == NL) {
1233              ins_eol(s->c);
1234            } else {
1235              ins_char(s->c);
1236            }
1237          }
1238          redo_append_lit(str, -1);
1239        }
1240        xfree(str);
1241        s->c = NUL;
1242      }
1243
1244      // If the new value is already inserted or an empty string
1245      // then don't insert any character.
1246      if (s->c == NUL) {
1247        break;
1248      }
1249    }
1250    // Try to perform smart-indenting.
1251    ins_try_si(s->c);
1252
1253    if (s->c == ' ') {
1254      s->inserted_space = true;
1255      if (inindent(0)) {
1256        Ins.can_cindent = false;
1257      }
1258      if (Ins.start_blank_vcol == MAXCOL
1259          && curwin->w_cursor.lnum == Ins.start.lnum) {
1260        Ins.start_blank_vcol = get_nolist_virtcol();
1261      }
1262    }
1263
1264    // Insert a normal character and check for abbreviations on a
1265    // special character.  Let CTRL-] expand abbreviations without
1266    // inserting it.
1267    if (vim_iswordc(s->c)
1268        // Add ABBR_OFF for characters above 0x100, this is
1269        // what check_abbr() expects.
1270        || (!echeck_abbr((s->c >= 0x100) ? (s->c + ABBR_OFF) : s->c)
1271            && s->c != Ctrl_RSB)) {
1272      insert_special(s->c, false, false);
1273      Ins.revins_legal++;
1274      Ins.revins_chars++;
1275    }
1276
1277    auto_format(false, true);
1278
1279    // When inserting a character the cursor line must never be in a
1280    // closed fold.
1281    foldOpenCursor();
1282    // Trigger autocompletion
1283    if (ins_compl_has_autocomplete() && !char_avail() && vim_isprintc(s->c)) {
1284      TRIGGER_AUTOCOMPLETE();
1285    }
1286
1287    break;
1288  }       // end of switch (s->c)
1289
1290  insert_handle_key_post(s);
1291  return 1;  // continue
1292}
1293
1294static void insert_do_complete(InsertState *s)
1295{
1296  ins_compl_clear_autocomplete_delay();
1297  compl_busy = true;
1298  disable_fold_update++;  // don't redraw folds here
1299  if (ins_complete(s->c, true) == FAIL) {
1300    compl_status_clear();
1301  }
1302  disable_fold_update--;
1303  compl_busy = false;
1304  Ins.can_si = may_do_si();  // allow smartindenting
1305}
1306
1307static void insert_do_cindent(InsertState *s)
1308{
1309  // Indent now if a key was typed that is in 'cinkeys'.
1310  if (in_cinkeys(s->c, ' ', s->line_is_white)) {
1311    if (stop_arrow() == OK) {
1312      // re-indent the current line
1313      do_c_expr_indent();
1314    }
1315  }
1316}
1317
1318static void insert_handle_key_post(InsertState *s)
1319{
1320  // If typed something may trigger CursorHoldI again; K_COMPLETE_DELAY is
1321  // injected, not typed.
1322  if (s->c != K_EVENT && s->c != K_COMPLETE_DELAY
1323      // but not in CTRL-X mode, a script can't restore the state
1324      && ctrl_x_mode_normal()) {
1325    did_cursorhold = false;
1326  }
1327
1328  // Check if we need to cancel completion mode because the window
1329  // or tab page was changed
1330  if (ins_compl_active() && !ins_compl_win_active(curwin)) {
1331    ins_compl_cancel();
1332  }
1333
1334  // If the cursor was moved we didn't just insert a space
1335  if (Ins.moved != kInsNone) {
1336    s->inserted_space = false;
1337  }
1338
1339  if (Ins.can_cindent && cindent_on() && ctrl_x_mode_normal()) {
1340    insert_do_cindent(s);
1341  }
1342}
1343
1344/// edit(): Start inserting text.
1345///
1346/// May nest: ":normal i…" and multicursor insert-cascade enters it while an outer edit() is
1347/// suspended. But i_CTRL-O does not nest: edit() returns, and the caller runs the Normal-mode
1348/// command.
1349///
1350/// @param  cmdchar  Command that started the insert:
1351///   - 'i'
1352///   - 'a'
1353///   - 'R'
1354///   - 'r': "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo, but still only one
1355///     <CR> is inserted. <Esc> is not used for redo.
1356///   - 'g': "gI" command.
1357///   - 'V': "gR" command: Virtual Replace mode.
1358///   - 'v': "gr" command: single-character Virtual Replace mode.
1359/// @param  startln  If true, insert at start of line.
1360/// @param  count    Repeat count for the command.
1361///
1362/// @return true if a CTRL-O command caused the return (insert mode pending).
1363bool edit(int cmdchar, bool startln, int count)
1364{
1365  if (curbuf->terminal) {
1366    if (ex_normal_busy) {
1367      // Do not enter terminal mode from ex_normal(), which would cause havoc
1368      // (such as terminal-mode recursiveness). Instead set a flag to force-set
1369      // the value of `restart_edit` before `ex_normal` returns.
1370      restart_edit = 'i';
1371      force_restart_edit = true;
1372      return false;
1373    }
1374    return terminal_enter();
1375  }
1376
1377  // Don't allow inserting in the sandbox.
1378  if (sandbox != 0) {
1379    emsg(_(e_sandbox));
1380    return false;
1381  }
1382
1383  // Disallow edit() (insert-mode) when:
1384  // - ins-completion is active
1385  // - textlock (the caller of getcmdline() may get confused)
1386  // - <expr> mapping eval
1387  if (textlock != 0 || ins_compl_active() || compl_busy || pum_visible()
1388      || expr_map_locked()) {
1389    emsg(_(e_textlock));
1390    return false;
1391  }
1392
1393  InsertState s[1];
1394  memset(s, 0, sizeof(InsertState));
1395  s->state.execute = insert_execute;
1396  s->state.check = insert_check;
1397  s->cmdchar = cmdchar;
1398  s->startln = startln;
1399  s->count = count;
1400  insert_enter(s);
1401  return s->c == Ctrl_O;
1402}
1403
1404/// Redraw for Insert mode.
1405/// This is postponed until getting the next character to make '$' in the 'cpo'
1406/// option work correctly.
1407/// Only redraw when there are no characters available.  This speeds up
1408/// inserting sequences of characters (e.g., for CTRL-R).
1409///
1410/// @param ready  not busy with something
1411void ins_redraw(bool ready)
1412{
1413  if (char_avail()) {
1414    return;
1415  }
1416
1417  // Trigger CursorMoved if the cursor moved.  Not when the popup menu is
1418  // visible, the command might delete it.
1419  if (ready && has_event(EVENT_CURSORMOVEDI)
1420      && (last_cursormoved_win != curwin
1421          || !equalpos(last_cursormoved, curwin->w_cursor))
1422      && !pum_visible()) {
1423    // Need to update the screen first, to make sure syntax
1424    // highlighting is correct after making a change (e.g., inserting
1425    // a "(".  The autocommand may also require a redraw, so it's done
1426    // again below, unfortunately.
1427    if (syntax_present(curwin) && must_redraw) {
1428      update_screen();
1429    }
1430    // Make sure curswant is correct, an autocommand may call
1431    // getcurpos()
1432    update_curswant();
1433    ins_apply_autocmds(EVENT_CURSORMOVEDI);
1434    last_cursormoved_win = curwin;
1435    last_cursormoved = curwin->w_cursor;
1436  }
1437
1438  // Trigger TextChangedI if changedtick_i differs.
1439  if (ready && has_event(EVENT_TEXTCHANGEDI)
1440      && curbuf->b_last_changedtick_i != buf_get_changedtick(curbuf)
1441      && !pum_visible()) {
1442    CtxSwitch aco = { 0 };
1443    varnumber_T tick = buf_get_changedtick(curbuf);
1444
1445    // save and restore curwin and curbuf, in case the autocmd changes them
1446    ctx_switch(&aco, NULL, NULL, curbuf, 0);
1447    apply_autocmds(EVENT_TEXTCHANGEDI, NULL, NULL, false, curbuf);
1448    ctx_restore(&aco);
1449    curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
1450    if (tick != buf_get_changedtick(curbuf)) {  // see ins_apply_autocmds()
1451      u_save(curwin->w_cursor.lnum,
1452             (linenr_T)(curwin->w_cursor.lnum + 1));
1453    }
1454  }
1455
1456  // Trigger TextChangedP if changedtick_pum differs. When the popupmenu
1457  // closes TextChangedI will need to trigger for backwards compatibility,
1458  // thus use different b_last_changedtick* variables.
1459  if (ready && has_event(EVENT_TEXTCHANGEDP)
1460      && curbuf->b_last_changedtick_pum != buf_get_changedtick(curbuf)
1461      && pum_visible()) {
1462    CtxSwitch aco = { 0 };
1463    varnumber_T tick = buf_get_changedtick(curbuf);
1464
1465    // save and restore curwin and curbuf, in case the autocmd changes them
1466    ctx_switch(&aco, NULL, NULL, curbuf, 0);
1467    apply_autocmds(EVENT_TEXTCHANGEDP, NULL, NULL, false, curbuf);
1468    ctx_restore(&aco);
1469    curbuf->b_last_changedtick_pum = buf_get_changedtick(curbuf);
1470    if (tick != buf_get_changedtick(curbuf)) {  // see ins_apply_autocmds()
1471      u_save(curwin->w_cursor.lnum,
1472             (linenr_T)(curwin->w_cursor.lnum + 1));
1473    }
1474  }
1475
1476  if (ready) {
1477    may_trigger_win_scrolled_resized();
1478  }
1479
1480  // Trigger SafeState if nothing is pending.
1481  may_trigger_safestate(ready && !ins_compl_active() && !pum_visible());
1482
1483  pum_check_clear();
1484  show_cursor_info_later(false);
1485  if (must_redraw) {
1486    update_screen();
1487  } else {
1488    redraw_statuslines();
1489    if (clear_cmdline || redraw_cmdline || redraw_mode) {
1490      showmode();  // clear cmdline and show mode
1491    }
1492  }
1493  setcursor();
1494  emsg_on_display = false;      // may remove error message now
1495}
1496
1497// Handle a CTRL-V or CTRL-Q typed in Insert mode.
1498static void ins_ctrl_v(void)
1499{
1500  bool did_putchar = false;
1501
1502  // may need to redraw when no more chars available now
1503  ins_redraw(false);
1504
1505  if (redrawing() && !char_avail()) {
1506    edit_putchar('^', true);
1507    did_putchar = true;
1508  }
1509  redo_append_str(S_LEN(CTRL_V_STR));
1510
1511  add_to_showcmd_c(Ctrl_V);
1512
1513  // Do not include modifiers into the key for CTRL-SHIFT-V.
1514  int c = get_literal(mod_mask & MOD_MASK_SHIFT);
1515  if (did_putchar) {
1516    // when the line fits in 'columns' the '^' is at the start of the next
1517    // line and will not removed by the redraw
1518    edit_unputchar();
1519  }
1520  clear_showcmd();
1521  insert_special(c, true, true);
1522  Ins.revins_chars++;
1523  Ins.revins_legal++;
1524}
1525
1526// Put a character directly onto the screen.  It's not stored in a buffer.
1527// Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1528static int pc_status;
1529#define PC_STATUS_UNSET 0  // nothing was put on screen
1530#define PC_STATUS_RIGHT 1  // right half of double-wide char
1531#define PC_STATUS_LEFT  2  // left half of double-wide char
1532#define PC_STATUS_SET   3  // pc_schar was filled
1533static schar_T pc_schar;   // saved char
1534static int pc_attr;
1535static int pc_row;
1536static int pc_col;
1537
1538void edit_putchar(int c, bool highlight)
1539{
1540  if (curwin->w_grid_alloc.chars == NULL && default_grid.chars == NULL) {
1541    return;
1542  }
1543
1544  int attr;
1545  update_topline(curwin);  // just in case w_topline isn't valid
1546  validate_cursor(curwin);
1547  if (highlight) {
1548    attr = HL_ATTR(HLF_8);
1549  } else {
1550    attr = 0;
1551  }
1552  pc_row = curwin->w_wrow;
1553  pc_status = PC_STATUS_UNSET;
1554  grid_line_start(&curwin->w_grid, pc_row);
1555  if (curwin->w_p_rl) {
1556    pc_col = curwin->w_view_width - 1 - curwin->w_wcol;
1557
1558    if (grid_line_getchar(pc_col, NULL) == NUL) {
1559      grid_line_put_schar(pc_col - 1, schar_from_ascii(' '), attr);
1560      curwin->w_wcol--;
1561      pc_status = PC_STATUS_RIGHT;
1562    }
1563  } else {
1564    pc_col = curwin->w_wcol;
1565
1566    if (grid_line_getchar(pc_col + 1, NULL) == NUL) {
1567      // pc_col is the left half of a double-width char
1568      pc_status = PC_STATUS_LEFT;
1569    }
1570  }
1571
1572  // save the character to be able to put it back
1573  if (pc_status == PC_STATUS_UNSET) {
1574    pc_schar = grid_line_getchar(pc_col, &pc_attr);
1575    pc_status = PC_STATUS_SET;
1576  }
1577
1578  char buf[MB_MAXCHAR + 1];
1579  grid_line_puts(pc_col, buf, utf_char2bytes(c, buf), attr);
1580  grid_line_flush();
1581}
1582
1583/// @return    the effective prompt for the specified buffer.
1584char *buf_prompt_text(const buf_T *const buf)
1585  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
1586{
1587  if (buf->b_prompt_text == NULL) {
1588    return "% ";
1589  }
1590  return buf->b_prompt_text;
1591}
1592
1593/// @return  the effective prompt for the current buffer.
1594char *prompt_text(void)
1595  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
1596{
1597  return buf_prompt_text(curbuf);
1598}
1599
1600// Prepare for prompt mode (buftype=prompt): Make sure the last line has the prompt text.
1601// Move the cursor to this line.
1602static void init_prompt(int cmdchar_todo)
1603{
1604  char *prompt = prompt_text();
1605  int prompt_len = (int)strlen(prompt);
1606
1607  // In case the mark is set to a nonexistent line.
1608  if (curbuf->b_prompt_start.mark.lnum < 1
1609      || curbuf->b_prompt_start.mark.lnum > curbuf->b_ml.ml_line_count) {
1610    curbuf->b_prompt_start.mark.lnum = MAX(1, MIN(curbuf->b_prompt_start.mark.lnum,
1611                                                  curbuf->b_ml.ml_line_count));
1612    curbuf->b_prompt_append_new_line = true;
1613  }
1614
1615  curwin->w_cursor.lnum = MAX(curwin->w_cursor.lnum, curbuf->b_prompt_start.mark.lnum);
1616  char *text = ml_get(curbuf->b_prompt_start.mark.lnum);
1617  colnr_T text_len = ml_get_len(curbuf->b_prompt_start.mark.lnum);
1618
1619  if ((curbuf->b_prompt_start.mark.lnum == curwin->w_cursor.lnum
1620       && (curbuf->b_prompt_start.mark.col < prompt_len
1621           || curbuf->b_prompt_start.mark.col > text_len
1622           || !strnequal(text + curbuf->b_prompt_start.mark.col - prompt_len, prompt,
1623                         (size_t)prompt_len)))) {
1624    // prompt is missing, insert it or append a line with it
1625    if (*text == NUL) {
1626      ml_replace(curbuf->b_prompt_start.mark.lnum, prompt, true);
1627      inserted_bytes(curbuf->b_prompt_start.mark.lnum, 0, 0, prompt_len);
1628    } else {
1629      const linenr_T lnum = curbuf->b_ml.ml_line_count;
1630      ml_append(lnum, prompt, 0, false);
1631      appended_lines_mark(lnum, 1);
1632      curbuf->b_prompt_start.mark.lnum = curbuf->b_ml.ml_line_count;
1633      curbuf->b_prompt_append_new_line = true;
1634      // Like submitting, undo history was relevant to the old prompt.
1635      u_clearallandblockfree(curbuf);
1636    }
1637    curbuf->b_prompt_start.mark.col = prompt_len;
1638    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
1639    coladvance(curwin, MAXCOL);
1640  }
1641
1642  // Insert always starts after the prompt, allow editing text after it.
1643  if (Ins.start_orig.lnum != curbuf->b_prompt_start.mark.lnum
1644      || Ins.start_orig.col != curbuf->b_prompt_start.mark.col) {
1645    set_insstart(curbuf->b_prompt_start.mark.lnum, curbuf->b_prompt_start.mark.col);
1646  }
1647
1648  if (cmdchar_todo == 'A') {
1649    coladvance(curwin, MAXCOL);
1650  }
1651  if (curbuf->b_prompt_start.mark.lnum == curwin->w_cursor.lnum) {
1652    curwin->w_cursor.col = MAX(curwin->w_cursor.col, curbuf->b_prompt_start.mark.col);
1653  }
1654  // Make sure the cursor is in a valid position.
1655  check_cursor(curwin);
1656}
1657
1658/// @return  true if the cursor is in the editable position of the prompt line.
1659bool prompt_curpos_editable(void)
1660  FUNC_ATTR_PURE
1661{
1662  return curwin->w_cursor.lnum > curbuf->b_prompt_start.mark.lnum
1663         || (curwin->w_cursor.lnum == curbuf->b_prompt_start.mark.lnum
1664             && curwin->w_cursor.col >= curbuf->b_prompt_start.mark.col);
1665}
1666
1667/// Set the insert start position for when using a prompt buffer.
1668///
1669/// @param[in]  lnum
1670/// @param[in]  col
1671static void set_insstart(linenr_T lnum, colnr_T col)
1672{
1673  Ins.start.lnum = lnum;
1674  Ins.start.col = col;
1675  Ins.start_orig = Ins.start;
1676  Ins.start_textlen = Ins.start.col;
1677  Ins.start_blank_vcol = MAXCOL;
1678  Ins.moved = kInsNone;
1679}
1680
1681// Undo the previous edit_putchar().
1682void edit_unputchar(void)
1683{
1684  if (pc_status != PC_STATUS_UNSET) {
1685    if (pc_status == PC_STATUS_RIGHT) {
1686      curwin->w_wcol++;
1687    }
1688    if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT) {
1689      redrawWinline(curwin, curwin->w_cursor.lnum);
1690    } else {
1691      // TODO(bfredl): this could be smarter and also handle the dubyawidth case
1692      grid_line_start(&curwin->w_grid, pc_row);
1693      grid_line_put_schar(pc_col, pc_schar, pc_attr);
1694      grid_line_flush();
1695    }
1696  }
1697}
1698
1699/// Called when "$" is in 'cpoptions': display a '$' at the end of the changed
1700/// text.  Only works when cursor is in the line that changes.
1701void display_dollar(colnr_T col_arg)
1702{
1703  colnr_T col = MAX(col_arg, 0);
1704
1705  if (!redrawing()) {
1706    return;
1707  }
1708
1709  colnr_T save_col = curwin->w_cursor.col;
1710  curwin->w_cursor.col = col;
1711
1712  // If on the last byte of a multi-byte move to the first byte.
1713  char *p = get_cursor_line_ptr();
1714  curwin->w_cursor.col -= utf_head_off(p, p + col);
1715  curs_columns(curwin, false);              // Recompute w_wrow and w_wcol
1716  if (curwin->w_wcol < curwin->w_view_width) {
1717    edit_putchar('$', false);
1718    dollar_vcol = curwin->w_virtcol;
1719  }
1720  curwin->w_cursor.col = save_col;
1721}
1722
1723// Call this function before moving the cursor from the normal insert position
1724// in insert mode.
1725void undisplay_dollar(void)
1726{
1727  if (dollar_vcol < 0) {
1728    return;
1729  }
1730
1731  dollar_vcol = -1;
1732  redrawWinline(curwin, curwin->w_cursor.lnum);
1733}
1734
1735/// Truncate the space at the end of a line.  This is to be used only in an
1736/// insert mode.  It handles fixing the replace stack for MODE_REPLACE and
1737/// MODE_VREPLACE modes.
1738void truncate_spaces(char *line, size_t len)
1739{
1740  int i;
1741
1742  // find start of trailing white space
1743  for (i = (int)len - 1; i >= 0 && ascii_iswhite(line[i]); i--) {
1744    if (State & REPLACE_FLAG) {
1745      replace_join(0);              // remove a NUL from the replace stack
1746    }
1747  }
1748  line[i + 1] = NUL;
1749}
1750
1751/// Backspace the cursor until the given column.  Handles MODE_REPLACE and
1752/// MODE_VREPLACE modes correctly.  May also be used when not in insert mode at
1753/// all.  Will attempt not to go before "col" even when there is a composing
1754/// character.
1755void backspace_until_column(int col)
1756{
1757  while ((int)curwin->w_cursor.col > col) {
1758    curwin->w_cursor.col--;
1759    if (State & REPLACE_FLAG) {
1760      replace_do_bs(col);
1761    } else if (!del_char_after_col(col)) {
1762      break;
1763    }
1764  }
1765}
1766
1767/// Like del_char(), but make sure not to go before column "limit_col".
1768/// Only matters when there are composing characters.
1769///
1770/// @param  limit_col  only delete the character if it is after this column
1771//
1772/// @return true when something was deleted.
1773static bool del_char_after_col(int limit_col)
1774{
1775  if (limit_col >= 0) {
1776    colnr_T ecol = curwin->w_cursor.col + 1;
1777
1778    // Make sure the cursor is at the start of a character, but
1779    // skip forward again when going too far back because of a
1780    // composing character.
1781    mb_adjust_cursor();
1782    while (curwin->w_cursor.col < (colnr_T)limit_col) {
1783      int l = utf_ptr2len(get_cursor_pos_ptr());
1784
1785      if (l == 0) {  // end of line
1786        break;
1787      }
1788      curwin->w_cursor.col += l;
1789    }
1790    if (*get_cursor_pos_ptr() == NUL || curwin->w_cursor.col == ecol) {
1791      return false;
1792    }
1793    del_bytes(ecol - curwin->w_cursor.col, false, true);
1794  } else {
1795    del_char(false);
1796  }
1797  return true;
1798}
1799
1800/// Next character is interpreted literally.
1801/// A one, two or three digit decimal number is interpreted as its byte value.
1802/// If one or two digits are entered, the next character is given to vungetc().
1803/// For Unicode a character > 255 may be returned.
1804///
1805/// @param  no_simplify  do not include modifiers into the key
1806int get_literal(bool no_simplify)
1807{
1808  int nc;
1809  bool hex = false;
1810  bool octal = false;
1811  int unicode = 0;
1812
1813  if (got_int) {
1814    return Ctrl_C;
1815  }
1816
1817  no_mapping++;                 // don't map the next key hits
1818  int cc = 0;
1819  int i = 0;
1820  while (true) {
1821    nc = plain_vgetc();
1822    if (!no_simplify) {
1823      nc = merge_modifiers(nc, &mod_mask);
1824    }
1825    if ((mod_mask & ~MOD_MASK_SHIFT) != 0) {
1826      // A character with non-Shift modifiers should not be a valid
1827      // character for i_CTRL-V_digit.
1828      break;
1829    }
1830    if ((State & MODE_CMDLINE) == 0 && MB_BYTE2LEN_CHECK(nc) == 1) {
1831      add_to_showcmd(nc);
1832    }
1833    if (nc == 'x' || nc == 'X') {
1834      hex = true;
1835    } else if (nc == 'o' || nc == 'O') {
1836      octal = true;
1837    } else if (nc == 'u' || nc == 'U') {
1838      unicode = nc;
1839    } else {
1840      if (hex
1841          || unicode != 0) {
1842        if (!ascii_isxdigit(nc)) {
1843          break;
1844        }
1845        cc = cc * 16 + hex2nr(nc);
1846      } else if (octal) {
1847        if (nc < '0' || nc > '7') {
1848          break;
1849        }
1850        cc = cc * 8 + nc - '0';
1851      } else {
1852        if (!ascii_isdigit(nc)) {
1853          break;
1854        }
1855        cc = cc * 10 + nc - '0';
1856      }
1857
1858      i++;
1859    }
1860
1861    if (cc > 255
1862        && unicode == 0) {
1863      cc = 255;                 // limit range to 0-255
1864    }
1865    nc = 0;
1866
1867    if (hex) {                  // hex: up to two chars
1868      if (i >= 2) {
1869        break;
1870      }
1871    } else if (unicode) {     // Unicode: up to four or eight chars
1872      if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8)) {
1873        break;
1874      }
1875    } else if (i >= 3) {        // decimal or octal: up to three chars
1876      break;
1877    }
1878  }
1879  if (i == 0) {     // no number entered
1880    if (nc == K_ZERO) {     // NUL is stored as NL
1881      cc = '\n';
1882      nc = 0;
1883    } else {
1884      cc = nc;
1885      nc = 0;
1886    }
1887  }
1888
1889  if (cc == 0) {        // NUL is stored as NL
1890    cc = '\n';
1891  }
1892
1893  no_mapping--;
1894  if (nc) {
1895    vungetc(nc);
1896    // A character typed with i_CTRL-V_digit cannot have modifiers.
1897    mod_mask = 0;
1898  }
1899  got_int = false;          // CTRL-C typed after CTRL-V is not an interrupt
1900  return cc;
1901}
1902
1903/// Insert character, taking care of special keys and mod_mask
1904///
1905/// @param ctrlv `c` was typed after CTRL-V
1906static void insert_special(int c, int allow_modmask, int ctrlv)
1907{
1908  // Special function key, translate into "<Key>". Up to the last '>' is
1909  // inserted with ins_str(), so as not to replace characters in replace
1910  // mode.
1911  // Only use mod_mask for special keys, to avoid things like <S-Space>,
1912  // unless 'allow_modmask' is true.
1913  if (mod_mask & MOD_MASK_CMD) {  // Command-key never produces a normal key.
1914    allow_modmask = true;
1915  }
1916  if (IS_SPECIAL(c) || (mod_mask && allow_modmask)) {
1917    char *p = get_special_key_name(c, mod_mask);
1918    int len = (int)strlen(p);
1919    c = (uint8_t)p[len - 1];
1920    if (len > 2) {
1921      if (stop_arrow() == FAIL) {
1922        return;
1923      }
1924      p[len - 1] = NUL;
1925      ins_str(p, (size_t)(len - 1));
1926      redo_append_lit(p, -1);
1927      ctrlv = false;
1928    }
1929  }
1930  if (stop_arrow() == OK) {
1931    insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
1932  }
1933}
1934
1935// Special characters in this context are those that need processing other
1936// than the simple insertion that can be performed here. This includes ESC
1937// which terminates the insert, and CR/NL which need special processing to
1938// open up a new line. This routine tries to optimize insertions performed by
1939// the "redo", "undo" or "put" commands, so it needs to know when it should
1940// stop and defer processing to the "normal" mechanism.
1941// '0' and '^' are special, because they can be followed by CTRL-D.
1942#define ISSPECIAL(c)   ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
1943
1944/// "flags": INSCHAR_FORMAT - force formatting
1945///          INSCHAR_CTRLV  - char typed just after CTRL-V
1946///          INSCHAR_NO_FEX - don't use 'formatexpr'
1947///
1948///   NOTE: passes the flags value straight through to internal_format() which,
1949///         beside INSCHAR_FORMAT (above), is also looking for these:
1950///          INSCHAR_DO_COM   - format comments
1951///          INSCHAR_COM_LIST - format comments with num list or 2nd line indent
1952///
1953/// @param c              character to insert or NUL
1954/// @param flags          INSCHAR_FORMAT, etc.
1955/// @param second_indent  indent for second line if >= 0
1956void insertchar(int c, int flags, int second_indent)
1957{
1958  char *p;
1959  int force_format = flags & INSCHAR_FORMAT;
1960
1961  const int textwidth = comp_textwidth(force_format);
1962  const bool fo_ins_blank = has_format_option(kFoInsBlank);
1963
1964  // Try to break the line in two or more pieces when:
1965  // - Always do this if we have been called to do formatting only.
1966  // - Always do this when 'formatoptions' has the 'a' flag and the line
1967  //   ends in white space.
1968  // - Otherwise:
1969  //     - Don't do this if inserting a blank
1970  //     - Don't do this if an existing character is being replaced, unless
1971  //       we're in MODE_VREPLACE state.
1972  //     - Do this if the cursor is not on the line where insert started
1973  //     or - 'formatoptions' doesn't have 'l' or the line was not too long
1974  //           before the insert.
1975  //        - 'formatoptions' doesn't have 'b' or a blank was inserted at or
1976  //          before 'textwidth'
1977  if (textwidth > 0
1978      && (force_format
1979          || (!ascii_iswhite(c)
1980              && !((State & REPLACE_FLAG)
1981                   && !(State & VREPLACE_FLAG)
1982                   && *get_cursor_pos_ptr() != NUL)
1983              && (curwin->w_cursor.lnum != Ins.start.lnum
1984                  || ((!has_format_option(kFoInsLong)
1985                       || Ins.start_textlen <= (colnr_T)textwidth)
1986                      && (!fo_ins_blank
1987                          || Ins.start_blank_vcol <= (colnr_T)textwidth)))))) {
1988    // Format with 'formatexpr' when it's set.  Use internal formatting
1989    // when 'formatexpr' isn't set or it returns non-zero.
1990    bool do_internal = true;
1991    colnr_T virtcol = get_nolist_virtcol()
1992                      + char2cells(c != NUL ? c : gchar_cursor());
1993
1994    if (curbuf->b_p_fex.type != kCallbackNone && (flags & INSCHAR_NO_FEX) == 0
1995        && (force_format || virtcol > (colnr_T)textwidth)) {
1996      do_internal = (fex_format(curwin->w_cursor.lnum, 1, c) != 0);
1997      // It may be required to save for undo again, e.g. when setline()
1998      // was called.
1999      Ins.need_undo = true;
2000    }
2001    if (do_internal) {
2002      internal_format(textwidth, second_indent, flags, c == NUL, c);
2003    }
2004  }
2005
2006  if (c == NUL) {           // only formatting was wanted
2007    return;
2008  }
2009
2010  // Check whether this character should end a comment.
2011  if (Ins.did_ai && c == Ins.end_comment_pending) {
2012    char lead_end[COM_MAX_LEN];  // end-comment string
2013
2014    // Need to remove existing (middle) comment leader and insert end
2015    // comment leader.  First, check what comment leader we can find.
2016    char *line = get_cursor_line_ptr();
2017    int i = get_leader_len(line, &p, false, true);
2018    if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) {  // Just checking
2019      // Skip middle-comment string
2020      while (*p && p[-1] != ':') {  // find end of middle flags
2021        p++;
2022      }
2023      int middle_len = (int)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
2024      // Don't count trailing white space for middle_len
2025      while (middle_len > 0 && ascii_iswhite(lead_end[middle_len - 1])) {
2026        middle_len--;
2027      }
2028
2029      // Find the end-comment string
2030      while (*p && p[-1] != ':') {  // find end of end flags
2031        p++;
2032      }
2033      int end_len = (int)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
2034
2035      // Skip white space before the cursor
2036      i = curwin->w_cursor.col;
2037      while (--i >= 0 && ascii_iswhite(line[i])) {}
2038      i++;
2039
2040      // Skip to before the middle leader
2041      i -= middle_len;
2042
2043      // Check some expected things before we go on
2044      if (i >= 0 && end_len > 0
2045          && (uint8_t)lead_end[end_len - 1] == Ins.end_comment_pending) {
2046        // Backspace over all the stuff we want to replace
2047        backspace_until_column(i);
2048
2049        // Insert the end-comment string, except for the last
2050        // character, which will get inserted as normal later.
2051        ins_bytes_len(lead_end, (size_t)(end_len - 1));
2052      }
2053    }
2054  }
2055  Ins.end_comment_pending = NUL;
2056
2057  Ins.did_ai = false;
2058  Ins.did_si = false;
2059  Ins.can_si = false;
2060  Ins.can_si_back = false;
2061
2062  // If there's any pending input, grab up to INPUT_BUFLEN at once.
2063  // This speeds up normal text input considerably.
2064  // Don't do this when 'cindent' or 'indentexpr' is set, because we might
2065  // need to re-indent at a ':', or any other character (but not what
2066  // 'paste' is set)..
2067  // Don't do this when there an InsertCharPre autocommand is defined,
2068  // because we need to fire the event for every character.
2069  // Do the check for InsertCharPre before the call to vpeekc() because the
2070  // InsertCharPre autocommand could change the input buffer.
2071  if (!ISSPECIAL(c)
2072      && (utf_char2len(c) == 1)
2073      && !has_event(EVENT_INSERTCHARPRE)
2074      && !test_disable_char_avail
2075      && vpeekc() != NUL
2076      && !(State & REPLACE_FLAG)
2077      && !cindent_on()
2078      && !p_ri) {
2079#define INPUT_BUFLEN 100
2080    char buf[INPUT_BUFLEN + 1];
2081    colnr_T virtcol = 0;
2082
2083    buf[0] = (char)c;
2084    int i = 1;
2085    if (textwidth > 0) {
2086      virtcol = get_nolist_virtcol();
2087    }
2088    // Stop the string when:
2089    // - no more chars available
2090    // - finding a special character (command key)
2091    // - buffer is full
2092    // - running into the 'textwidth' boundary
2093    // - need to check for abbreviation: A non-word char after a word-char
2094    while ((c = vpeekc()) != NUL
2095           && !ISSPECIAL(c)
2096           && MB_BYTE2LEN(c) == 1
2097           && i < INPUT_BUFLEN
2098           && (textwidth == 0
2099               || (virtcol += ascii2cells((uint8_t)buf[i - 1])) < (colnr_T)textwidth)
2100           && !(!no_abbr && !vim_iswordc(c) && vim_iswordc((uint8_t)buf[i - 1]))) {
2101      c = vgetc();
2102      buf[i++] = (char)c;
2103    }
2104
2105    do_digraph(-1);                     // clear digraphs
2106    do_digraph((uint8_t)buf[i - 1]);               // may be the start of a digraph
2107    buf[i] = NUL;
2108    ins_str(buf, (size_t)i);
2109    if (flags & INSCHAR_CTRLV) {
2110      redo_literal((uint8_t)(*buf));
2111      i = 1;
2112    } else {
2113      i = 0;
2114    }
2115    if (buf[i] != NUL) {
2116      redo_append_lit(buf + i, -1);
2117    }
2118  } else {
2119    int cc;
2120
2121    if ((cc = utf_char2len(c)) > 1) {
2122      char buf[MB_MAXCHAR + 1];
2123
2124      utf_char2bytes(c, buf);
2125      buf[cc] = NUL;
2126      ins_char_bytes(buf, (size_t)cc);
2127      redo_append_char(c);
2128    } else {
2129      ins_char(c);
2130      if (flags & INSCHAR_CTRLV) {
2131        redo_literal(c);
2132      } else {
2133        redo_append_char(c);
2134      }
2135    }
2136  }
2137}
2138
2139// Put a character in the redo buffer, for when just after a CTRL-V.
2140static void redo_literal(int c)
2141{
2142  char buf[10];
2143
2144  // Only digits need special treatment.  Translate them into a string of
2145  // three digits.
2146  if (ascii_isdigit(c)) {
2147    vim_snprintf(buf, sizeof(buf), "%03d", c);
2148    redo_append_str(buf, -1);
2149  } else {
2150    redo_append_char(c);
2151  }
2152}
2153
2154/// Called when the cursor moves in insert-mode without editing text (arrow keys, <Home>, mouse).
2155/// For undo/redo it resembles hitting the <ESC> key.
2156///
2157/// @param end_insert_pos  Can be NULL
2158/// @param end_change      End undoable change
2159/// @param move_key        Cursor-move key, captured in the CmdAtom (replayed at mc-cascade).
2160///                        NUL for non-captured jumps (mouse, <PageUp>, <C-Home>); then the next
2161///                        edit restarts a new insert-session (stop_arrow()).
2162void start_arrow(pos_T *end_insert_pos, bool end_change, int move_key)
2163{
2164  if (Ins.moved == kInsNone && end_change) {  // something has been inserted
2165    stop_insert(end_insert_pos, false, false);  // this stops the current insert
2166  }
2167  if (Ins.moved != kInsJump) {
2168    if (move_key == NUL) {
2169      redo_append_str(S_LEN(ESC_STR));
2170      Ins.moved = kInsJump;
2171    } else {
2172      if (!IS_SPECIAL(move_key)) {
2173        // CTRL-G j/k: the only captured cursor-moves typed as plain chars.
2174        redo_append_char(Ctrl_G);
2175      }
2176      redo_append_char(move_key);
2177      if (end_change) {
2178        Ins.moved = kInsArrow;
2179      }
2180    }
2181  }
2182  check_spell_redraw();
2183}
2184
2185/// Like start_arrow(); if `end_change` is false (CTRL-G U pending), also captures the CTRL-G U
2186/// keys in the atom, ahead of "move_key": replay re-executes the whole "<C-g>U<Left>".
2187///
2188/// (Capturing them here, before start_arrow(), cannot corrupt stop_insert()'s last_insert
2189/// harvest: they append only when "end_change" is false, and stop_insert() runs only when it
2190/// is true.)
2191///
2192/// @param end_insert_pos  Can be NULL
2193/// @param end_change      End undoable change
2194/// @param move_key        @see start_arrow()
2195static void start_arrow_with_change(pos_T *end_insert_pos, bool end_change, int move_key)
2196{
2197  if (!end_change && Ins.moved != kInsJump) {
2198    redo_append_char(Ctrl_G);
2199    redo_append_char('U');
2200  }
2201  start_arrow(end_insert_pos, end_change, move_key);
2202}
2203
2204// If we skipped highlighting word at cursor, do it now.
2205// It may be skipped again, thus reset spell_redraw_lnum first.
2206static void check_spell_redraw(void)
2207{
2208  if (spell_redraw_lnum != 0) {
2209    linenr_T lnum = spell_redraw_lnum;
2210
2211    spell_redraw_lnum = 0;
2212    redrawWinline(curwin, lnum);
2213  }
2214}
2215
2216// stop_arrow() is called before a change is made in insert mode.
2217//
2218// After a cursor-move (`Ins.moved`), the change starts a new INSERTION (see `Ins.start`).
2219// Returns FAIL if undo is impossible, shouldn't insert then.
2220int stop_arrow(void)
2221{
2222  if (Ins.moved != kInsNone) {
2223    Ins.start = curwin->w_cursor;  // new insertion starts here
2224    if (Ins.start.col > Ins.start_orig.col && !Ins.need_undo) {
2225      // Don't update the original insert position when moved to the
2226      // right, except when nothing was inserted yet.
2227      Ins.update_start_orig = false;
2228    }
2229    Ins.start_textlen = linetabsize_str(get_cursor_line_ptr());
2230
2231    const bool jumped = Ins.moved == kInsJump;
2232    if (u_save_cursor() == OK) {
2233      Ins.moved = kInsNone;
2234      Ins.need_undo = false;
2235    }
2236    Ins.ai_col = 0;
2237    if (State & VREPLACE_FLAG) {
2238      orig_line_count = curbuf->b_ml.ml_line_count;
2239      vr_lines_changed = 1;
2240    }
2241    if (jumped) {
2242      // Non-captured cursor-move (mouse, <PageUp>, …): restart the capture as a "1i" insertion.
2243      // The count is a spec field (not body bytes), so "[count]." replaces it ("3i…").
2244      prep_redo(false, false, (CmdSpec){ .count = 1, .cmd = 'i' });
2245      Ins.new_insert_skip = 2;
2246      mc_ins_cascade_restart();
2247    } else {
2248      // Cursor-move was captured (start_arrow()): the atom mc-cascade will replay it.
2249      // Only `last_insert` (the ". register, i_CTRL-A) restarts here, like Vim.
2250      String redo = redo_keys(NULL);
2251      Ins.new_insert_skip = (int)redo.size;
2252      xfree(redo.data);
2253    }
2254  } else if (Ins.need_undo) {
2255    if (u_save_cursor() == OK) {
2256      // A command or event may have moved the cursor before the next
2257      // edit. Pull Ins.start back only when the cursor moved above it,
2258      // so that later edits can properly decide whether an extra undo
2259      // entry is needed. Advancing Ins.start would mis-place '[ after a
2260      // register paste.
2261      if (lt(curwin->w_cursor, Ins.start)) {
2262        Ins.start = curwin->w_cursor;
2263        Ins.start_textlen = (colnr_T)linetabsize_str(get_cursor_line_ptr());
2264      }
2265      Ins.need_undo = false;
2266    }
2267  }
2268
2269  // Always open fold at the cursor line when inserting something.
2270  foldOpenCursor();
2271
2272  return Ins.moved != kInsNone || Ins.need_undo ? FAIL : OK;
2273}
2274
2275/// Do a few things to stop inserting.
2276/// "end_insert_pos" is where insert ended.  It is NULL when we already jumped
2277/// to another window/buffer.
2278///
2279/// @param esc     called by ins_esc()
2280/// @param nomove  <c-\><c-o>, don't move cursor
2281static void stop_insert(pos_T *end_insert_pos, int esc, int nomove)
2282{
2283  stop_redo_ins();
2284  kv_destroy(replace_stack);  // abandon replace stack (reinitializes)
2285
2286  // Save the inserted text for later redo with ^@ and CTRL-A.
2287  // Don't do it when "restart_edit" was set and nothing was inserted,
2288  // otherwise CTRL-O w and then <Left> will clear "last_insert".
2289  String redo = redo_keys(NULL);
2290  int added = redo.data == NULL ? 0 : (int)redo.size - Ins.new_insert_skip;
2291  if (Ins.did_restart_edit == 0 || added > 0) {
2292    xfree(last_insert.data);
2293    last_insert = redo;  // structure copy
2294    last_insert_skip = added < 0 ? 0 : Ins.new_insert_skip;
2295  } else {
2296    xfree(redo.data);
2297  }
2298
2299  if (Ins.moved == kInsNone && end_insert_pos != NULL) {
2300    int cc;
2301    // Auto-format now.  It may seem strange to do this when stopping an
2302    // insertion (or moving the cursor), but it's required when appending
2303    // a line and having it end in a space.  But only do it when something
2304    // was actually inserted, otherwise undo won't work.
2305    if (!Ins.need_undo && has_format_option(kFoAuto)) {
2306      pos_T tpos = curwin->w_cursor;
2307
2308      // When the cursor is at the end of the line after a space the
2309      // formatting will move it to the following word.  Avoid that by
2310      // moving the cursor onto the space.
2311      cc = 'x';
2312      if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL) {
2313        dec_cursor();
2314        cc = gchar_cursor();
2315        if (!ascii_iswhite(cc)) {
2316          curwin->w_cursor = tpos;
2317        }
2318      }
2319
2320      auto_format(true, false);
2321
2322      if (ascii_iswhite(cc)) {
2323        if (gchar_cursor() != NUL) {
2324          inc_cursor();
2325        }
2326        // If the cursor is still at the same character, also keep
2327        // the "coladd".
2328        if (gchar_cursor() == NUL
2329            && curwin->w_cursor.lnum == tpos.lnum
2330            && curwin->w_cursor.col == tpos.col) {
2331          curwin->w_cursor.coladd = tpos.coladd;
2332        }
2333      }
2334    }
2335
2336    // If a space was inserted for auto-formatting, remove it now.
2337    check_auto_format(true);
2338
2339    // If we just did an auto-indent, remove the whitespace from EOL, and put the cursor back.
2340    // Do this when ESC was used or moving the cursor up/down.
2341    // Check for the old position still being valid, just in case the text changed unexpectedly.
2342    // Not for span replay during a mc-session: its synthetic <Esc> ends the nested session early.
2343    if (!nomove && Ins.did_ai && !mc_ins_replaying()
2344        && (esc || (vim_strchr(p_cpo, kCpoIndent) == NULL
2345                    && curwin->w_cursor.lnum != end_insert_pos->lnum))
2346        && end_insert_pos->lnum <= curbuf->b_ml.ml_line_count) {
2347      pos_T tpos = curwin->w_cursor;
2348      colnr_T prev_col = end_insert_pos->col;
2349
2350      curwin->w_cursor = *end_insert_pos;
2351      check_cursor_col(curwin);        // make sure it is not past the line
2352
2353      // Where the loop would actually start (back up if NUL).
2354      colnr_T strip_col = curwin->w_cursor.col;
2355      if (gchar_cursor() == NUL && strip_col > 0) {
2356        strip_col--;
2357      }
2358
2359      // Don't strip if non-whitespace follows: setline() from a <Cmd>
2360      // mapping or CursorHoldI autocmd may have inserted content.
2361      if (*skipwhite(get_cursor_line_ptr() + strip_col) == NUL) {
2362        curwin->w_cursor.col = strip_col;
2363        while (true) {
2364          if (gchar_cursor() == NUL && curwin->w_cursor.col > 0) {
2365            curwin->w_cursor.col--;
2366          }
2367          cc = gchar_cursor();
2368          if (!ascii_iswhite(cc)) {
2369            break;
2370          }
2371          if (del_char(true) == FAIL) {
2372            break;            // should not happen
2373          }
2374        }
2375        if (curwin->w_cursor.lnum != tpos.lnum) {
2376          curwin->w_cursor = tpos;
2377        } else if (curwin->w_cursor.col < prev_col) {
2378          // reset tpos, could have been invalidated in the loop above
2379          tpos = curwin->w_cursor;
2380          tpos.col++;
2381          if (cc != NUL && gchar_pos(&tpos) == NUL) {
2382            curwin->w_cursor.col++;         // put cursor back on the NUL
2383          }
2384        }
2385
2386        // <C-S-Right> may have started Visual mode, adjust the position for
2387        // deleted characters.
2388        if (Visual.active) {
2389          check_visual_pos();
2390        }
2391      } else {
2392        // Non-whitespace follows, keep original cursor.
2393        curwin->w_cursor = tpos;
2394      }
2395    }
2396  }
2397  Ins.did_ai = false;
2398  Ins.did_si = false;
2399  Ins.can_si = false;
2400  Ins.can_si_back = false;
2401
2402  // Set '[ and '] to the inserted text.  When end_insert_pos is NULL we are
2403  // now in a different buffer.
2404  if (end_insert_pos != NULL) {
2405    curbuf->b_op_start = Ins.start;
2406    curbuf->b_op_start_orig = Ins.start_orig;
2407    curbuf->b_op_end = *end_insert_pos;
2408  }
2409}
2410
2411// Set the last inserted text to a single character.
2412// Used for the replace command.
2413void set_last_insert(int c)
2414{
2415  xfree(last_insert.data);
2416  last_insert.data = xmalloc(MB_MAXBYTES * 3 + 5);
2417  char *s = last_insert.data;
2418  // Use the CTRL-V only when entering a special char
2419  if (c < ' ' || c == DEL) {
2420    *s++ = Ctrl_V;
2421  }
2422  s = add_char2buf(c, s);
2423  *s++ = ESC;
2424  *s = NUL;
2425  last_insert.size = (size_t)(s - last_insert.data);
2426  last_insert_skip = 0;
2427}
2428
2429#ifdef EXITFREE
2430void free_last_insert(void)
2431{
2432  API_CLEAR_STRING(last_insert);
2433}
2434#endif
2435
2436// move cursor to start of line
2437// if flags & BL_WHITE  move to first non-white
2438// if flags & BL_SOL    move to first non-white if startofline is set,
2439//                          otherwise keep "curswant" column
2440// if flags & BL_FIX    don't leave the cursor on a NUL.
2441void beginline(int flags)
2442{
2443  if ((flags & BL_SOL) && !p_sol) {
2444    coladvance(curwin, curwin->w_curswant);
2445  } else {
2446    curwin->w_cursor.col = 0;
2447    curwin->w_cursor.coladd = 0;
2448
2449    if (flags & (BL_WHITE | BL_SOL)) {
2450      for (char *ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr)
2451           && !((flags & BL_FIX) && ptr[1] == NUL); ptr++) {
2452        curwin->w_cursor.col++;
2453      }
2454    }
2455    curwin->w_set_curswant = true;
2456  }
2457  adjust_skipcol();
2458}
2459
2460// oneright oneleft cursor_down cursor_up
2461//
2462// Move one char {right,left,down,up}.
2463// Doesn't move onto the NUL past the end of the line, unless it is allowed.
2464// Return OK when successful, FAIL when we hit a line of file boundary.
2465
2466int oneright(void)
2467{
2468  char *ptr;
2469
2470  if (virtual_active(curwin)) {
2471    pos_T prevpos = curwin->w_cursor;
2472
2473    // Adjust for multi-wide char (excluding TAB)
2474    ptr = get_cursor_pos_ptr();
2475    coladvance(curwin, getviscol() + ((*ptr != TAB && vim_isprintc(utf_ptr2char(ptr)))
2476                                      ? ptr2cells(ptr) : 1));
2477    curwin->w_set_curswant = true;
2478    // Return OK if the cursor moved, FAIL otherwise (at window edge).
2479    return (prevpos.col != curwin->w_cursor.col
2480            || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
2481  }
2482
2483  ptr = get_cursor_pos_ptr();
2484  if (*ptr == NUL) {
2485    return FAIL;            // already at the very end
2486  }
2487
2488  int l = utfc_ptr2len(ptr);
2489
2490  // move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
2491  // contains "onemore".
2492  if (ptr[l] == NUL && (get_ve_flags(curwin) & kOptVeFlagOnemore) == 0) {
2493    return FAIL;
2494  }
2495  curwin->w_cursor.col += l;
2496
2497  curwin->w_set_curswant = true;
2498  adjust_skipcol();
2499  return OK;
2500}
2501
2502int oneleft(void)
2503{
2504  if (virtual_active(curwin)) {
2505    int v = getviscol();
2506
2507    if (v == 0) {
2508      return FAIL;
2509    }
2510
2511    // We might get stuck on 'showbreak', skip over it.
2512    int width = 1;
2513    while (true) {
2514      coladvance(curwin, v - width);
2515      // getviscol() is slow, skip it when 'showbreak' is empty,
2516      // 'breakindent' is not set and there are no multi-byte
2517      // characters
2518      if (getviscol() < v) {
2519        break;
2520      }
2521      width++;
2522    }
2523
2524    if (curwin->w_cursor.coladd == 1) {
2525      // Adjust for multi-wide char (not a TAB)
2526      char *ptr = get_cursor_pos_ptr();
2527      if (*ptr != TAB && vim_isprintc(utf_ptr2char(ptr)) && ptr2cells(ptr) > 1) {
2528        curwin->w_cursor.coladd = 0;
2529      }
2530    }
2531
2532    curwin->w_set_curswant = true;
2533    adjust_skipcol();
2534    return OK;
2535  }
2536
2537  if (curwin->w_cursor.col == 0) {
2538    return FAIL;
2539  }
2540
2541  curwin->w_set_curswant = true;
2542  curwin->w_cursor.col--;
2543
2544  // if the character on the left of the current cursor is a multi-byte
2545  // character, move to its first byte
2546  mb_adjust_cursor();
2547  adjust_skipcol();
2548  return OK;
2549}
2550
2551/// Move the cursor up "n" lines in window "wp". Takes care of closed folds.
2552/// Skips over concealed lines when "skip_conceal" is true.
2553void cursor_up_inner(win_T *wp, linenr_T n, bool skip_conceal)
2554{
2555  linenr_T lnum = wp->w_cursor.lnum;
2556
2557  if (n >= lnum) {
2558    lnum = 1;
2559  } else if (win_lines_concealed(wp)) {
2560    // Count each sequence of folded lines as one logical line.
2561
2562    // go to the start of the current fold
2563    hasFolding(wp, lnum, &lnum, NULL);
2564
2565    while (n--) {
2566      // move up one line
2567      lnum--;
2568      if (lnum <= 1) {
2569        break;
2570      }
2571      n += skip_conceal && decor_conceal_line(wp, lnum - 1, true);
2572      // If we entered a fold, move to the beginning, unless in
2573      // Insert mode or when 'foldopen' contains "all": it will open
2574      // in a moment.
2575      if (n > 0 || !((State & MODE_INSERT) || (fdo_flags & kOptFdoFlagAll))) {
2576        hasFolding(wp, lnum, &lnum, NULL);
2577      }
2578    }
2579    lnum = MAX(lnum, 1);
2580  } else {
2581    lnum -= n;
2582  }
2583
2584  wp->w_cursor.lnum = lnum;
2585}
2586
2587/// @param upd_topline  When true: update topline
2588int cursor_up(linenr_T n, bool upd_topline)
2589{
2590  // This fails if the cursor is already in the first line.
2591  if (n > 0 && curwin->w_cursor.lnum <= 1) {
2592    return FAIL;
2593  }
2594  cursor_up_inner(curwin, n, false);
2595
2596  // try to advance to the column we want to be at
2597  coladvance(curwin, curwin->w_curswant);
2598
2599  if (upd_topline) {
2600    update_topline(curwin);  // make sure curwin->w_topline is valid
2601  }
2602
2603  return OK;
2604}
2605
2606/// Move the cursor down "n" lines in window "wp". Takes care of closed folds.
2607/// Skips over concealed lines when "skip_conceal" is true.
2608void cursor_down_inner(win_T *wp, int n, bool skip_conceal)
2609{
2610  linenr_T lnum = wp->w_cursor.lnum;
2611  linenr_T line_count = wp->w_buffer->b_ml.ml_line_count;
2612
2613  if (lnum + n >= line_count) {
2614    lnum = line_count;
2615  } else if (win_lines_concealed(wp)) {
2616    linenr_T last;
2617
2618    // count each sequence of folded lines as one logical line
2619    while (n--) {
2620      if (hasFoldingWin(wp, lnum, NULL, &last, true, NULL)) {
2621        lnum = last + 1;
2622      } else {
2623        lnum++;
2624      }
2625      if (lnum >= line_count) {
2626        break;
2627      }
2628      n += skip_conceal && decor_conceal_line(wp, lnum - 1, true);
2629    }
2630    lnum = MIN(lnum, line_count);
2631  } else {
2632    lnum += (linenr_T)n;
2633  }
2634
2635  wp->w_cursor.lnum = lnum;
2636}
2637
2638/// @param upd_topline  When true: update topline
2639int cursor_down(int n, bool upd_topline)
2640{
2641  linenr_T lnum = curwin->w_cursor.lnum;
2642  // This fails if the cursor is already in the last (folded) line.
2643  hasFoldingWin(curwin, lnum, NULL, &lnum, true, NULL);
2644  if (n > 0 && lnum >= curwin->w_buffer->b_ml.ml_line_count) {
2645    return FAIL;
2646  }
2647  cursor_down_inner(curwin, n, false);
2648
2649  // try to advance to the column we want to be at
2650  coladvance(curwin, curwin->w_curswant);
2651
2652  if (upd_topline) {
2653    update_topline(curwin);           // make sure curwin->w_topline is valid
2654  }
2655
2656  return OK;
2657}
2658
2659/// Stuff the last inserted text in the read buffer.
2660/// Last_insert actually is a copy of the redo buffer, so we
2661/// first have to remove the command.
2662///
2663/// @param c       Command character to be inserted
2664/// @param count   Repeat this many times
2665/// @param no_esc  Don't add an ESC at the end
2666int stuff_inserted(int c, int count, int no_esc)
2667{
2668  char last = NUL;
2669
2670  String insert = get_last_insert();  // text to be inserted
2671  if (insert.data == NULL) {
2672    emsg(_(e_noinstext));
2673    return FAIL;
2674  }
2675
2676  // may want to stuff the command character, to start Insert mode
2677  if (c != NUL) {
2678    stuffcharReadbuff(c);
2679  }
2680
2681  if (insert.size > 0) {
2682    // look for the last ESC in 'insert'
2683    for (char *p = insert.data + insert.size - 1; p >= insert.data; p--) {
2684      if (*p == ESC) {
2685        insert.size = (size_t)(p - insert.data);
2686        break;
2687      }
2688    }
2689  }
2690
2691  if (insert.size > 0) {
2692    char *p = insert.data + insert.size - 1;
2693    // when the last char is either "0" or "^" it will be quoted if no ESC
2694    // comes after it OR if it will inserted more than once and "ptr"
2695    // starts with ^D.  -- Acevedo
2696    if ((*p == '0' || *p == '^')
2697        && (no_esc || (*insert.data == Ctrl_D && count > 1))) {
2698      last = *p;
2699      insert.size--;
2700    }
2701  }
2702
2703  do {
2704    stuffReadbuffLen(insert.data, (ptrdiff_t)insert.size);
2705    // A trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^".
2706    switch (last) {
2707    case '0':
2708      stuffReadbuffLen(S_LEN("\026\060\064\070"));
2709      break;
2710    case '^':
2711      stuffReadbuffLen(S_LEN("\026^"));
2712      break;
2713    default:
2714      break;
2715    }
2716  } while (--count > 0);
2717
2718  // may want to stuff a trailing ESC, to get out of Insert mode
2719  if (!no_esc) {
2720    stuffcharReadbuff(ESC);
2721  }
2722
2723  return OK;
2724}
2725
2726String get_last_insert(void)
2727  FUNC_ATTR_PURE
2728{
2729  return last_insert.data == NULL ? NULL_STRING : (String){
2730    .data = last_insert.data + last_insert_skip,
2731    .size = last_insert.size - (size_t)last_insert_skip,
2732  };
2733}
2734
2735// Get last inserted string, and remove trailing <Esc>.
2736// Returns pointer to allocated memory (must be freed) or NULL.
2737char *get_last_insert_save(void)
2738{
2739  String insert = get_last_insert();
2740
2741  if (insert.data == NULL) {
2742    return NULL;
2743  }
2744
2745  char *s = xmemdupz(insert.data, insert.size);
2746  if (insert.size > 0 && s[insert.size - 1] == ESC) {  // remain trailing ESC
2747    s[--insert.size] = NUL;
2748  }
2749  return s;
2750}
2751
2752/// Check the word in front of the cursor for an abbreviation.
2753/// Called when the non-id character "c" has been entered.
2754/// When an abbreviation is recognized it is removed from the text and
2755/// the replacement string is inserted in typebuf.tb_buf[], followed by "c".
2756///
2757/// @param  c  character
2758///
2759/// @return true if the word is a known abbreviation.
2760static bool echeck_abbr(int c)
2761  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2762{
2763  // Don't check for abbreviation in paste mode, when disabled and just
2764  // after moving around with cursor keys.
2765  if (p_paste || no_abbr || Ins.moved != kInsNone) {
2766    return false;
2767  }
2768
2769  return check_abbr(c, get_cursor_line_ptr(), curwin->w_cursor.col,
2770                    curwin->w_cursor.lnum == Ins.start.lnum ? Ins.start.col : 0);
2771}
2772
2773// replace-stack functions
2774//
2775// When replacing characters, the replaced characters are remembered for each
2776// new character.  This is used to re-insert the old text when backspacing.
2777//
2778// There is a NUL headed list of characters for each character that is
2779// currently in the file after the insertion point.  When BS is used, one NUL
2780// headed list is put back for the deleted character.
2781//
2782// For a newline, there are two NUL headed lists.  One contains the characters
2783// that the NL replaced.  The extra one stores the characters after the cursor
2784// that were deleted (always white space).
2785
2786/// Push character that is replaced onto the replace stack.
2787///
2788/// replace_offset is normally 0, in which case replace_push will add a new
2789/// character at the end of the stack.  If replace_offset is not 0, that many
2790/// characters will be left on the stack above the newly inserted character.
2791///
2792/// @param str character that is replaced (NUL is none)
2793/// @param len length of character in bytes
2794void replace_push(char *str, size_t len)
2795{
2796  // TODO(bfredl): replace_offset is suss af, if we don't need it, this
2797  // function is just kv_concat() :p
2798  if (kv_size(replace_stack) < (size_t)replace_offset) {  // nothing to do
2799    return;
2800  }
2801
2802  kv_ensure_space(replace_stack, len);
2803
2804  char *p = replace_stack.items + kv_size(replace_stack) - replace_offset;
2805  if (replace_offset) {
2806    memmove(p + len, p, (size_t)replace_offset);
2807  }
2808  memcpy(p, str, len);
2809  kv_size(replace_stack) += len;
2810}
2811
2812/// push NUL as separator between entries in the stack
2813void replace_push_nul(void)
2814{
2815  replace_push("", 1);
2816}
2817
2818/// Check top of replace stack, pop it if it was NUL
2819///
2820/// when a non-NUL byte is found, use mb_replace_pop_ins() to
2821/// pop one complete multibyte character.
2822///
2823/// @return -1 if stack is empty, last byte of char or NUL otherwise
2824static int replace_pop_if_nul(void)
2825{
2826  int ch = (kv_size(replace_stack)) ? (uint8_t)kv_A(replace_stack, kv_size(replace_stack) - 1) : -1;
2827  if (ch == NUL) {
2828    kv_size(replace_stack)--;
2829  }
2830  return ch;
2831}
2832
2833/// Join the top two items on the replace stack.  This removes to "off"'th NUL
2834/// encountered.
2835///
2836/// @param off  offset for which NUL to remove
2837void replace_join(int off)
2838{
2839  for (ssize_t i = (ssize_t)kv_size(replace_stack); --i >= 0;) {
2840    if (kv_A(replace_stack, i) == NUL && off-- <= 0) {
2841      kv_size(replace_stack)--;
2842      memmove(&kv_A(replace_stack, i), &kv_A(replace_stack, i + 1),
2843              (kv_size(replace_stack) - (size_t)i));
2844      return;
2845    }
2846  }
2847}
2848
2849/// Pop bytes from the replace stack until a NUL is found, and insert them
2850/// before the cursor.  Can only be used in MODE_REPLACE or MODE_VREPLACE state.
2851static void replace_pop_ins(void)
2852{
2853  int oldState = State;
2854
2855  State = MODE_NORMAL;                       // don't want MODE_REPLACE here
2856  while ((replace_pop_if_nul()) > 0) {
2857    mb_replace_pop_ins();
2858    dec_cursor();
2859  }
2860  State = oldState;
2861}
2862
2863/// Insert multibyte char popped from the replace stack.
2864///
2865/// caller must already have checked the top of the stack is not NUL!!
2866static void mb_replace_pop_ins(void)
2867{
2868  int len = utf_head_off(&kv_A(replace_stack, 0),
2869                         &kv_A(replace_stack, kv_size(replace_stack) - 1)) + 1;
2870  kv_size(replace_stack) -= (size_t)len;
2871  ins_bytes_len(&kv_A(replace_stack, kv_size(replace_stack)), (size_t)len);
2872}
2873
2874// Handle doing a BS for one character.
2875// cc < 0: replace stack empty, just move cursor
2876// cc == 0: character was inserted, delete it
2877// cc > 0: character was replaced, put cc (first byte of original char) back
2878// and check for more characters to be put back
2879// When "limit_col" is >= 0, don't delete before this column.  Matters when
2880// using composing characters, use del_char_after_col() instead of del_char().
2881static void replace_do_bs(int limit_col)
2882{
2883  colnr_T start_vcol;
2884  const int l_State = State;
2885
2886  int cc = replace_pop_if_nul();
2887  if (cc > 0) {
2888    int orig_len = 0;
2889    int orig_vcols = 0;
2890    if (l_State & VREPLACE_FLAG) {
2891      // Get the number of screen cells used by the character we are
2892      // going to delete.
2893      getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL, 0);
2894      orig_vcols = win_chartabsize(curwin, get_cursor_pos_ptr(), start_vcol);
2895    }
2896    del_char_after_col(limit_col);
2897    if (l_State & VREPLACE_FLAG) {
2898      orig_len = get_cursor_pos_len();
2899    }
2900    replace_pop_ins();
2901
2902    if (l_State & VREPLACE_FLAG) {
2903      // Get the number of screen cells used by the inserted characters
2904      char *p = get_cursor_pos_ptr();
2905      int ins_len = get_cursor_pos_len() - orig_len;
2906      int vcol = start_vcol;
2907      for (int i = 0; i < ins_len; i++) {
2908        vcol += win_chartabsize(curwin, p + i, vcol);
2909        i += utfc_ptr2len(p + i) - 1;
2910      }
2911      vcol -= start_vcol;
2912
2913      // Delete spaces that were inserted after the cursor to keep the
2914      // text aligned.
2915      curwin->w_cursor.col += ins_len;
2916      while (vcol > orig_vcols && gchar_cursor() == ' ') {
2917        del_char(false);
2918        orig_vcols++;
2919      }
2920      curwin->w_cursor.col -= ins_len;
2921    }
2922
2923    // mark the buffer as changed and prepare for displaying
2924    changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
2925  } else if (cc == 0) {
2926    del_char_after_col(limit_col);
2927  }
2928}
2929
2930static void ins_reg(void)
2931{
2932  bool need_redraw = false;
2933  int literally = 0;
2934  int vis_active = Visual.active;
2935
2936  // If we are going to wait for a character, show a '"'.
2937  pc_status = PC_STATUS_UNSET;
2938  if (redrawing() && !char_avail()) {
2939    // may need to redraw when no more chars available now
2940    ins_redraw(false);
2941
2942    edit_putchar('"', true);
2943    add_to_showcmd_c(Ctrl_R);
2944  }
2945
2946  // Don't map the register name. This also prevents the mode message to be
2947  // deleted when ESC is hit.
2948  no_mapping++;
2949  allow_keys++;
2950  int regname = plain_vgetc();
2951  LANGMAP_ADJUST(regname, true);
2952  if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P) {
2953    // Get a third key for literal register insertion
2954    literally = regname;
2955    add_to_showcmd_c(literally);
2956    regname = plain_vgetc();
2957    LANGMAP_ADJUST(regname, true);
2958  }
2959  no_mapping--;
2960  allow_keys--;
2961
2962  // Don't call u_sync() while typing the expression or giving an error
2963  // message for it. Only call it explicitly.
2964  no_u_sync++;
2965  if (regname == '=') {
2966    pos_T curpos = curwin->w_cursor;
2967
2968    // Sync undo when evaluating the expression calls setline() or
2969    // append(), so that it can be undone separately.
2970    u_sync_once = 2;
2971
2972    regname = get_expr_register();
2973
2974    // Cursor may be moved back a column.
2975    curwin->w_cursor = curpos;
2976    check_cursor(curwin);
2977  }
2978  if (regname == NUL || !valid_yank_reg(regname, false)) {
2979    vim_beep(kOptBoFlagRegister);
2980    need_redraw = true;  // remove the '"'
2981  } else {
2982    yankreg_T *reg = get_yank_register(regname, YREG_PASTE);
2983
2984    if (literally == Ctrl_O || literally == Ctrl_P) {
2985      // Append the command to the redo buffer.
2986      redo_append_char(Ctrl_R);
2987      redo_append_char(literally);
2988      redo_append_char(regname);
2989
2990      do_put(regname, NULL, BACKWARD, 1,
2991             (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
2992    } else if (reg->y_size > 1 && is_literal_register(regname)) {
2993      redo_append_char(Ctrl_R);
2994      redo_append_char(regname);
2995      do_put(regname, NULL, BACKWARD, 1, PUT_CURSEND);
2996    } else if (insert_reg(regname, NULL, !!literally) == FAIL) {
2997      vim_beep(kOptBoFlagRegister);
2998      need_redraw = true;  // remove the '"'
2999    } else if (Ins.stop_insert_mode) {
3000      // When the '=' register was used and a function was invoked that
3001      // did ":stopinsert" then stuff_empty() returns false but we won't
3002      // insert anything, need to remove the '"'
3003      need_redraw = true;
3004    }
3005  }
3006  no_u_sync--;
3007  if (u_sync_once == 1) {
3008    Ins.need_undo = true;
3009  }
3010  u_sync_once = 0;
3011
3012  // If the inserted register is empty, we need to remove the '"'. Do this before
3013  // clearing showcmd, which emits an event that can also update the screen.
3014  if (need_redraw || stuff_empty()) {
3015    edit_unputchar();
3016  }
3017  clear_showcmd();
3018
3019  // Disallow starting Visual mode here, would get a weird mode.
3020  if (!vis_active && Visual.active) {
3021    end_visual_mode();
3022  }
3023}
3024
3025// CTRL-G commands in Insert mode.
3026static void ins_ctrl_g(void)
3027{
3028  // Right after CTRL-X the cursor will be after the ruler.
3029  setcursor();
3030
3031  // Don't map the second key. This also prevents the mode message to be
3032  // deleted when ESC is hit.
3033  no_mapping++;
3034  allow_keys++;
3035  int c = plain_vgetc();
3036  no_mapping--;
3037  allow_keys--;
3038  switch (c) {
3039  // CTRL-G k and CTRL-G <Up>: cursor up to Ins.start.col
3040  case K_UP:
3041  case Ctrl_K:
3042  case 'k':
3043    ins_up(true);
3044    break;
3045
3046  // CTRL-G j and CTRL-G <Down>: cursor down to Ins.start.col
3047  case K_DOWN:
3048  case Ctrl_J:
3049  case 'j':
3050    ins_down(true);
3051    break;
3052
3053  // CTRL-G u: start new undoable edit
3054  case 'u':
3055    u_sync(true);
3056    Ins.need_undo = true;
3057
3058    // Need to reset Ins.start, esp. because a BS that joins
3059    // a line to the previous one must save for undo.
3060    Ins.update_start_orig = false;
3061    Ins.start = curwin->w_cursor;
3062    break;
3063
3064  // CTRL-G U: do not break undo with the next char.
3065  case 'U':
3066    // Allow one left/right cursor movement with the next char,
3067    // without breaking undo.
3068    Ins.dont_sync_undo = kNone;
3069    break;
3070
3071  case ESC:
3072    // Esc after CTRL-G cancels it.
3073    break;
3074
3075  // Unknown CTRL-G command, reserved for future expansion.
3076  default:
3077    vim_beep(kOptBoFlagCtrlg);
3078  }
3079}
3080
3081// CTRL-^ in Insert mode.
3082static void ins_ctrl_hat(void)
3083{
3084  if (map_to_exists_mode("", MODE_LANGMAP, false)) {
3085    // ":lmap" mappings exists, Toggle use of ":lmap" mappings.
3086    if (State & MODE_LANGMAP) {
3087      curbuf->b_p_iminsert = B_IMODE_NONE;
3088      State &= ~MODE_LANGMAP;
3089    } else {
3090      curbuf->b_p_iminsert = B_IMODE_LMAP;
3091      State |= MODE_LANGMAP;
3092    }
3093  }
3094  set_iminsert_global(curbuf);
3095  showmode();
3096  // Show/unshow value of 'keymap' in status lines.
3097  status_redraw_curbuf();
3098}
3099
3100/// Handle ESC in insert mode.
3101///
3102/// @param[in,out]  count    repeat count of the insert command
3103/// @param          cmdchar  command that started the insert
3104/// @param          nomove   when true, don't move the cursor
3105///
3106/// @return true when leaving insert mode, false when repeating the insert.
3107static bool ins_esc(int *count, int cmdchar, bool nomove)
3108  FUNC_ATTR_NONNULL_ARG(1)
3109{
3110  static bool disabled_redraw = false;
3111
3112  check_spell_redraw();
3113
3114  int temp = curwin->w_cursor.col;
3115  if (disabled_redraw) {
3116    RedrawingDisabled--;
3117    disabled_redraw = false;
3118  }
3119  if (Ins.moved == kInsNone) {
3120    // Don't append the ESC for "r<CR>" and "grx".
3121    if (cmdchar != 'r' && cmdchar != 'v') {
3122      redo_append_str(S_LEN(ESC_STR));
3123    }
3124
3125    // Repeating insert may take a long time.  Check for
3126    // interrupt now and then.
3127    if (*count > 0) {
3128      line_breakcheck();
3129      if (got_int) {
3130        *count = 0;
3131      }
3132    }
3133
3134    if (--*count > 0) {         // repeat what was typed
3135      // Vi repeats the insert without replacing characters.
3136      if (vim_strchr(p_cpo, kCpoReplcnt) != NULL) {
3137        State &= ~REPLACE_FLAG;
3138      }
3139
3140      start_redo_ins();
3141      if (cmdchar == 'r' || cmdchar == 'v') {
3142        stuffRedoReadbuff(ESC_STR);  // No ESC in redo buffer
3143      }
3144      RedrawingDisabled++;
3145      disabled_redraw = true;
3146      // Repeat the insert
3147      return false;
3148    }
3149    stop_insert(&curwin->w_cursor, true, nomove);
3150    undisplay_dollar();
3151  } else if (Ins.moved == kInsArrow && cmdchar != 'r' && cmdchar != 'v') {
3152    // The session ended just after a cursor-move: close the atom, so the whole session (including
3153    // cursor-move) replays.
3154    redo_append_str(S_LEN(ESC_STR));
3155  }
3156
3157  if (cmdchar != 'r' && cmdchar != 'v') {
3158    ins_apply_autocmds(EVENT_INSERTLEAVEPRE);
3159  }
3160
3161  // When an autoindent was removed, curswant stays after the
3162  // indent
3163  if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col) {
3164    curwin->w_set_curswant = true;
3165  }
3166
3167  // Remember the last Insert position in the '^ mark.
3168  if ((cmdmod.cmod_flags & CMOD_KEEPJUMPS) == 0) {
3169    fmarkv_T view = mark_view_make(curwin, curwin->w_cursor);
3170    RESET_FMARK(&curbuf->b_last_insert, curwin->w_cursor, curbuf->b_fnum, view);
3171  }
3172
3173  // The cursor should end up on the last inserted character.
3174  // Don't do it for CTRL-O, unless past the end of the line.
3175  if (!nomove
3176      && (curwin->w_cursor.col != 0 || curwin->w_cursor.coladd > 0)
3177      && (restart_edit == NUL || (gchar_cursor() == NUL && !Visual.active))
3178      && !Ins.revins_on) {
3179    if (curwin->w_cursor.coladd > 0 || get_ve_flags(curwin) == kOptVeFlagAll) {
3180      oneleft();
3181      if (restart_edit != NUL) {
3182        curwin->w_cursor.coladd++;
3183      }
3184    } else {
3185      curwin->w_cursor.col--;
3186      curwin->w_valid &= ~(VALID_WCOL|VALID_VIRTCOL);
3187      // Correct cursor for multi-byte character.
3188      mb_adjust_cursor();
3189    }
3190  }
3191
3192  State = MODE_NORMAL;
3193  may_trigger_modechanged();
3194  // need to position cursor again when on a TAB and
3195  // when on a char with inline virtual text
3196  if (gchar_cursor() == TAB || buf_meta_total(curbuf, kMTMetaInline) > 0) {
3197    curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL);
3198  }
3199
3200  setmouse();
3201  ui_cursor_shape();            // may show different cursor shape
3202
3203  // When recording or for CTRL-O, need to display the new mode.
3204  // Otherwise remove the mode message.
3205  if (reg_recording != 0 || restart_edit != NUL) {
3206    showmode();
3207  } else if (p_smd && (got_int || !skip_showmode())
3208             && !(p_ch == 0 && !ui_has(kUIMessages))) {
3209    unshowmode(false);
3210  }
3211  // Exit Insert mode
3212  return true;
3213}
3214
3215// Toggle language: Ins.revins_on.
3216// Move to end of reverse inserted text.
3217static void ins_ctrl_(void)
3218{
3219  if (Ins.revins_on && Ins.revins_chars && Ins.revins_scol >= 0) {
3220    while (gchar_cursor() != NUL && Ins.revins_chars--) {
3221      curwin->w_cursor.col++;
3222    }
3223  }
3224  p_ri = !p_ri;
3225  Ins.revins_on = (State == MODE_INSERT && p_ri);
3226  if (Ins.revins_on) {
3227    Ins.revins_scol = curwin->w_cursor.col;
3228    Ins.revins_legal++;
3229    Ins.revins_chars = 0;
3230    undisplay_dollar();
3231  } else {
3232    Ins.revins_scol = -1;
3233  }
3234  showmode();
3235}
3236
3237/// If 'keymodel' contains "startsel", may start selection.
3238///
3239/// @param  c  character to check
3240//
3241/// @return true when a CTRL-O and other keys stuffed.
3242static bool ins_start_select(int c)
3243  FUNC_ATTR_WARN_UNUSED_RESULT
3244{
3245  if (!km_startsel) {
3246    return false;
3247  }
3248  switch (c) {
3249  case K_KHOME:
3250  case K_KEND:
3251  case K_PAGEUP:
3252  case K_KPAGEUP:
3253  case K_PAGEDOWN:
3254  case K_KPAGEDOWN:
3255    if (!(mod_mask & MOD_MASK_SHIFT)) {
3256      break;
3257    }
3258    FALLTHROUGH;
3259  case K_S_LEFT:
3260  case K_S_RIGHT:
3261  case K_S_UP:
3262  case K_S_DOWN:
3263  case K_S_END:
3264  case K_S_HOME:
3265    // Start selection right away, the cursor can move with CTRL-O when
3266    // beyond the end of the line.
3267    start_selection();
3268
3269    // Execute the key in (insert) Select mode.
3270    stuffcharReadbuff(Ctrl_O);
3271    if (mod_mask) {
3272      const char buf[] = { (char)K_SPECIAL, (char)KS_MODIFIER,
3273                           (char)(uint8_t)mod_mask, NUL };
3274      stuffReadbuffLen(buf, 3);
3275    }
3276    stuffcharReadbuff(c);
3277    return true;
3278  }
3279  return false;
3280}
3281
3282// <Insert> key in Insert mode: toggle insert/replace mode.
3283static void ins_insert(int replaceState)
3284{
3285  set_vim_var_string(VV_INSERTMODE, ((State & REPLACE_FLAG)
3286                                     ? "i"
3287                                     : replaceState == MODE_VREPLACE ? "v" : "r"), 1);
3288  ins_apply_autocmds(EVENT_INSERTCHANGE);
3289  if (State & REPLACE_FLAG) {
3290    State = MODE_INSERT | (State & MODE_LANGMAP);
3291  } else {
3292    State = replaceState | (State & MODE_LANGMAP);
3293  }
3294  may_trigger_modechanged();
3295  redo_append_char(K_INS);
3296  showmode();
3297  ui_cursor_shape();            // may show different cursor shape
3298}
3299
3300// Pressed CTRL-O in Insert mode.
3301static void ins_ctrl_o(void)
3302{
3303  Visual.restart_select = 0;
3304  if (State & VREPLACE_FLAG) {
3305    restart_edit = 'V';
3306  } else if (State & REPLACE_FLAG) {
3307    restart_edit = 'R';
3308  } else {
3309    restart_edit = 'I';
3310  }
3311  if (virtual_active(curwin)) {
3312    ins_at_eol = false;         // cursor always keeps its column
3313  } else {
3314    ins_at_eol = (gchar_cursor() == NUL);
3315  }
3316}
3317
3318// If the cursor is on an indent, ^T/^D insert/delete one
3319// shiftwidth.  Otherwise ^T/^D behave like a "<<" or ">>".
3320// Always round the indent to 'shiftwidth', this is compatible
3321// with vi.  But vi only supports ^T and ^D after an
3322// autoindent, we support it everywhere.
3323static void ins_shift(int c, int lastc)
3324{
3325  if (stop_arrow() == FAIL) {
3326    return;
3327  }
3328  redo_append_char(c);
3329
3330  // 0^D and ^^D: remove all indent.
3331  if (c == Ctrl_D && (lastc == '0' || lastc == '^')
3332      && curwin->w_cursor.col > 0) {
3333    curwin->w_cursor.col--;
3334    del_char(false);              // delete the '^' or '0'
3335    // In Replace mode, restore the characters that '^' or '0' replaced.
3336    if (State & REPLACE_FLAG) {
3337      replace_pop_ins();
3338    }
3339    if (lastc == '^') {
3340      old_indent = get_indent();        // remember curr. indent
3341    }
3342    change_indent(INDENT_SET, 0, true, true);
3343  } else {
3344    change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, true, true);
3345  }
3346
3347  if (Ins.did_ai && *skipwhite(get_cursor_line_ptr()) != NUL) {
3348    Ins.did_ai = false;
3349  }
3350  Ins.did_si = false;
3351  Ins.can_si = false;
3352  Ins.can_si_back = false;
3353  Ins.can_cindent = false;          // no cindenting after ^D or ^T
3354}
3355
3356static void ins_del(void)
3357{
3358  if (stop_arrow() == FAIL) {
3359    return;
3360  }
3361  if (gchar_cursor() == NUL) {          // delete newline
3362    const int temp = curwin->w_cursor.col;
3363    if (!can_bs(BS_EOL)  // only if "eol" included
3364        || do_join(2, false, true, false, false) == FAIL) {
3365      vim_beep(kOptBoFlagBackspace);
3366    } else {
3367      mc_ins_join();
3368      curwin->w_cursor.col = temp;
3369      // Adjust orig_line_count in case more lines have been deleted than
3370      // have been added. That makes sure, that open_line() later
3371      // can access all buffer lines correctly
3372      if (State & VREPLACE_FLAG
3373          && orig_line_count > curbuf->b_ml.ml_line_count) {
3374        orig_line_count = curbuf->b_ml.ml_line_count;
3375      }
3376    }
3377  } else if (del_char(false) == FAIL) {  // delete char under cursor
3378    vim_beep(kOptBoFlagBackspace);
3379  }
3380  Ins.did_ai = false;
3381  Ins.did_si = false;
3382  Ins.can_si = false;
3383  Ins.can_si_back = false;
3384  redo_append_char(K_DEL);
3385}
3386
3387/// Handle Backspace, delete-word and delete-line in Insert mode.
3388///
3389/// @param          c                 character that was typed
3390/// @param          mode              backspace mode to use
3391/// @param[in,out]  inserted_space_p  whether a space was the last
3392//                                    character inserted
3393///
3394/// @return true when backspace was actually used.
3395static bool ins_bs(int c, int mode, int *inserted_space_p)
3396  FUNC_ATTR_NONNULL_ARG(3)
3397{
3398  int cc;
3399  int temp = 0;                     // init for GCC
3400  bool did_backspace = false;
3401  bool call_fix_indent = false;
3402
3403  // can't delete anything in an empty file
3404  // can't backup past first character in buffer
3405  // can't backup past starting point unless 'backspace' > 1
3406  // can backup to a previous line if 'backspace' == 0
3407  if (buf_is_empty(curbuf)
3408      || (!Ins.revins_on
3409          && ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
3410              || (!can_bs(BS_START)
3411                  && ((Ins.moved != kInsNone && !bt_prompt(curbuf))
3412                      || (curwin->w_cursor.lnum == Ins.start_orig.lnum
3413                          && curwin->w_cursor.col <= Ins.start_orig.col)))
3414              || (!can_bs(BS_INDENT) && Ins.moved == kInsNone && Ins.ai_col > 0
3415                  && curwin->w_cursor.col <= Ins.ai_col)
3416              || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0)))) {
3417    vim_beep(kOptBoFlagBackspace);
3418    return false;
3419  }
3420
3421  if (stop_arrow() == FAIL) {
3422    return false;
3423  }
3424  bool in_indent = inindent(0);
3425  if (in_indent) {
3426    Ins.can_cindent = false;
3427  }
3428  Ins.end_comment_pending = NUL;  // After BS, don't auto-end comment
3429  if (Ins.revins_on) {            // put cursor after last inserted char
3430    inc_cursor();
3431  }
3432  // Virtualedit:
3433  //    BACKSPACE_CHAR eats a virtual space
3434  //    BACKSPACE_WORD eats all coladd
3435  //    BACKSPACE_LINE eats all coladd and keeps going
3436  if (curwin->w_cursor.coladd > 0) {
3437    if (mode == BACKSPACE_CHAR) {
3438      curwin->w_cursor.coladd--;
3439      return true;
3440    }
3441    if (mode == BACKSPACE_WORD) {
3442      curwin->w_cursor.coladd = 0;
3443      return true;
3444    }
3445    curwin->w_cursor.coladd = 0;
3446  }
3447
3448  // Delete newline!
3449  if (curwin->w_cursor.col == 0) {
3450    mc_ins_join();
3451    linenr_T lnum = Ins.start.lnum;
3452    if (curwin->w_cursor.lnum == lnum || Ins.revins_on) {
3453      if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
3454                 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL) {
3455        return false;
3456      }
3457      Ins.start.lnum--;
3458      Ins.start.col = ml_get_len(Ins.start.lnum);
3459    }
3460    // In replace mode:
3461    // cc < 0: NL was inserted, delete it
3462    // cc >= 0: NL was replaced, put original characters back
3463    cc = -1;
3464    if (State & REPLACE_FLAG) {
3465      cc = replace_pop_if_nul();  // returns -1 if NL was inserted
3466    }
3467    // In replace mode, in the line we started replacing, we only move the
3468    // cursor.
3469    if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum) {
3470      dec_cursor();
3471    } else {
3472      if (!(State & VREPLACE_FLAG)
3473          || curwin->w_cursor.lnum > orig_line_count) {
3474        temp = gchar_cursor();          // remember current char
3475        curwin->w_cursor.lnum--;
3476
3477        // When "aw" is in 'formatoptions' we must delete the space at
3478        // the end of the line, otherwise the line will be broken
3479        // again when auto-formatting.
3480        if (has_format_option(kFoAuto)
3481            && has_format_option(kFoWhitePar)) {
3482          const char *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum);
3483          int len = get_cursor_line_len();
3484          if (len > 0 && ptr[len - 1] == ' ') {
3485            char *newp = xmemdupz(ptr, (size_t)(len - 1));
3486
3487            if (curbuf->b_ml.ml_flags & (ML_LINE_DIRTY | ML_ALLOCATED)) {
3488              xfree(curbuf->b_ml.ml_line_ptr);
3489            }
3490            curbuf->b_ml.ml_line_ptr = newp;
3491            curbuf->b_ml.ml_line_textlen--;
3492            curbuf->b_ml.ml_flags |= ML_LINE_DIRTY;
3493          }
3494        }
3495
3496        do_join(2, false, false, false, false);
3497        if (temp == NUL && gchar_cursor() != NUL) {
3498          inc_cursor();
3499        }
3500      } else {
3501        dec_cursor();
3502      }
3503
3504      // In MODE_REPLACE mode we have to put back the text that was
3505      // replaced by the NL. On the replace stack is first a
3506      // NUL-terminated sequence of characters that were deleted and then
3507      // the characters that NL replaced.
3508      if (State & REPLACE_FLAG) {
3509        // Do the next ins_char() in MODE_NORMAL state, to
3510        // prevent ins_char() from replacing characters and
3511        // avoiding showmatch().
3512        int oldState = State;
3513        State = MODE_NORMAL;
3514        // restore characters (blanks) deleted after cursor
3515        while (cc > 0) {
3516          colnr_T save_col = curwin->w_cursor.col;
3517          mb_replace_pop_ins();
3518          curwin->w_cursor.col = save_col;
3519          cc = replace_pop_if_nul();
3520        }
3521        // restore the characters that NL replaced
3522        replace_pop_ins();
3523        State = oldState;
3524      }
3525    }
3526    Ins.did_ai = false;
3527  } else {
3528    // Delete character(s) before the cursor.
3529    if (Ins.revins_on) {            // put cursor on last inserted char
3530      dec_cursor();
3531    }
3532    colnr_T mincol = 0;
3533    // keep indent
3534    if (mode == BACKSPACE_LINE
3535        && (curbuf->b_p_ai || cindent_on())
3536        && !Ins.revins_on) {
3537      colnr_T save_col = curwin->w_cursor.col;
3538      beginline(BL_WHITE);
3539      if (curwin->w_cursor.col < save_col) {
3540        mincol = curwin->w_cursor.col;
3541        // should now fix the indent to match with the previous line
3542        call_fix_indent = true;
3543      }
3544      curwin->w_cursor.col = save_col;
3545    }
3546
3547    // Handle deleting one 'shiftwidth' or 'softtabstop'.
3548    if (mode == BACKSPACE_CHAR
3549        && ((p_sta && in_indent)
3550            || ((get_sts_value() != 0 || tabstop_count(curbuf->b_p_vsts_array))
3551                && curwin->w_cursor.col > 0
3552                && (*(get_cursor_pos_ptr() - 1) == TAB
3553                    || (*(get_cursor_pos_ptr() - 1) == ' '
3554                        && (!*inserted_space_p || Ins.moved != kInsNone)))))) {
3555      *inserted_space_p = false;
3556
3557      bool const use_ts = !curwin->w_p_list || curwin->w_p_lcs_chars.tab1;
3558      char *const line = get_cursor_line_ptr();
3559      char *const cursor_ptr = line + curwin->w_cursor.col;
3560
3561      colnr_T vcol = 0;
3562      colnr_T space_vcol = 0;
3563      StrCharInfo sci = utf_ptr2StrCharInfo(line);
3564      StrCharInfo space_sci = sci;
3565      bool prev_space = false;
3566
3567      // Compute virtual column of cursor position, and find the last
3568      // whitespace before cursor that is preceded by non-whitespace.
3569      // Use charsize_nowrap() so that virtual text and wrapping are ignored.
3570      while (sci.ptr < cursor_ptr) {
3571        bool cur_space = ascii_iswhite(sci.chr.value);
3572        if (!prev_space && cur_space) {
3573          space_sci = sci;
3574          space_vcol = vcol;
3575        }
3576        ClusterInfo cli = utf_ClusterInfo(sci);
3577        vcol += charsize_nowrap(curbuf, sci.ptr, use_ts, vcol, sci.chr.value, cli.cells);
3578        sci = cli.next;
3579        prev_space = cur_space;
3580      }
3581
3582      // Compute the virtual column where we want to be.
3583      colnr_T want_vcol = vcol > 0 ? vcol - 1 : 0;
3584      if (p_sta && in_indent) {
3585        want_vcol -= want_vcol % get_sw_value(curbuf);
3586      } else {
3587        want_vcol = tabstop_start(want_vcol, get_sts_value(), curbuf->b_p_vsts_array);
3588      }
3589
3590      // Find the position to stop backspacing.
3591      // Use charsize_nowrap() so that virtual text and wrapping are ignored.
3592      while (true) {
3593        ClusterInfo cli = utf_ClusterInfo(space_sci);
3594        int size = charsize_nowrap(curbuf, space_sci.ptr, use_ts, space_vcol, space_sci.chr.value,
3595                                   cli.cells);
3596        if (space_vcol + size > want_vcol) {
3597          break;
3598        }
3599        space_vcol += size;
3600        space_sci = cli.next;
3601      }
3602      colnr_T const want_col = (int)(space_sci.ptr - line);
3603
3604      // Delete characters until we are at or before want_col.
3605      while (curwin->w_cursor.col > want_col) {
3606        dec_cursor();
3607        if (State & REPLACE_FLAG) {
3608          // Don't delete characters before the insert point when in Replace mode.
3609          if (curwin->w_cursor.lnum != Ins.start.lnum
3610              || curwin->w_cursor.col >= Ins.start.col) {
3611            replace_do_bs(-1);
3612          }
3613        } else {
3614          del_char(false);
3615        }
3616      }
3617
3618      // Insert extra spaces until we are at want_vcol.
3619      for (; space_vcol < want_vcol; space_vcol++) {
3620        // Remember the first char we inserted.
3621        if (curwin->w_cursor.lnum == Ins.start_orig.lnum
3622            && curwin->w_cursor.col < Ins.start_orig.col) {
3623          Ins.start_orig.col = curwin->w_cursor.col;
3624        }
3625
3626        if (State & VREPLACE_FLAG) {
3627          ins_char(' ');
3628        } else {
3629          ins_str(S_LEN(" "));
3630          if ((State & REPLACE_FLAG)) {
3631            replace_push_nul();
3632          }
3633        }
3634      }
3635    } else {
3636      // Delete up to starting point, start of line or previous word.
3637
3638      int cclass = mb_get_class(get_cursor_pos_ptr());
3639      do {
3640        if (!Ins.revins_on) {   // put cursor on char to be deleted
3641          dec_cursor();
3642        }
3643        cc = gchar_cursor();
3644        // look multi-byte character class
3645        int prev_cclass = cclass;
3646        cclass = mb_get_class(get_cursor_pos_ptr());
3647        if (mode == BACKSPACE_WORD && !ascii_isspace(cc)) {   // start of word?
3648          mode = BACKSPACE_WORD_NOT_SPACE;
3649          temp = vim_iswordc(cc);
3650        } else if (mode == BACKSPACE_WORD_NOT_SPACE
3651                   && ((ascii_isspace(cc) || vim_iswordc(cc) != temp)
3652                       || prev_cclass != cclass)) {   // end of word?
3653          if (!Ins.revins_on) {
3654            inc_cursor();
3655          } else if (State & REPLACE_FLAG) {
3656            dec_cursor();
3657          }
3658          break;
3659        }
3660        if (State & REPLACE_FLAG) {
3661          replace_do_bs(-1);
3662        } else {
3663          bool has_composing = false;
3664          if (p_deco) {
3665            char *p0 = get_cursor_pos_ptr();
3666            has_composing = utf_composinglike(p0, p0 + utf_ptr2len(p0), NULL);
3667          }
3668          del_char(false);
3669          // If there are combining characters and 'delcombine' is set
3670          // move the cursor back.  Don't back up before the base character.
3671          if (has_composing) {
3672            inc_cursor();
3673          }
3674          if (Ins.revins_chars) {
3675            Ins.revins_chars--;
3676            Ins.revins_legal++;
3677          }
3678          if (Ins.revins_on && gchar_cursor() == NUL) {
3679            break;
3680          }
3681        }
3682        // Just a single backspace?:
3683        if (mode == BACKSPACE_CHAR) {
3684          break;
3685        }
3686      } while (Ins.revins_on
3687               || (curwin->w_cursor.col > mincol
3688                   && (can_bs(BS_NOSTOP)
3689                       || (curwin->w_cursor.lnum != Ins.start_orig.lnum
3690                           || curwin->w_cursor.col != Ins.start_orig.col))));
3691    }
3692    did_backspace = true;
3693  }
3694  Ins.did_si = false;
3695  Ins.can_si = false;
3696  Ins.can_si_back = false;
3697  if (curwin->w_cursor.col <= 1) {
3698    Ins.did_ai = false;
3699  }
3700
3701  if (call_fix_indent) {
3702    fix_indent();
3703  }
3704
3705  // It's a little strange to put backspaces into the redo
3706  // buffer, but it makes auto-indent a lot easier to deal
3707  // with.
3708  redo_append_char(c);
3709
3710  // If deleted before the insertion point, adjust it
3711  if (curwin->w_cursor.lnum == Ins.start_orig.lnum
3712      && curwin->w_cursor.col < Ins.start_orig.col) {
3713    Ins.start_orig.col = curwin->w_cursor.col;
3714  }
3715
3716  // vi behaviour: the cursor moves backward but the character that
3717  //               was there remains visible
3718  // Vim behaviour: the cursor moves backward and the character that
3719  //                was there is erased from the screen.
3720  // We can emulate the vi behaviour by pretending there is a dollar
3721  // displayed even when there isn't.
3722  //  --pkv Sun Jan 19 01:56:40 EST 2003
3723  if (vim_strchr(p_cpo, kCpoBackspace) != NULL && dollar_vcol == -1) {
3724    dollar_vcol = curwin->w_virtcol;
3725  }
3726
3727  // When deleting a char the cursor line must never be in a closed fold.
3728  // E.g., when 'foldmethod' is indent and deleting the first non-white
3729  // char before a Tab.
3730  if (did_backspace) {
3731    foldOpenCursor();
3732  }
3733  return did_backspace;
3734}
3735
3736static void ins_left(void)
3737{
3738  const bool end_change = Ins.dont_sync_undo == kFalse;  // end undoable change
3739
3740  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped) {
3741    foldOpenCursor();
3742  }
3743  undisplay_dollar();
3744  pos_T tpos = curwin->w_cursor;
3745  if (oneleft() == OK) {
3746    start_arrow_with_change(&tpos, end_change, K_LEFT);
3747    // If exit reversed string, position is fixed
3748    if (Ins.revins_scol != -1 && (int)curwin->w_cursor.col >= Ins.revins_scol) {
3749      Ins.revins_legal++;
3750    }
3751    Ins.revins_chars++;
3752  } else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1) {
3753    // if 'whichwrap' set for cursor in insert mode may go to previous line.
3754    // always break undo when moving upwards/downwards, else undo may break
3755    start_arrow(&tpos, true, K_LEFT);
3756    curwin->w_cursor.lnum--;
3757    coladvance(curwin, MAXCOL);
3758    curwin->w_set_curswant = true;  // so we stay at the end
3759  } else {
3760    vim_beep(kOptBoFlagCursor);
3761  }
3762  Ins.dont_sync_undo = kFalse;
3763}
3764
3765static void ins_home(int c)
3766{
3767  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped) {
3768    foldOpenCursor();
3769  }
3770  undisplay_dollar();
3771  pos_T tpos = curwin->w_cursor;
3772  if (c == K_C_HOME) {
3773    curwin->w_cursor.lnum = 1;
3774  }
3775  curwin->w_cursor.col = 0;
3776  curwin->w_cursor.coladd = 0;
3777  curwin->w_curswant = 0;
3778  start_arrow(&tpos, true, c == K_C_HOME ? NUL : K_HOME);
3779}
3780
3781static void ins_end(int c)
3782{
3783  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped) {
3784    foldOpenCursor();
3785  }
3786  undisplay_dollar();
3787  pos_T tpos = curwin->w_cursor;
3788  if (c == K_C_END) {
3789    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3790  }
3791  coladvance(curwin, MAXCOL);
3792  curwin->w_curswant = MAXCOL;
3793
3794  start_arrow(&tpos, true, c == K_C_END ? NUL : K_END);
3795}
3796
3797static void ins_s_left(void)
3798{
3799  const bool end_change = Ins.dont_sync_undo == kFalse;  // end undoable change
3800  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped) {
3801    foldOpenCursor();
3802  }
3803  undisplay_dollar();
3804  if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0) {
3805    start_arrow_with_change(&curwin->w_cursor, end_change, K_S_LEFT);
3806    bck_word(1, false, false);
3807    curwin->w_set_curswant = true;
3808  } else {
3809    vim_beep(kOptBoFlagCursor);
3810  }
3811  Ins.dont_sync_undo = kFalse;
3812}
3813
3814/// @param end_change      end undoable change
3815static void ins_right(void)
3816{
3817  const bool end_change = Ins.dont_sync_undo == kFalse;  // end undoable change
3818  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped) {
3819    foldOpenCursor();
3820  }
3821  undisplay_dollar();
3822  if (gchar_cursor() != NUL || virtual_active(curwin)) {
3823    start_arrow_with_change(&curwin->w_cursor, end_change, K_RIGHT);
3824    curwin->w_set_curswant = true;
3825    if (virtual_active(curwin)) {
3826      oneright();
3827    } else {
3828      curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr());
3829    }
3830
3831    Ins.revins_legal++;
3832    if (Ins.revins_chars) {
3833      Ins.revins_chars--;
3834    }
3835  } else if (vim_strchr(p_ww, ']') != NULL
3836             && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
3837    // if 'whichwrap' set for cursor in insert mode, may move the
3838    // cursor to the next line
3839    start_arrow(&curwin->w_cursor, true, K_RIGHT);
3840    curwin->w_set_curswant = true;
3841    curwin->w_cursor.lnum++;
3842    curwin->w_cursor.col = 0;
3843  } else {
3844    vim_beep(kOptBoFlagCursor);
3845  }
3846  Ins.dont_sync_undo = kFalse;
3847}
3848
3849static void ins_s_right(void)
3850{
3851  const bool end_change = Ins.dont_sync_undo == kFalse;  // end undoable change
3852  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped) {
3853    foldOpenCursor();
3854  }
3855  undisplay_dollar();
3856  if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
3857      || gchar_cursor() != NUL) {
3858    start_arrow_with_change(&curwin->w_cursor, end_change, K_S_RIGHT);
3859    fwd_word(1, false, 0);
3860    curwin->w_set_curswant = true;
3861  } else {
3862    vim_beep(kOptBoFlagCursor);
3863  }
3864  Ins.dont_sync_undo = kFalse;
3865}
3866
3867/// @param startcol  when true move to Ins.start.col
3868static void ins_up(bool startcol)
3869{
3870  linenr_T old_topline = curwin->w_topline;
3871  int old_topfill = curwin->w_topfill;
3872
3873  undisplay_dollar();
3874  pos_T tpos = curwin->w_cursor;
3875  if (cursor_up(1, true) == OK) {
3876    if (startcol) {
3877      coladvance(curwin, getvcol_nolist(&Ins.start));
3878    }
3879    if (old_topline != curwin->w_topline
3880        || old_topfill != curwin->w_topfill) {
3881      redraw_later(curwin, UPD_VALID);
3882    }
3883    start_arrow(&tpos, true, startcol ? 'k' : K_UP);
3884    Ins.can_cindent = true;
3885  } else {
3886    vim_beep(kOptBoFlagCursor);
3887  }
3888}
3889
3890static void ins_pageup(void)
3891{
3892  undisplay_dollar();
3893
3894  if (mod_mask & MOD_MASK_CTRL) {
3895    // <C-PageUp>: tab page back
3896    if (first_tabpage->tp_next != NULL) {
3897      start_arrow(&curwin->w_cursor, true, NUL);
3898      goto_tabpage(-1);
3899    }
3900    return;
3901  }
3902
3903  pos_T tpos = curwin->w_cursor;
3904  if (pagescroll(BACKWARD, 1, false) == OK) {
3905    start_arrow(&tpos, true, NUL);
3906    Ins.can_cindent = true;
3907  } else {
3908    vim_beep(kOptBoFlagCursor);
3909  }
3910}
3911
3912/// @param startcol  when true move to Ins.start.col
3913static void ins_down(bool startcol)
3914{
3915  linenr_T old_topline = curwin->w_topline;
3916  int old_topfill = curwin->w_topfill;
3917
3918  undisplay_dollar();
3919  pos_T tpos = curwin->w_cursor;
3920  if (cursor_down(1, true) == OK) {
3921    if (startcol) {
3922      coladvance(curwin, getvcol_nolist(&Ins.start));
3923    }
3924    if (old_topline != curwin->w_topline
3925        || old_topfill != curwin->w_topfill) {
3926      redraw_later(curwin, UPD_VALID);
3927    }
3928    start_arrow(&tpos, true, startcol ? 'j' : K_DOWN);
3929    Ins.can_cindent = true;
3930  } else {
3931    vim_beep(kOptBoFlagCursor);
3932  }
3933}
3934
3935static void ins_pagedown(void)
3936{
3937  undisplay_dollar();
3938
3939  if (mod_mask & MOD_MASK_CTRL) {
3940    // <C-PageDown>: tab page forward
3941    if (first_tabpage->tp_next != NULL) {
3942      start_arrow(&curwin->w_cursor, true, NUL);
3943      goto_tabpage(0);
3944    }
3945    return;
3946  }
3947
3948  pos_T tpos = curwin->w_cursor;
3949  if (pagescroll(FORWARD, 1, false) == OK) {
3950    start_arrow(&tpos, true, NUL);
3951    Ins.can_cindent = true;
3952  } else {
3953    vim_beep(kOptBoFlagCursor);
3954  }
3955}
3956
3957/// Handle TAB in Insert or Replace mode.
3958///
3959/// @return true when the TAB needs to be inserted like a normal character.
3960static bool ins_tab(void)
3961  FUNC_ATTR_WARN_UNUSED_RESULT
3962{
3963  int temp;
3964
3965  if (Ins.start_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Ins.start.lnum) {
3966    Ins.start_blank_vcol = get_nolist_virtcol();
3967  }
3968  if (echeck_abbr(TAB + ABBR_OFF)) {
3969    return false;
3970  }
3971
3972  bool ind = inindent(0);
3973  if (ind) {
3974    Ins.can_cindent = false;
3975  }
3976
3977  // When nothing special, insert TAB like a normal character.
3978  if (!curbuf->b_p_et
3979      && !(
3980           p_sta
3981           && ind
3982           // These five lines mean 'tabstop' != 'shiftwidth'
3983           && ((tabstop_count(curbuf->b_p_vts_array) > 1)
3984               || (tabstop_count(curbuf->b_p_vts_array) == 1
3985                   && tabstop_first(curbuf->b_p_vts_array)
3986                   != get_sw_value(curbuf))
3987               || (tabstop_count(curbuf->b_p_vts_array) == 0
3988                   && curbuf->b_p_ts != get_sw_value(curbuf))))
3989      && tabstop_count(curbuf->b_p_vsts_array) == 0 && get_sts_value() == 0) {
3990    return true;
3991  }
3992
3993  if (stop_arrow() == FAIL) {
3994    return true;
3995  }
3996
3997  Ins.did_ai = false;
3998  Ins.did_si = false;
3999  Ins.can_si = false;
4000  Ins.can_si_back = false;
4001  redo_append_str(S_LEN("\t"));
4002
4003  if (p_sta && ind) {  // insert tab in indent, use 'shiftwidth'
4004    temp = get_sw_value(curbuf);
4005    temp -= get_nolist_virtcol() % temp;
4006  } else if (tabstop_count(curbuf->b_p_vsts_array) > 0
4007             || curbuf->b_p_sts != 0) {
4008    // use 'softtabstop' when set
4009    temp = tabstop_padding(get_nolist_virtcol(),
4010                           get_sts_value(),
4011                           curbuf->b_p_vsts_array);
4012  } else {
4013    // otherwise use 'tabstop'
4014    temp = tabstop_padding(get_nolist_virtcol(),
4015                           curbuf->b_p_ts,
4016                           curbuf->b_p_vts_array);
4017  }
4018
4019  // Insert the first space with ins_char().    It will delete one char in
4020  // replace mode.  Insert the rest with ins_str(); it will not delete any
4021  // chars.  For MODE_VREPLACE state, we use ins_char() for all characters.
4022  ins_char(' ');
4023  while (--temp > 0) {
4024    if (State & VREPLACE_FLAG) {
4025      ins_char(' ');
4026    } else {
4027      ins_str(S_LEN(" "));
4028      if (State & REPLACE_FLAG) {            // no char replaced
4029        replace_push_nul();
4030      }
4031    }
4032  }
4033
4034  // When 'expandtab' not set: Replace spaces by TABs where possible.
4035  if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_array) > 0
4036                          || get_sts_value() > 0
4037                          || (p_sta && ind))) {
4038    char *ptr;
4039    char *saved_line = NULL;         // init for GCC
4040    pos_T pos;
4041    pos_T *cursor;
4042    colnr_T want_vcol, vcol;
4043    int change_col = -1;
4044    int save_list = curwin->w_p_list;
4045
4046    // Get the current line.  For MODE_VREPLACE state, don't make real
4047    // changes yet, just work on a copy of the line.
4048    if (State & VREPLACE_FLAG) {
4049      pos = curwin->w_cursor;
4050      cursor = &pos;
4051      saved_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len());
4052      ptr = saved_line + pos.col;
4053    } else {
4054      ptr = get_cursor_pos_ptr();
4055      cursor = &curwin->w_cursor;
4056    }
4057
4058    // When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces.
4059    if (vim_strchr(p_cpo, kCpoListwm) == NULL) {
4060      curwin->w_p_list = false;
4061    }
4062
4063    // Find first white before the cursor
4064    pos_T fpos = curwin->w_cursor;
4065    while (fpos.col > 0 && ascii_iswhite(ptr[-1])) {
4066      fpos.col--;
4067      ptr--;
4068    }
4069
4070    // In Replace mode, don't change characters before the insert point.
4071    if ((State & REPLACE_FLAG)
4072        && fpos.lnum == Ins.start.lnum
4073        && fpos.col < Ins.start.col) {
4074      ptr += Ins.start.col - fpos.col;
4075      fpos.col = Ins.start.col;
4076    }
4077
4078    // compute virtual column numbers of first white and cursor
4079    getvcol(curwin, &fpos, &vcol, NULL, NULL, 0);
4080    getvcol(curwin, cursor, &want_vcol, NULL, NULL, 0);
4081
4082    char *tab = "\t";
4083    int32_t tab_v = (uint8_t)(*tab);
4084
4085    CharsizeArg csarg;
4086    CSType cstype = init_charsize_arg(&csarg, curwin, 0, tab);
4087
4088    // Use as many TABs as possible.  Beware of 'breakindent', 'showbreak'
4089    // and 'linebreak' adding extra virtual columns.
4090    while (ascii_iswhite(*ptr)) {
4091      int i = win_charsize(cstype, vcol, tab, tab_v, &csarg, 1).width;
4092      if (vcol + i > want_vcol) {
4093        break;
4094      }
4095      if (*ptr != TAB) {
4096        *ptr = TAB;
4097        if (change_col < 0) {
4098          change_col = fpos.col;            // Column of first change
4099          // May have to adjust Ins.start
4100          if (fpos.lnum == Ins.start.lnum && fpos.col < Ins.start.col) {
4101            Ins.start.col = fpos.col;
4102          }
4103        }
4104      }
4105      fpos.col++;
4106      ptr++;
4107      vcol += i;
4108    }
4109
4110    if (change_col >= 0) {
4111      int repl_off = 0;
4112      // Skip over the spaces we need.
4113      cstype = init_charsize_arg(&csarg, curwin, 0, ptr);
4114      while (vcol < want_vcol && *ptr == ' ') {
4115        vcol += win_charsize(cstype, vcol, ptr, ' ', &csarg, 1).width;
4116        ptr++;
4117        repl_off++;
4118      }
4119
4120      if (vcol > want_vcol) {
4121        // Must have a char with 'showbreak' just before it.
4122        ptr--;
4123        repl_off--;
4124      }
4125      fpos.col += repl_off;
4126
4127      // Delete following spaces.
4128      int i = cursor->col - fpos.col;
4129      if (i > 0) {
4130        if (!(State & VREPLACE_FLAG)) {
4131          const colnr_T newp_len = curbuf->b_ml.ml_line_textlen - i;
4132          char *newp = xmalloc((size_t)newp_len);
4133          ptrdiff_t col = ptr - curbuf->b_ml.ml_line_ptr;
4134          if (col > 0) {
4135            memmove(newp, ptr - col, (size_t)col);
4136          }
4137          memmove(newp + col, ptr + i, (size_t)(newp_len - col));
4138          if (curbuf->b_ml.ml_flags & (ML_LINE_DIRTY | ML_ALLOCATED)) {
4139            xfree(curbuf->b_ml.ml_line_ptr);
4140          }
4141          curbuf->b_ml.ml_line_ptr = newp;
4142          curbuf->b_ml.ml_line_textlen = newp_len;
4143          curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
4144          inserted_bytes(fpos.lnum, change_col,
4145                         cursor->col - change_col, fpos.col - change_col);
4146        } else {
4147          STRMOVE(ptr, ptr + i);
4148        }
4149        // correct replace stack.
4150        if ((State & REPLACE_FLAG) && !(State & VREPLACE_FLAG)) {
4151          for (temp = i; --temp >= 0;) {
4152            replace_join(repl_off);
4153          }
4154        }
4155      }
4156      cursor->col -= i;
4157
4158      // In MODE_VREPLACE state, we haven't changed anything yet.  Do it
4159      // now by backspacing over the changed spacing and then inserting
4160      // the new spacing.
4161      if (State & VREPLACE_FLAG) {
4162        // Backspace from real cursor to change_col
4163        backspace_until_column(change_col);
4164
4165        // Insert each char in saved_line from changed_col to
4166        // ptr-cursor
4167        ins_bytes_len(saved_line + change_col, (size_t)(cursor->col - change_col));
4168      }
4169    }
4170
4171    if (State & VREPLACE_FLAG) {
4172      xfree(saved_line);
4173    }
4174    curwin->w_p_list = save_list;
4175  }
4176
4177  return false;
4178}
4179
4180/// Handle CR or NL in insert mode.
4181///
4182/// @return false when it can't undo.
4183bool ins_eol(int c)
4184{
4185  if (echeck_abbr(c + ABBR_OFF)) {
4186    return true;
4187  }
4188  if (stop_arrow() == FAIL) {
4189    return false;
4190  }
4191  undisplay_dollar();
4192
4193  // Strange Vi behaviour: In Replace mode, typing a NL will not delete the
4194  // character under the cursor.  Only push a NUL on the replace stack,
4195  // nothing to put back when the NL is deleted.
4196  if ((State & REPLACE_FLAG) && !(State & VREPLACE_FLAG)) {
4197    replace_push_nul();
4198  }
4199
4200  // In MODE_VREPLACE state, a NL replaces the rest of the line, and starts
4201  // replacing the next line, so we push all of the characters left on the
4202  // line onto the replace stack.  This is not done here though, it is done
4203  // in open_line().
4204
4205  // Put cursor on NUL if on the last char and coladd is 1 (happens after
4206  // CTRL-O).
4207  if (virtual_active(curwin) && curwin->w_cursor.coladd > 0) {
4208    coladvance(curwin, getviscol());
4209  }
4210
4211  // NL in reverse insert will always start in the end of current line.
4212  if (Ins.revins_on) {
4213    curwin->w_cursor.col += get_cursor_pos_len();
4214  }
4215
4216  redo_append_str(S_LEN(NL_STR));
4217  bool i = open_line(FORWARD,
4218                     has_format_option(kFoRetComs) ? OPENLINE_DO_COM : 0,
4219                     old_indent, NULL);
4220  old_indent = 0;
4221  Ins.can_cindent = true;
4222  // When inserting a line the cursor line must never be in a closed fold.
4223  foldOpenCursor();
4224
4225  return i;
4226}
4227
4228// Handle digraph in insert mode.
4229// Returns character still to be inserted, or NUL when nothing remaining to be
4230// done.
4231static int ins_digraph(void)
4232{
4233  bool did_putchar = false;
4234
4235  pc_status = PC_STATUS_UNSET;
4236  if (redrawing() && !char_avail()) {
4237    // may need to redraw when no more chars available now
4238    ins_redraw(false);
4239
4240    edit_putchar('?', true);
4241    did_putchar = true;
4242    add_to_showcmd_c(Ctrl_K);
4243  }
4244
4245  // don't map the digraph chars. This also prevents the
4246  // mode message to be deleted when ESC is hit
4247  no_mapping++;
4248  allow_keys++;
4249  int c = plain_vgetc();
4250  no_mapping--;
4251  allow_keys--;
4252  if (did_putchar) {
4253    // when the line fits in 'columns' the '?' is at the start of the next
4254    // line and will not be removed by the redraw
4255    edit_unputchar();
4256  }
4257
4258  if (IS_SPECIAL(c) || mod_mask) {          // special key
4259    clear_showcmd();
4260    insert_special(c, true, false);
4261    return NUL;
4262  }
4263  if (c != ESC) {
4264    did_putchar = false;
4265    if (redrawing() && !char_avail()) {
4266      // may need to redraw when no more chars available now
4267      ins_redraw(false);
4268
4269      if (char2cells(c) == 1) {
4270        ins_redraw(false);
4271        edit_putchar(c, true);
4272        did_putchar = true;
4273      }
4274      add_to_showcmd_c(c);
4275    }
4276    no_mapping++;
4277    allow_keys++;
4278    int cc = plain_vgetc();
4279    no_mapping--;
4280    allow_keys--;
4281    if (did_putchar) {
4282      // when the line fits in 'columns' the '?' is at the start of the
4283      // next line and will not be removed by a redraw
4284      edit_unputchar();
4285    }
4286    if (cc != ESC) {
4287      redo_append_str(S_LEN(CTRL_V_STR));
4288      c = digraph_get(c, cc, true);
4289      clear_showcmd();
4290      return c;
4291    }
4292  }
4293  clear_showcmd();
4294  return NUL;
4295}
4296
4297// Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
4298// Returns the char to be inserted, or NUL if none found.
4299int ins_copychar(linenr_T lnum)
4300{
4301  if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) {
4302    vim_beep(kOptBoFlagCopy);
4303    return NUL;
4304  }
4305
4306  // try to advance to the cursor column
4307  validate_virtcol(curwin);
4308  int const end_vcol = curwin->w_virtcol;
4309  char *line = ml_get(lnum);
4310
4311  CharsizeArg csarg;
4312  CSType cstype = init_charsize_arg(&csarg, curwin, lnum, line);
4313  StrCharInfo ci = utf_ptr2StrCharInfo(line);
4314  int vcol = 0;
4315  while (vcol < end_vcol && *ci.ptr != NUL) {
4316    ClusterInfo cli = utf_ClusterInfo(ci);
4317    vcol += win_charsize(cstype, vcol, ci.ptr, ci.chr.value, &csarg, cli.cells).width;
4318    if (vcol > end_vcol) {
4319      break;
4320    }
4321    ci = cli.next;
4322  }
4323
4324  int c = ci.chr.value < 0 ? (uint8_t)(*ci.ptr) : ci.chr.value;
4325  if (c == NUL) {
4326    vim_beep(kOptBoFlagCopy);
4327  }
4328  return c;
4329}
4330
4331// CTRL-Y or CTRL-E typed in Insert mode.
4332static int ins_ctrl_ey(int tc)
4333{
4334  int c = tc;
4335
4336  if (ctrl_x_mode_scroll()) {
4337    if (c == Ctrl_Y) {
4338      scrolldown_clamp();
4339    } else {
4340      scrollup_clamp();
4341    }
4342    redraw_later(curwin, UPD_VALID);
4343  } else {
4344    c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
4345    if (c != NUL) {
4346      // The character must be taken literally, insert like it
4347      // was typed after a CTRL-V, and pretend 'textwidth'
4348      // wasn't set.  Digits, 'o' and 'x' are special after a
4349      // CTRL-V, don't use it for these.
4350      if (c < 256 && !isalnum(c)) {
4351        redo_append_str(S_LEN(CTRL_V_STR));
4352      }
4353      OptInt tw_save = curbuf->b_p_tw;
4354      curbuf->b_p_tw = -1;
4355      insert_special(c, true, false);
4356      curbuf->b_p_tw = tw_save;
4357      Ins.revins_chars++;
4358      Ins.revins_legal++;
4359      c = Ctrl_V;       // pretend CTRL-V is last character
4360      auto_format(false, true);
4361    }
4362  }
4363  return c;
4364}
4365
4366// Get the value that w_virtcol would have when 'list' is off.
4367// Unless 'cpo' contains the 'L' flag.
4368colnr_T get_nolist_virtcol(void)
4369{
4370  // check validity of cursor in current buffer
4371  if (curwin->w_buffer == NULL || curwin->w_buffer->b_ml.ml_mfp == NULL
4372      || curwin->w_cursor.lnum > curwin->w_buffer->b_ml.ml_line_count) {
4373    return 0;
4374  }
4375  if (curwin->w_p_list && vim_strchr(p_cpo, kCpoListwm) == NULL) {
4376    return getvcol_nolist(&curwin->w_cursor);
4377  }
4378  validate_virtcol(curwin);
4379  return curwin->w_virtcol;
4380}
4381
4382// Handle the InsertCharPre autocommand.
4383// "c" is the character that was typed.
4384// Return a pointer to allocated memory with the replacement string.
4385// Return NULL to continue inserting "c".
4386static char *do_insert_char_pre(int c)
4387{
4388  char buf[MB_MAXBYTES + 1];
4389  const int save_State = State;
4390
4391  if (c == Ctrl_RSB  // i_CTRL-] only triggers abbreviations.
4392      // Stuffed text was transformed when typed and appended to redobuf (redo_append_lit).
4393      // Like abbreviations (vgetorpeek()), don't transform it again.
4394      || KeyStuffed
4395      || !has_event(EVENT_INSERTCHARPRE)) {
4396    return NULL;
4397  }
4398
4399  size_t buflen = (size_t)utf_char2bytes(c, buf);
4400  buf[buflen] = NUL;
4401
4402  // Lock the text to avoid weird things from happening.
4403  textlock++;
4404  set_vim_var_string(VV_CHAR, buf, (ptrdiff_t)buflen);  // set v:char
4405
4406  char *res = NULL;
4407  if (ins_apply_autocmds(EVENT_INSERTCHARPRE)) {
4408    // Get the value of v:char.  It may be empty or more than one
4409    // character.  Only use it when changed, otherwise continue with the
4410    // original character to avoid breaking autoindent.
4411    if (strcmp(buf, get_vim_var_str(VV_CHAR)) != 0) {
4412      res = xstrdup(get_vim_var_str(VV_CHAR));
4413    }
4414  }
4415
4416  set_vim_var_string(VV_CHAR, NULL, -1);
4417  textlock--;
4418
4419  // Restore the State, it may have been changed.
4420  State = save_State;
4421
4422  return res;
4423}
4424
4425bool get_can_cindent(void)
4426{
4427  return Ins.can_cindent;
4428}
4429
4430void set_can_cindent(bool val)
4431{
4432  Ins.can_cindent = val;
4433}
4434
4435/// Trigger "event" and take care of fixing undo.
4436int ins_apply_autocmds(event_T event)
4437{
4438  varnumber_T tick = buf_get_changedtick(curbuf);
4439
4440  int r = apply_autocmds(event, NULL, NULL, false, curbuf);
4441
4442  // If u_savesub() was called then we are not prepared to start
4443  // a new line.  Call u_save() with no contents to fix that.
4444  // Except when leaving Insert mode.
4445  if (event != EVENT_INSERTLEAVE && tick != buf_get_changedtick(curbuf)) {
4446    u_save(curwin->w_cursor.lnum, (linenr_T)(curwin->w_cursor.lnum + 1));
4447  }
4448
4449  return r;
4450}