robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
202.8 KiB6788 linesraw
1//
2// normal.c:    Contains the main routine for processing characters in command
3//              mode.  Communicates closely with the code in ops.c to handle
4//              the operators.
5//
6
7#include <assert.h>
8#include <ctype.h>
9#include <inttypes.h>
10#include <limits.h>
11#include <stdbool.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <time.h>
16
17#include "nvim/api/buffer.h"
18#include "nvim/api/extmark.h"
19#include "nvim/api/private/helpers.h"
20#include "nvim/api/vim.h"
21#include "nvim/ascii_defs.h"
22#include "nvim/autocmd.h"
23#include "nvim/autocmd_defs.h"
24#include "nvim/buffer.h"
25#include "nvim/buffer_defs.h"
26#include "nvim/change.h"
27#include "nvim/charset.h"
28#include "nvim/clipboard.h"
29#include "nvim/cmdhist.h"
30#include "nvim/cursor.h"
31#include "nvim/decoration.h"
32#include "nvim/diff.h"
33#include "nvim/digraph.h"
34#include "nvim/drawscreen.h"
35#include "nvim/errors.h"
36#include "nvim/eval.h"
37#include "nvim/eval/buffer.h"
38#include "nvim/eval/typval.h"
39#include "nvim/eval/vars.h"
40#include "nvim/ex_cmds.h"
41#include "nvim/ex_cmds2.h"
42#include "nvim/ex_docmd.h"
43#include "nvim/ex_eval.h"
44#include "nvim/ex_getln.h"
45#include "nvim/extmark.h"
46#include "nvim/file_search.h"
47#include "nvim/fileio.h"
48#include "nvim/fold.h"
49#include "nvim/gettext_defs.h"
50#include "nvim/globals.h"
51#include "nvim/grid.h"
52#include "nvim/help.h"
53#include "nvim/highlight.h"
54#include "nvim/highlight_defs.h"
55#include "nvim/highlight_group.h"
56#include "nvim/indent_c.h"
57#include "nvim/input.h"
58#include "nvim/input_cmdatom.h"
59#include "nvim/insert.h"
60#include "nvim/insexpand.h"
61#include "nvim/keycodes.h"
62#include "nvim/lua/executor.h"
63#include "nvim/macros_defs.h"
64#include "nvim/mapping.h"
65#include "nvim/mark.h"
66#include "nvim/mark_defs.h"
67#include "nvim/marktree.h"
68#include "nvim/math.h"
69#include "nvim/mbyte.h"
70#include "nvim/mbyte_defs.h"
71#include "nvim/mcursor.h"
72#include "nvim/memline.h"
73#include "nvim/memline_defs.h"
74#include "nvim/memory.h"
75#include "nvim/message.h"
76#include "nvim/mouse.h"
77#include "nvim/move.h"
78#include "nvim/normal.h"
79#include "nvim/ops.h"
80#include "nvim/option.h"
81#include "nvim/option_vars.h"
82#include "nvim/os/input.h"
83#include "nvim/os/time.h"
84#include "nvim/plines.h"
85#include "nvim/profile.h"
86#include "nvim/quickfix.h"
87#include "nvim/register.h"
88#include "nvim/search.h"
89#include "nvim/spell.h"
90#include "nvim/spell_defs.h"
91#include "nvim/spellfile.h"
92#include "nvim/spellsuggest.h"
93#include "nvim/state.h"
94#include "nvim/state_defs.h"
95#include "nvim/statusline.h"
96#include "nvim/strings.h"
97#include "nvim/syntax.h"
98#include "nvim/tag.h"
99#include "nvim/terminal.h"
100#include "nvim/textformat.h"
101#include "nvim/textobject.h"
102#include "nvim/types_defs.h"
103#include "nvim/ui.h"
104#include "nvim/ui_defs.h"
105#include "nvim/undo.h"
106#include "nvim/vim_defs.h"
107#include "nvim/window.h"
108
109typedef struct {
110  VimState state;
111  bool command_finished;
112  bool ctrl_w;
113  bool need_flushbuf;
114  bool set_prevcount;
115  bool previous_got_int;  ///< `got_int` was true.
116  bool toplevel;          ///< This is a (poorly-named) _behavior_ opt-in, not a state indicator.
117                          ///< It enables "full interactive-command treatment":
118                          ///< - count prep, v:count publication.
119                          ///< - scrollbind/cursorbind syncing after the command.
120                          ///< - callers pair it with readbuf1_empty() to exclude stuffed keys.
121  oparg_T oa;             ///< Operator arguments.
122  cmdarg_T ca;            ///< Command arguments.
123  int mapped_len;
124  int old_mapped_len;
125  int idx;
126  int c;
127  int old_col;
128  pos_T old_pos;
129} NormalState;
130
131static int VIsual_mode_orig = NUL;              // saved Visual mode
132
133#include "normal.c.generated.h"
134
135static const char e_changelist_is_empty[] = N_("E664: Changelist is empty");
136static const char e_cmdline_window_already_open[]
137  = N_("E1292: Command-line window is already open");
138
139static inline void normal_state_init(NormalState *s)
140{
141  memset(s, 0, sizeof(NormalState));
142  s->state.check = normal_check;
143  s->state.execute = normal_execute;
144}
145
146// nv_*(): functions called to handle Normal and Visual mode commands.
147// n_*(): functions called to handle Normal mode commands.
148// v_*(): functions called to handle Visual mode commands.
149
150/// Function to be called for a Normal or Visual mode command.
151/// The argument is a cmdarg_T.
152typedef void (*nv_func_T)(cmdarg_T *cap);
153
154// Generally speaking, every Normal mode command should either clear any
155// pending operator (with *clearop*()), or set the motion type variable
156// oap->motion_type.
157//
158// When a cursor motion command is made, it is marked as being a character or
159// line oriented motion.  Then, if an operator is in effect, the operation
160// becomes character or line oriented accordingly.
161
162/// This table contains one entry for every Normal or Visual mode command.
163/// The order doesn't matter, init_normal_cmds() will create a sorted index.
164/// It is faster when all keys from zero to '~' are present.
165static const struct nv_cmd {
166  int cmd_char;                 ///< (first) command character
167  nv_func_T cmd_func;           ///< function for this command
168  uint16_t cmd_flags;           ///< NV_ flags
169  int16_t cmd_arg;              ///< value for ca.arg
170} nv_cmds[] = {
171  { NUL,       nv_error,       0,                      0 },
172  { Ctrl_A,    nv_addsub,      0,                      0 },
173  { Ctrl_B,    nv_page,        NV_STS,                 BACKWARD },
174  { Ctrl_C,    nv_esc,         0,                      true },
175  { Ctrl_D,    nv_halfpage,    0,                      0 },
176  { Ctrl_E,    nv_scroll_line, 0,                      true },
177  { Ctrl_F,    nv_page,        NV_STS,                 FORWARD },
178  { Ctrl_G,    nv_ctrlg,       0,                      0 },
179  { Ctrl_H,    nv_ctrlh,       NV_MOTION,              0 },
180  { Ctrl_I,    nv_pcmark,      NV_JUMP,                0 },
181  { NL,        nv_down,        NV_MOTION,              false },
182  { Ctrl_K,    nv_error,       0,                      0 },
183  { Ctrl_L,    nv_clear,       0,                      0 },
184  { CAR,       nv_down,        NV_MOTION,              true },
185  { Ctrl_N,    nv_down,        NV_STS|NV_MOTION,       false },
186  { Ctrl_O,    nv_ctrlo,       NV_JUMP,                0 },
187  { Ctrl_P,    nv_up,          NV_STS|NV_MOTION,       false },
188  { Ctrl_Q,    nv_visual,      0,                      false },
189  { Ctrl_R,    nv_redo_or_register, 0,                      0 },
190  { Ctrl_S,    nv_ignore,      0,                      0 },
191  { Ctrl_T,    nv_tagpop,      NV_NCW|NV_JUMP,         0 },
192  { Ctrl_U,    nv_halfpage,    0,                      0 },
193  { Ctrl_V,    nv_visual,      0,                      false },
194  { 'V',       nv_visual,      0,                      false },
195  { 'v',       nv_visual,      0,                      false },
196  { Ctrl_W,    nv_window,      0,                      0 },
197  { Ctrl_X,    nv_addsub,      0,                      0 },
198  { Ctrl_Y,    nv_scroll_line, 0,                      false },
199  { Ctrl_Z,    nv_suspend,     0,                      0 },
200  { ESC,       nv_esc,         0,                      false },
201  { Ctrl_BSL,  nv_normal,      NV_NCH_ALW,             0 },
202  { Ctrl_RSB,  nv_ident,       NV_NCW,                 0 },
203  { Ctrl_HAT,  nv_hat,         NV_NCW,                 0 },
204  { Ctrl__,    nv_error,       0,                      0 },
205  { ' ',       nv_right,       NV_MOTION,              0 },
206  { '!',       nv_operator,    0,                      0 },
207  { '"',       nv_regname,     NV_NCH_NOP|NV_NCH_ARG|NV_KEEPREG, 0 },
208  { '#',       nv_ident,       NV_MOTION,              0 },
209  { '$',       nv_dollar,      NV_MOTION,              0 },
210  { '%',       nv_percent,     NV_MOTION,              0 },
211  { '&',       nv_optrans,     0,                      0 },
212  { '\'',      nv_gomark,      NV_NCH_ALW|NV_NCH_ARG,  true },
213  { '(',       nv_brace,       NV_MOTION,              BACKWARD },
214  { ')',       nv_brace,       NV_MOTION,              FORWARD },
215  { '*',       nv_ident,       NV_MOTION,              0 },
216  { '+',       nv_down,        NV_MOTION,              true },
217  { ',',       nv_csearch,     NV_MOTION,              true },
218  { '-',       nv_up,          NV_MOTION,              true },
219  { '.',       nv_dot,         NV_KEEPREG,             0 },
220  { '/',       nv_search,      0,                      false },
221  { '0',       nv_beginline,   NV_MOTION,              0 },
222  { '1',       nv_ignore,      0,                      0 },
223  { '2',       nv_ignore,      0,                      0 },
224  { '3',       nv_ignore,      0,                      0 },
225  { '4',       nv_ignore,      0,                      0 },
226  { '5',       nv_ignore,      0,                      0 },
227  { '6',       nv_ignore,      0,                      0 },
228  { '7',       nv_ignore,      0,                      0 },
229  { '8',       nv_ignore,      0,                      0 },
230  { '9',       nv_ignore,      0,                      0 },
231  { ':',       nv_colon,       0,                      0 },
232  { ';',       nv_csearch,     NV_MOTION,              false },
233  { '<',       nv_operator,    NV_RL,                  0 },
234  { '=',       nv_operator,    0,                      0 },
235  { '>',       nv_operator,    NV_RL,                  0 },
236  { '?',       nv_search,      0,                      false },
237  { '@',       nv_at,          NV_NCH_NOP|NV_NCH_ARG,  false },
238  { 'A',       nv_edit,        0,                      0 },
239  { 'B',       nv_bck_word,    NV_MOTION,              1 },
240  { 'C',       nv_abbrev,      NV_KEEPREG,             0 },
241  { 'D',       nv_abbrev,      NV_KEEPREG,             0 },
242  { 'E',       nv_wordcmd,     NV_MOTION,              true },
243  { 'F',       nv_csearch,     NV_NCH_ALW|NV_LANG|NV_MOTION, BACKWARD },
244  { 'G',       nv_goto,        NV_JUMP,                true },
245  { 'H',       nv_scroll,      NV_JUMP,                0 },
246  { 'I',       nv_edit,        0,                      0 },
247  { 'J',       nv_join,        0,                      0 },
248  { 'K',       nv_ident,       0,                      0 },
249  { 'L',       nv_scroll,      NV_JUMP,                0 },
250  { 'M',       nv_scroll,      NV_JUMP,                0 },
251  { 'N',       nv_next,        NV_MOTION,              SEARCH_REV },
252  { 'O',       nv_open,        0,                      0 },
253  { 'P',       nv_put,         0,                      0 },
254  { 'Q',       nv_Q,           0,                      0 },
255  { 'R',       nv_Replace,     0,                      false },
256  { 'S',       nv_subst,       NV_KEEPREG,             0 },
257  { 'T',       nv_csearch,     NV_NCH_ALW|NV_LANG|NV_MOTION, BACKWARD },
258  { 'U',       nv_Undo,        0,                      0 },
259  { 'W',       nv_wordcmd,     NV_MOTION,              true },
260  { 'X',       nv_abbrev,      NV_KEEPREG,             0 },
261  { 'Y',       nv_abbrev,      NV_KEEPREG,             0 },
262  { 'Z',       nv_Zet,         NV_NCH_NOP|NV_NCW,      0 },
263  { '[',       nv_brackets,    NV_NCH_ALW,             BACKWARD },
264  { '\\',      nv_error,       0,                      0 },
265  { ']',       nv_brackets,    NV_NCH_ALW,             FORWARD },
266  { '^',       nv_beginline,   NV_MOTION,              BL_WHITE | BL_FIX },
267  { '_',       nv_lineop,      NV_MOTION,              0 },
268  { '`',       nv_gomark,      NV_NCH_ALW|NV_NCH_ARG,  false },
269  { 'a',       nv_edit,        NV_NCH,                 0 },
270  { 'b',       nv_bck_word,    NV_MOTION,              0 },
271  { 'c',       nv_operator,    0,                      0 },
272  { 'd',       nv_operator,    0,                      0 },
273  { 'e',       nv_wordcmd,     NV_MOTION,              false },
274  { 'f',       nv_csearch,     NV_NCH_ALW|NV_LANG|NV_MOTION, FORWARD },
275  { 'g',       nv_g_cmd,       NV_NCH_ALW,             false },
276  { 'h',       nv_left,        NV_RL|NV_MOTION,        0 },
277  { 'i',       nv_edit,        NV_NCH,                 0 },
278  { 'j',       nv_down,        NV_MOTION,              false },
279  { 'k',       nv_up,          NV_MOTION,              false },
280  { 'l',       nv_right,       NV_RL|NV_MOTION,        0 },
281  { 'm',       nv_mark,        NV_NCH_NOP|NV_NCH_ARG,  0 },
282  { 'n',       nv_next,        NV_MOTION,              0 },
283  { 'o',       nv_open,        0,                      0 },
284  { 'p',       nv_put,         0,                      0 },
285  { 'q',       nv_q,           NV_NCH|NV_NCH_ARG,      0 },
286  { 'r',       nv_replace,     NV_NCH_NOP|NV_LANG,     0 },
287  { 's',       nv_subst,       NV_KEEPREG,             0 },
288  { 't',       nv_csearch,     NV_NCH_ALW|NV_LANG|NV_MOTION, FORWARD },
289  { 'u',       nv_undo,        0,                      0 },
290  { 'w',       nv_wordcmd,     NV_MOTION,              false },
291  { 'x',       nv_abbrev,      NV_KEEPREG,             0 },
292  { 'y',       nv_operator,    0,                      0 },
293  { 'z',       nv_zet,         NV_NCH_ALW,             0 },
294  { '{',       nv_findpar,     NV_MOTION,              BACKWARD },
295  { '|',       nv_pipe,        NV_MOTION,              0 },
296  { '}',       nv_findpar,     NV_MOTION,              FORWARD },
297  { '~',       nv_tilde,       0,                      0 },
298
299  // pound sign
300  { POUND,     nv_ident,       0,                      0 },
301  { K_MOUSEUP, nv_mousescroll, 0,                      MSCR_UP },
302  { K_MOUSEDOWN, nv_mousescroll, 0,                    MSCR_DOWN },
303  { K_MOUSELEFT, nv_mousescroll, 0,                    MSCR_LEFT },
304  { K_MOUSERIGHT, nv_mousescroll, 0,                   MSCR_RIGHT },
305  { K_LEFTMOUSE, nv_mouse,     0,                      0 },
306  { K_LEFTMOUSE_NM, nv_mouse,  0,                      0 },
307  { K_LEFTDRAG, nv_mouse,      0,                      0 },
308  { K_LEFTRELEASE, nv_mouse,   0,                      0 },
309  { K_LEFTRELEASE_NM, nv_mouse, 0,                     0 },
310  { K_MOUSEMOVE, nv_mouse,     0,                      0 },
311  { K_MIDDLEMOUSE, nv_mouse,   0,                      0 },
312  { K_MIDDLEDRAG, nv_mouse,    0,                      0 },
313  { K_MIDDLERELEASE, nv_mouse, 0,                      0 },
314  { K_RIGHTMOUSE, nv_mouse,    0,                      0 },
315  { K_RIGHTDRAG, nv_mouse,     0,                      0 },
316  { K_RIGHTRELEASE, nv_mouse,  0,                      0 },
317  { K_X1MOUSE, nv_mouse,       0,                      0 },
318  { K_X1DRAG, nv_mouse,        0,                      0 },
319  { K_X1RELEASE, nv_mouse,     0,                      0 },
320  { K_X2MOUSE, nv_mouse,       0,                      0 },
321  { K_X2DRAG, nv_mouse,        0,                      0 },
322  { K_X2RELEASE, nv_mouse,     0,                      0 },
323  { K_IGNORE,  nv_ignore,      NV_KEEPREG,             0 },
324  { K_NOP,     nv_nop,         0,                      0 },
325  { K_INS,     nv_edit,        0,                      0 },
326  { K_KINS,    nv_edit,        0,                      0 },
327  { K_BS,      nv_ctrlh,       NV_MOTION,              0 },
328  { K_UP,      nv_up,          NV_SSS|NV_STS|NV_MOTION, false },
329  { K_S_UP,    nv_page,        NV_SS,                  BACKWARD },
330  { K_DOWN,    nv_down,        NV_SSS|NV_STS|NV_MOTION, false },
331  { K_S_DOWN,  nv_page,        NV_SS,                  FORWARD },
332  { K_LEFT,    nv_left,        NV_SSS|NV_STS|NV_RL|NV_MOTION, 0 },
333  { K_S_LEFT,  nv_bck_word,    NV_SS|NV_RL|NV_MOTION,  0 },
334  { K_C_LEFT,  nv_bck_word,    NV_SSS|NV_RL|NV_STS|NV_MOTION, 1 },
335  { K_RIGHT,   nv_right,       NV_SSS|NV_STS|NV_RL|NV_MOTION, 0 },
336  { K_S_RIGHT, nv_wordcmd,     NV_SS|NV_RL|NV_MOTION,  false },
337  { K_C_RIGHT, nv_wordcmd,     NV_SSS|NV_RL|NV_STS|NV_MOTION, true },
338  { K_PAGEUP,  nv_page,        NV_SSS|NV_STS,          BACKWARD },
339  { K_KPAGEUP, nv_page,        NV_SSS|NV_STS,          BACKWARD },
340  { K_PAGEDOWN, nv_page,       NV_SSS|NV_STS,          FORWARD },
341  { K_KPAGEDOWN, nv_page,      NV_SSS|NV_STS,          FORWARD },
342  { K_END,     nv_end,         NV_SSS|NV_STS|NV_MOTION, false },
343  { K_KEND,    nv_end,         NV_SSS|NV_STS|NV_MOTION, false },
344  { K_S_END,   nv_end,         NV_SS|NV_MOTION,        false },
345  { K_C_END,   nv_end,         NV_SSS|NV_STS|NV_MOTION, true },
346  { K_HOME,    nv_home,        NV_SSS|NV_STS|NV_MOTION, 0 },
347  { K_KHOME,   nv_home,        NV_SSS|NV_STS|NV_MOTION, 0 },
348  { K_S_HOME,  nv_home,        NV_SS|NV_MOTION,        0 },
349  { K_C_HOME,  nv_goto,        NV_SSS|NV_STS|NV_MOTION, false },
350  { K_DEL,     nv_abbrev,      0,                      0 },
351  { K_KDEL,    nv_abbrev,      0,                      0 },
352  { K_UNDO,    nv_kundo,       0,                      0 },
353  { K_HELP,    nv_help,        NV_NCW,                 0 },
354  { K_F1,      nv_help,        NV_NCW,                 0 },
355  { K_XF1,     nv_help,        NV_NCW,                 0 },
356  { K_SELECT,  nv_select,      0,                      0 },
357  { K_PASTE_START, nv_paste,   NV_KEEPREG,             0 },
358  { K_EVENT,   nv_event,       NV_KEEPREG,             0 },
359  { K_COMMAND, nv_colon,       0,                      0 },
360  { K_LUA, nv_colon,           0,                      0 },
361};
362
363// Number of commands in nv_cmds[].
364#define NV_CMDS_SIZE ARRAY_SIZE(nv_cmds)
365
366// Sorted index of commands in nv_cmds[].
367static int16_t nv_cmd_idx[NV_CMDS_SIZE];
368
369// The highest index for which
370// nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char]
371static int nv_max_linear;
372
373/// Compare functions for qsort() below, that checks the command character
374/// through the index in nv_cmd_idx[].
375static int nv_compare(const void *s1, const void *s2)
376{
377  // The commands are sorted on absolute value.
378  int c1 = nv_cmds[*(const int16_t *)s1].cmd_char;
379  int c2 = nv_cmds[*(const int16_t *)s2].cmd_char;
380  if (c1 < 0) {
381    c1 = -c1;
382  }
383  if (c2 < 0) {
384    c2 = -c2;
385  }
386  return c1 == c2 ? 0 : c1 > c2 ? 1 : -1;
387}
388
389/// Initialize the nv_cmd_idx[] table.
390void init_normal_cmds(void)
391{
392  assert(NV_CMDS_SIZE <= SHRT_MAX);
393
394  // Fill the index table with a one to one relation.
395  for (int16_t i = 0; i < (int16_t)NV_CMDS_SIZE; i++) {
396    nv_cmd_idx[i] = i;
397  }
398
399  // Sort the commands by the command character.
400  qsort(&nv_cmd_idx, NV_CMDS_SIZE, sizeof(int16_t), nv_compare);
401
402  // Find the first entry that can't be indexed by the command character.
403  int16_t i;
404  for (i = 0; i < (int16_t)NV_CMDS_SIZE; i++) {
405    if (i != nv_cmds[nv_cmd_idx[i]].cmd_char) {
406      break;
407    }
408  }
409  nv_max_linear = i - 1;
410}
411
412/// True if command `cmdchar` has any of the given NV_XX `flags`.
413///
414/// Multiplexed commands (g/[/]/z) have one entry for all their second chars, see atom_key_class().
415bool nv_is(int cmdchar, int flags)
416{
417  int idx = find_command(cmdchar);
418  return idx >= 0 && (nv_cmds[idx].cmd_flags & flags) != 0;
419}
420
421/// Search for a command in the commands table.
422///
423/// @return  -1 for invalid command.
424static int find_command(int cmdchar)
425{
426  // A multi-byte character is never a command.
427  if (cmdchar >= 0x100) {
428    return -1;
429  }
430
431  // We use the absolute value of the character.  Special keys have a
432  // negative value, but are sorted on their absolute value.
433  if (cmdchar < 0) {
434    cmdchar = -cmdchar;
435  }
436
437  // If the character is in the first part: The character is the index into
438  // nv_cmd_idx[].
439  assert(nv_max_linear < (int)NV_CMDS_SIZE);
440  if (cmdchar <= nv_max_linear) {
441    return nv_cmd_idx[cmdchar];
442  }
443
444  // Perform a binary search.
445  int bot = nv_max_linear + 1;
446  int top = NV_CMDS_SIZE - 1;
447  int idx = -1;
448  while (bot <= top) {
449    int i = (top + bot) / 2;
450    int c = nv_cmds[nv_cmd_idx[i]].cmd_char;
451    if (c < 0) {
452      c = -c;
453    }
454    if (cmdchar == c) {
455      idx = nv_cmd_idx[i];
456      break;
457    }
458    if (cmdchar > c) {
459      bot = i + 1;
460    } else {
461      top = i - 1;
462    }
463  }
464  return idx;
465}
466
467/// If currently editing a cmdline or text is locked: beep and give an error
468/// message, return true.
469static bool check_text_locked(oparg_T *oap)
470{
471  if (!text_locked()) {
472    return false;
473  }
474
475  if (oap != NULL) {
476    clearopbeep(oap);
477  }
478  text_locked_msg();
479  return true;
480}
481
482/// If text is locked, "curbuf->b_ro_locked" or "allbuf_lock" is set:
483/// Give an error message, possibly beep and return true.
484/// "oap" may be NULL.
485bool check_text_or_curbuf_locked(oparg_T *oap)
486{
487  if (check_text_locked(oap)) {
488    return true;
489  }
490
491  if (!curbuf_locked()) {
492    return false;
493  }
494
495  if (oap != NULL) {
496    clearop(oap);
497  }
498  return true;
499}
500
501static oparg_T *current_oap = NULL;
502
503/// Check if an operator was started but not finished yet.
504/// Includes typing a count or a register name.
505bool op_pending(void)
506{
507  return !(current_oap != NULL
508           && !finish_op
509           && current_oap->prev_opcount == 0
510           && current_oap->prev_count0 == 0
511           && current_oap->op_type == OP_NOP
512           && current_oap->regname == NUL);
513}
514
515/// Normal state entry point: the main loop. Never returns.
516void normal_enter(void)
517{
518  NormalState state;
519  normal_state_init(&state);
520  oparg_T *prev_oap = current_oap;
521  current_oap = &state.oa;
522  state.toplevel = true;
523  state_enter(&state.state);
524  current_oap = prev_oap;
525}
526
527static void normal_prepare(NormalState *s)
528{
529  CLEAR_FIELD(s->ca);  // also resets s->ca.retval
530  s->ca.oap = &s->oa;
531
532  // Use a count remembered from before entering an operator. After typing "3d"
533  // we return from normal_cmd() and come back here, the "3" is remembered in
534  // "opcount".
535  s->ca.opcount = opcount;
536
537  // If there is an operator pending, then the command we take this time will
538  // terminate it. Finish_op tells us to finish the operation before returning
539  // this time (unless the operation was cancelled).
540  int c = finish_op;
541  finish_op = (s->oa.op_type != OP_NOP);
542  if (finish_op != c) {
543    ui_cursor_shape();  // may show different cursor shape
544  }
545  may_trigger_modechanged();
546
547  s->set_prevcount = false;
548  // When not finishing an operator and no register name typed, reset the count.
549  if (!finish_op && !s->oa.regname) {
550    s->ca.opcount = 0;
551    s->set_prevcount = true;
552  }
553
554  // Restore counts from before receiving K_EVENT.  This means after
555  // typing "3", handling K_EVENT and then typing "2" we get "32", not
556  // "3 * 2".
557  if (s->oa.prev_opcount > 0 || s->oa.prev_count0 > 0) {
558    s->ca.opcount = s->oa.prev_opcount;
559    s->ca.count0 = s->oa.prev_count0;
560    s->oa.prev_opcount = 0;
561    s->oa.prev_count0 = 0;
562  }
563
564  s->mapped_len = typebuf_maplen();
565  State = MODE_NORMAL_BUSY;
566
567  // Set v:count here, when called from main() and not a stuffed command, so
568  // that v:count can be used in an expression mapping when there is no count.
569  // Do set it for redo
570  if (s->toplevel && readbuf1_empty()) {
571    set_vcount_ca(&s->ca, &s->set_prevcount);
572  }
573}
574
575static bool normal_handle_special_visual_command(NormalState *s)
576{
577  // when 'keymodel' contains "stopsel" may stop Select/Visual mode
578  if (km_stopsel
579      && (nv_cmds[s->idx].cmd_flags & NV_STS)
580      && !(mod_mask & MOD_MASK_SHIFT)) {
581    end_visual_mode();
582    redraw_curbuf_later(UPD_INVERTED);
583  }
584
585  // Keys that work different when 'keymodel' contains "startsel"
586  if (km_startsel) {
587    if (nv_cmds[s->idx].cmd_flags & NV_SS) {
588      unshift_special(&s->ca);
589      s->idx = find_command(s->ca.cmdchar);
590      if (s->idx < 0) {
591        // Just in case
592        clearopbeep(&s->oa);
593        return true;
594      }
595    } else if ((nv_cmds[s->idx].cmd_flags & NV_SSS)
596               && (mod_mask & MOD_MASK_SHIFT)) {
597      mod_mask &= ~MOD_MASK_SHIFT;
598    }
599  }
600  return false;
601}
602
603static bool normal_need_additional_char(NormalState *s)
604{
605  int flags = nv_cmds[s->idx].cmd_flags;
606  bool pending_op = s->oa.op_type != OP_NOP;
607  int cmdchar = s->ca.cmdchar;
608  // without NV_NCH we never need to check for an additional char
609  return flags & NV_NCH && (
610                            // NV_NCH_NOP is set and no operator is pending, get a second char
611                            ((flags & NV_NCH_NOP) == NV_NCH_NOP && !pending_op)
612                            // NV_NCH_ALW is set, always get a second char
613                            || (flags & NV_NCH_ALW) == NV_NCH_ALW
614                            // 'q' without a pending operator, recording or executing a register,
615                            // needs to be followed by a second char, examples:
616                            // - qc => record using register c
617                            // - q: => open command-line window
618                            || (cmdchar == 'q'
619                                && !pending_op
620                                && reg_recording == 0
621                                && reg_executing == 0)
622                            // 'a' or 'i' after an operator is a text object, examples:
623                            // - ciw => change inside word
624                            // - da( => delete parenthesis and everything inside.
625                            // Also, don't do anything when these keys are received in visual mode
626                            // so just get another char.
627                            //
628                            // TODO(tarruda): Visual state needs to be refactored into a
629                            // separate state that "inherits" from normal state.
630                            || ((cmdchar == 'a' || cmdchar == 'i')
631                                && (pending_op || Visual.active)));
632}
633
634static bool normal_need_redraw_mode_message(NormalState *s)
635{
636  // In Visual mode and with "^O" in Insert mode, a short message will be
637  // overwritten by the mode message.  Wait a bit, until a key is hit.
638  // In Visual mode, it's more important to keep the Visual area updated
639  // than keeping a message (e.g. from a /pat search).
640  // Only do this if the command was typed, not from a mapping.
641  // Don't wait when emsg_silent is non-zero.
642  // Also wait a bit after an error message, e.g. for "^O:".
643  // Don't redraw the screen, it would remove the message.
644  return (
645          // 'showmode' is set and messages can be printed
646          ((p_smd && msg_silent == 0
647            // must restart insert mode (ctrl+o or ctrl+l) or just entered visual mode
648            && (restart_edit != 0 || (Visual.active
649                                      && s->old_pos.lnum == curwin->w_cursor.lnum
650                                      && s->old_pos.col == curwin->w_cursor.col))
651            // command-line must be cleared or redrawn
652            && (clear_cmdline || redraw_cmdline)
653            // some message was printed or scrolled
654            && (msg_didout || (msg_didany && msg_scroll))
655            // it is fine to remove the current message
656            && !msg_nowait
657            // the command was the result of direct user input and not a mapping
658            && KeyTyped)
659           // must restart insert mode, not in visual mode and error message is
660           // being shown
661           || (restart_edit != 0 && !Visual.active && msg_scroll
662               && emsg_on_display))
663          // no register was used
664          && s->oa.regname == 0
665          && !(s->ca.retval & CA_COMMAND_BUSY)
666          && stuff_empty()
667          && typebuf_typed()
668          && emsg_silent == 0
669          && !in_assert_fails
670          && !did_wait_return
671          && s->oa.op_type == OP_NOP);
672}
673
674static void normal_redraw_mode_message(NormalState *s)
675{
676  int save_State = State;
677
678  // Draw the cursor with the right shape here
679  if (restart_edit != 0) {
680    State = MODE_INSERT;
681  }
682
683  // If need to redraw, and there is a "keep_msg", redraw before the
684  // delay
685  if (must_redraw && keep_msg != NULL && !emsg_on_display) {
686    char *kmsg;
687
688    kmsg = keep_msg;
689    keep_msg = NULL;
690    // Showmode() will clear keep_msg, but we want to use it anyway.
691    // First update w_topline.
692    setcursor();
693    update_screen();
694    // now reset it, otherwise it's put in the history again
695    keep_msg = kmsg;
696
697    kmsg = xstrdup(keep_msg);
698    msg(kmsg, keep_msg_hl_id);
699    xfree(kmsg);
700  }
701  setcursor();
702  ui_cursor_shape();                  // show different cursor shape
703  ui_flush();
704  if (msg_scroll || emsg_on_display) {
705    msg_delay(1003, true);    // wait extra second for scrolled or error message
706  }
707  msg_delay(3003, false);    // wait three seconds before doing 'showmode'
708  State = save_State;
709
710  msg_scroll = false;
711  emsg_on_display = false;
712}
713
714// TODO(tarruda): Split into a "normal pending" state that can handle K_EVENT
715static void normal_get_additional_char(NormalState *s)
716{
717  int *cp;
718  bool repl = false;            // get character for replace mode
719  bool lit = false;             // get extra character literally
720  bool lang;                    // getting a text character
721
722  no_mapping++;
723  allow_keys++;                 // no mapping for nchar, but allow key codes
724  // Don't generate a CursorHold event here, most commands can't handle
725  // it, e.g., nv_replace(), nv_csearch().
726  did_cursorhold = true;
727  if (s->ca.cmdchar == 'g') {
728    // For 'g' get the next character now, so that we can check for
729    // "gr", "g'" and "g`".
730    s->ca.nchar = plain_vgetc();
731    LANGMAP_ADJUST(s->ca.nchar, true);
732    s->need_flushbuf |= add_to_showcmd(s->ca.nchar);
733    if (s->ca.nchar == 'r' || s->ca.nchar == '\'' || s->ca.nchar == '`'
734        || s->ca.nchar == Ctrl_BSL) {
735      cp = &s->ca.extra_char;            // need to get a third character
736      if (s->ca.nchar != 'r') {
737        lit = true;                           // get it literally
738      } else {
739        repl = true;                          // get it in replace mode
740      }
741    } else {
742      cp = NULL;                      // no third character needed
743    }
744  } else {
745    if (s->ca.cmdchar == 'r') {
746      // get it in replace mode
747      repl = true;
748    }
749    cp = &s->ca.nchar;
750  }
751  lang = (repl || (nv_cmds[s->idx].cmd_flags & NV_LANG));
752
753  // Get a second or third character.
754  if (cp != NULL) {
755    bool langmap_active = false;  // using :lmap mappings
756    if (repl) {
757      State = MODE_REPLACE;                // pretend Replace mode
758      ui_cursor_shape_no_check_conceal();  // show different cursor shape
759    }
760    if (lang && curbuf->b_p_iminsert == B_IMODE_LMAP) {
761      // Allow mappings defined with ":lmap".
762      no_mapping--;
763      allow_keys--;
764      if (repl) {
765        State = MODE_LREPLACE;
766      } else {
767        State = MODE_LANGMAP;
768      }
769      langmap_active = true;
770    }
771
772    *cp = plain_vgetc();
773
774    if (langmap_active) {
775      // Undo the decrement done above
776      no_mapping++;
777      allow_keys++;
778    }
779    State = MODE_NORMAL_BUSY;
780    s->need_flushbuf |= add_to_showcmd(*cp);
781
782    if (!lit) {
783      // Typing CTRL-K gets a digraph.
784      if (*cp == Ctrl_K && ((nv_cmds[s->idx].cmd_flags & NV_LANG)
785                            || cp == &s->ca.extra_char)
786          && vim_strchr(p_cpo, kCpoDigraph) == NULL) {
787        s->c = get_digraph(false);
788        if (s->c > 0) {
789          *cp = s->c;
790          // Guessing how to update showcmd here...
791          del_from_showcmd(3);
792          s->need_flushbuf |= add_to_showcmd(*cp);
793        }
794      }
795
796      // adjust chars > 127, except after "tTfFr" commands
797      LANGMAP_ADJUST(*cp, !lang);
798    }
799
800    // When the next character is CTRL-\ a following CTRL-N means the
801    // command is aborted and we go to Normal mode.
802    if (cp == &s->ca.extra_char
803        && s->ca.nchar == Ctrl_BSL
804        && (s->ca.extra_char == Ctrl_N || s->ca.extra_char == Ctrl_G)) {
805      s->ca.cmdchar = Ctrl_BSL;
806      s->ca.nchar = s->ca.extra_char;
807      s->idx = find_command(s->ca.cmdchar);
808    } else if ((s->ca.nchar == 'n' || s->ca.nchar == 'N')
809               && s->ca.cmdchar == 'g') {
810      s->ca.oap->op_type = get_op_type(*cp, NUL);
811    } else if (*cp == Ctrl_BSL) {
812      int towait = (p_ttm >= 0 ? (int)p_ttm : (int)p_tm);
813
814      // There is a busy wait here when typing "f<C-\>" and then
815      // something different from CTRL-N.  Can't be avoided.
816      while ((s->c = vpeekc()) <= 0 && towait > 0) {
817        do_sleep(towait > 50 ? 50 : towait, false);
818        towait -= 50;
819      }
820      if (s->c > 0) {
821        s->c = plain_vgetc();
822        if (s->c != Ctrl_N && s->c != Ctrl_G) {
823          vungetc(s->c);
824        } else {
825          s->ca.cmdchar = Ctrl_BSL;
826          s->ca.nchar = s->c;
827          s->idx = find_command(s->ca.cmdchar);
828          assert(s->idx >= 0);
829        }
830      }
831    }
832
833    if (lang) {
834      // When getting a text character and the next character is a
835      // multi-byte character, it could be a composing character.
836      // However, don't wait for it to arrive. Also, do enable mapping,
837      // because if it's put back with vungetc() it's too late to apply
838      // mapping.
839      no_mapping--;
840      GraphemeState state = GRAPHEME_STATE_INIT;
841      int prev_code = s->ca.nchar;
842
843      while ((s->c = vpeekc()) > 0
844             && (s->c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1)) {
845        s->c = plain_vgetc();
846
847        if (!utf_iscomposing(prev_code, s->c, &state)) {
848          vungetc(s->c);                   // it wasn't, put it back
849          break;
850        }
851
852        // first composing char, first put base char into buffer
853        if (s->ca.nchar_len == 0) {
854          s->ca.nchar_len = utf_char2bytes(s->ca.nchar, s->ca.nchar_composing);
855        }
856
857        if (s->ca.nchar_len + utf_char2len(s->c) < (int)sizeof(s->ca.nchar_composing)) {
858          s->ca.nchar_len += utf_char2bytes(s->c, s->ca.nchar_composing + s->ca.nchar_len);
859        }
860        prev_code = s->c;
861      }
862      s->ca.nchar_composing[s->ca.nchar_len] = NUL;
863      no_mapping++;
864      // Vim may be in a different mode when the user types the next key,
865      // but when replaying a recording the next key is already in the
866      // typeahead buffer, so record an <Ignore> before that to prevent
867      // the vpeekc() above from applying wrong mappings when replaying.
868      no_u_sync++;
869      gotchars_ignore();
870      no_u_sync--;
871    }
872  }
873  no_mapping--;
874  allow_keys--;
875}
876
877static void normal_invert_horizontal(NormalState *s)
878{
879  switch (s->ca.cmdchar) {
880  case 'l':
881    s->ca.cmdchar = 'h'; break;
882  case K_RIGHT:
883    s->ca.cmdchar = K_LEFT; break;
884  case K_S_RIGHT:
885    s->ca.cmdchar = K_S_LEFT; break;
886  case K_C_RIGHT:
887    s->ca.cmdchar = K_C_LEFT; break;
888  case 'h':
889    s->ca.cmdchar = 'l'; break;
890  case K_LEFT:
891    s->ca.cmdchar = K_RIGHT; break;
892  case K_S_LEFT:
893    s->ca.cmdchar = K_S_RIGHT; break;
894  case K_C_LEFT:
895    s->ca.cmdchar = K_C_RIGHT; break;
896  case '>':
897    s->ca.cmdchar = '<'; break;
898  case '<':
899    s->ca.cmdchar = '>'; break;
900  }
901  s->idx = find_command(s->ca.cmdchar);
902}
903
904static bool normal_get_command_count(NormalState *s)
905{
906  if (Visual.active && Visual.select) {
907    return false;
908  }
909  // Handle a count before a command and compute ca.count0.
910  // Note that '0' is a command and not the start of a count, but it's
911  // part of a count after other digits.
912  while ((s->c >= '1' && s->c <= '9')
913         || (s->ca.count0 != 0 && (s->c == K_DEL || s->c == K_KDEL || s->c == '0'))) {
914    if (s->c == K_DEL || s->c == K_KDEL) {
915      s->ca.count0 /= 10;
916      del_from_showcmd(4);            // delete the digit and ~@%
917    } else if (s->ca.count0 > 99999999) {
918      s->ca.count0 = 999999999;
919    } else {
920      s->ca.count0 = s->ca.count0 * 10 + (s->c - '0');
921    }
922
923    // Set v:count here, when called from main() and not a stuffed
924    // command, so that v:count can be used in an expression mapping
925    // right after the count. Do set it for redo.
926    if (s->toplevel && readbuf1_empty()) {
927      set_vcount_ca(&s->ca, &s->set_prevcount);
928    }
929
930    if (s->ctrl_w) {
931      no_mapping++;
932      allow_keys++;                   // no mapping for nchar, but keys
933    }
934
935    no_zero_mapping++;                // don't map zero here
936    s->c = plain_vgetc();
937    LANGMAP_ADJUST(s->c, true);
938    no_zero_mapping--;
939    if (s->ctrl_w) {
940      no_mapping--;
941      allow_keys--;
942    }
943    s->need_flushbuf |= add_to_showcmd(s->c);
944  }
945
946  // If we got CTRL-W there may be a/another count
947  if (s->c == Ctrl_W && !s->ctrl_w && s->oa.op_type == OP_NOP) {
948    s->ctrl_w = true;
949    s->ca.opcount = s->ca.count0;           // remember first count
950    s->ca.count0 = 0;
951    no_mapping++;
952    allow_keys++;                        // no mapping for nchar, but keys
953    s->c = plain_vgetc();                // get next character
954    LANGMAP_ADJUST(s->c, true);
955    no_mapping--;
956    allow_keys--;
957    s->need_flushbuf |= add_to_showcmd(s->c);
958    return true;
959  }
960
961  return false;
962}
963
964static void normal_finish_command(NormalState *s, CmdFrame *frame)
965{
966  bool did_visual_op = false;
967
968  if (s->command_finished) {
969    goto normal_end;
970  }
971
972  // If we didn't start or finish an operator, reset oap->regname, unless we
973  // need it later.
974  if (!finish_op
975      && !s->oa.op_type
976      && (s->idx < 0 || !(nv_cmds[s->idx].cmd_flags & NV_KEEPREG))) {
977    clearop(&s->oa);
978    set_reg_var(get_default_register_name());
979  }
980
981  // Get the length of mapped chars again after typing a count, second
982  // character or "z333<cr>".
983  if (s->old_mapped_len > 0) {
984    s->old_mapped_len = typebuf_maplen();
985  }
986
987  // If an operation is pending, handle it.  But not for K_IGNORE or
988  // K_MOUSEMOVE.
989  if (s->ca.cmdchar != K_IGNORE && s->ca.cmdchar != K_MOUSEMOVE) {
990    did_visual_op = Visual.active && s->oa.op_type != OP_NOP
991                    // For OP_COLON, do_pending_operator() stuffs ':' into
992                    // the read buffer, which isn't executed immediately.
993                    && s->oa.op_type != OP_COLON;
994    do_pending_operator(&s->ca, s->old_col, false);
995  }
996
997  // Wait for a moment when a message is displayed that will be overwritten
998  // by the mode message.
999  if (normal_need_redraw_mode_message(s)) {
1000    normal_redraw_mode_message(s);
1001  }
1002
1003  // Finish up after executing a Normal mode command.
1004normal_end:
1005
1006  if (Visual.need_end) {
1007    Visual.need_end = false;
1008    reset_VIsual();
1009  }
1010
1011  msg_nowait = false;
1012
1013  if (finish_op || did_visual_op) {
1014    set_reg_var(get_default_register_name());
1015  }
1016
1017  const bool prev_finish_op = finish_op;
1018  if (s->oa.op_type == OP_NOP) {
1019    // Reset finish_op, in case it was set
1020    finish_op = false;
1021    may_trigger_modechanged();
1022  }
1023  // Redraw the cursor with another shape, if we were in Operator-pending
1024  // mode or did a replace command.
1025  if (prev_finish_op || s->ca.cmdchar == 'r'
1026      || (s->ca.cmdchar == 'g' && s->ca.nchar == 'r')) {
1027    ui_cursor_shape();                  // may show different cursor shape
1028  }
1029
1030  checkpcmark();                // check if we moved since setting pcmark
1031
1032  mb_check_adjust_col(curwin);  // #6203
1033
1034  if (curwin->w_p_scb && s->toplevel) {
1035    validate_cursor(curwin);          // may need to update w_leftcol
1036    do_check_scrollbind(true);
1037  }
1038
1039  if (curwin->w_p_crb && s->toplevel) {
1040    validate_cursor(curwin);          // may need to update w_leftcol
1041    do_check_cursorbind();
1042  }
1043
1044  // May restart edit(), if we got here with CTRL-O in Insert mode (but not
1045  // if still inside a mapping that started in Visual mode).
1046  // May switch from Visual to Select mode after CTRL-O command.
1047  if (s->oa.op_type == OP_NOP
1048      && ((restart_edit != 0 && !Visual.active && s->old_mapped_len == 0)
1049          || Visual.restart_select == 1)
1050      && !(s->ca.retval & CA_COMMAND_BUSY)
1051      && stuff_empty()
1052      && s->oa.regname == 0) {
1053    if (Visual.restart_select == 1) {
1054      Visual.select = true;
1055      Visual.select_reg = 0;
1056      may_trigger_modechanged();
1057      showmode();
1058      Visual.restart_select = 0;
1059    }
1060    if (restart_edit != 0 && !Visual.active && s->old_mapped_len == 0) {
1061      edit(restart_edit, false, 1);
1062    }
1063  }
1064
1065  if (Visual.restart_select == 2) {
1066    Visual.restart_select = 1;
1067  }
1068
1069  // Save count before an operator for next time
1070  opcount = s->ca.opcount;
1071
1072  atom_cmd_end(&s->ca, frame);
1073
1074  // Redraw 'showcmd' AFTER all multicursor effects have settled (atom_cmd_end).
1075  if (s->oa.op_type == OP_NOP && s->oa.regname == 0 && s->ca.cmdchar != K_EVENT) {
1076    clear_showcmd();
1077  }
1078}
1079
1080static int normal_execute(VimState *state, int key)
1081{
1082  CmdFrame frame;
1083  atom_cmd_start(&frame, key);
1084
1085  NormalState *s = (NormalState *)state;
1086  s->command_finished = false;
1087  s->ctrl_w = false;                  // got CTRL-W command
1088  s->old_col = curwin->w_curswant;
1089  s->c = key;
1090
1091  LANGMAP_ADJUST(s->c, get_real_state() != MODE_SELECT);
1092
1093  // If a mapping was started in Visual or Select mode, remember the length
1094  // of the mapping.  This is used below to not return to Insert mode for as
1095  // long as the mapping is being executed.
1096  if (restart_edit == 0) {
1097    s->old_mapped_len = 0;
1098  } else if (s->old_mapped_len || (Visual.active && s->mapped_len == 0
1099                                   && typebuf_maplen() > 0)) {
1100    s->old_mapped_len = typebuf_maplen();
1101  }
1102
1103  if (s->c == NUL) {
1104    s->c = K_ZERO;
1105  }
1106
1107  // In Select mode, typed text replaces the selection.
1108  if (Visual.active && Visual.select && (vim_isprintc(s->c)
1109                                         || s->c == NL || s->c == CAR || s->c == K_KENTER)) {
1110    // Fake a "c"hange command.
1111    // When "restart_edit" is set fake a "d"elete command, Insert mode will restart automatically.
1112    // Insert the typed character in the typeahead buffer, so that it can
1113    // be mapped in Insert mode.  Required for ":lmap" to work.
1114    requeue_key(vgetc_char, vgetc_mod_mask, 0, true);
1115
1116    if (restart_edit != 0) {
1117      s->c = 'd';
1118    } else {
1119      s->c = 'c';
1120    }
1121    msg_nowait = true;          // don't delay going to insert mode
1122    s->old_mapped_len = 0;      // do go to Insert mode
1123  }
1124
1125  s->need_flushbuf = add_to_showcmd(s->c);
1126
1127  while (normal_get_command_count(s)) {}
1128
1129  if (s->c == K_EVENT) {
1130    // Save the count values so that ca.opcount and ca.count0 are exactly
1131    // the same when coming back here after handling K_EVENT.
1132    s->oa.prev_opcount = s->ca.opcount;
1133    s->oa.prev_count0 = s->ca.count0;
1134  } else if (s->ca.opcount != 0) {
1135    // If we're in the middle of an operator (including after entering a
1136    // yank buffer with '"') AND we had a count before the operator, then
1137    // that count overrides the current value of ca.count0.
1138    // What this means effectively, is that commands like "3dw" get turned
1139    // into "d3w" which makes things fall into place pretty neatly.
1140    // If you give a count before AND after the operator, they are
1141    // multiplied.
1142    if (s->ca.count0) {
1143      if (s->ca.opcount >= 999999999 / s->ca.count0) {
1144        s->ca.count0 = 999999999;
1145      } else {
1146        s->ca.count0 *= s->ca.opcount;
1147      }
1148    } else {
1149      s->ca.count0 = s->ca.opcount;
1150    }
1151  }
1152
1153  // Always remember the count.  It will be set to zero (on the next call,
1154  // above) when there is no pending operator.
1155  // When called from toplevel, save the count for use by v:count.
1156  s->ca.opcount = s->ca.count0;
1157  s->ca.count1 = (s->ca.count0 == 0 ? 1 : s->ca.count0);
1158
1159  // Only set v:count when called from toplevel and not a stuffed command.
1160  // Do set it for redo.
1161  if (s->toplevel && readbuf1_empty()) {
1162    set_vcount(s->ca.count0, s->ca.count1, s->set_prevcount);
1163  }
1164
1165  // Find the command character in the table of commands.
1166  // For CTRL-W we already got nchar when looking for a count.
1167  if (s->ctrl_w) {
1168    s->ca.nchar = s->c;
1169    s->ca.cmdchar = Ctrl_W;
1170  } else {
1171    s->ca.cmdchar = s->c;
1172  }
1173
1174  s->idx = find_command(s->ca.cmdchar);
1175
1176  if (s->idx < 0) {
1177    // Not a known command: beep.
1178    clearopbeep(&s->oa);
1179    s->command_finished = true;
1180    goto finish;
1181  }
1182
1183  if ((nv_cmds[s->idx].cmd_flags & NV_NCW) && check_text_or_curbuf_locked(&s->oa)) {
1184    // this command is not allowed now
1185    s->command_finished = true;
1186    goto finish;
1187  }
1188
1189  // In Visual/Select mode, a few keys are handled in a special way.
1190  if (Visual.active && normal_handle_special_visual_command(s)) {
1191    s->command_finished = true;
1192    goto finish;
1193  }
1194
1195  if (curwin->w_p_rl && KeyTyped && !KeyStuffed
1196      && (nv_cmds[s->idx].cmd_flags & NV_RL)) {
1197    // Invert horizontal movements and operations.  Only when typed by the
1198    // user directly, not when the result of a mapping or "x" translated
1199    // to "dl".
1200    normal_invert_horizontal(s);
1201  }
1202
1203  // Get an additional character if we need one.
1204  if (normal_need_additional_char(s)) {
1205    normal_get_additional_char(s);
1206  }
1207
1208  // Flush the showcmd characters onto the screen so we can see them while
1209  // the command is being executed.  Only do this when the shown command was
1210  // actually displayed, otherwise this will slow down a lot when executing
1211  // mappings.
1212  if (s->need_flushbuf) {
1213    ui_flush();
1214  }
1215
1216  if (s->ca.cmdchar != K_IGNORE && s->ca.cmdchar != K_EVENT) {
1217    did_cursorhold = false;
1218  }
1219
1220  State = MODE_NORMAL;
1221
1222  if (s->ca.nchar == ESC || s->ca.extra_char == ESC) {
1223    clearop(&s->oa);
1224    s->command_finished = true;
1225    goto finish;
1226  }
1227
1228  if (s->ca.cmdchar != K_IGNORE) {
1229    msg_didout = false;        // don't scroll screen up for normal command
1230    msg_col = 0;
1231  }
1232
1233  s->old_pos = curwin->w_cursor;           // remember where the cursor was
1234
1235  // When 'keymodel' contains "startsel" some keys start Select/Visual
1236  // mode.
1237  if (!Visual.active && km_startsel) {
1238    if (nv_cmds[s->idx].cmd_flags & NV_SS) {
1239      start_selection();
1240      unshift_special(&s->ca);
1241      s->idx = find_command(s->ca.cmdchar);
1242      assert(s->idx >= 0);
1243    } else if ((nv_cmds[s->idx].cmd_flags & NV_SSS)
1244               && (mod_mask & MOD_MASK_SHIFT)) {
1245      start_selection();
1246      mod_mask &= ~MOD_MASK_SHIFT;
1247    }
1248  }
1249
1250  // Execute the command!
1251  // Call the command function found in the commands table.
1252  s->ca.arg = nv_cmds[s->idx].cmd_arg;
1253  (nv_cmds[s->idx].cmd_func)(&s->ca);
1254
1255finish:
1256  normal_finish_command(s, &frame);
1257  xfree(s->ca.searchbuf);
1258  return 1;
1259}
1260
1261static void normal_check_stuff_buffer(NormalState *s)
1262{
1263  if (stuff_empty()) {
1264    did_check_timestamps = false;
1265
1266    if (need_check_timestamps) {
1267      check_timestamps(false);
1268    }
1269
1270    if (need_wait_return) {
1271      // if wait_return still needed call it now
1272      wait_return(false);
1273    }
1274  }
1275}
1276
1277static void normal_check_interrupt(NormalState *s)
1278{
1279  // Reset "got_int" now that we got back to the main loop.
1280  if (got_int) {
1281    if (!quit_more) {
1282      // flush all buffers
1283      vgetc();
1284    }
1285    got_int = false;
1286    s->previous_got_int = true;
1287  } else {
1288    s->previous_got_int = false;
1289  }
1290}
1291
1292static void normal_check_window_scrolled(NormalState *s)
1293{
1294  if (!finish_op) {
1295    may_trigger_win_scrolled_resized();
1296  }
1297}
1298
1299static void normal_check_cursor_moved(NormalState *s)
1300{
1301  // Trigger CursorMoved if the cursor moved.
1302  if (!finish_op && has_event(EVENT_CURSORMOVED)
1303      && (last_cursormoved_win != curwin
1304          || !equalpos(last_cursormoved, curwin->w_cursor))) {
1305    apply_autocmds(EVENT_CURSORMOVED, NULL, NULL, false, curbuf);
1306    last_cursormoved_win = curwin;
1307    last_cursormoved = curwin->w_cursor;
1308  }
1309}
1310
1311static void normal_check_text_changed(NormalState *s)
1312{
1313  // Trigger TextChanged if changedtick differs.
1314  if (!finish_op && has_event(EVENT_TEXTCHANGED)
1315      && curbuf->b_last_changedtick != buf_get_changedtick(curbuf)) {
1316    apply_autocmds(EVENT_TEXTCHANGED, NULL, NULL, false, curbuf);
1317    curbuf->b_last_changedtick = buf_get_changedtick(curbuf);
1318  }
1319}
1320
1321/// If nothing is pending and we are going to wait for the user to
1322/// type a character, trigger SafeState.
1323static void normal_check_safe_state(NormalState *s)
1324{
1325  may_trigger_safestate(!op_pending() && restart_edit == 0);
1326}
1327
1328static void normal_check_folds(NormalState *s)
1329{
1330  // Include a closed fold completely in the Visual area.
1331  foldAdjustVisual();
1332
1333  // When 'foldclose' is set, apply 'foldlevel' to folds that don't
1334  // contain the cursor.
1335  // When 'foldopen' is "all", open the fold(s) under the cursor.
1336  // This may mark the window for redrawing.
1337  if (hasAnyFolding(curwin) && !char_avail()) {
1338    foldCheckClose();
1339
1340    if (fdo_flags & kOptFdoFlagAll) {
1341      foldOpenCursor();
1342    }
1343  }
1344}
1345
1346static void normal_redraw(NormalState *s)
1347{
1348  // Before redrawing, make sure w_topline is correct, and w_leftcol
1349  // if lines don't wrap, and w_skipcol if lines wrap.
1350  update_topline(curwin);
1351  validate_cursor(curwin);
1352
1353  show_cursor_info_later(false);
1354
1355  if (must_redraw) {
1356    update_screen();
1357  } else {
1358    redraw_statuslines();
1359    if (redraw_cmdline || clear_cmdline || redraw_mode) {
1360      showmode();
1361    }
1362  }
1363
1364  curbuf->b_last_used = time(NULL);
1365
1366  // Display message after redraw.
1367  if (keep_msg != NULL) {
1368    char *const p = xstrdup(keep_msg);
1369
1370    // msg_start() will set keep_msg to NULL, make a copy
1371    // first.  Don't reset keep_msg, msg_attr_keep() uses it to
1372    // check for duplicates.  Never put this message in
1373    // history.
1374    msg_hist_off = true;
1375    msg(p, keep_msg_hl_id);
1376    msg_hist_off = false;
1377    xfree(p);
1378  }
1379
1380  // show fileinfo after redraw
1381  if (need_fileinfo && !shortmess(kShmFileinfo)) {
1382    fileinfo(false, true, false);
1383    need_fileinfo = false;
1384  }
1385
1386  emsg_on_display = false;  // can delete error message now
1387  did_emsg = false;
1388  msg_didany = false;  // reset lines_left in msg_start()
1389  may_clear_sb_text();  // clear scroll-back text on next msg
1390
1391  setcursor();
1392}
1393
1394/// Function executed before each iteration of normal mode.
1395///
1396/// @return:
1397///           1 if the iteration should continue normally
1398///          -1 if the iteration should be skipped
1399///           0 if the main loop must exit
1400static int normal_check(VimState *state)
1401{
1402  NormalState *s = (NormalState *)state;
1403  normal_check_stuff_buffer(s);
1404  normal_check_interrupt(s);
1405
1406  // At the toplevel there is no exception handling.  Discard any that
1407  // may be hanging around (e.g. from "interrupt" at the debug prompt).
1408  if (did_throw && !ex_normal_busy) {
1409    discard_current_exception();
1410  }
1411
1412  msg_scroll = false;
1413  quit_more = false;
1414
1415  state_no_longer_safe(NULL);
1416
1417  // If skip redraw is set (for ":" in wait_return()), don't redraw now.
1418  // If there is nothing in the stuff_buffer or do_redraw is true,
1419  // update cursor and redraw.
1420  if (skip_redraw) {
1421    skip_redraw = false;
1422    setcursor();
1423  } else if (do_redraw || stuff_empty()) {
1424    terminal_check_refresh();
1425
1426    // Ensure curwin->w_topline and curwin->w_leftcol are up to date
1427    // before triggering a WinScrolled autocommand.
1428    update_topline(curwin);
1429    validate_cursor(curwin);
1430
1431    normal_check_cursor_moved(s);
1432    normal_check_text_changed(s);
1433    normal_check_window_scrolled(s);
1434    normal_check_safe_state(s);
1435
1436    // Updating diffs from changed() does not always work properly,
1437    // esp. updating folds.  Do an update just before redrawing if
1438    // needed.
1439    if (curtab->tp_diff_update || curtab->tp_diff_invalid) {
1440      ex_diffupdate(NULL);
1441      curtab->tp_diff_update = false;
1442    }
1443
1444    // Scroll-binding for diff mode may have been postponed until
1445    // here.  Avoids doing it for every change.
1446    if (diff_need_scrollbind) {
1447      check_scrollbind(0, 0);
1448      diff_need_scrollbind = false;
1449    }
1450
1451    normal_check_folds(s);
1452    normal_redraw(s);
1453    do_redraw = false;
1454
1455    // Now that we have drawn the first screen all the startup stuff
1456    // has been done, close any file for startup messages.
1457    if (time_fd != NULL) {
1458      TIME_MSG("first screen update");
1459      time_finish();
1460    }
1461    // After the first screen update may start triggering WinScrolled
1462    // autocmd events.  Store all the scroll positions and sizes now.
1463    may_make_initial_scroll_size_snapshot();
1464  }
1465
1466  // May perform garbage collection when waiting for a character, but
1467  // only at the very toplevel.  Otherwise we may be using a List or
1468  // Dict internally somewhere.
1469  // "may_garbage_collect" is reset in vgetc() which is invoked through
1470  // normal_cmd().
1471  may_garbage_collect = true;
1472
1473  // Update w_curswant if w_set_curswant has been set.
1474  // Postponed until here to avoid computing w_virtcol too often.
1475  update_curswant();
1476
1477  normal_prepare(s);
1478  return 1;
1479}
1480
1481/// Set v:count and v:count1 according to "cap".
1482/// Set v:prevcount only when "set_prevcount" is true.
1483static void set_vcount_ca(cmdarg_T *cap, bool *set_prevcount)
1484{
1485  int64_t count = cap->count0;
1486
1487  // multiply with cap->opcount the same way as above
1488  if (cap->opcount != 0) {
1489    count = cap->opcount * (count == 0 ? 1 : count);
1490  }
1491  set_vcount(count, count == 0 ? 1 : count, *set_prevcount);
1492  *set_prevcount = false;    // only set v:prevcount once
1493}
1494
1495/// The active Visual area: `Visual.start` to the cursor. What `b_visual` saves for '< and '> marks,
1496/// and "gv".
1497visualinfo_T visualinfo(void)
1498{
1499  return (visualinfo_T){
1500    .vi_start = Visual.start,
1501    .vi_end = curwin->w_cursor,
1502    .vi_mode = Visual.mode,
1503    .vi_curswant = curwin->w_curswant,
1504  };
1505}
1506
1507/// End Visual mode.
1508/// This function should ALWAYS be called to end Visual mode, except from
1509/// do_pending_operator().
1510void end_visual_mode(void)
1511{
1512  Visual.select_exclu_adj = false;
1513  Visual.active = false;
1514  setmouse();
1515  mouse_dragging = 0;
1516
1517  // Save the current Visual area for '< and '> marks, and "gv"
1518  curbuf->b_visual = visualinfo();
1519  curbuf->b_visual_mode_eval = Visual.mode;
1520  if (!virtual_active(curwin)) {
1521    curwin->w_cursor.coladd = 0;
1522  }
1523
1524  may_clear_cmdline();
1525
1526  adjust_cursor_eol();
1527  may_trigger_modechanged();
1528}
1529
1530/// Reset Visual.active and Visual.reselect.
1531void reset_VIsual_and_resel(void)
1532{
1533  if (Visual.active) {
1534    end_visual_mode();
1535    redraw_curbuf_later(UPD_INVERTED);  // delete the inversion later
1536  }
1537  Visual.reselect = false;
1538}
1539
1540/// Reset Visual.active and Visual.reselect if it's set.
1541void reset_VIsual(void)
1542{
1543  if (Visual.active) {
1544    end_visual_mode();
1545    redraw_curbuf_later(UPD_INVERTED);  // delete the inversion later
1546    Visual.reselect = false;
1547  }
1548}
1549
1550void restore_visual_mode(void)
1551{
1552  if (VIsual_mode_orig != NUL) {
1553    curbuf->b_visual.vi_mode = VIsual_mode_orig;
1554    VIsual_mode_orig = NUL;
1555  }
1556}
1557
1558/// Check for a <cexpr> special item to include when searching for an identifier: "ptr->arg",
1559/// "list[idx]", "s.var".  When `dir` is BACKWARD `ptr[-1]` must be valid!
1560///
1561/// @return  true if the character at `*ptr` should be included.
1562///
1563/// @param dir    Direction of searching, either FORWARD or BACKWARD.
1564/// @param *colp  Is in/decremented if "ptr[-dir]" should also be included.
1565/// @param bnp    Points to a counter for square brackets.
1566static bool find_is_eval_item(const char *const ptr, int *const colp, int *const bnp, const int dir)
1567{
1568  // Accept everything inside [].
1569  if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD)) {
1570    *bnp += 1;
1571  }
1572  if (*bnp > 0) {
1573    if ((*ptr == '[' && dir == BACKWARD) || (*ptr == ']' && dir == FORWARD)) {
1574      *bnp -= 1;
1575    }
1576    return true;
1577  }
1578
1579  // skip over "s.var"
1580  if (*ptr == '.') {
1581    return true;
1582  }
1583
1584  // two-character item: s->var
1585  if (ptr[dir == BACKWARD ? 0 : 1] == '>'
1586      && ptr[dir == BACKWARD ? -1 : 0] == '-') {
1587    *colp += dir;
1588    return true;
1589  }
1590  return false;
1591}
1592
1593/// Finds the identifier under or to the right of the cursor, and stores it in `text`.
1594///
1595/// There are three steps:
1596/// 1. Search forward for the start of an identifier/text.  Doesn't move if
1597///    already on one.
1598/// 2. Search backward for the start of this identifier/text.
1599///    This doesn't match the real Vi but I like it a little better and it
1600///    shouldn't bother anyone.
1601/// 3. Search forward to the end of this identifier/text.
1602///    When FIND_IDENT isn't defined, we backup until a blank.
1603///
1604/// @param text If text is found, a pointer to the text is put in `*text`. This points into the
1605/// current buffer line and is not always NUL terminated.
1606/// @param find_type One of three values:
1607///        - FIND_IDENT:   find an identifier (keyword)
1608///        - FIND_STRING:  find any non-white text
1609///        - FIND_IDENT + FIND_STRING: find any non-white text, identifier preferred.
1610///        - FIND_EVAL:    also include "->", "[]" and "." (<cexpr>)
1611/// @param offset  If not NULL, gets cursor position relative to start of `text`.
1612/// @return  Text length, or zero if no text is found.
1613size_t find_ident_under_cursor(char **text, int find_type, int *offset)
1614  FUNC_ATTR_NONNULL_ARG(1)
1615{
1616  int textcol = 0;
1617  size_t len = find_ident_at_pos(curwin, curwin->w_cursor.lnum,
1618                                 curwin->w_cursor.col, text, offset ? &textcol : NULL, find_type);
1619  if (offset) {
1620    *offset = curwin->w_cursor.col - textcol;
1621  }
1622  return len;
1623}
1624
1625/// Like find_ident_under_cursor(), but for any window and any position.
1626/// However: Uses 'iskeyword' from the current window!.
1627///
1628/// @param textcol  column where "text" starts, can be NULL
1629size_t find_ident_at_pos(win_T *wp, linenr_T lnum, colnr_T startcol, char **text, int *textcol,
1630                         int find_type)
1631  FUNC_ATTR_NONNULL_ARG(1, 4)
1632{
1633  int col = 0;         // init to shut up GCC
1634  int i;
1635  int this_class = 0;
1636  int prev_class;
1637  int prevcol;
1638  int bn = 0;                       // bracket nesting
1639
1640  // if i == 0: try to find an identifier
1641  // if i == 1: try to find any non-white text
1642  char *ptr = ml_get_buf(wp->w_buffer, lnum);
1643  for (i = (find_type & FIND_IDENT) ? 0 : 1; i < 2; i++) {
1644    // 1. skip to start of identifier/text
1645    col = startcol;
1646    while (ptr[col] != NUL) {
1647      // Stop at a ']' to evaluate "a[x]".
1648      if ((find_type & FIND_EVAL) && ptr[col] == ']') {
1649        break;
1650      }
1651      this_class = mb_get_class(ptr + col);
1652      if (this_class != 0 && (i == 1 || this_class != 1)) {
1653        break;
1654      }
1655      col += utfc_ptr2len(ptr + col);
1656    }
1657
1658    // When starting on a ']' count it, so that we include the '['.
1659    bn = ptr[col] == ']';
1660
1661    // 2. Back up to start of identifier/text.
1662    //
1663    // Remember class of character under cursor.
1664    if ((find_type & FIND_EVAL) && ptr[col] == ']') {
1665      this_class = mb_get_class("a");
1666    } else {
1667      this_class = mb_get_class(ptr + col);
1668    }
1669    while (col > 0 && this_class != 0) {
1670      prevcol = col - 1 - utf_head_off(ptr, ptr + col - 1);
1671      prev_class = mb_get_class(ptr + prevcol);
1672      if (this_class != prev_class
1673          && (i == 0
1674              || prev_class == 0
1675              || (find_type & FIND_IDENT))
1676          && (!(find_type & FIND_EVAL)
1677              || prevcol == 0
1678              || !find_is_eval_item(ptr + prevcol, &prevcol, &bn, BACKWARD))) {
1679        break;
1680      }
1681      col = prevcol;
1682    }
1683
1684    // If we don't want just any old text, or we've found an
1685    // identifier, stop searching.
1686    this_class = MIN(this_class, 2);
1687    if (!(find_type & FIND_STRING) || this_class == 2) {
1688      break;
1689    }
1690  }
1691
1692  if (ptr[col] == NUL || (i == 0 && this_class != 2)) {
1693    // Didn't find an identifier or text.
1694    if (find_type & FIND_STRING) {
1695      emsg(_("E348: No string under cursor"));
1696    } else {
1697      emsg(_(e_noident));
1698    }
1699    return 0;
1700  }
1701  ptr += col;
1702  *text = ptr;
1703  if (textcol != NULL) {
1704    *textcol = col;
1705  }
1706
1707  // 3. Find the end if the identifier/text.
1708  bn = 0;
1709  startcol -= col;
1710  col = 0;
1711  // Search for point of changing multibyte character class.
1712  this_class = mb_get_class(ptr);
1713  while (ptr[col] != NUL
1714         && ((i == 0
1715              ? mb_get_class(ptr + col) == this_class
1716              : mb_get_class(ptr + col) != 0)
1717             || ((find_type & FIND_EVAL)
1718                 && col <= (int)startcol
1719                 && find_is_eval_item(ptr + col, &col, &bn, FORWARD)))) {
1720    col += utfc_ptr2len(ptr + col);
1721  }
1722
1723  assert(col >= 0);
1724  return (size_t)col;
1725}
1726
1727/// Prepare for redo of a normal command.
1728static void prep_redo_cmd(cmdarg_T *cap)
1729{
1730  // Composing chars: the operand's byte form is the composed string, not the single char.
1731  bool composing = cap->nchar_len > 0;
1732  prep_redo(true, composing, atom_cmd_spec(cap));
1733  if (composing) {
1734    redo_append_str(cap->nchar_composing, -1);
1735  }
1736}
1737
1738/// Check for operator active and clear it.
1739///
1740/// Beep and return true if an operator was active.
1741static bool checkclearop(oparg_T *oap)
1742{
1743  if (oap->op_type == OP_NOP) {
1744    return false;
1745  }
1746  clearopbeep(oap);
1747  return true;
1748}
1749
1750/// Checks for operator or Visual active, and clears active operator.
1751///
1752/// Beep and return true if an operator or Visual was active.
1753static bool checkclearopq(oparg_T *oap)
1754{
1755  if (oap->op_type == OP_NOP && !Visual.active) {
1756    return false;
1757  }
1758  clearopbeep(oap);
1759  return true;
1760}
1761
1762void clearop(oparg_T *oap)
1763{
1764  oap->op_type = OP_NOP;
1765  oap->regname = 0;
1766  oap->motion_force = NUL;
1767  oap->use_reg_one = false;
1768  oap->restore_cursor = false;
1769  motion_force = NUL;
1770}
1771
1772void clearopbeep(oparg_T *oap)
1773{
1774  if (oap->op_type == OP_MCURSOR && oap->motion_type != kMTUnknown) {
1775    return;  // "zq": motion failing at primary, does not cancel the op.
1776  }
1777  clearop(oap);
1778  beep_flush();
1779}
1780
1781/// Remove the shift modifier from a special key.
1782static void unshift_special(cmdarg_T *cap)
1783{
1784  switch (cap->cmdchar) {
1785  case K_S_RIGHT:
1786    cap->cmdchar = K_RIGHT; break;
1787  case K_S_LEFT:
1788    cap->cmdchar = K_LEFT; break;
1789  case K_S_UP:
1790    cap->cmdchar = K_UP; break;
1791  case K_S_DOWN:
1792    cap->cmdchar = K_DOWN; break;
1793  case K_S_HOME:
1794    cap->cmdchar = K_HOME; break;
1795  case K_S_END:
1796    cap->cmdchar = K_END; break;
1797  }
1798  cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask);
1799}
1800
1801/// If the mode is currently displayed clear the command line or update the
1802/// command displayed.
1803void may_clear_cmdline(void)
1804{
1805  if (mode_displayed) {
1806    // unshow visual mode later
1807    clear_cmdline = true;
1808  } else {
1809    clear_showcmd();
1810  }
1811}
1812
1813// Routines for displaying a partly typed command
1814static char old_showcmd_buf[SHOWCMD_BUFLEN];    // For push_showcmd()
1815static bool showcmd_is_clear = true;
1816static bool showcmd_visual = false;
1817
1818void clear_showcmd(void)
1819{
1820  if (!p_sc) {
1821    return;
1822  }
1823
1824  if (Visual.active && !char_avail()) {
1825    bool cursor_bot = lt(Visual.start, curwin->w_cursor);
1826    int lines;
1827    colnr_T leftcol, rightcol;
1828    linenr_T top, bot;
1829
1830    // Show the size of the Visual area.
1831    if (cursor_bot) {
1832      top = Visual.start.lnum;
1833      bot = curwin->w_cursor.lnum;
1834    } else {
1835      top = curwin->w_cursor.lnum;
1836      bot = Visual.start.lnum;
1837    }
1838    // Include closed folds as a whole.
1839    hasFolding(curwin, top, &top, NULL);
1840    hasFolding(curwin, bot, NULL, &bot);
1841    lines = bot - top + 1;
1842
1843    if (Visual.mode == Ctrl_V) {
1844      char *const saved_sbr = p_sbr;
1845      char *const saved_w_sbr = curwin->w_p_sbr;
1846
1847      // Make 'sbr' empty for a moment to get the correct size.
1848      p_sbr = empty_string_option;
1849      curwin->w_p_sbr = empty_string_option;
1850      getvcols(curwin, &curwin->w_cursor, &Visual.start,
1851               &leftcol, &rightcol, GETVCOL_END_EXCL_LBR);
1852      p_sbr = saved_sbr;
1853      curwin->w_p_sbr = saved_w_sbr;
1854      snprintf(showcmd_buf, SHOWCMD_BUFLEN, "%" PRId64 "x%" PRId64,
1855               (int64_t)lines, (int64_t)rightcol - leftcol + 1);
1856    } else if (Visual.mode == 'V' || Visual.start.lnum != curwin->w_cursor.lnum) {
1857      snprintf(showcmd_buf, SHOWCMD_BUFLEN, "%" PRId64, (int64_t)lines);
1858    } else {
1859      char *s, *e;
1860      int bytes = 0;
1861      int chars = 0;
1862
1863      if (cursor_bot) {
1864        s = ml_get_pos(&Visual.start);
1865        e = get_cursor_pos_ptr();
1866      } else {
1867        s = get_cursor_pos_ptr();
1868        e = ml_get_pos(&Visual.start);
1869      }
1870      while ((*p_sel != 'e') ? s <= e : s < e) {
1871        int l = utfc_ptr2len(s);
1872        if (l == 0) {
1873          bytes++;
1874          chars++;
1875          break;            // end of line
1876        }
1877        bytes += l;
1878        chars++;
1879        s += l;
1880      }
1881      if (bytes == chars) {
1882        snprintf(showcmd_buf, SHOWCMD_BUFLEN, "%d", chars);
1883      } else {
1884        snprintf(showcmd_buf, SHOWCMD_BUFLEN, "%d-%d", chars, bytes);
1885      }
1886    }
1887    int limit = ui_has(kUIMessages) ? SHOWCMD_BUFLEN - 1 : SHOWCMD_COLS;
1888    showcmd_buf[limit] = NUL;  // truncate
1889    showcmd_visual = true;
1890  } else {
1891    showcmd_buf[0] = NUL;
1892    showcmd_visual = false;
1893
1894    // Don't actually display something if there is nothing to clear.
1895    if (showcmd_is_clear) {
1896      return;
1897    }
1898  }
1899
1900  display_showcmd();
1901}
1902
1903/// Add 'c' to string of shown command chars.
1904///
1905/// @return  true if output has been written (and setcursor() has been called).
1906bool add_to_showcmd(int c)
1907{
1908  static int ignore[] = {
1909    K_IGNORE,
1910    K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE, K_MOUSEMOVE,
1911    K_MIDDLEMOUSE, K_MIDDLEDRAG, K_MIDDLERELEASE,
1912    K_RIGHTMOUSE, K_RIGHTDRAG, K_RIGHTRELEASE,
1913    K_MOUSEDOWN, K_MOUSEUP, K_MOUSELEFT, K_MOUSERIGHT,
1914    K_X1MOUSE, K_X1DRAG, K_X1RELEASE, K_X2MOUSE, K_X2DRAG, K_X2RELEASE,
1915    K_EVENT, K_COMMAND, K_LUA,
1916    0
1917  };
1918
1919  // Not for stuffed (replay): "." executes as atomic unit; displaying the keys would churn
1920  // 'showcmd' mid-replay, redrawing transient states (e.g. selection of a replayed visual op).
1921  if (!p_sc || msg_silent != 0 || ex_normal_busy || KeyStuffed) {
1922    return false;
1923  }
1924
1925  if (showcmd_visual) {
1926    showcmd_buf[0] = NUL;
1927    showcmd_visual = false;
1928  }
1929
1930  // Ignore keys that are scrollbar updates and mouse clicks
1931  if (IS_SPECIAL(c)) {
1932    for (int i = 0; ignore[i] != 0; i++) {
1933      if (ignore[i] == c) {
1934        return false;
1935      }
1936    }
1937  }
1938
1939  char *p;
1940  char mbyte_buf[MB_MAXCHAR + 1];
1941  if (c <= 0x7f || !vim_isprintc(c)) {
1942    p = transchar(c);
1943    if (*p == ' ') {
1944      STRCPY(p, "<20>");
1945    }
1946  } else {
1947    mbyte_buf[utf_char2bytes(c, mbyte_buf)] = NUL;
1948    p = mbyte_buf;
1949  }
1950  size_t old_len = strlen(showcmd_buf);
1951  size_t extra_len = strlen(p);
1952  size_t limit = ui_has(kUIMessages) ? SHOWCMD_BUFLEN - 1 : SHOWCMD_COLS;
1953  if (old_len + extra_len > limit) {
1954    size_t overflow = old_len + extra_len - limit;
1955    memmove(showcmd_buf, showcmd_buf + overflow, old_len - overflow + 1);
1956  }
1957  strcat(showcmd_buf, p);
1958
1959  if (char_avail()) {
1960    return false;
1961  }
1962
1963  display_showcmd();
1964
1965  return true;
1966}
1967
1968void add_to_showcmd_c(int c)
1969{
1970  add_to_showcmd(c);
1971  setcursor();
1972}
1973
1974/// Delete 'len' characters from the end of the shown command.
1975static void del_from_showcmd(int len)
1976{
1977  if (!p_sc) {
1978    return;
1979  }
1980
1981  int old_len = (int)strlen(showcmd_buf);
1982  len = MIN(len, old_len);
1983  showcmd_buf[old_len - len] = NUL;
1984
1985  if (!char_avail()) {
1986    display_showcmd();
1987  }
1988}
1989
1990/// push_showcmd() and pop_showcmd() are used when waiting for the user to type
1991/// something and there is a partial mapping.
1992void push_showcmd(void)
1993{
1994  if (p_sc) {
1995    STRCPY(old_showcmd_buf, showcmd_buf);
1996  }
1997}
1998
1999void pop_showcmd(void)
2000{
2001  if (!p_sc) {
2002    return;
2003  }
2004
2005  STRCPY(showcmd_buf, old_showcmd_buf);
2006
2007  display_showcmd();
2008}
2009
2010void showcmd_update_clear_state(void)
2011{
2012  showcmd_is_clear = (showcmd_buf[0] == NUL);
2013}
2014
2015/// Displays 'showcmd' info, and a ("2×") hint if multicursor is active.
2016void display_showcmd(void)
2017{
2018  if (mc_replaying()) {
2019    return;  // Skip useless/broken redraws (n * cursors) during multicursor cascade.
2020  }
2021
2022  showcmd_update_clear_state();
2023
2024  if (*p_sloc == 's') {
2025    if (showcmd_is_clear && !vgetc_busy) {
2026      curwin->w_redr_status = true;
2027    } else {
2028      win_redr_status(curwin);
2029      setcursor();  // put cursor back where it belongs
2030    }
2031    return;
2032  }
2033  if (*p_sloc == 't') {
2034    if (showcmd_is_clear && !vgetc_busy) {
2035      redraw_tabline = true;
2036    } else {
2037      draw_tabline();
2038      setcursor();  // put cursor back where it belongs
2039    }
2040    return;
2041  }
2042  // 'showcmdloc' is "last" or empty
2043
2044  // Multicursor count prefixes the pending command: "2× ciw".
2045  char mc_buf[16];
2046  size_t mc_len = mc_showcmd(mc_buf, sizeof(mc_buf));
2047
2048  if (ui_has(kUIMessages)) {
2049    MAXSIZE_TEMP_ARRAY(content, 1);
2050    MAXSIZE_TEMP_ARRAY(chunk, 3);
2051    char ext_buf[sizeof(mc_buf) + SHOWCMD_BUFLEN];
2052    STRCPY(ext_buf, mc_buf);
2053    xstrlcpy(ext_buf + mc_len, showcmd_is_clear ? "" : showcmd_buf, sizeof(ext_buf) - mc_len);
2054    if (*ext_buf != NUL) {
2055      // placeholder for future highlight support
2056      ADD_C(chunk, INTEGER_OBJ(0));
2057      ADD_C(chunk, CSTR_AS_OBJ(ext_buf));
2058      ADD_C(chunk, INTEGER_OBJ(0));
2059      ADD_C(content, ARRAY_OBJ(chunk));
2060    }
2061    ui_call_msg_showcmd(content);
2062    return;
2063  }
2064  if (p_ch == 0) {
2065    return;
2066  }
2067
2068  msg_grid_validate();
2069  int showcmd_row = Rows - 1;
2070  grid_line_start(&msg_grid_adj, showcmd_row);
2071
2072  int len = mc_len > 0 ? grid_line_puts(sc_col, mc_buf, -1, 0) : 0;
2073  if (!showcmd_is_clear) {
2074    len += grid_line_puts(sc_col + len, showcmd_buf, -1, HL_ATTR(HLF_MSG));
2075  }
2076  // Clamp so the padding arithmetic below stays in bounds.
2077  len = MIN(len, (int)SHOWCMD_COLS);
2078
2079  // clear the rest of an old message by outputting up to SHOWCMD_COLS spaces
2080  grid_line_puts(sc_col + len, (char *)"          " + len, -1, HL_ATTR(HLF_MSG));
2081
2082  grid_line_flush();
2083}
2084
2085int get_vtopline(win_T *wp)
2086{
2087  return plines_m_win_fill(wp, 1, wp->w_topline) - wp->w_topfill;
2088}
2089
2090/// When "check" is false, prepare for commands that scroll the window.
2091/// When "check" is true, take care of scroll-binding after the window has
2092/// scrolled.  Called from normal_cmd() and edit().
2093void do_check_scrollbind(bool check)
2094{
2095  static win_T *old_curwin = NULL;
2096  static linenr_T old_vtopline = 0;
2097  static buf_T *old_buf = NULL;
2098  static colnr_T old_leftcol = 0;
2099
2100  int vtopline = get_vtopline(curwin);
2101
2102  if (check && curwin->w_p_scb) {
2103    // If a ":syncbind" command was just used, don't scroll, only reset
2104    // the values.
2105    if (did_syncbind) {
2106      did_syncbind = false;
2107    } else if (curwin == old_curwin) {
2108      // Synchronize other windows, as necessary according to
2109      // 'scrollbind'.  Don't do this after an ":edit" command, except
2110      // when 'diff' is set.
2111      if ((curwin->w_buffer == old_buf
2112           || curwin->w_p_diff
2113           )
2114          && (vtopline != old_vtopline
2115              || curwin->w_leftcol != old_leftcol)) {
2116        check_scrollbind(vtopline - old_vtopline, curwin->w_leftcol - old_leftcol);
2117      }
2118    } else if (vim_strchr(p_sbo, 'j')) {  // jump flag set in 'scrollopt'
2119      // When switching between windows, make sure that the relative
2120      // vertical offset is valid for the new window.  The relative
2121      // offset is invalid whenever another 'scrollbind' window has
2122      // scrolled to a point that would force the current window to
2123      // scroll past the beginning or end of its buffer.  When the
2124      // resync is performed, some of the other 'scrollbind' windows may
2125      // need to jump so that the current window's relative position is
2126      // visible on-screen.
2127      check_scrollbind(vtopline - curwin->w_scbind_pos, 0);
2128    }
2129    curwin->w_scbind_pos = vtopline;
2130  }
2131
2132  old_curwin = curwin;
2133  old_vtopline = vtopline;
2134  old_buf = curwin->w_buffer;
2135  old_leftcol = curwin->w_leftcol;
2136}
2137
2138/// Synchronize any windows that have "scrollbind" set, based on the
2139/// number of rows by which the current window has changed
2140/// (1998-11-02 16:21:01  R. Edward Ralston <eralston@computer.org>)
2141void check_scrollbind(linenr_T vtopline_diff, int leftcol_diff)
2142{
2143  win_T *old_curwin = curwin;
2144  buf_T *old_curbuf = curbuf;
2145  int old_VIsual_select = Visual.select;
2146  int old_VIsual_active = Visual.active;
2147  colnr_T tgt_leftcol = curwin->w_leftcol;
2148
2149  // check 'scrollopt' string for vertical and horizontal scroll options
2150  bool want_ver = old_curwin->w_p_diff
2151                  || (vim_strchr(p_sbo, 'v') && vtopline_diff != 0);
2152  bool want_hor = (vim_strchr(p_sbo, 'h') && (leftcol_diff || vtopline_diff != 0));
2153
2154  // loop through the scrollbound windows and scroll accordingly
2155  Visual.select = Visual.active = 0;
2156  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2157    curwin = wp;
2158    curbuf = curwin->w_buffer;
2159    // skip original window and windows with 'noscrollbind'
2160    if (curwin == old_curwin || !curwin->w_p_scb) {
2161      continue;
2162    }
2163
2164    // do the vertical scroll
2165    if (want_ver) {
2166      if (old_curwin->w_p_diff && curwin->w_p_diff) {
2167        diff_set_topline(old_curwin, curwin);
2168      } else {
2169        curwin->w_scbind_pos += vtopline_diff;
2170        int curr_vtopline = get_vtopline(curwin);
2171
2172        // Perf: reuse curr_vtopline to reduce the time in plines_m_win_fill().
2173        // Equivalent to:
2174        //   int max_vtopline = plines_m_win_fill(curwin, 1, curbuf->b_ml.ml_line_count);
2175        int max_vtopline = curr_vtopline + curwin->w_topfill
2176                           + plines_m_win_fill(curwin, curwin->w_topline + 1,
2177                                               curbuf->b_ml.ml_line_count);
2178
2179        int new_vtopline = MAX(MIN((linenr_T)curwin->w_scbind_pos, max_vtopline), 1);
2180
2181        int y = new_vtopline - curr_vtopline;
2182        if (y > 0) {
2183          scrollup(curwin, y, false);
2184        } else {
2185          scrolldown(curwin, -y, false);
2186        }
2187      }
2188
2189      redraw_later(curwin, UPD_VALID);
2190      cursor_correct(curwin);
2191      curwin->w_redr_status = true;
2192    }
2193
2194    // do the horizontal scroll
2195    if (want_hor) {
2196      set_leftcol(tgt_leftcol);
2197    }
2198  }
2199
2200  // reset current-window
2201  Visual.select = old_VIsual_select;
2202  Visual.active = old_VIsual_active;
2203  curwin = old_curwin;
2204  curbuf = old_curbuf;
2205}
2206
2207/// Command character that's ignored.
2208/// Used for CTRL-Q and CTRL-S to avoid problems with terminals that use
2209/// xon/xoff.
2210static void nv_ignore(cmdarg_T *cap)
2211{
2212  cap->retval |= CA_COMMAND_BUSY;       // don't call edit() now
2213}
2214
2215/// Command character that doesn't do anything, but unlike nv_ignore() does
2216/// start edit().  Used for "startinsert" executed while starting up.
2217static void nv_nop(cmdarg_T *cap)
2218{
2219}
2220
2221/// Command character doesn't exist.
2222static void nv_error(cmdarg_T *cap)
2223{
2224  clearopbeep(cap->oap);
2225}
2226
2227/// <Help> and <F1> commands.
2228static void nv_help(cmdarg_T *cap)
2229{
2230  if (!checkclearopq(cap->oap)) {
2231    ex_help(NULL);
2232  }
2233}
2234
2235/// CTRL-A and CTRL-X: Add or subtract from letter or number under cursor.
2236static void nv_addsub(cmdarg_T *cap)
2237{
2238  if (bt_prompt(curbuf) && !prompt_curpos_editable()) {
2239    clearopbeep(cap->oap);
2240  } else if (!Visual.active && cap->oap->op_type == OP_NOP) {
2241    prep_redo_cmd(cap);
2242    cap->oap->op_type = cap->cmdchar == Ctrl_A ? OP_NR_ADD : OP_NR_SUB;
2243    op_addsub(cap->oap, cap->count1, cap->arg);
2244    cap->oap->op_type = OP_NOP;
2245  } else if (Visual.active) {
2246    nv_operator(cap);
2247  } else {
2248    clearop(cap->oap);
2249  }
2250}
2251
2252/// CTRL-F, CTRL-B, etc: Scroll page up or down.
2253static void nv_page(cmdarg_T *cap)
2254{
2255  if (checkclearop(cap->oap)) {
2256    return;
2257  }
2258
2259  if (mod_mask & MOD_MASK_CTRL) {
2260    // <C-PageUp>: tab page back; <C-PageDown>: tab page forward
2261    if (cap->arg == BACKWARD) {
2262      goto_tabpage(-cap->count1);
2263    } else {
2264      goto_tabpage(cap->count0);
2265    }
2266  } else {
2267    pagescroll(cap->arg, cap->count1, false);
2268  }
2269}
2270
2271/// Implementation of "gd" and "gD" command.
2272///
2273/// @param thisblock  1 for "1gd" and "1gD"
2274static void nv_gd(oparg_T *oap, int nchar, int thisblock)
2275{
2276  size_t len;
2277  char *ptr;
2278  if ((len = find_ident_under_cursor(&ptr, FIND_IDENT, NULL)) == 0
2279      || !find_decl(ptr, len, nchar == 'd', thisblock, SEARCH_START)) {
2280    clearopbeep(oap);
2281    return;
2282  }
2283
2284  if ((fdo_flags & kOptFdoFlagSearch) && KeyTyped && oap->op_type == OP_NOP) {
2285    foldOpenCursor();
2286  }
2287  // clear any search statistics
2288  if (messaging() && !msg_silent && !shortmess(kShmSearchcount)) {
2289    clear_cmdline = true;
2290  }
2291}
2292
2293/// @return true if line[offset] is not inside a C-style comment or string,
2294///         false otherwise.
2295static bool is_ident(const char *line, int offset)
2296{
2297  bool incomment = false;
2298  int instring = 0;
2299  int prev = 0;
2300
2301  for (int i = 0; i < offset && line[i] != NUL; i++) {
2302    if (instring != 0) {
2303      if (prev != '\\' && (uint8_t)line[i] == instring) {
2304        instring = 0;
2305      }
2306    } else if ((line[i] == '"' || line[i] == '\'') && !incomment) {
2307      instring = (uint8_t)line[i];
2308    } else {
2309      if (incomment) {
2310        if (prev == '*' && line[i] == '/') {
2311          incomment = false;
2312        }
2313      } else if (prev == '/' && line[i] == '*') {
2314        incomment = true;
2315      } else if (prev == '/' && line[i] == '/') {
2316        return false;
2317      }
2318    }
2319
2320    prev = (uint8_t)line[i];
2321  }
2322
2323  return incomment == false && instring == 0;
2324}
2325
2326/// Search for variable declaration of "ptr[len]".
2327/// When "locally" is true in the current function ("gd"), otherwise in the
2328/// current file ("gD").
2329///
2330/// @param thisblock  when true check the {} block scope.
2331/// @param flags_arg  flags passed to searchit()
2332///
2333/// @return           fail when not found.
2334bool find_decl(char *ptr, size_t len, bool locally, bool thisblock, int flags_arg)
2335{
2336  pos_T par_pos;
2337  pos_T found_pos;
2338  bool t;
2339  bool retval = true;
2340  bool incll;
2341  int searchflags = flags_arg;
2342
2343  size_t patsize = len + 7;
2344  char *pat = xmalloc(patsize);
2345
2346  // Put "\V" before the pattern to avoid that the special meaning of "."
2347  // and "~" causes trouble.
2348  assert(patsize <= INT_MAX);
2349  size_t patlen = (size_t)snprintf(pat, patsize,
2350                                   vim_iswordp(ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s",
2351                                   (int)len, ptr);
2352  pos_T old_pos = curwin->w_cursor;
2353  bool save_p_ws = p_ws;
2354  bool save_p_scs = p_scs;
2355  p_ws = false;         // don't wrap around end of file now
2356  p_scs = false;        // don't switch ignorecase off now
2357
2358  // With "gD" go to line 1.
2359  // With "gd" Search back for the start of the current function, then go
2360  // back until a blank line.  If this fails go to line 1.
2361  if (!locally || !findpar(&incll, BACKWARD, 1, '{', false)) {
2362    setpcmark();                        // Set in findpar() otherwise
2363    curwin->w_cursor.lnum = 1;
2364    par_pos = curwin->w_cursor;
2365  } else {
2366    par_pos = curwin->w_cursor;
2367    while (curwin->w_cursor.lnum > 1
2368           && *skipwhite(get_cursor_line_ptr()) != NUL) {
2369      curwin->w_cursor.lnum--;
2370    }
2371  }
2372  curwin->w_cursor.col = 0;
2373
2374  // Search forward for the identifier, ignore comment lines.
2375  clearpos(&found_pos);
2376  while (true) {
2377    t = searchit(curwin, curbuf, &curwin->w_cursor, NULL, FORWARD,
2378                 pat, patlen, 1, searchflags, RE_LAST, false, NULL);
2379    if (curwin->w_cursor.lnum >= old_pos.lnum) {
2380      t = false;         // match after start is failure too
2381    }
2382
2383    if (thisblock && t != false) {
2384      const int64_t maxtravel = old_pos.lnum - curwin->w_cursor.lnum + 1;
2385      const pos_T *pos = findmatchlimit(NULL, '}', FM_FORWARD, maxtravel);
2386
2387      // Check that the block the match is in doesn't end before the
2388      // position where we started the search from.
2389      if (pos != NULL && pos->lnum < old_pos.lnum) {
2390        // There can't be a useful match before the end of this block.
2391        // Skip to the end
2392        curwin->w_cursor = *pos;
2393        continue;
2394      }
2395    }
2396
2397    if (t == false) {
2398      // If we previously found a valid position, use it.
2399      if (found_pos.lnum != 0) {
2400        curwin->w_cursor = found_pos;
2401        t = true;
2402      }
2403      break;
2404    }
2405    if (get_leader_len(get_cursor_line_ptr(), NULL, false, true) > 0) {
2406      // Ignore this line, continue at start of next line.
2407      curwin->w_cursor.lnum++;
2408      curwin->w_cursor.col = 0;
2409      continue;
2410    }
2411    bool valid = is_ident(get_cursor_line_ptr(), curwin->w_cursor.col);
2412
2413    // If the current position is not a valid identifier and a previous match is
2414    // present, favor that one instead.
2415    if (!valid && found_pos.lnum != 0) {
2416      curwin->w_cursor = found_pos;
2417      break;
2418    }
2419    // global search: use first match found
2420    if (valid && !locally) {
2421      break;
2422    }
2423    if (valid && curwin->w_cursor.lnum >= par_pos.lnum) {
2424      // If we previously found a valid position, use it.
2425      if (found_pos.lnum != 0) {
2426        curwin->w_cursor = found_pos;
2427      }
2428      break;
2429    }
2430
2431    // For finding a local variable and the match is before the "{" or
2432    // inside a comment, continue searching.  For K&R style function
2433    // declarations this skips the function header without types.
2434    if (!valid) {
2435      clearpos(&found_pos);
2436    } else {
2437      found_pos = curwin->w_cursor;
2438    }
2439    // Remove SEARCH_START from flags to avoid getting stuck at one position.
2440    searchflags &= ~SEARCH_START;
2441  }
2442
2443  if (t == false) {
2444    retval = false;
2445    curwin->w_cursor = old_pos;
2446  } else {
2447    curwin->w_set_curswant = true;
2448    // "n" searches forward now
2449    reset_search_dir();
2450  }
2451
2452  xfree(pat);
2453  p_ws = save_p_ws;
2454  p_scs = save_p_scs;
2455
2456  return retval;
2457}
2458
2459/// Move 'dist' lines in direction 'dir', counting lines by *screen*
2460/// lines rather than lines in the file.
2461/// 'dist' must be positive.
2462///
2463/// @return  true if able to move cursor, false otherwise.
2464bool nv_screengo(oparg_T *oap, int dir, int dist, bool skip_conceal)
2465{
2466  int linelen = linetabsize(curwin, curwin->w_cursor.lnum);
2467  bool retval = true;
2468  bool atend = false;
2469  int col_off1;                 // margin offset for first screen line
2470  int col_off2;                 // margin offset for wrapped screen line
2471  int width1;                   // text width for first screen line
2472  int width2;                   // text width for wrapped screen line
2473
2474  oap->motion_type = kMTCharWise;
2475  oap->inclusive = (curwin->w_curswant == MAXCOL);
2476
2477  col_off1 = win_col_off(curwin);
2478  col_off2 = col_off1 - win_col_off2(curwin);
2479  width1 = curwin->w_view_width - col_off1;
2480  width2 = curwin->w_view_width - col_off2;
2481
2482  if (width2 == 0) {
2483    width2 = 1;  // Avoid divide by zero.
2484  }
2485
2486  if (curwin->w_view_width != 0) {
2487    int n;
2488    // Instead of sticking at the last character of the buffer line we
2489    // try to stick in the last column of the screen.
2490    if (curwin->w_curswant == MAXCOL) {
2491      atend = true;
2492      validate_virtcol(curwin);
2493      if (width1 <= 0) {
2494        curwin->w_curswant = 0;
2495      } else {
2496        curwin->w_curswant = width1 - 1;
2497        if (curwin->w_virtcol > curwin->w_curswant) {
2498          curwin->w_curswant += ((curwin->w_virtcol
2499                                  - curwin->w_curswant -
2500                                  1) / width2 + 1) * width2;
2501        }
2502      }
2503    } else {
2504      if (linelen > width1) {
2505        n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1;
2506      } else {
2507        n = width1;
2508      }
2509      curwin->w_curswant = MIN(curwin->w_curswant, n - 1);
2510    }
2511
2512    while (dist--) {
2513      if (dir == BACKWARD) {
2514        if (curwin->w_curswant >= width1
2515            && !hasFolding(curwin, curwin->w_cursor.lnum, NULL, NULL)) {
2516          // Move back within the line. This can give a negative value
2517          // for w_curswant if width1 < width2 (with cpoptions+=n),
2518          // which will get clipped to column 0.
2519          curwin->w_curswant -= width2;
2520        } else {
2521          // to previous line
2522          if (curwin->w_cursor.lnum <= 1) {
2523            retval = false;
2524            break;
2525          }
2526          cursor_up_inner(curwin, 1, skip_conceal);
2527
2528          linelen = linetabsize(curwin, curwin->w_cursor.lnum);
2529          if (linelen > width1) {
2530            int w = (((linelen - width1 - 1) / width2) + 1) * width2;
2531            assert(w <= 0 || curwin->w_curswant <= INT_MAX - w);
2532            curwin->w_curswant += w;
2533          }
2534        }
2535      } else {  // dir == FORWARD
2536        if (linelen > width1) {
2537          n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1;
2538        } else {
2539          n = width1;
2540        }
2541        if (curwin->w_curswant + width2 < (colnr_T)n
2542            && !hasFolding(curwin, curwin->w_cursor.lnum, NULL, NULL)) {
2543          // move forward within line
2544          curwin->w_curswant += width2;
2545        } else {
2546          // to next line
2547          if (curwin->w_cursor.lnum >= curwin->w_buffer->b_ml.ml_line_count) {
2548            retval = false;
2549            break;
2550          }
2551          cursor_down_inner(curwin, 1, skip_conceal);
2552          curwin->w_curswant %= width2;
2553
2554          // Check if the cursor has moved below the number display
2555          // when width1 < width2 (with cpoptions+=n). Subtract width2
2556          // to get a negative value for w_curswant, which will get
2557          // clipped to column 0.
2558          if (curwin->w_curswant >= width1) {
2559            curwin->w_curswant -= width2;
2560          }
2561          linelen = linetabsize(curwin, curwin->w_cursor.lnum);
2562        }
2563      }
2564    }
2565  }
2566
2567  if (virtual_active(curwin) && atend) {
2568    coladvance(curwin, MAXCOL);
2569  } else {
2570    coladvance(curwin, curwin->w_curswant);
2571  }
2572
2573  if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) {
2574    // Check for landing on a character that got split at the end of the
2575    // last line.  We want to advance a screenline, not end up in the same
2576    // screenline or move two screenlines.
2577    validate_virtcol(curwin);
2578    colnr_T virtcol = curwin->w_virtcol;
2579    if (virtcol > (colnr_T)width1 && *get_showbreak_value(curwin) != NUL) {
2580      virtcol -= vim_strsize(get_showbreak_value(curwin));
2581    }
2582
2583    int c = utf_ptr2char(get_cursor_pos_ptr());
2584    if (dir == FORWARD && virtcol < curwin->w_curswant
2585        && (curwin->w_curswant <= (colnr_T)width1)
2586        && !vim_isprintc(c) && c > 255) {
2587      oneright();
2588    }
2589
2590    if (virtcol > curwin->w_curswant
2591        && (curwin->w_curswant < (colnr_T)width1
2592            ? (curwin->w_curswant > (colnr_T)width1 / 2)
2593            : ((curwin->w_curswant - width1) % width2
2594               > (colnr_T)width2 / 2))) {
2595      curwin->w_cursor.col--;
2596    }
2597  }
2598
2599  if (atend) {
2600    curwin->w_curswant = MAXCOL;            // stick in the last column
2601  }
2602  adjust_skipcol();
2603
2604  return retval;
2605}
2606
2607/// Handle CTRL-E and CTRL-Y commands: scroll a line up or down.
2608/// cap->arg must be true for CTRL-E.
2609void nv_scroll_line(cmdarg_T *cap)
2610{
2611  if (!checkclearop(cap->oap)) {
2612    scroll_redraw(cap->arg, cap->count1);
2613  }
2614}
2615
2616/// Get the count specified after a 'z' command. Only the 'z<CR>', 'zl', 'zh',
2617/// 'z<Left>', and 'z<Right>' commands accept a count after 'z'.
2618/// @return  true to process the 'z' command and false to skip it.
2619static bool nv_z_get_count(cmdarg_T *cap, int *nchar_arg)
2620{
2621  int nchar = *nchar_arg;
2622
2623  // "z123{nchar}": edit the count before obtaining {nchar}
2624  if (checkclearop(cap->oap)) {
2625    return false;
2626  }
2627  int n = nchar - '0';
2628
2629  while (true) {
2630    no_mapping++;
2631    allow_keys++;         // no mapping for nchar, but allow key codes
2632    nchar = plain_vgetc();
2633    LANGMAP_ADJUST(nchar, true);
2634    no_mapping--;
2635    allow_keys--;
2636    add_to_showcmd(nchar);
2637
2638    if (nchar == K_DEL || nchar == K_KDEL) {
2639      n /= 10;
2640    } else if (ascii_isdigit(nchar)) {
2641      if (vim_append_digit_int(&n, nchar - '0') == FAIL) {
2642        clearopbeep(cap->oap);
2643        break;
2644      }
2645    } else if (nchar == CAR) {
2646      win_setheight(n);
2647      break;
2648    } else if (nchar == 'l'
2649               || nchar == 'h'
2650               || nchar == K_LEFT
2651               || nchar == K_RIGHT) {
2652      cap->count1 = n ? n * cap->count1 : cap->count1;
2653      *nchar_arg = nchar;
2654      return true;
2655    } else {
2656      clearopbeep(cap->oap);
2657      break;
2658    }
2659  }
2660  cap->oap->op_type = OP_NOP;
2661  return false;
2662}
2663
2664/// "zug" and "zuw": undo "zg" and "zw"
2665/// "zg": add good word to word list
2666/// "zw": add wrong word to word list
2667/// "zG": add good word to temp word list
2668/// "zW": add wrong word to temp word list
2669static int nv_zg_zw(cmdarg_T *cap, int nchar)
2670{
2671  bool undo = false;
2672
2673  if (nchar == 'u') {
2674    no_mapping++;
2675    allow_keys++;               // no mapping for nchar, but allow key codes
2676    nchar = plain_vgetc();
2677    LANGMAP_ADJUST(nchar, true);
2678    no_mapping--;
2679    allow_keys--;
2680    add_to_showcmd(nchar);
2681
2682    if (vim_strchr("gGwW", nchar) == NULL) {
2683      clearopbeep(cap->oap);
2684      return OK;
2685    }
2686    undo = true;
2687  }
2688
2689  if (checkclearop(cap->oap)) {
2690    return OK;
2691  }
2692  char *ptr = NULL;
2693  size_t len;
2694  if (Visual.active && !get_visual_text(cap, &ptr, &len)) {
2695    return FAIL;
2696  }
2697  if (ptr == NULL) {
2698    pos_T pos = curwin->w_cursor;
2699
2700    // Find bad word under the cursor.  When 'spell' is
2701    // off this fails and find_ident_under_cursor() is
2702    // used below.
2703    emsg_off++;
2704    len = spell_move_to(curwin, FORWARD, SMT_ALL, true, NULL);
2705    emsg_off--;
2706    if (len != 0 && curwin->w_cursor.col <= pos.col) {
2707      ptr = ml_get_pos(&curwin->w_cursor);
2708    }
2709    curwin->w_cursor = pos;
2710  }
2711
2712  if (ptr == NULL && (len = find_ident_under_cursor(&ptr, FIND_IDENT, NULL)) == 0) {
2713    return FAIL;
2714  }
2715  assert(len <= INT_MAX);
2716  spell_add_word(ptr, (int)len,
2717                 nchar == 'w' || nchar == 'W' ? SPELL_ADD_BAD : SPELL_ADD_GOOD,
2718                 (nchar == 'G' || nchar == 'W') ? 0 : cap->count1,
2719                 undo);
2720
2721  return OK;
2722}
2723
2724/// Commands that start with "z".
2725static void nv_zet(cmdarg_T *cap)
2726{
2727  colnr_T col;
2728  int nchar = cap->nchar;
2729  OptInt foldlevel = -1;
2730  int foldenable = kNone;
2731
2732  int64_t siso = get_sidescrolloff_value(curwin);
2733
2734  if (ascii_isdigit(nchar) && !nv_z_get_count(cap, &nchar)) {
2735    return;
2736  }
2737
2738  // "zf" and "zF" are always an operator, "zd", "zo", "zO", "zc"
2739  // and "zC" only in Visual mode.  "zj" and "zk" are motion
2740  // commands.
2741  if (cap->nchar != 'f' && cap->nchar != 'F'
2742      && !(Visual.active && vim_strchr("dcCoO", cap->nchar))
2743      && cap->nchar != 'j' && cap->nchar != 'k'
2744      && checkclearop(cap->oap)) {
2745    return;
2746  }
2747
2748  // For "z+", "z<CR>", "zt", "z.", "zz", "z^", "z-", "zb":
2749  // If line number given, set cursor.
2750  if ((vim_strchr("+\r\nt.z^-b", nchar) != NULL)
2751      && cap->count0
2752      && cap->count0 != curwin->w_cursor.lnum) {
2753    setpcmark();
2754    if (cap->count0 > curbuf->b_ml.ml_line_count) {
2755      curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
2756    } else {
2757      curwin->w_cursor.lnum = cap->count0;
2758    }
2759    check_cursor_col(curwin);
2760  }
2761
2762  switch (nchar) {
2763  // "z+", "z<CR>" and "zt": put cursor at top of screen
2764  case '+':
2765    if (cap->count0 == 0) {
2766      // No count given: put cursor at the line below screen
2767      validate_botline_win(curwin);  // make sure w_botline is valid
2768      curwin->w_cursor.lnum = MIN(curwin->w_botline, curbuf->b_ml.ml_line_count);
2769    }
2770    FALLTHROUGH;
2771  case NL:
2772  case CAR:
2773  case K_KENTER:
2774    beginline(BL_WHITE | BL_FIX);
2775    FALLTHROUGH;
2776
2777  case 't':
2778    scroll_cursor_top(curwin, 0, true);
2779    redraw_later(curwin, UPD_VALID);
2780    set_fraction(curwin);
2781    break;
2782
2783  // "z." and "zz": put cursor in middle of screen
2784  case '.':
2785    beginline(BL_WHITE | BL_FIX);
2786    FALLTHROUGH;
2787
2788  case 'z':
2789    scroll_cursor_halfway(curwin, true, false);
2790    redraw_later(curwin, UPD_VALID);
2791    set_fraction(curwin);
2792    break;
2793
2794  // "z^", "z-" and "zb": put cursor at bottom of screen
2795  case '^':     // Strange Vi behavior: <count>z^ finds line at top of window
2796                // when <count> is at bottom of window, and puts that one at
2797                // bottom of window.
2798    if (cap->count0 != 0) {
2799      scroll_cursor_bot(curwin, 0, true);
2800      curwin->w_cursor.lnum = curwin->w_topline;
2801    } else if (curwin->w_topline == 1) {
2802      curwin->w_cursor.lnum = 1;
2803    } else {
2804      curwin->w_cursor.lnum = curwin->w_topline - 1;
2805    }
2806    FALLTHROUGH;
2807  case '-':
2808    beginline(BL_WHITE | BL_FIX);
2809    FALLTHROUGH;
2810
2811  case 'b':
2812    scroll_cursor_bot(curwin, 0, true);
2813    redraw_later(curwin, UPD_VALID);
2814    set_fraction(curwin);
2815    break;
2816
2817  // "zH" - scroll screen right half-page
2818  case 'H':
2819    cap->count1 *= curwin->w_view_width / 2;
2820    FALLTHROUGH;
2821
2822  // "zh" - scroll screen to the right
2823  case 'h':
2824  case K_LEFT:
2825    if (!curwin->w_p_wrap) {
2826      set_leftcol((colnr_T)cap->count1 > curwin->w_leftcol
2827                  ? 0 : curwin->w_leftcol - (colnr_T)cap->count1);
2828    }
2829    break;
2830
2831  // "zL" - scroll window left half-page
2832  case 'L':
2833    cap->count1 *= curwin->w_view_width / 2;
2834    FALLTHROUGH;
2835
2836  // "zl" - scroll window to the left if not wrapping
2837  case 'l':
2838  case K_RIGHT:
2839    if (!curwin->w_p_wrap) {
2840      set_leftcol(curwin->w_leftcol + (colnr_T)cap->count1);
2841    }
2842    break;
2843
2844  // "zs" - scroll screen, cursor at the start
2845  case 's':
2846    if (!curwin->w_p_wrap) {
2847      if (hasFolding(curwin, curwin->w_cursor.lnum, NULL, NULL)) {
2848        col = 0;                        // like the cursor is in col 0
2849      } else {
2850        getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL, 0);
2851      }
2852      if (col > siso) {
2853        col -= (int)siso;
2854      } else {
2855        col = 0;
2856      }
2857      if (curwin->w_leftcol != col) {
2858        curwin->w_leftcol = col;
2859        redraw_later(curwin, UPD_NOT_VALID);
2860      }
2861    }
2862    break;
2863
2864  // "ze" - scroll screen, cursor at the end
2865  case 'e':
2866    if (!curwin->w_p_wrap) {
2867      if (hasFolding(curwin, curwin->w_cursor.lnum, NULL, NULL)) {
2868        col = 0;                        // like the cursor is in col 0
2869      } else {
2870        getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col, 0);
2871      }
2872      int n = curwin->w_view_width - win_col_off(curwin);
2873      if (col + siso < n) {
2874        col = 0;
2875      } else if (siso - n < INT_MAX - col) {
2876        col = (int)(col + siso - n + 1);
2877      } else {
2878        col = INT_MAX;
2879      }
2880      if (curwin->w_leftcol != col) {
2881        curwin->w_leftcol = col;
2882        redraw_later(curwin, UPD_NOT_VALID);
2883      }
2884    }
2885    break;
2886
2887  // "zp", "zP" in block mode put without adding trailing spaces
2888  case 'P':
2889  case 'p':
2890    nv_put(cap);
2891    break;
2892  // "zy" Yank without trailing spaces
2893  case 'y':
2894    nv_operator(cap);
2895    break;
2896
2897  // "zq": place multicursor(s) at (repeated) motion.
2898  case 'q':
2899    if (reg_recording != 0 || reg_executing != 0) {
2900      // Not allowed while recording/executing a macro. |mcursor-limitations|
2901      clearopbeep(cap->oap);
2902      break;
2903    }
2904    mc_zq_start(cap);
2905    nv_operator(cap);
2906    break;
2907
2908  // "zF": create fold command
2909  // "zf": create fold operator
2910  case 'F':
2911  case 'f':
2912    if (foldManualAllowed(true)) {
2913      cap->nchar = 'f';
2914      nv_operator(cap);
2915      foldenable = true;
2916    } else {
2917      clearopbeep(cap->oap);
2918    }
2919    break;
2920
2921  // "zd": delete fold at cursor
2922  // "zD": delete fold at cursor recursively
2923  case 'd':
2924  case 'D':
2925    if (foldManualAllowed(false)) {
2926      if (Visual.active) {
2927        nv_operator(cap);
2928      } else {
2929        deleteFold(curwin, curwin->w_cursor.lnum,
2930                   curwin->w_cursor.lnum, nchar == 'D', false);
2931      }
2932    }
2933    break;
2934
2935  // "zE": erase all folds
2936  case 'E':
2937    if (foldmethodIsManual(curwin)) {
2938      clearFolding(curwin);
2939      changed_window_setting(curwin);
2940    } else if (foldmethodIsMarker(curwin)) {
2941      deleteFold(curwin, 1, curbuf->b_ml.ml_line_count, true, false);
2942    } else {
2943      emsg(_("E352: Cannot erase folds with current 'foldmethod'"));
2944    }
2945    break;
2946
2947  // "zn": fold none: reset 'foldenable'
2948  case 'n':
2949    foldenable = false;
2950    break;
2951
2952  // "zN": fold Normal: set 'foldenable'
2953  case 'N':
2954    foldenable = true;
2955    break;
2956
2957  // "zi": invert folding: toggle 'foldenable'
2958  case 'i':
2959    foldenable = !curwin->w_p_fen;
2960    break;
2961
2962  // "za": open closed fold or close open fold at cursor
2963  case 'a':
2964    if (hasFolding(curwin, curwin->w_cursor.lnum, NULL, NULL)) {
2965      openFold(curwin->w_cursor, cap->count1);
2966    } else {
2967      closeFold(curwin->w_cursor, cap->count1);
2968      foldenable = true;
2969    }
2970    break;
2971
2972  // "zA": open fold at cursor recursively
2973  case 'A':
2974    if (hasFolding(curwin, curwin->w_cursor.lnum, NULL, NULL)) {
2975      openFoldRecurse(curwin->w_cursor);
2976    } else {
2977      closeFoldRecurse(curwin->w_cursor);
2978      foldenable = true;
2979    }
2980    break;
2981
2982  // "zo": open fold at cursor or Visual area
2983  case 'o':
2984    if (Visual.active) {
2985      nv_operator(cap);
2986    } else {
2987      openFold(curwin->w_cursor, cap->count1);
2988    }
2989    break;
2990
2991  // "zO": open fold recursively
2992  case 'O':
2993    if (Visual.active) {
2994      nv_operator(cap);
2995    } else {
2996      openFoldRecurse(curwin->w_cursor);
2997    }
2998    break;
2999
3000  // "zc": close fold at cursor or Visual area
3001  case 'c':
3002    if (Visual.active) {
3003      nv_operator(cap);
3004    } else {
3005      closeFold(curwin->w_cursor, cap->count1);
3006    }
3007    foldenable = true;
3008    break;
3009
3010  // "zC": close fold recursively
3011  case 'C':
3012    if (Visual.active) {
3013      nv_operator(cap);
3014    } else {
3015      closeFoldRecurse(curwin->w_cursor);
3016    }
3017    foldenable = true;
3018    break;
3019
3020  // "zv": open folds at the cursor
3021  case 'v':
3022    foldOpenCursor();
3023    break;
3024
3025  // "zx": re-apply 'foldlevel' and open folds at the cursor
3026  case 'x':
3027    foldenable = true;
3028    curwin->w_foldinvalid = true;               // recompute folds
3029    foldlevel = curwin->w_p_fdl;                // re-apply even when unchanged
3030    break;
3031
3032  // "zX": undo manual opens/closes, re-apply 'foldlevel'
3033  case 'X':
3034    foldenable = true;
3035    curwin->w_foldinvalid = true;               // recompute folds
3036    foldlevel = curwin->w_p_fdl;                // re-apply even when unchanged
3037    break;
3038
3039  // "zm": fold more
3040  case 'm':
3041    foldlevel = MAX(curwin->w_p_fdl - cap->count1, 0);
3042    foldenable = true;
3043    break;
3044
3045  // "zM": close all folds
3046  case 'M':
3047    foldlevel = 0;
3048    foldenable = true;
3049    break;
3050
3051  // "zr": reduce folding
3052  case 'r': {
3053    const int depth = getDeepestNesting(curwin);
3054    OptInt level = MIN(curwin->w_p_fdl + cap->count1, depth);
3055    if (level != curwin->w_p_fdl) {
3056      foldlevel = level;
3057    }
3058    break;
3059  }
3060
3061  case 'R':     //  "zR": open all folds
3062    foldlevel = getDeepestNesting(curwin);
3063    break;
3064
3065  case 'j':     // "zj" move to next fold downwards
3066  case 'k':     // "zk" move to next fold upwards
3067    if (foldMoveTo(true, nchar == 'j' ? FORWARD : BACKWARD,
3068                   cap->count1) == false) {
3069      clearopbeep(cap->oap);
3070    }
3071    break;
3072
3073  case 'u':     // "zug" and "zuw": undo "zg" and "zw"
3074  case 'g':     // "zg": add good word to word list
3075  case 'w':     // "zw": add wrong word to word list
3076  case 'G':     // "zG": add good word to temp word list
3077  case 'W':     // "zW": add wrong word to temp word list
3078    if (nv_zg_zw(cap, nchar) == FAIL) {
3079      return;
3080    }
3081    break;
3082
3083  case '=':     // "z=": suggestions for a badly spelled word
3084    if (!checkclearop(cap->oap)) {
3085      spell_suggest(cap->count0);
3086    }
3087    break;
3088
3089  default:
3090    clearopbeep(cap->oap);
3091  }
3092
3093  // Use the same validation, redraw and synchronization as explicit option assignments.
3094  const handle_T win_handle = curwin->handle;
3095  const handle_T buf_handle = curbuf->handle;
3096  if (foldenable != kNone && foldenable != curwin->w_p_fen) {
3097    set_option_value(kOptFoldenable, BOOLEAN_OBJ(foldenable), OPT_LOCAL, true, NULL);
3098    if (curwin->handle != win_handle || curbuf->handle != buf_handle) {
3099      // OptionSet left the command's window or buffer; don't finish a pending fold there.
3100      clearop(cap->oap);
3101      return;
3102    }
3103  }
3104  // "zF" is like "zfzf": enable folding before counting lines.
3105  if (nchar == 'F' && cap->oap->op_type == OP_FOLD) {
3106    nv_operator(cap);
3107    finish_op = true;
3108  }
3109  if (foldlevel >= 0) {
3110    // Re-apply even an unchanged value to undo manual opens/closes.
3111    set_option_value(kOptFoldlevel, INTEGER_OBJ(foldlevel), OPT_LOCAL, true, NULL);
3112  }
3113  if (nchar == 'x' && curwin->handle == win_handle && curbuf->handle == buf_handle) {
3114    foldOpenCursor();
3115  }
3116}
3117
3118/// "Q" command: Toggles a multicursor at the cursor position ("1Q": add, "2Q": remove).
3119/// "{visual}Q": Places a multicursor on each selected line.
3120static void nv_Q(cmdarg_T *cap)
3121{
3122  if (reg_recording != 0 || reg_executing != 0 || (!Visual.active && cap->count0 > 2)) {
3123    // Not allowed while recording/executing a macro. |mcursor-limitations|
3124    vim_beep(0);
3125  } else if (!checkclearop(cap->oap)) {
3126    if (Visual.active) {
3127      do_cmdline_cmd("normal! zqj");  // |v_zq|: each line at the cursor column.
3128      mc_follow_set(kTrue);
3129    } else {
3130      mc_toggle(curbuf, curwin->w_cursor, true,
3131                cap->count0 == 0 ? kNone : cap->count0 == 1 ? kTrue : kFalse);
3132    }
3133  }
3134}
3135
3136/// Handle a ":" command and <Cmd> or Lua mappings.
3137static void nv_colon(cmdarg_T *cap)
3138{
3139  bool cmd_result;
3140  bool is_cmdkey = cap->cmdchar == K_COMMAND;
3141  bool is_lua = cap->cmdchar == K_LUA;
3142
3143  if (Visual.active && !is_cmdkey && !is_lua) {
3144    nv_operator(cap);
3145    return;
3146  }
3147
3148  if (cap->oap->op_type != OP_NOP) {
3149    // Using ":" as a movement is charwise exclusive.
3150    cap->oap->motion_type = kMTCharWise;
3151    cap->oap->inclusive = false;
3152  } else if (cap->count0 && !is_cmdkey && !is_lua) {
3153    // translate "count:" into ":.,.+(count - 1)"
3154    stuffcharReadbuff('.');
3155    if (cap->count0 > 1) {
3156      stuffReadbuff(",.+");
3157      stuffnumReadbuff(cap->count0 - 1);
3158    }
3159  }
3160
3161  if (KeyTyped) {
3162    msg_ext_set_trigger("typed_cmd");  // distinguish msg_show emitted for typed cmd
3163    compute_cmdrow();                  // when typing, don't type below an old message
3164  }
3165
3166  if (is_lua) {
3167    cmd_result = map_execute_lua(true, false);
3168  } else {
3169    // get a command line and execute it
3170    cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL,
3171                            cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0);
3172  }
3173  msg_ext_set_trigger("");
3174
3175  if (cmd_result == false) {
3176    // The Ex command failed, do not execute the operator.
3177    clearop(cap->oap);
3178  } else if (cap->oap->op_type != OP_NOP
3179             && (cap->oap->start.lnum > curbuf->b_ml.ml_line_count
3180                 || cap->oap->start.col > ml_get_len(cap->oap->start.lnum)
3181                 || did_emsg)) {
3182    // The start of the operator has become invalid by the Ex command.
3183    clearopbeep(cap->oap);
3184  }
3185}
3186
3187/// Handle CTRL-G command.
3188static void nv_ctrlg(cmdarg_T *cap)
3189{
3190  if (Visual.active) {  // toggle Selection/Visual mode
3191    Visual.select = !Visual.select;
3192    may_trigger_modechanged();
3193    showmode();
3194  } else if (!checkclearop(cap->oap)) {
3195    // print full name if count given or :cd used
3196    fileinfo(cap->count0, false, true);
3197  }
3198}
3199
3200/// Handle CTRL-H <Backspace> command.
3201static void nv_ctrlh(cmdarg_T *cap)
3202{
3203  if (Visual.active && Visual.select) {
3204    cap->cmdchar = 'x';         // BS key behaves like 'x' in Select mode
3205    v_visop(cap);
3206  } else {
3207    nv_left(cap);
3208  }
3209}
3210
3211/// CTRL-L: clear screen and redraw.
3212static void nv_clear(cmdarg_T *cap)
3213{
3214  if (checkclearop(cap->oap)) {
3215    return;
3216  }
3217
3218  // Clear all syntax states to force resyncing.
3219  syn_stack_free_all(curwin->w_s);
3220  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
3221    wp->w_s->b_syn_slow = false;
3222  }
3223  redraw_later(curwin, UPD_CLEAR);
3224}
3225
3226/// CTRL-O: In Select mode: switch to Visual mode for one command.
3227/// Otherwise: Go to older pcmark.
3228static void nv_ctrlo(cmdarg_T *cap)
3229{
3230  if (Visual.active && Visual.select) {
3231    Visual.select = false;
3232    may_trigger_modechanged();
3233    showmode();
3234    Visual.restart_select = 2;          // restart Select mode later
3235  } else {
3236    cap->count1 = -cap->count1;
3237    nv_pcmark(cap);
3238  }
3239}
3240
3241/// CTRL-^ command, short for ":e #".  Works even when the alternate buffer is
3242/// not named.
3243static void nv_hat(cmdarg_T *cap)
3244{
3245  if (!checkclearopq(cap->oap)) {
3246    buflist_getfile(cap->count0, 0,
3247                    GETF_SETMARK|GETF_ALT, false);
3248  }
3249}
3250
3251/// "Z" commands.
3252static void nv_Zet(cmdarg_T *cap)
3253{
3254  if (checkclearopq(cap->oap)) {
3255    return;
3256  }
3257
3258  switch (cap->nchar) {
3259  // "ZZ": equivalent to ":x".
3260  case 'Z':
3261    do_cmdline_cmd("x");
3262    break;
3263
3264  // "ZQ": equivalent to ":q!" (Elvis compatible).
3265  case 'Q':
3266    do_cmdline_cmd("q!");
3267    break;
3268
3269  // "ZR": restart. With count, does not restore session/check for changes.
3270  case 'R':
3271    if (cap->count0 >= 1 && cap->count0 <= 8) {
3272      do_cmdline_cmd("restart!");
3273    } else if (cap->count0 == 9) {
3274      do_cmdline_cmd("restart! +qall!");
3275    } else {
3276      do_cmdline_cmd("restart");
3277    }
3278    break;
3279
3280  default:
3281    clearopbeep(cap->oap);
3282  }
3283}
3284
3285/// Call nv_ident() as if "c1" was used, with "c2" as next character.
3286void do_nv_ident(int c1, int c2)
3287{
3288  oparg_T oa;
3289  cmdarg_T ca;
3290
3291  clear_oparg(&oa);
3292  CLEAR_FIELD(ca);
3293  ca.oap = &oa;
3294  ca.cmdchar = c1;
3295  ca.nchar = c2;
3296  nv_ident(&ca);
3297}
3298
3299/// Sets `buf` to the Ex command which will perform the "K" normal-mode command.
3300static size_t nv_K_getcmd(cmdarg_T *cap, char *kp, bool kp_help, bool kp_ex, char **ptr_arg,
3301                          size_t n, char *buf, size_t bufsize, size_t *buflen)
3302{
3303  if (kp_help) {
3304    // :help or :help!
3305    STRCPY(buf, "help! ");
3306    *buflen = STRLEN_LITERAL("help! ");
3307    return n;
3308  }
3309
3310  if (kp_ex) {
3311    *buflen = 0;
3312    // 'keywordprg' is an ex command
3313    *buflen = (size_t)snprintf(buf, bufsize, "%s ", kp);
3314    if (cap->count0 != 0) {  // Send the count to the ex command.
3315      *buflen += (size_t)snprintf(buf + *buflen, bufsize - *buflen,
3316                                  "%" PRId64 " ", (int64_t)cap->count0);
3317    }
3318    return n;
3319  }
3320
3321  char *ptr = *ptr_arg;
3322
3323  // An external command will probably use an argument starting
3324  // with "-" as an option.  To avoid trouble we skip the "-".
3325  while (*ptr == '-' && n > 0) {
3326    ptr++;
3327    n--;
3328  }
3329  if (n == 0) {
3330    // found dashes only
3331    emsg(_(e_noident));
3332    xfree(buf);
3333    *ptr_arg = ptr;
3334    return 0;
3335  }
3336
3337  // When a count is given, turn it into a range.  Is this
3338  // really what we want?
3339  bool isman = (strcmp(kp, "man") == 0);
3340  bool isman_s = (strcmp(kp, "man -s") == 0);
3341  if (cap->count0 != 0 && !(isman || isman_s)) {
3342    *buflen = (size_t)snprintf(buf, bufsize, ".,.+%" PRId64, (int64_t)(cap->count0 - 1));
3343  }
3344
3345  do_cmdline_cmd("tabnew");
3346  *buflen += (size_t)snprintf(buf + *buflen, bufsize - *buflen, "terminal ");
3347  if (cap->count0 == 0 && isman_s) {
3348    *buflen += (size_t)snprintf(buf + *buflen, bufsize - *buflen, "man ");
3349  } else {
3350    *buflen += (size_t)snprintf(buf + *buflen, bufsize - *buflen, "%s ", kp);
3351  }
3352  if (cap->count0 != 0 && (isman || isman_s)) {
3353    *buflen += (size_t)snprintf(buf + *buflen, bufsize - *buflen,
3354                                "%" PRId64 " ", (int64_t)cap->count0);
3355  }
3356
3357  *ptr_arg = ptr;
3358  return n;
3359}
3360
3361/// Handle the commands that use the word under the cursor.
3362/// [g] CTRL-]   :ta to current identifier
3363/// [g] 'K'      run program for current identifier
3364/// [g] '*'      / to current identifier or string
3365/// [g] '#'      ? to current identifier or string
3366///  g  ']'      :tselect for current identifier
3367static void nv_ident(cmdarg_T *cap)
3368{
3369  char *ptr = NULL;
3370  char *p;
3371  size_t n = 0;                 // init for GCC
3372  int cmdchar;
3373  bool g_cmd;                   // "g" command
3374  bool tag_cmd = false;
3375
3376  if (cap->cmdchar == 'g') {    // "g*", "g#", "g]" and "gCTRL-]"
3377    cmdchar = cap->nchar;
3378    g_cmd = true;
3379  } else {
3380    cmdchar = cap->cmdchar;
3381    g_cmd = false;
3382  }
3383
3384  if (cmdchar == POUND) {       // the pound sign, '#' for English keyboards
3385    cmdchar = '#';
3386  }
3387
3388  // The "]", "CTRL-]" and "K" commands accept an argument in Visual mode.
3389  bool visual_sel = false;
3390  if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K') {
3391    if (Visual.active && get_visual_text(cap, &ptr, &n) == false) {
3392      return;
3393    }
3394    visual_sel = (ptr != NULL);
3395    if (checkclearopq(cap->oap)) {
3396      return;
3397    }
3398  }
3399
3400  int ident_offset = 0;
3401  if (ptr == NULL && (n = find_ident_under_cursor(&ptr,
3402                                                  ((cmdchar == '*'
3403                                                    || cmdchar == '#')
3404                                                   ? FIND_IDENT|FIND_STRING
3405                                                   : FIND_IDENT), &ident_offset)) == 0) {
3406    clearop(cap->oap);
3407    return;
3408  }
3409
3410  // Allocate buffer to put the command in.  Inserting backslashes can
3411  // double the length of the word.  p_kp / curbuf->b_p_kp could be added
3412  // and some numbers.
3413  char *kp = *curbuf->b_p_kp == NUL ? p_kp : curbuf->b_p_kp;  // 'keywordprg'
3414  bool kp_helpbang = strequal(kp, ":help!");
3415  bool kp_help = kp_helpbang || *kp == NUL || strequal(kp, ":he") || strequal(kp, ":help");
3416  if (kp_help && !kp_helpbang && *skipwhite(ptr) == NUL) {
3417    emsg(_(e_noident));   // found white space only
3418    return;
3419  }
3420  bool kp_ex = (*kp == ':');  // 'keywordprg' is an ex command
3421  size_t bufsize = n * 2 + 30 + strlen(kp);
3422  char *buf = xmalloc(bufsize);
3423  buf[0] = NUL;
3424  size_t buflen = 0;
3425
3426  switch (cmdchar) {
3427  case '*':
3428  case '#':
3429    // Put cursor at start of word, makes search skip the word
3430    // under the cursor.
3431    // Call setpcmark() first, so "*``" puts the cursor back where
3432    // it was.
3433    setpcmark();
3434    curwin->w_cursor.col = (colnr_T)(ptr - get_cursor_line_ptr());
3435
3436    if (!g_cmd && vim_iswordp(ptr)) {
3437      STRCPY(buf, "\\<");
3438      buflen = STRLEN_LITERAL("\\<");
3439    }
3440    Search.no_smartcase = true;  // don't use 'smartcase' now
3441    break;
3442
3443  case 'K':
3444    n = nv_K_getcmd(cap, kp, kp_help, kp_ex, &ptr, n, buf, bufsize, &buflen);
3445    if (n == 0) {
3446      return;
3447    }
3448    break;
3449
3450  case ']':
3451    tag_cmd = true;
3452    STRCPY(buf, "tselect ");
3453    buflen = STRLEN_LITERAL("tselect ");
3454    break;
3455
3456  default:
3457    tag_cmd = true;
3458    if (curbuf->b_help) {
3459      STRCPY(buf, "help! ");
3460      buflen = STRLEN_LITERAL("help! ");
3461    } else {
3462      if (g_cmd) {
3463        STRCPY(buf, "tjump ");
3464        buflen = STRLEN_LITERAL("tjump ");
3465      } else if (cap->count0 == 0) {
3466        STRCPY(buf, "tag ");
3467        buflen = STRLEN_LITERAL("tag ");
3468      } else {
3469        buflen = (size_t)snprintf(buf, bufsize, ":%" PRId64 "tag ", (int64_t)cap->count0);
3470      }
3471    }
3472  }
3473
3474  // Get the identifier at cursor/selection and append to `buf` (to get ":foo <identifier").
3475  if (cmdchar == 'K' && kp_helpbang && !visual_sel) {
3476    // Special case: ":help!": Don't get the identifier, ex_help will get cWORD at cursor.
3477    // nv_K_getcmd already set `buf="help!"` so we don't need to do anything here.
3478    STRCPY(buf, "help!");
3479    buflen = STRLEN_LITERAL("help!");
3480  } else if (cmdchar == 'K' && !kp_help) {
3481    ptr = xstrnsave(ptr, n);
3482    if (kp_ex) {
3483      // Escape the argument properly for an Ex command
3484      p = vim_strsave_fnameescape(ptr, VSE_NONE);
3485    } else {
3486      // Escape the argument properly for a shell command
3487      p = vim_strsave_shellescape(ptr, true, true);
3488    }
3489    xfree(ptr);
3490    size_t plen = strlen(p);
3491    char *newbuf = xrealloc(buf, buflen + plen + 1);
3492    buf = newbuf;
3493    STRCPY(buf + buflen, p);
3494    buflen += plen;
3495    xfree(p);
3496  } else {
3497    char *aux_ptr;
3498    if (cmdchar == '*') {
3499      aux_ptr = (p_magic ? "/.*~[^$\\" : "/^$\\");
3500    } else if (cmdchar == '#') {
3501      aux_ptr = (p_magic ? "/?.*~[^$\\" : "/?^$\\");
3502    } else if (tag_cmd) {
3503      if (strcmp(curbuf->b_p_ft, "help") == 0) {
3504        // ":help" handles unescaped argument
3505        aux_ptr = "";
3506      } else {
3507        aux_ptr = "\\|\"\n[";
3508      }
3509    } else {
3510      aux_ptr = "\\|\"\n*?[";
3511    }
3512
3513    p = buf + buflen;
3514    // Escape various chars with a backslash "\".
3515    while (n-- > 0) {
3516      if (vim_strchr(aux_ptr, (uint8_t)(*ptr)) != NULL) {
3517        *p++ = '\\';
3518      }
3519
3520      // When current byte is a part of multibyte character, copy all
3521      // bytes of that character.
3522      const size_t len = (size_t)(utfc_ptr2len(ptr) - 1);
3523      for (size_t i = 0; i < len && n > 0; i++, n--) {
3524        *p++ = *ptr++;
3525      }
3526      *p++ = *ptr++;
3527    }
3528    *p = NUL;
3529    buflen = (size_t)(p - buf);
3530  }
3531
3532  // Execute the command.
3533  if (cmdchar == '*' || cmdchar == '#') {
3534    if (!g_cmd && vim_iswordp(mb_prevptr(get_cursor_line_ptr(), ptr))) {
3535      STRCPY(buf + buflen, "\\>");
3536      buflen += STRLEN_LITERAL("\\>");
3537    }
3538
3539    // put pattern in search history
3540    init_history();
3541    add_to_history(HIST_SEARCH, buf, buflen, true, NUL);
3542
3543    normal_search(cap, cmdchar == '*' ? '/' : '?', buf, buflen, 0, NULL);
3544  } else {
3545    g_tag_at_cursor = true;
3546    do_cmdline_cmd(buf);
3547    g_tag_at_cursor = false;
3548
3549    if (cmdchar == 'K' && !kp_ex && !kp_help) {
3550      // Start insert mode in terminal buffer
3551      restart_edit = 'i';
3552
3553      add_map("<esc>", "<Cmd>bdelete!<CR>", MODE_TERMINAL, true);
3554    }
3555  }
3556
3557  xfree(buf);
3558}
3559
3560/// Get visually selected text, within one line only.
3561///
3562/// @param pp    return: start of selected text
3563/// @param lenp  return: length of selected text
3564///
3565/// @return      false if more than one line selected.
3566bool get_visual_text(cmdarg_T *cap, char **pp, size_t *lenp)
3567{
3568  if (Visual.mode != 'V') {
3569    unadjust_for_sel();
3570  }
3571  if (Visual.start.lnum != curwin->w_cursor.lnum) {
3572    if (cap != NULL) {
3573      clearopbeep(cap->oap);
3574    }
3575    return false;
3576  }
3577  if (Visual.mode == 'V') {
3578    *pp = get_cursor_line_ptr();
3579    *lenp = (size_t)get_cursor_line_len();
3580  } else {
3581    if (lt(curwin->w_cursor, Visual.start)) {
3582      *pp = ml_get_pos(&curwin->w_cursor);
3583      *lenp = (size_t)Visual.start.col - (size_t)curwin->w_cursor.col + 1;
3584    } else {
3585      *pp = ml_get_pos(&Visual.start);
3586      *lenp = (size_t)curwin->w_cursor.col - (size_t)Visual.start.col + 1;
3587    }
3588    if (**pp == NUL) {
3589      *lenp = 0;
3590    }
3591    if (*lenp > 0) {
3592      // Correct the length to include all bytes of the last character.
3593      *lenp += (size_t)(utfc_ptr2len(*pp + (*lenp - 1)) - 1);
3594    }
3595  }
3596  reset_VIsual_and_resel();
3597  return true;
3598}
3599
3600/// CTRL-T: backwards in tag stack
3601static void nv_tagpop(cmdarg_T *cap)
3602{
3603  if (!checkclearopq(cap->oap)) {
3604    do_tag(NULL, "", DT_POP, cap->count1, false, true);
3605  }
3606}
3607
3608/// Handle scrolling command 'H', 'L' and 'M'.
3609static void nv_scroll(cmdarg_T *cap)
3610{
3611  int n;
3612  linenr_T lnum;
3613
3614  cap->oap->motion_type = kMTLineWise;
3615  setpcmark();
3616
3617  if (cap->cmdchar == 'L') {
3618    validate_botline_win(curwin);  // make sure curwin->w_botline is valid
3619    curwin->w_cursor.lnum = curwin->w_botline - 1;
3620    if (cap->count1 - 1 >= curwin->w_cursor.lnum) {
3621      curwin->w_cursor.lnum = 1;
3622    } else {
3623      if (win_lines_concealed(curwin)) {
3624        // Count a fold for one screen line.
3625        for (n = cap->count1 - 1; n > 0 && curwin->w_cursor.lnum > curwin->w_topline; n--) {
3626          hasFolding(curwin, curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL);
3627          n += decor_conceal_line(curwin, curwin->w_cursor.lnum, true);
3628          if (curwin->w_cursor.lnum > curwin->w_topline) {
3629            curwin->w_cursor.lnum--;
3630          }
3631        }
3632      } else {
3633        curwin->w_cursor.lnum -= cap->count1 - 1;
3634      }
3635    }
3636  } else {
3637    if (cap->cmdchar == 'M') {
3638      int used = 0;
3639      // Don't count filler lines above the window.
3640      used -= win_get_fill(curwin, curwin->w_topline) - curwin->w_topfill;
3641      validate_botline_win(curwin);  // make sure w_empty_rows is valid
3642      int half = (curwin->w_view_height - curwin->w_empty_rows + 1) / 2;
3643      for (n = 0; curwin->w_topline + n < curbuf->b_ml.ml_line_count; n++) {
3644        // Count half the number of filler lines to be "below this
3645        // line" and half to be "above the next line".
3646        if (n > 0 && used + win_get_fill(curwin, curwin->w_topline + n) / 2 >= half) {
3647          n--;
3648          break;
3649        }
3650        used += plines_win(curwin, curwin->w_topline + n, true);
3651        if (used >= half) {
3652          break;
3653        }
3654        if (hasFolding(curwin, curwin->w_topline + n, NULL, &lnum)) {
3655          n = lnum - curwin->w_topline;
3656        }
3657      }
3658      if (n > 0 && used > curwin->w_view_height) {
3659        n--;
3660      }
3661    } else {  // (cap->cmdchar == 'H')
3662      n = cap->count1 - 1;
3663      if (win_lines_concealed(curwin)) {
3664        // Count a fold for one screen line.
3665        lnum = curwin->w_topline;
3666        while ((decor_conceal_line(curwin, lnum - 1, true) || n-- > 0)
3667               && lnum < curwin->w_botline - 1) {
3668          hasFolding(curwin, lnum, NULL, &lnum);
3669          lnum++;
3670        }
3671        n = lnum - curwin->w_topline;
3672      }
3673    }
3674    curwin->w_cursor.lnum = MIN(curwin->w_topline + n, curbuf->b_ml.ml_line_count);
3675  }
3676
3677  // Correct for 'so', except when an operator is pending.
3678  if (cap->oap->op_type == OP_NOP) {
3679    cursor_correct(curwin);
3680  }
3681  beginline(BL_SOL | BL_FIX);
3682}
3683
3684/// Cursor right commands.
3685static void nv_right(cmdarg_T *cap)
3686{
3687  int n;
3688
3689  if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) {
3690    // <C-Right> and <S-Right> move a word or WORD right
3691    if (mod_mask & MOD_MASK_CTRL) {
3692      cap->arg = true;
3693    }
3694    nv_wordcmd(cap);
3695    return;
3696  }
3697
3698  cap->oap->motion_type = kMTCharWise;
3699  cap->oap->inclusive = false;
3700  bool past_line = (Visual.active && *p_sel != 'o');
3701
3702  // In virtual edit mode, there's no such thing as "past_line", as lines
3703  // are (theoretically) infinitely long.
3704  if (virtual_active(curwin)) {
3705    past_line = false;
3706  }
3707
3708  for (n = cap->count1; n > 0; n--) {
3709    if ((!past_line && oneright() == false)
3710        || (past_line && *get_cursor_pos_ptr() == NUL)) {
3711      //    <Space> wraps to next line if 'whichwrap' has 's'.
3712      //        'l' wraps to next line if 'whichwrap' has 'l'.
3713      // CURS_RIGHT wraps to next line if 'whichwrap' has '>'.
3714      if (((cap->cmdchar == ' ' && vim_strchr(p_ww, 's') != NULL)
3715           || (cap->cmdchar == 'l' && vim_strchr(p_ww, 'l') != NULL)
3716           || (cap->cmdchar == K_RIGHT && vim_strchr(p_ww, '>') != NULL))
3717          && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
3718        // When deleting we also count the NL as a character.
3719        // Set cap->oap->inclusive when last char in the line is
3720        // included, move to next line after that
3721        if (cap->oap->op_type != OP_NOP
3722            && !cap->oap->inclusive
3723            && !LINEEMPTY(curwin->w_cursor.lnum)) {
3724          cap->oap->inclusive = true;
3725        } else {
3726          curwin->w_cursor.lnum++;
3727          curwin->w_cursor.col = 0;
3728          curwin->w_cursor.coladd = 0;
3729          curwin->w_set_curswant = true;
3730          cap->oap->inclusive = false;
3731        }
3732        continue;
3733      }
3734      if (cap->oap->op_type == OP_NOP) {
3735        // Only beep and flush if not moved at all
3736        if (n == cap->count1) {
3737          beep_flush();
3738        }
3739      } else {
3740        if (!LINEEMPTY(curwin->w_cursor.lnum)) {
3741          cap->oap->inclusive = true;
3742        }
3743      }
3744      break;
3745    } else if (past_line) {
3746      curwin->w_set_curswant = true;
3747      if (virtual_active(curwin)) {
3748        oneright();
3749      } else {
3750        curwin->w_cursor.col += utfc_ptr2len(get_cursor_pos_ptr());
3751      }
3752    }
3753  }
3754  if (n != cap->count1 && (fdo_flags & kOptFdoFlagHor) && KeyTyped
3755      && cap->oap->op_type == OP_NOP) {
3756    foldOpenCursor();
3757  }
3758}
3759
3760/// Cursor left commands.
3761///
3762/// @return  true when operator end should not be adjusted.
3763static void nv_left(cmdarg_T *cap)
3764{
3765  int n;
3766
3767  if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)) {
3768    // <C-Left> and <S-Left> move a word or WORD left
3769    if (mod_mask & MOD_MASK_CTRL) {
3770      cap->arg = 1;
3771    }
3772    nv_bck_word(cap);
3773    return;
3774  }
3775
3776  cap->oap->motion_type = kMTCharWise;
3777  cap->oap->inclusive = false;
3778  for (n = cap->count1; n > 0; n--) {
3779    if (oneleft() == false) {
3780      // <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'.
3781      //                 'h' wraps to previous line if 'whichwrap' has 'h'.
3782      //           CURS_LEFT wraps to previous line if 'whichwrap' has '<'.
3783      if ((((cap->cmdchar == K_BS || cap->cmdchar == Ctrl_H)
3784            && vim_strchr(p_ww, 'b') != NULL)
3785           || (cap->cmdchar == 'h' && vim_strchr(p_ww, 'h') != NULL)
3786           || (cap->cmdchar == K_LEFT && vim_strchr(p_ww, '<') != NULL))
3787          && curwin->w_cursor.lnum > 1) {
3788        curwin->w_cursor.lnum--;
3789        coladvance(curwin, MAXCOL);
3790        curwin->w_set_curswant = true;
3791
3792        // When the NL before the first char has to be deleted we
3793        // put the cursor on the NUL after the previous line.
3794        // This is a very special case, be careful!
3795        // Don't adjust op_end now, otherwise it won't work.
3796        if ((cap->oap->op_type == OP_DELETE || cap->oap->op_type == OP_CHANGE)
3797            && !LINEEMPTY(curwin->w_cursor.lnum)) {
3798          char *cp = get_cursor_pos_ptr();
3799
3800          if (*cp != NUL) {
3801            curwin->w_cursor.col += utfc_ptr2len(cp);
3802          }
3803          cap->retval |= CA_NO_ADJ_OP_END;
3804        }
3805        continue;
3806      } else if (cap->oap->op_type == OP_NOP && n == cap->count1) {
3807        // Only beep and flush if not moved at all
3808        beep_flush();
3809      }
3810      break;
3811    }
3812  }
3813  if (n != cap->count1 && (fdo_flags & kOptFdoFlagHor) && KeyTyped
3814      && cap->oap->op_type == OP_NOP) {
3815    foldOpenCursor();
3816  }
3817}
3818
3819/// Cursor up commands.
3820/// cap->arg is true for "-": Move cursor to first non-blank.
3821static void nv_up(cmdarg_T *cap)
3822{
3823  if (mod_mask & MOD_MASK_SHIFT) {
3824    // <S-Up> is page up
3825    cap->arg = BACKWARD;
3826    nv_page(cap);
3827    return;
3828  }
3829
3830  cap->oap->motion_type = kMTLineWise;
3831  if (cursor_up(cap->count1, cap->oap->op_type == OP_NOP) == false) {
3832    clearopbeep(cap->oap);
3833  } else if (cap->arg) {
3834    beginline(BL_WHITE | BL_FIX);
3835  }
3836}
3837
3838/// Cursor down commands.
3839/// cap->arg is true for CR and "+": Move cursor to first non-blank.
3840static void nv_down(cmdarg_T *cap)
3841{
3842  if (mod_mask & MOD_MASK_SHIFT) {
3843    // <S-Down> is page down
3844    cap->arg = FORWARD;
3845    nv_page(cap);
3846  } else if (bt_cmdwin(curbuf) && cap->cmdchar == CAR) {
3847    // cmdwin: execute the command-line under the cursor.
3848    cmdwin_do_action("confirm");
3849  } else if (bt_quickfix(curbuf) && cap->cmdchar == CAR) {
3850    // Quickfix window: view the result under the cursor.
3851    qf_view_result(false);
3852  } else {
3853    if (bt_prompt(curbuf) && cap->cmdchar == CAR
3854        && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) {
3855      // In a prompt buffer a <CR> in the last line invokes the callback.
3856      prompt_invoke_callback();
3857      if (restart_edit == 0) {
3858        restart_edit = 'a';
3859      }
3860    } else {
3861      cap->oap->motion_type = kMTLineWise;
3862      if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == false) {
3863        clearopbeep(cap->oap);
3864      } else if (cap->arg) {
3865        beginline(BL_WHITE | BL_FIX);
3866      }
3867    }
3868  }
3869}
3870
3871/// Grab the file name under the cursor and edit it.
3872static void nv_gotofile(cmdarg_T *cap)
3873{
3874  linenr_T lnum = -1;
3875
3876  if (check_text_or_curbuf_locked(cap->oap)) {
3877    return;
3878  }
3879
3880  if (!check_can_set_curbuf_disabled()) {
3881    return;
3882  }
3883
3884  char *ptr = grab_file_name(cap->count1, &lnum);
3885
3886  if (ptr != NULL) {
3887    // do autowrite if necessary
3888    if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !buf_hide(curbuf)) {
3889      autowrite(curbuf, false);
3890    }
3891    setpcmark();
3892    if (do_ecmd(0, ptr, NULL, NULL, ECMD_LAST,
3893                buf_hide(curbuf) ? ECMD_HIDE : 0, curwin) == OK
3894        && cap->nchar == 'F' && lnum >= 0) {
3895      curwin->w_cursor.lnum = lnum;
3896      check_cursor_lnum(curwin);
3897      beginline(BL_SOL | BL_FIX);
3898    }
3899    xfree(ptr);
3900  } else {
3901    clearop(cap->oap);
3902  }
3903}
3904
3905/// <End> command: to end of current line or last line.
3906static void nv_end(cmdarg_T *cap)
3907{
3908  if (cap->arg || (mod_mask & MOD_MASK_CTRL)) {  // CTRL-END = goto last line
3909    cap->arg = true;
3910    nv_goto(cap);
3911    cap->count1 = 1;                    // to end of current line
3912  }
3913  nv_dollar(cap);
3914}
3915
3916/// Handle the "$" command.
3917static void nv_dollar(cmdarg_T *cap)
3918{
3919  cap->oap->motion_type = kMTCharWise;
3920  cap->oap->inclusive = true;
3921  // In virtual mode when off the edge of a line and an operator
3922  // is pending (whew!) keep the cursor where it is.
3923  // Otherwise, send it to the end of the line.
3924  if (!virtual_active(curwin) || gchar_cursor() != NUL
3925      || cap->oap->op_type == OP_NOP) {
3926    curwin->w_curswant = MAXCOL;        // so we stay at the end
3927  }
3928  if (cursor_down(cap->count1 - 1,
3929                  cap->oap->op_type == OP_NOP) == false) {
3930    clearopbeep(cap->oap);
3931  } else if ((fdo_flags & kOptFdoFlagHor) && KeyTyped && cap->oap->op_type == OP_NOP) {
3932    foldOpenCursor();
3933  }
3934}
3935
3936/// Implementation of '?' and '/' commands.
3937/// If cap->arg is true don't set PC mark.
3938static void nv_search(cmdarg_T *cap)
3939{
3940  oparg_T *oap = cap->oap;
3941  pos_T save_cursor = curwin->w_cursor;
3942
3943  if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13) {
3944    // Translate "g??" to "g?g?"
3945    cap->cmdchar = 'g';
3946    cap->nchar = '?';
3947    nv_operator(cap);
3948    return;
3949  }
3950
3951  // When using 'incsearch' the cursor may be moved to set a different search
3952  // start position.
3953  cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0, true);
3954
3955  if (cap->searchbuf == NULL) {
3956    clearop(oap);
3957    return;
3958  }
3959
3960  normal_search(cap, cap->cmdchar, cap->searchbuf, strlen(cap->searchbuf),
3961                (cap->arg || !equalpos(save_cursor, curwin->w_cursor))
3962                ? 0 : SEARCH_MARK, NULL);
3963}
3964
3965/// Handle "N" and "n" commands.
3966/// cap->arg is SEARCH_REV for "N", 0 for "n".
3967static void nv_next(cmdarg_T *cap)
3968{
3969  pos_T old = curwin->w_cursor;
3970  int wrapped = false;
3971  int i = normal_search(cap, 0, NULL, 0, SEARCH_MARK | cap->arg, &wrapped);
3972
3973  if (i == 1 && !wrapped && equalpos(old, curwin->w_cursor)) {
3974    // Avoid getting stuck on the current cursor position, which can happen when
3975    // an offset is given and the cursor is on the last char in the buffer:
3976    // Repeat with count + 1.
3977    cap->count1 += 1;
3978    normal_search(cap, 0, NULL, 0, SEARCH_MARK | cap->arg, NULL);
3979    cap->count1 -= 1;
3980  }
3981
3982  // Redraw the window to refresh the highlighted matches.
3983  if (i > 0 && p_hls && !Search.no_hlsearch
3984      && win_hl_attr(curwin, HLF_LC) != win_hl_attr(curwin, HLF_L)) {
3985    redraw_later(curwin, UPD_SOME_VALID);
3986  }
3987}
3988
3989/// Search for "pat" in direction "dir" ('/' or '?', 0 for repeat).
3990/// Uses only cap->count1 and cap->oap from "cap".
3991///
3992/// @param opt  extra flags for do_search()
3993///
3994/// @return 0 for failure, 1 for found, 2 for found and line offset added.
3995static int normal_search(cmdarg_T *cap, int dir, char *pat, size_t patlen, int opt, int *wrapped)
3996{
3997  searchit_arg_T sia;
3998  pos_T const prev_cursor = curwin->w_cursor;
3999
4000  cap->oap->motion_type = kMTCharWise;
4001  cap->oap->inclusive = false;
4002  cap->oap->use_reg_one = true;
4003  curwin->w_set_curswant = true;
4004
4005  CLEAR_FIELD(sia);
4006  int i = do_search(cap->oap, dir, dir, pat, patlen, cap->count1,
4007                    opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, p_magic, &sia);
4008  if (wrapped != NULL) {
4009    *wrapped = sia.sa_wrapped;
4010  }
4011  if (i == 0) {
4012    clearop(cap->oap);
4013  } else {
4014    if (i == 2) {
4015      cap->oap->motion_type = kMTLineWise;
4016    }
4017    curwin->w_cursor.coladd = 0;
4018    if (cap->oap->op_type == OP_NOP && (fdo_flags & kOptFdoFlagSearch) && KeyTyped) {
4019      foldOpenCursor();
4020    }
4021  }
4022  // Redraw the window to refresh the highlighted matches.
4023  if (!equalpos(curwin->w_cursor, prev_cursor) && p_hls && !Search.no_hlsearch
4024      && win_hl_attr(curwin, HLF_LC) != win_hl_attr(curwin, HLF_L)) {
4025    redraw_later(curwin, UPD_SOME_VALID);
4026  }
4027
4028  // "/$" will put the cursor after the end of the line, may need to
4029  // correct that here
4030  check_cursor(curwin);
4031
4032  return i;
4033}
4034
4035/// Character search commands.
4036/// cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', true for
4037/// ',' and false for ';'.
4038/// cap->nchar is NUL for ',' and ';' (repeat the search)
4039static void nv_csearch(cmdarg_T *cap)
4040{
4041  bool cursor_dec = false;
4042
4043  // If adjusted cursor position previously, unadjust it.
4044  if (*p_sel == 'e' && Visual.active && Visual.mode == 'v'
4045      && Visual.select_exclu_adj) {
4046    unadjust_for_sel();
4047    cursor_dec = true;
4048  }
4049
4050  bool t_cmd = cap->cmdchar == 't' || cap->cmdchar == 'T';
4051
4052  cap->oap->motion_type = kMTCharWise;
4053  if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == false) {
4054    clearopbeep(cap->oap);
4055    // Revert unadjust when failed.
4056    if (cursor_dec) {
4057      adjust_for_sel(cap);
4058    }
4059    return;
4060  }
4061
4062  curwin->w_set_curswant = true;
4063  // Include a Tab for "tx" and for "dfx".
4064  if (gchar_cursor() == TAB && virtual_active(curwin) && cap->arg == FORWARD
4065      && (t_cmd || cap->oap->op_type != OP_NOP)) {
4066    colnr_T scol, ecol;
4067
4068    getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol, 0);
4069    curwin->w_cursor.coladd = ecol - scol;
4070  } else {
4071    curwin->w_cursor.coladd = 0;
4072  }
4073  adjust_for_sel(cap);
4074  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped && cap->oap->op_type == OP_NOP) {
4075    foldOpenCursor();
4076  }
4077}
4078
4079/// "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')'
4080/// "[#", "]#": go to start/end of Nth innermost #if..#endif construct.
4081/// "[/", "[*", "]/", "]*": go to Nth comment start/end.
4082/// "[m" or "]m" search for prev/next start of (Java) method.
4083/// "[M" or "]M" search for prev/next end of (Java) method.
4084static void nv_bracket_block(cmdarg_T *cap, const pos_T *old_pos)
4085{
4086  pos_T new_pos = { 0, 0, 0 };
4087  pos_T *pos = NULL;  // init for GCC
4088  pos_T prev_pos;
4089  int n;
4090  int findc;
4091
4092  if (cap->nchar == '*') {
4093    cap->nchar = '/';
4094  }
4095  prev_pos.lnum = 0;
4096  if (cap->nchar == 'm' || cap->nchar == 'M') {
4097    if (cap->cmdchar == '[') {
4098      findc = '{';
4099    } else {
4100      findc = '}';
4101    }
4102    n = 9999;
4103  } else {
4104    findc = cap->nchar;
4105    n = cap->count1;
4106  }
4107  for (; n > 0; n--) {
4108    if ((pos = findmatchlimit(cap->oap, findc,
4109                              (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL) {
4110      if (new_pos.lnum == 0) {        // nothing found
4111        if (cap->nchar != 'm' && cap->nchar != 'M') {
4112          clearopbeep(cap->oap);
4113        }
4114      } else {
4115        pos = &new_pos;               // use last one found
4116      }
4117      break;
4118    }
4119    prev_pos = new_pos;
4120    curwin->w_cursor = *pos;
4121    new_pos = *pos;
4122  }
4123  curwin->w_cursor = *old_pos;
4124
4125  // Handle "[m", "]m", "[M" and "[M".  The findmatchlimit() only
4126  // brought us to the match for "[m" and "]M" when inside a method.
4127  // Try finding the '{' or '}' we want to be at.
4128  // Also repeat for the given count.
4129  if (cap->nchar == 'm' || cap->nchar == 'M') {
4130    int c;
4131    // norm is true for "]M" and "[m"
4132    bool norm = ((findc == '{') == (cap->nchar == 'm'));
4133
4134    n = cap->count1;
4135    // found a match: we were inside a method
4136    if (prev_pos.lnum != 0) {
4137      pos = &prev_pos;
4138      curwin->w_cursor = prev_pos;
4139      if (norm) {
4140        n--;
4141      }
4142    } else {
4143      pos = NULL;
4144    }
4145    while (n > 0) {
4146      while (true) {
4147        if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0) {
4148          // if not found anything, that's an error
4149          if (pos == NULL) {
4150            clearopbeep(cap->oap);
4151          }
4152          n = 0;
4153          break;
4154        }
4155        c = gchar_cursor();
4156        if (c == '{' || c == '}') {
4157          // Must have found end/start of class: use it.
4158          // Or found the place to be at.
4159          if ((c == findc && norm) || (n == 1 && !norm)) {
4160            new_pos = curwin->w_cursor;
4161            pos = &new_pos;
4162            n = 0;
4163          } else if (new_pos.lnum == 0) {
4164            // if no match found at all, we started outside of the
4165            // class and we're inside now.  Just go on.
4166            new_pos = curwin->w_cursor;
4167            pos = &new_pos;
4168          } else if ((pos = findmatchlimit(cap->oap, findc,
4169                                           (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD,
4170                                           0)) == NULL) {
4171            // found start/end of other method: go to match
4172            n = 0;
4173          } else {
4174            curwin->w_cursor = *pos;
4175          }
4176          break;
4177        }
4178      }
4179      n--;
4180    }
4181    curwin->w_cursor = *old_pos;
4182    if (pos == NULL && new_pos.lnum != 0) {
4183      clearopbeep(cap->oap);
4184    }
4185  }
4186  if (pos != NULL) {
4187    setpcmark();
4188    curwin->w_cursor = *pos;
4189    curwin->w_set_curswant = true;
4190    if ((fdo_flags & kOptFdoFlagBlock) && KeyTyped
4191        && cap->oap->op_type == OP_NOP) {
4192      foldOpenCursor();
4193    }
4194  }
4195}
4196
4197/// "[" and "]" commands.
4198/// cap->arg is BACKWARD for "[" and FORWARD for "]".
4199static void nv_brackets(cmdarg_T *cap)
4200{
4201  int flag;
4202  int n;
4203
4204  cap->oap->motion_type = kMTCharWise;
4205  cap->oap->inclusive = false;
4206  pos_T old_pos = curwin->w_cursor;         // cursor position before command
4207  curwin->w_cursor.coladd = 0;              // TODO(Unknown): don't do this for an error.
4208
4209  // "[f" or "]f" : Edit file under the cursor (same as "gf")
4210  if (cap->nchar == 'f') {
4211    nv_gotofile(cap);
4212  } else if (vim_strchr("iI\011dD\004", cap->nchar) != NULL) {
4213    // Find the occurrence(s) of the identifier or define under cursor
4214    // in current and included files or jump to the first occurrence.
4215    //
4216    //                    search       list           jump
4217    //                  fwd   bwd    fwd   bwd     fwd    bwd
4218    // identifier       "]i"  "[i"   "]I"  "[I"   "]^I"  "[^I"
4219    // define           "]d"  "[d"   "]D"  "[D"   "]^D"  "[^D"
4220    char *ptr;
4221    size_t len;
4222
4223    if ((len = find_ident_under_cursor(&ptr, FIND_IDENT, NULL)) == 0) {
4224      clearop(cap->oap);
4225    } else {
4226      // Make a copy, if the line was changed it will be freed.
4227      ptr = xmemdupz(ptr, len);
4228      find_pattern_in_path(ptr, 0, len, true,
4229                           cap->count0 == 0 ? !isupper(cap->nchar) : false,
4230                           (((cap->nchar & 0xf) == ('d' & 0xf))
4231                            ? FIND_DEFINE
4232                            : FIND_ANY),
4233                           cap->count1,
4234                           (isupper(cap->nchar) ? ACTION_SHOW_ALL
4235                                                : islower(cap->nchar) ? ACTION_SHOW
4236                                                                      : ACTION_GOTO),
4237                           (cap->cmdchar == ']'
4238                            ? curwin->w_cursor.lnum + 1
4239                            : 1),
4240                           MAXLNUM,
4241                           false, false);
4242      xfree(ptr);
4243      curwin->w_set_curswant = true;
4244    }
4245  } else if ((cap->cmdchar == '[' && vim_strchr("{(*/#mM", cap->nchar) != NULL)
4246             || (cap->cmdchar == ']' && vim_strchr("})*/#mM", cap->nchar) != NULL)) {
4247    // "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')'
4248    // "[#", "]#": go to start/end of Nth innermost #if..#endif construct.
4249    // "[/", "[*", "]/", "]*": go to Nth comment start/end.
4250    // "[m" or "]m" search for prev/next start of (Java) method.
4251    // "[M" or "]M" search for prev/next end of (Java) method.
4252    nv_bracket_block(cap, &old_pos);
4253  } else if (cap->nchar == '[' || cap->nchar == ']') {
4254    // "[[", "[]", "]]" and "][": move to start or end of function
4255    if (cap->nchar == cap->cmdchar) {               // "]]" or "[["
4256      flag = '{';
4257    } else {
4258      flag = '}';                   // "][" or "[]"
4259    }
4260    curwin->w_set_curswant = true;
4261    // Imitate strange Vi behaviour: When using "]]" with an operator we also stop at '}'.
4262    if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag,
4263                 (cap->oap->op_type != OP_NOP
4264                  && cap->arg == FORWARD && flag == '{'))) {
4265      clearopbeep(cap->oap);
4266    } else {
4267      if (cap->oap->op_type == OP_NOP) {
4268        beginline(BL_WHITE | BL_FIX);
4269      }
4270      if ((fdo_flags & kOptFdoFlagBlock) && KeyTyped && cap->oap->op_type == OP_NOP) {
4271        foldOpenCursor();
4272      }
4273    }
4274  } else if (cap->nchar == 'p' || cap->nchar == 'P') {
4275    // "[p", "[P", "]P" and "]p": put with indent adjustment
4276    nv_put_opt(cap, true);
4277  } else if (cap->nchar == '\'' || cap->nchar == '`') {
4278    // "['", "[`", "]'" and "]`": jump to next mark
4279    fmark_T *fm = pos_to_mark(curbuf, NULL, curwin->w_cursor);
4280    assert(fm != NULL);
4281    fmark_T *prev_fm;
4282    for (n = cap->count1; n > 0; n--) {
4283      prev_fm = fm;
4284      fm = getnextmark(&fm->mark, cap->cmdchar == '[' ? BACKWARD : FORWARD,
4285                       cap->nchar == '\'');
4286      if (fm == NULL) {
4287        break;
4288      }
4289    }
4290    if (fm == NULL) {
4291      fm = prev_fm;
4292    }
4293    MarkMove flags = kMarkContext;
4294    flags |= cap->nchar == '\'' ? kMarkBeginLine : 0;
4295    nv_mark_move_to(cap, flags, fm);
4296  } else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE) {
4297    // [ or ] followed by a middle mouse click: put selected text with
4298    // indent adjustment.  Any other button just does as usual.
4299    do_mouse(cap->oap, cap->nchar,
4300             (cap->cmdchar == ']') ? FORWARD : BACKWARD,
4301             cap->count1, PUT_FIXINDENT);
4302  } else if (cap->nchar == 'z') {
4303    // "[z" and "]z": move to start or end of open fold.
4304    if (foldMoveTo(false, cap->cmdchar == ']' ? FORWARD : BACKWARD,
4305                   cap->count1) == false) {
4306      clearopbeep(cap->oap);
4307    }
4308  } else if (cap->nchar == 'c') {
4309    // "[c" and "]c": move to next or previous diff-change.
4310    if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD,
4311                     cap->count1) == false) {
4312      clearopbeep(cap->oap);
4313    }
4314  } else if (cap->nchar == 'C') {
4315    // "[C" and "]C": jump to previous/next multicursor.
4316    if (cap->oap->op_type != OP_NOP) {
4317      // Not an operator motion: a cascaded "d]C" would consume its own targets.
4318      clearopbeep(cap->oap);
4319    } else {
4320      typval_T tv_args[] = {
4321        { .v_type = VAR_BOOL, .vval.v_bool = cap->cmdchar == ']' ? kBoolVarTrue : kBoolVarFalse },
4322        { .v_type = VAR_NUMBER, .vval.v_number = cap->count1 },
4323        { .v_type = VAR_UNKNOWN },
4324      };
4325      typval_T rettv = TV_INITIAL_VALUE;
4326      nlua_call_typval("vim._core.mcursor", "jump", tv_args, &rettv);
4327      if (rettv.v_type != VAR_BOOL || rettv.vval.v_bool != kBoolVarTrue) {
4328        clearopbeep(cap->oap);
4329      }
4330      tv_clear(&rettv);
4331    }
4332  } else if (cap->nchar == 'r' || cap->nchar == 's' || cap->nchar == 'S') {
4333    // "[r", "[s", "[S", "]r", "]s" and "]S": move to next spell error.
4334    setpcmark();
4335    for (n = 0; n < cap->count1; n++) {
4336      if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD,
4337                        cap->nchar == 's'
4338                        ? SMT_ALL
4339                        : cap->nchar == 'r' ? SMT_RARE : SMT_BAD,
4340                        false, NULL) == 0) {
4341        clearopbeep(cap->oap);
4342        break;
4343      }
4344      curwin->w_set_curswant = true;
4345    }
4346    if (cap->oap->op_type == OP_NOP && (fdo_flags & kOptFdoFlagSearch) && KeyTyped) {
4347      foldOpenCursor();
4348    }
4349  } else {
4350    // Not a valid cap->nchar.
4351    clearopbeep(cap->oap);
4352  }
4353}
4354
4355/// Return true when 'comments' defines a C-style line ("//") or block comment.
4356/// This is when "%" should skip matching parens in comments, like the "="
4357/// operator does.
4358static bool buf_has_cstyle_comments(void)
4359{
4360  char part_buf[COM_MAX_LEN];  // buffer for one 'comments' part
4361
4362  for (char *list = curbuf->b_p_com; *list;) {
4363    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
4364    char *string = vim_strchr(part_buf, ':');  // flags and comment leader
4365    if (string != NULL && string[1] == '/' && (string[2] == '/' || string[2] == '*')) {
4366      return true;
4367    }
4368  }
4369  return false;
4370}
4371
4372/// Handle Normal mode "%" command.
4373static void nv_percent(cmdarg_T *cap)
4374{
4375  linenr_T lnum = curwin->w_cursor.lnum;
4376
4377  cap->oap->inclusive = true;
4378  if (cap->count0) {  // {cnt}% : goto {cnt} percentage in file
4379    if (cap->count0 > 100) {
4380      clearopbeep(cap->oap);
4381    } else {
4382      cap->oap->motion_type = kMTLineWise;
4383      setpcmark();
4384      // Round up, so 'normal 100%' always jumps at the line line.
4385      // Beyond 21474836 lines, (ml_line_count * 100 + 99) would
4386      // overflow on 32-bits, so use a formula with less accuracy
4387      // to avoid overflows.
4388      if (curbuf->b_ml.ml_line_count >= 21474836) {
4389        curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99)
4390                                / 100 * cap->count0;
4391      } else {
4392        curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count *
4393                                 cap->count0 + 99) / 100;
4394      }
4395      curwin->w_cursor.lnum = MIN(MAX(curwin->w_cursor.lnum, 1), curbuf->b_ml.ml_line_count);
4396
4397      beginline(BL_SOL | BL_FIX);
4398    }
4399  } else {  // "%" : go to matching paren
4400    int flags = 0;
4401    // Skip matching parens inside C-style comments, like the "=" operator
4402    // does, but not when "%" is in 'cpoptions' (Vi-compatible) or the
4403    // cursor sits in a line comment (so a match there can still be found).
4404    if (vim_strchr(p_cpo, kCpoMatch) == NULL && buf_has_cstyle_comments()) {
4405      int comment_col = check_linecomment(get_cursor_line_ptr());
4406      if (comment_col == MAXCOL || curwin->w_cursor.col < (colnr_T)comment_col) {
4407        flags = FM_SKIPCOMM;
4408      }
4409    }
4410
4411    pos_T *pos;
4412    cap->oap->motion_type = kMTCharWise;
4413    cap->oap->use_reg_one = true;
4414    if ((pos = findmatchlimit(cap->oap, NUL, flags, 0)) == NULL) {
4415      clearopbeep(cap->oap);
4416    } else {
4417      setpcmark();
4418      curwin->w_cursor = *pos;
4419      curwin->w_set_curswant = true;
4420      curwin->w_cursor.coladd = 0;
4421      adjust_for_sel(cap);
4422    }
4423  }
4424  if (cap->oap->op_type == OP_NOP
4425      && lnum != curwin->w_cursor.lnum
4426      && (fdo_flags & kOptFdoFlagPercent)
4427      && KeyTyped) {
4428    foldOpenCursor();
4429  }
4430}
4431
4432/// Handle "(" and ")" commands.
4433/// cap->arg is BACKWARD for "(" and FORWARD for ")".
4434static void nv_brace(cmdarg_T *cap)
4435{
4436  cap->oap->motion_type = kMTCharWise;
4437  cap->oap->use_reg_one = true;
4438  // The motion used to be inclusive for "(", but that is not what Vi does.
4439  cap->oap->inclusive = false;
4440  curwin->w_set_curswant = true;
4441
4442  if (findsent(cap->arg, cap->count1) == FAIL) {
4443    clearopbeep(cap->oap);
4444    return;
4445  }
4446
4447  // Don't leave the cursor on the NUL past end of line.
4448  adjust_cursor(cap->oap);
4449  curwin->w_cursor.coladd = 0;
4450  if ((fdo_flags & kOptFdoFlagBlock) && KeyTyped && cap->oap->op_type == OP_NOP) {
4451    foldOpenCursor();
4452  }
4453}
4454
4455/// "m" command: Mark a position.
4456static void nv_mark(cmdarg_T *cap)
4457{
4458  if (checkclearop(cap->oap)) {
4459    return;
4460  }
4461
4462  if (setmark(cap->nchar) == false) {
4463    clearopbeep(cap->oap);
4464  }
4465}
4466
4467/// "{" and "}" commands.
4468/// cmd->arg is BACKWARD for "{" and FORWARD for "}".
4469static void nv_findpar(cmdarg_T *cap)
4470{
4471  cap->oap->motion_type = kMTCharWise;
4472  cap->oap->inclusive = false;
4473  cap->oap->use_reg_one = true;
4474  curwin->w_set_curswant = true;
4475  if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, false)) {
4476    clearopbeep(cap->oap);
4477    return;
4478  }
4479
4480  curwin->w_cursor.coladd = 0;
4481  if ((fdo_flags & kOptFdoFlagBlock) && KeyTyped && cap->oap->op_type == OP_NOP) {
4482    foldOpenCursor();
4483  }
4484}
4485
4486/// "u" command: Undo or make lower case.
4487static void nv_undo(cmdarg_T *cap)
4488{
4489  if (cap->oap->op_type == OP_LOWER
4490      || Visual.active) {
4491    // translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu"
4492    cap->cmdchar = 'g';
4493    cap->nchar = 'u';
4494    nv_operator(cap);
4495  } else {
4496    nv_kundo(cap);
4497  }
4498}
4499
4500/// <Undo> command.
4501static void nv_kundo(cmdarg_T *cap)
4502{
4503  if (checkclearopq(cap->oap)) {
4504    return;
4505  }
4506
4507  u_undo(cap->count1);
4508  curwin->w_set_curswant = true;
4509}
4510
4511/// Handle the "r" command.
4512static void nv_replace(cmdarg_T *cap)
4513{
4514  int had_ctrl_v;
4515
4516  if (checkclearop(cap->oap)) {
4517    return;
4518  }
4519  if (bt_prompt(curbuf) && !prompt_curpos_editable()) {
4520    clearopbeep(cap->oap);
4521    return;
4522  }
4523
4524  // get another character
4525  if (cap->nchar == Ctrl_V || cap->nchar == Ctrl_Q) {
4526    had_ctrl_v = Ctrl_V;
4527    cap->nchar = get_literal(false);
4528    // Don't redo a multibyte character with CTRL-V.
4529    if (cap->nchar > DEL) {
4530      had_ctrl_v = NUL;
4531    }
4532  } else {
4533    had_ctrl_v = NUL;
4534  }
4535
4536  // Abort if the character is a special key.
4537  if (IS_SPECIAL(cap->nchar)) {
4538    clearopbeep(cap->oap);
4539    return;
4540  }
4541
4542  // Visual mode "r"
4543  if (Visual.active) {
4544    if (got_int) {
4545      got_int = false;
4546    }
4547    if (had_ctrl_v) {
4548      // Use a special (negative) number to make a difference between a
4549      // literal CR or NL and a line break.
4550      if (cap->nchar == CAR) {
4551        cap->nchar = REPLACE_CR_NCHAR;
4552      } else if (cap->nchar == NL) {
4553        cap->nchar = REPLACE_NL_NCHAR;
4554      }
4555    }
4556    nv_operator(cap);
4557    return;
4558  }
4559
4560  // Break tabs, etc.
4561  if (virtual_active(curwin)) {
4562    if (u_save_cursor() == false) {
4563      return;
4564    }
4565    if (gchar_cursor() == NUL) {
4566      // Add extra space and put the cursor on the first one.
4567      coladvance_force((colnr_T)(getviscol() + cap->count1));
4568      assert(cap->count1 <= INT_MAX);
4569      curwin->w_cursor.col -= (colnr_T)cap->count1;
4570    } else if (gchar_cursor() == TAB) {
4571      coladvance_force(getviscol());
4572    }
4573  }
4574
4575  // Abort if not enough characters to replace.
4576  if ((size_t)get_cursor_pos_len() < (unsigned)cap->count1
4577      || (mb_charlen(get_cursor_pos_ptr()) < cap->count1)) {
4578    clearopbeep(cap->oap);
4579    return;
4580  }
4581
4582  // Replacing with a TAB is done by edit() when it is complicated because
4583  // 'expandtab' or 'smarttab' is set.  CTRL-V TAB inserts a literal TAB.
4584  // Other characters are done below to avoid problems with things like
4585  // CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC).
4586  if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta)) {
4587    stuffnumReadbuff(cap->count1);
4588    stuffcharReadbuff('R');
4589    stuffcharReadbuff('\t');
4590    stuffcharReadbuff(ESC);
4591    exec_stuffed(cap);
4592    return;
4593  }
4594
4595  // save line for undo
4596  if (u_save_cursor() == false) {
4597    return;
4598  }
4599
4600  if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) {
4601    // Replace character(s) by a single newline.
4602    // Strange vi behaviour: Only one newline is inserted.
4603    // Delete the characters here.
4604    // Insert the newline with an insert command, takes care of
4605    // autoindent.      The insert command depends on being on the last
4606    // character of a line or not.
4607    del_chars(cap->count1, false);        // delete the characters
4608    stuffcharReadbuff('\r');
4609    stuffcharReadbuff(ESC);
4610
4611    // Give 'r' to edit(), to get the redo command right.
4612    invoke_edit(cap, true, 'r', false);
4613  } else {
4614    prep_redo(true, true, (CmdSpec){ .regname = cap->oap->regname, .count = cap->count1,
4615                                     .cmd = 'r', .cmdarg = cap->nchar });
4616    if (had_ctrl_v != NUL) {
4617      redo_append_char(had_ctrl_v);
4618    }
4619
4620    curbuf->b_op_start = curwin->w_cursor;
4621    const int old_State = State;
4622
4623    if (cap->nchar_len > 0) {
4624      redo_append_str(cap->nchar_composing, -1);
4625    } else {
4626      redo_append_char(cap->nchar);
4627    }
4628
4629    // This is slow, but it handles replacing a single-byte with a
4630    // multi-byte and the other way around.  Also handles adding
4631    // composing characters for utf-8.
4632    for (int n = cap->count1; n > 0; n--) {
4633      State = MODE_REPLACE;
4634      if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) {
4635        int c = ins_copychar(curwin->w_cursor.lnum
4636                             + (cap->nchar == Ctrl_Y ? -1 : 1));
4637        if (c != NUL) {
4638          ins_char(c);
4639        } else {
4640          // will be decremented further down
4641          curwin->w_cursor.col++;
4642        }
4643      } else {
4644        if (cap->nchar_len) {
4645          ins_char_bytes(cap->nchar_composing, (size_t)cap->nchar_len);
4646        } else {
4647          ins_char(cap->nchar);
4648        }
4649      }
4650      State = old_State;
4651    }
4652    curwin->w_cursor.col--;         // cursor on the last replaced char
4653    // if the character on the left of the current cursor is a multi-byte
4654    // character, move two characters left
4655    mb_adjust_cursor();
4656    curbuf->b_op_end = curwin->w_cursor;
4657    curwin->w_set_curswant = true;
4658    set_last_insert(cap->nchar);
4659  }
4660
4661  foldUpdateAfterInsert();
4662}
4663
4664/// 'o': Exchange start and end of Visual area.
4665/// 'O': same, but in block mode exchange left and right corners.
4666static void v_swap_corners(int cmdchar)
4667{
4668  colnr_T left, right;
4669
4670  if (cmdchar == 'O' && Visual.mode == Ctrl_V) {
4671    pos_T old_cursor = curwin->w_cursor;
4672    getvcols(curwin, &old_cursor, &Visual.start, &left, &right, 0);
4673    curwin->w_cursor.lnum = Visual.start.lnum;
4674    coladvance(curwin, left);
4675    Visual.start = curwin->w_cursor;
4676
4677    curwin->w_cursor.lnum = old_cursor.lnum;
4678    curwin->w_curswant = right;
4679    // 'selection "exclusive" and cursor at right-bottom corner: move it
4680    // right one column
4681    if (old_cursor.lnum >= Visual.start.lnum && *p_sel == 'e') {
4682      curwin->w_curswant++;
4683    }
4684    coladvance(curwin, curwin->w_curswant);
4685    if (curwin->w_cursor.col == old_cursor.col
4686        && (!virtual_active(curwin)
4687            || curwin->w_cursor.coladd ==
4688            old_cursor.coladd)) {
4689      curwin->w_cursor.lnum = Visual.start.lnum;
4690      if (old_cursor.lnum <= Visual.start.lnum && *p_sel == 'e') {
4691        right++;
4692      }
4693      coladvance(curwin, right);
4694      Visual.start = curwin->w_cursor;
4695
4696      curwin->w_cursor.lnum = old_cursor.lnum;
4697      coladvance(curwin, left);
4698      curwin->w_curswant = left;
4699    }
4700  } else {
4701    pos_T old_cursor = curwin->w_cursor;
4702    curwin->w_cursor = Visual.start;
4703    Visual.start = old_cursor;
4704    curwin->w_set_curswant = true;
4705  }
4706}
4707
4708/// "R" (cap->arg is false) and "gR" (cap->arg is true).
4709static void nv_Replace(cmdarg_T *cap)
4710{
4711  if (Visual.active) {          // "R" is replace lines
4712    cap->cmdchar = 'c';
4713    cap->nchar = NUL;
4714    VIsual_mode_orig = Visual.mode;     // remember original area for gv
4715    Visual.mode = 'V';
4716    nv_operator(cap);
4717    return;
4718  }
4719
4720  if (checkclearopq(cap->oap)) {
4721    return;
4722  }
4723
4724  if (!MODIFIABLE(curbuf)) {
4725    emsg(_(e_modifiable));
4726  } else {
4727    if (virtual_active(curwin)) {
4728      coladvance(curwin, getviscol());
4729    }
4730    invoke_edit(cap, false, cap->arg ? 'V' : 'R', false);
4731  }
4732}
4733
4734/// "gr".
4735static void nv_vreplace(cmdarg_T *cap)
4736{
4737  if (Visual.active) {
4738    cap->cmdchar = 'r';
4739    cap->nchar = cap->extra_char;
4740    nv_replace(cap);            // Do same as "r" in Visual mode for now
4741    return;
4742  }
4743
4744  if (checkclearopq(cap->oap)) {
4745    return;
4746  }
4747
4748  if (!MODIFIABLE(curbuf)) {
4749    emsg(_(e_modifiable));
4750  } else {
4751    if (cap->extra_char == Ctrl_V || cap->extra_char == Ctrl_Q) {
4752      // get another character
4753      cap->extra_char = get_literal(false);
4754    }
4755    if (cap->extra_char < ' ') {
4756      // Prefix a control character with CTRL-V to avoid it being used as
4757      // a command.
4758      stuffcharReadbuff(Ctrl_V);
4759    }
4760    stuffcharReadbuff(cap->extra_char);
4761    stuffcharReadbuff(ESC);
4762    if (virtual_active(curwin)) {
4763      coladvance(curwin, getviscol());
4764    }
4765    invoke_edit(cap, true, 'v', false);
4766  }
4767}
4768
4769/// Swap case for "~" command, when it does not work like an operator.
4770static void n_swapchar(cmdarg_T *cap)
4771{
4772  bool did_change = false;
4773
4774  if (checkclearopq(cap->oap)) {
4775    return;
4776  }
4777
4778  if (LINEEMPTY(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL) {
4779    clearopbeep(cap->oap);
4780    return;
4781  }
4782
4783  prep_redo_cmd(cap);
4784
4785  if (u_save_cursor() == false) {
4786    return;
4787  }
4788
4789  pos_T startpos = curwin->w_cursor;
4790  for (int n = cap->count1; n > 0; n--) {
4791    did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor);
4792    inc_cursor();
4793    if (gchar_cursor() == NUL) {
4794      if (vim_strchr(p_ww, '~') != NULL
4795          && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
4796        curwin->w_cursor.lnum++;
4797        curwin->w_cursor.col = 0;
4798        if (n > 1) {
4799          if (u_savesub(curwin->w_cursor.lnum) == false) {
4800            break;
4801          }
4802          u_clearline(curbuf);
4803        }
4804      } else {
4805        break;
4806      }
4807    }
4808  }
4809
4810  check_cursor(curwin);
4811  curwin->w_set_curswant = true;
4812  if (did_change) {
4813    changed_lines(curbuf, startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1,
4814                  0, true);
4815    curbuf->b_op_start = startpos;
4816    curbuf->b_op_end = curwin->w_cursor;
4817    if (curbuf->b_op_end.col > 0) {
4818      curbuf->b_op_end.col--;
4819    }
4820  }
4821}
4822
4823/// Move the cursor to the mark position
4824///
4825/// Wrapper to mark_move_to() that also handles normal mode command arguments.
4826/// @note  It will switch the buffer if neccesarry, move the cursor and set the
4827/// view depending on the given flags.
4828/// @param cap  command line arguments
4829/// @param flags for mark_move_to()
4830/// @param mark  mark
4831/// @return  The result of calling mark_move_to()
4832static MarkMoveRes nv_mark_move_to(cmdarg_T *cap, MarkMove flags, fmark_T *fm)
4833{
4834  MarkMoveRes res = mark_move_to(fm, flags);
4835  if (res & kMarkMoveFailed) {
4836    clearop(cap->oap);
4837  }
4838  cap->oap->motion_type = flags & kMarkBeginLine ? kMTLineWise : kMTCharWise;
4839  if (cap->cmdchar == '`') {
4840    cap->oap->use_reg_one = true;
4841  }
4842  cap->oap->inclusive = false;  // ignored if not kMTCharWise
4843  curwin->w_set_curswant = true;
4844  return res;
4845}
4846
4847/// Handle commands that are operators in Visual mode.
4848static void v_visop(cmdarg_T *cap)
4849{
4850  static char trans[] = "YyDdCcxdXdAAIIrr";
4851
4852  // Uppercase means linewise, except in block mode, then "D" deletes till
4853  // the end of the line, and "C" replaces till EOL
4854  if (isupper(cap->cmdchar)) {
4855    if (Visual.mode != Ctrl_V) {
4856      VIsual_mode_orig = Visual.mode;
4857      Visual.mode = 'V';
4858    } else if (cap->cmdchar == 'C' || cap->cmdchar == 'D') {
4859      curwin->w_curswant = MAXCOL;
4860    }
4861  }
4862  cap->cmdchar = (uint8_t)(*(vim_strchr(trans, cap->cmdchar) + 1));
4863  nv_operator(cap);
4864}
4865
4866/// "s" and "S" commands.
4867static void nv_subst(cmdarg_T *cap)
4868{
4869  if (bt_prompt(curbuf) && !prompt_curpos_editable()) {
4870    clearopbeep(cap->oap);
4871    return;
4872  }
4873  if (Visual.active) {  // "vs" and "vS" are the same as "vc"
4874    if (cap->cmdchar == 'S') {
4875      VIsual_mode_orig = Visual.mode;
4876      Visual.mode = 'V';
4877    }
4878    cap->cmdchar = 'c';
4879    nv_operator(cap);
4880  } else {
4881    nv_optrans(cap);
4882  }
4883}
4884
4885/// Abbreviated commands.
4886static void nv_abbrev(cmdarg_T *cap)
4887{
4888  if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL) {
4889    cap->cmdchar = 'x';                 // DEL key behaves like 'x'
4890  }
4891  // in Visual mode these commands are operators
4892  if (Visual.active) {
4893    v_visop(cap);
4894  } else {
4895    nv_optrans(cap);
4896  }
4897}
4898
4899/// Translate a command into another command, and execute it.
4900static void nv_optrans(cmdarg_T *cap)
4901{
4902  static const char *(ar[]) = { "dl", "dh", "d$", "c$", "cl", "cc", "yy",
4903                                ":s\r" };
4904  static const char *str = "xXDCsSY&";
4905
4906  if (!checkclearopq(cap->oap)) {
4907    if (cap->count0) {
4908      stuffnumReadbuff(cap->count0);
4909    }
4910    stuffReadbuff(ar[strchr(str, (char)cap->cmdchar) - str]);
4911    exec_stuffed(cap);
4912  }
4913  cap->opcount = 0;
4914}
4915
4916/// "'" and "`" commands.  Also for "g'" and "g`".
4917/// cap->arg is true for "'" and "g'".
4918static void nv_gomark(cmdarg_T *cap)
4919{
4920  int name;
4921  MarkMove flags = jop_flags & kOptJopFlagView ? kMarkSetView : 0;  // flags for moving to the mark
4922  if (cap->oap->op_type != OP_NOP) {
4923    // When there is a pending operator, do not restore the view as this is usually unexpected.
4924    flags = 0;
4925  }
4926  MarkMoveRes move_res = 0;  // Result from moving to the mark
4927  const bool old_KeyTyped = KeyTyped;  // getting file may reset it
4928
4929  if (cap->cmdchar == 'g') {
4930    name = cap->extra_char;
4931    flags |= KMarkNoContext;
4932  } else {
4933    name = cap->nchar;
4934    flags |= kMarkContext;
4935  }
4936  flags |= cap->arg ? kMarkBeginLine : 0;
4937  flags |= cap->count0 ? kMarkSetView : 0;
4938
4939  fmark_T *fm = mark_get(curbuf, curwin, NULL, kMarkAll, name);
4940  move_res = nv_mark_move_to(cap, flags, fm);
4941
4942  // May need to clear the coladd that a mark includes.
4943  if (!virtual_active(curwin)) {
4944    curwin->w_cursor.coladd = 0;
4945  }
4946
4947  if (cap->oap->op_type == OP_NOP
4948      && move_res & kMarkMoveSuccess
4949      && (move_res & kMarkSwitchedBuf || move_res & kMarkChangedCursor)
4950      && (fdo_flags & kOptFdoFlagMark)
4951      && old_KeyTyped) {
4952    foldOpenCursor();
4953  }
4954}
4955
4956/// Handle CTRL-O, CTRL-I, "g;", "g,", and "CTRL-Tab" commands.
4957/// Movement in the jumplist and changelist.
4958static void nv_pcmark(cmdarg_T *cap)
4959{
4960  fmark_T *fm = NULL;
4961  MarkMove flags = jop_flags & kOptJopFlagView ? kMarkSetView : 0;  // flags for moving to the mark
4962  MarkMoveRes move_res = 0;  // Result from moving to the mark
4963  const bool old_KeyTyped = KeyTyped;  // getting file may reset it.
4964
4965  if (checkclearopq(cap->oap)) {
4966    return;
4967  }
4968
4969  if (cap->cmdchar == TAB && mod_mask == MOD_MASK_CTRL) {
4970    if (!goto_tabpage_lastused()) {
4971      clearopbeep(cap->oap);
4972    }
4973    return;
4974  }
4975
4976  if (cap->cmdchar == 'g') {
4977    fm = get_changelist(curbuf, curwin, cap->count1);
4978  } else {
4979    fm = get_jumplist(curwin, cap->count1);
4980    flags |= KMarkNoContext | kMarkJumpList;
4981  }
4982  // Changelist and jumplist have their own error messages. Therefore avoid
4983  // calling nv_mark_move_to() when not found to avoid incorrect error
4984  // messages.
4985  if (fm != NULL) {
4986    move_res = nv_mark_move_to(cap, flags, fm);
4987  } else if (cap->cmdchar == 'g') {
4988    if (curbuf->b_changelistlen == 0) {
4989      emsg(_(e_changelist_is_empty));
4990    } else if (cap->count1 < 0) {
4991      emsg(_("E662: At start of changelist"));
4992    } else {
4993      emsg(_("E663: At end of changelist"));
4994    }
4995  } else {
4996    clearopbeep(cap->oap);
4997  }
4998  if (cap->oap->op_type == OP_NOP
4999      && (move_res & kMarkSwitchedBuf || move_res & kMarkChangedLine)
5000      && (fdo_flags & kOptFdoFlagMark)
5001      && old_KeyTyped) {
5002    foldOpenCursor();
5003  }
5004}
5005
5006/// Handle '"' command.
5007static void nv_regname(cmdarg_T *cap)
5008{
5009  if (checkclearop(cap->oap)) {
5010    return;
5011  }
5012  if (cap->nchar == '=') {
5013    cap->nchar = get_expr_register();
5014  }
5015  if (cap->nchar != NUL && valid_yank_reg(cap->nchar, false)) {
5016    cap->oap->regname = cap->nchar;
5017    cap->opcount = cap->count0;         // remember count before '"'
5018    set_reg_var(cap->oap->regname);
5019  } else {
5020    clearopbeep(cap->oap);
5021  }
5022}
5023
5024/// Handle "v", "V" and "CTRL-V" commands.
5025/// Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg
5026/// is true.
5027/// Handle CTRL-Q just like CTRL-V.
5028static void nv_visual(cmdarg_T *cap)
5029{
5030  if (cap->cmdchar == Ctrl_Q) {
5031    cap->cmdchar = Ctrl_V;
5032  }
5033
5034  // 'v', 'V' and CTRL-V can be used while an operator is pending to make it
5035  // charwise, linewise, or blockwise.
5036  if (cap->oap->op_type != OP_NOP) {
5037    motion_force = cap->oap->motion_force = cap->cmdchar;
5038    finish_op = false;          // operator doesn't finish now but later
5039    return;
5040  }
5041
5042  Visual.select = cap->arg;
5043  if (Visual.active) {      // change Visual mode
5044    if (Visual.mode == cap->cmdchar) {      // stop visual mode
5045      end_visual_mode();
5046    } else {                                  // toggle char/block mode
5047                                              //           or char/line mode
5048      Visual.mode = cap->cmdchar;
5049      showmode();
5050      may_trigger_modechanged();
5051    }
5052    redraw_curbuf_later(UPD_INVERTED);  // update the inversion
5053  } else {                // start Visual mode
5054    if (cap->count0 > 0 && Visual.resel.mode != NUL) {
5055      // use previously selected part
5056      Visual.start = curwin->w_cursor;
5057
5058      Visual.active = true;
5059      Visual.reselect = true;
5060      if (!cap->arg) {
5061        // start Select mode when 'selectmode' contains "cmd"
5062        may_start_select('c');
5063      }
5064      setmouse();
5065      if (p_smd && msg_silent == 0) {
5066        redraw_cmdline = true;              // show visual mode later
5067      }
5068      // For V and ^V, we multiply the number of lines even if there
5069      // was only one -- webb
5070      if (Visual.resel.mode != 'v' || Visual.resel.line_count > 1) {
5071        curwin->w_cursor.lnum += Visual.resel.line_count * cap->count0 - 1;
5072        check_cursor(curwin);
5073      }
5074      Visual.mode = Visual.resel.mode;
5075      if (Visual.mode == 'v') {
5076        if (Visual.resel.line_count <= 1) {
5077          update_curswant_force();
5078          assert(cap->count0 >= INT_MIN && cap->count0 <= INT_MAX);
5079          curwin->w_curswant += Visual.resel.vcol * cap->count0;
5080          if (*p_sel != 'e') {
5081            curwin->w_curswant--;
5082          }
5083        } else {
5084          curwin->w_curswant = Visual.resel.vcol;
5085        }
5086        coladvance(curwin, curwin->w_curswant);
5087      }
5088      if (Visual.resel.vcol == MAXCOL) {
5089        curwin->w_curswant = MAXCOL;
5090        coladvance(curwin, MAXCOL);
5091      } else if (Visual.mode == Ctrl_V) {
5092        // Update curswant at the original cursor position.
5093        pos_T tmp_cursor = curwin->w_cursor;
5094        curwin->w_cursor = Visual.start;
5095        update_curswant_force();
5096        assert(cap->count0 >= INT_MIN && cap->count0 <= INT_MAX);
5097        curwin->w_curswant += Visual.resel.vcol * cap->count0 - 1;
5098        curwin->w_cursor = tmp_cursor;
5099        if (*p_sel == 'e') {
5100          curwin->w_curswant++;
5101        }
5102        coladvance(curwin, curwin->w_curswant);
5103      } else {
5104        curwin->w_set_curswant = true;
5105      }
5106      redraw_curbuf_later(UPD_INVERTED);  // show the inversion
5107    } else {
5108      if (!cap->arg) {
5109        // start Select mode when 'selectmode' contains "cmd"
5110        may_start_select('c');
5111      }
5112      n_start_visual_mode(cap->cmdchar);
5113      if (Visual.mode != 'V' && *p_sel == 'e') {
5114        cap->count1++;          // include one more char
5115      } else {
5116        Visual.select_exclu_adj = false;
5117      }
5118      if (cap->count0 > 0 && --cap->count1 > 0) {
5119        // With a count select that many characters or lines.
5120        if (Visual.mode == 'v' || Visual.mode == Ctrl_V) {
5121          nv_right(cap);
5122        } else if (Visual.mode == 'V') {
5123          nv_down(cap);
5124        }
5125      }
5126    }
5127  }
5128}
5129
5130/// Start selection for Shift-movement keys.
5131void start_selection(void)
5132{
5133  // if 'selectmode' contains "key", start Select mode
5134  may_start_select('k');
5135  n_start_visual_mode('v');
5136}
5137
5138/// Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu.
5139/// When "c" is 'o' (checking for "mouse") then also when mapped.
5140void may_start_select(int c)
5141{
5142  Visual.select = (c == 'o' || (stuff_empty() && typebuf_typed()))
5143                  && vim_strchr(p_slm, c) != NULL;
5144}
5145
5146/// Start Visual mode "c".
5147/// Should set Visual.select before calling this.
5148static void n_start_visual_mode(int c)
5149{
5150  Visual.mode = c;
5151  Visual.active = true;
5152  Visual.reselect = true;
5153  // Corner case: the 0 position in a tab may change when going into
5154  // virtualedit.  Recalculate curwin->w_cursor to avoid bad highlighting.
5155  //
5156  if (c == Ctrl_V && (get_ve_flags(curwin) & kOptVeFlagBlock) && gchar_cursor() == TAB) {
5157    validate_virtcol(curwin);
5158    coladvance(curwin, curwin->w_virtcol);
5159  }
5160  Visual.start = curwin->w_cursor;
5161
5162  foldAdjustVisual();
5163
5164  may_trigger_modechanged();
5165  setmouse();
5166  // Check for redraw after changing the state.
5167  conceal_check_cursor_line();
5168
5169  if (p_smd && msg_silent == 0) {
5170    redraw_cmdline = true;      // show visual mode later
5171  }
5172  // Only need to redraw this line, unless still need to redraw an old
5173  // Visual area (when 'lazyredraw' is set).
5174  if (curwin->w_redr_type < UPD_INVERTED) {
5175    curwin->w_old_cursor_lnum = curwin->w_cursor.lnum;
5176    curwin->w_old_visual_lnum = curwin->w_cursor.lnum;
5177  }
5178  redraw_curbuf_later(UPD_VALID);
5179}
5180
5181/// CTRL-W: Window commands
5182static void nv_window(cmdarg_T *cap)
5183{
5184  if (cap->nchar == ':') {
5185    // "CTRL-W :" is the same as typing ":"; useful in a terminal window
5186    cap->cmdchar = ':';
5187    cap->nchar = NUL;
5188    nv_colon(cap);
5189  } else if (!checkclearop(cap->oap)) {
5190    do_window(cap->nchar, cap->count0, NUL);  // everything is in window.c
5191  }
5192}
5193
5194/// CTRL-Z: Suspend
5195static void nv_suspend(cmdarg_T *cap)
5196{
5197  clearop(cap->oap);
5198  if (Visual.active) {
5199    end_visual_mode();                  // stop Visual mode
5200  }
5201  do_cmdline_cmd("stop");
5202}
5203
5204/// "gv": Reselect the previous Visual area.  If Visual already active,
5205///       exchange previous and current Visual area.
5206static void nv_gv_cmd(cmdarg_T *cap)
5207{
5208  if (curbuf->b_visual.vi_start.lnum == 0
5209      || curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count
5210      || curbuf->b_visual.vi_end.lnum == 0) {
5211    beep_flush();
5212    return;
5213  }
5214
5215  // set w_cursor to the start of the Visual area, tpos to the end
5216  const visualinfo_T prev = curbuf->b_visual;
5217  if (Visual.active) {
5218    curbuf->b_visual = visualinfo();
5219    curbuf->b_visual_mode_eval = Visual.mode;
5220  }
5221  Visual.mode = prev.vi_mode;
5222  curwin->w_curswant = prev.vi_curswant;
5223  pos_T tpos = prev.vi_end;
5224  curwin->w_cursor = prev.vi_start;
5225
5226  Visual.active = true;
5227  Visual.reselect = true;
5228
5229  // Set Visual to the start and w_cursor to the end of the Visual
5230  // area.  Make sure they are on an existing character.
5231  check_cursor(curwin);
5232  Visual.start = curwin->w_cursor;
5233  curwin->w_cursor = tpos;
5234  check_cursor(curwin);
5235  update_topline(curwin);
5236
5237  // When called from normal "g" command: start Select mode when
5238  // 'selectmode' contains "cmd".  When called for K_SELECT, always
5239  // start Select mode.
5240  if (cap->arg) {
5241    Visual.select = true;
5242    Visual.select_reg = 0;
5243  } else {
5244    may_start_select('c');
5245  }
5246  setmouse();
5247  redraw_curbuf_later(UPD_INVERTED);
5248  showmode();
5249}
5250
5251/// "g0", "g^" : Like "0" and "^" but for screen lines.
5252/// "gm": middle of "g0" and "g$".
5253void nv_g_home_m_cmd(cmdarg_T *cap)
5254{
5255  int i;
5256  const bool flag = cap->nchar == '^';
5257
5258  cap->oap->motion_type = kMTCharWise;
5259  cap->oap->inclusive = false;
5260  if (curwin->w_p_wrap && curwin->w_view_width != 0) {
5261    int width1 = curwin->w_view_width - win_col_off(curwin);
5262    int width2 = width1 + win_col_off2(curwin);
5263
5264    validate_virtcol(curwin);
5265    i = 0;
5266    if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0) {
5267      i = (curwin->w_virtcol - width1) / width2 * width2 + width1;
5268    }
5269
5270    // When ending up below 'smoothscroll' marker, move just beyond it so
5271    // that skipcol is not adjusted later.
5272    if (curwin->w_skipcol > 0 && curwin->w_cursor.lnum == curwin->w_topline) {
5273      int overlap = sms_marker_overlap(curwin, curwin->w_view_width - width2);
5274      if (overlap > 0 && i == curwin->w_skipcol) {
5275        i += overlap;
5276      }
5277    }
5278  } else {
5279    i = curwin->w_leftcol;
5280  }
5281  // Go to the middle of the screen line.  When 'number' or
5282  // 'relativenumber' is on and lines are wrapping the middle can be more
5283  // to the left.
5284  if (cap->nchar == 'm') {
5285    i += (curwin->w_view_width - win_col_off(curwin)
5286          + ((curwin->w_p_wrap && i > 0) ? win_col_off2(curwin) : 0)) / 2;
5287  }
5288  coladvance(curwin, (colnr_T)i);
5289  if (flag) {
5290    do {
5291      i = gchar_cursor();
5292    } while (ascii_iswhite(i) && oneright() == OK);
5293    curwin->w_valid &= ~VALID_WCOL;
5294  }
5295  curwin->w_set_curswant = true;
5296  if (hasAnyFolding(curwin)) {
5297    validate_cheight(curwin);
5298    if (curwin->w_cline_folded) {
5299      update_curswant_force();
5300    }
5301  }
5302  adjust_skipcol();
5303}
5304
5305/// "g_": to the last non-blank character in the line or <count> lines downward.
5306static void nv_g_underscore_cmd(cmdarg_T *cap)
5307{
5308  cap->oap->motion_type = kMTCharWise;
5309  cap->oap->inclusive = true;
5310  curwin->w_curswant = MAXCOL;
5311  if (cursor_down(cap->count1 - 1, cap->oap->op_type == OP_NOP) == false) {
5312    clearopbeep(cap->oap);
5313    return;
5314  }
5315
5316  char *ptr = get_cursor_line_ptr();
5317
5318  // In Visual mode we may end up after the line.
5319  if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL) {
5320    curwin->w_cursor.col--;
5321  }
5322
5323  // Decrease the cursor column until it's on a non-blank.
5324  while (curwin->w_cursor.col > 0 && ascii_iswhite(ptr[curwin->w_cursor.col])) {
5325    curwin->w_cursor.col--;
5326  }
5327  curwin->w_set_curswant = true;
5328  adjust_for_sel(cap);
5329}
5330
5331/// "g$" : Like "$" but for screen lines.
5332static void nv_g_dollar_cmd(cmdarg_T *cap)
5333{
5334  oparg_T *oap = cap->oap;
5335  int i;
5336  int col_off = win_col_off(curwin);
5337  const bool flag = cap->nchar == K_END || cap->nchar == K_KEND;
5338
5339  oap->motion_type = kMTCharWise;
5340  oap->inclusive = true;
5341  if (curwin->w_p_wrap && curwin->w_view_width != 0) {
5342    curwin->w_curswant = MAXCOL;              // so we stay at the end
5343    if (cap->count1 == 1) {
5344      int width1 = curwin->w_view_width - col_off;
5345      int width2 = width1 + win_col_off2(curwin);
5346
5347      validate_virtcol(curwin);
5348      i = width1 - 1;
5349      if (curwin->w_virtcol >= (colnr_T)width1) {
5350        i += ((curwin->w_virtcol - width1) / width2 + 1) * width2;
5351      }
5352      coladvance(curwin, (colnr_T)i);
5353
5354      // Make sure we stick in this column.
5355      update_curswant_force();
5356      if (curwin->w_cursor.col > 0 && curwin->w_p_wrap) {
5357        // Check for landing on a character that got split at
5358        // the end of the line.  We do not want to advance to
5359        // the next screen line.
5360        if (curwin->w_virtcol > (colnr_T)i) {
5361          curwin->w_cursor.col--;
5362        }
5363      }
5364    } else if (nv_screengo(oap, FORWARD, cap->count1 - 1, false) == false) {
5365      clearopbeep(oap);
5366    }
5367  } else {
5368    if (cap->count1 > 1) {
5369      // if it fails, let the cursor still move to the last char
5370      cursor_down(cap->count1 - 1, false);
5371    }
5372    i = curwin->w_leftcol + curwin->w_view_width - col_off - 1;
5373    coladvance(curwin, (colnr_T)i);
5374
5375    // if the character doesn't fit move one back
5376    if (curwin->w_cursor.col > 0 && utf_ptr2cells(get_cursor_pos_ptr()) > 1) {
5377      colnr_T vcol;
5378
5379      getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &vcol, 0);
5380      if (vcol >= curwin->w_leftcol + curwin->w_view_width - col_off) {
5381        curwin->w_cursor.col--;
5382      }
5383    }
5384
5385    // Make sure we stick in this column.
5386    update_curswant_force();
5387  }
5388  if (flag) {
5389    do {
5390      i = gchar_cursor();
5391    } while (ascii_iswhite_or_nul(i) && oneleft() == OK);
5392    curwin->w_valid &= ~VALID_WCOL;
5393  }
5394}
5395
5396/// "gi": start Insert at the last position.
5397static void nv_gi_cmd(cmdarg_T *cap)
5398{
5399  if (curbuf->b_last_insert.mark.lnum != 0) {
5400    curwin->w_cursor = curbuf->b_last_insert.mark;
5401    check_cursor_lnum(curwin);
5402    int i = (int)get_cursor_line_len();
5403    if (curwin->w_cursor.col > (colnr_T)i) {
5404      if (virtual_active(curwin)) {
5405        curwin->w_cursor.coladd += curwin->w_cursor.col - i;
5406      }
5407      curwin->w_cursor.col = i;
5408    }
5409  }
5410  cap->cmdchar = 'i';
5411  nv_edit(cap);
5412}
5413
5414/// Commands starting with "g".
5415static void nv_g_cmd(cmdarg_T *cap)
5416{
5417  oparg_T *oap = cap->oap;
5418  int i;
5419
5420  switch (cap->nchar) {
5421  // "g^A/g^X": Sequentially increment visually selected region.
5422  case Ctrl_A:
5423  case Ctrl_X:
5424    if (Visual.active) {
5425      cap->arg = true;
5426      cap->cmdchar = cap->nchar;
5427      cap->nchar = NUL;
5428      nv_addsub(cap);
5429    } else if (cap->nchar == Ctrl_A && cap->oap->op_type == OP_NOP && mc_buf_has_cursors(curbuf)) {
5430      mc_counter(cap->count1);
5431    } else {
5432      clearopbeep(oap);
5433    }
5434    break;
5435
5436  // "gR": Enter virtual replace mode.
5437  case 'R':
5438    cap->arg = true;
5439    nv_Replace(cap);
5440    break;
5441
5442  case 'r':
5443    nv_vreplace(cap);
5444    break;
5445
5446  case '&':
5447    do_cmdline_cmd("%s//~/&");
5448    break;
5449
5450  // "gv": Reselect the previous Visual area.  If Visual already active,
5451  //       exchange previous and current Visual area.
5452  case 'v':
5453    nv_gv_cmd(cap);
5454    break;
5455  // "gV": Don't reselect the previous Visual area after a Select mode mapping of menu.
5456  case 'V':
5457    Visual.reselect = false;
5458    break;
5459
5460  // "gQ": restore the previous multicursors (analogous to "gv").
5461  case 'Q':
5462    if (reg_recording != 0 || reg_executing != 0) {
5463      // Not allowed while recording/executing a macro. |mcursor-limitations|
5464      vim_beep(0);
5465    } else {
5466      typval_T tv_args[] = { { .v_type = VAR_UNKNOWN } };
5467      nlua_call_typval("vim._core.mcursor", "restore", tv_args, NULL);
5468    }
5469    break;
5470
5471  // "gh":  start Select mode.
5472  // "gH":  start Select line mode.
5473  // "g^H": start Select block mode.
5474  case K_BS:
5475    cap->nchar = Ctrl_H;
5476    FALLTHROUGH;
5477  case 'h':
5478  case 'H':
5479  case Ctrl_H:
5480    cap->cmdchar = cap->nchar + ('v' - 'h');
5481    cap->arg = true;
5482    nv_visual(cap);
5483    break;
5484
5485  // "gn", "gN" visually select next/previous search match
5486  // "gn" selects next match
5487  // "gN" selects previous match
5488  case 'N':
5489  case 'n':
5490    if (!current_search(cap->count1, cap->nchar == 'n')) {
5491      clearopbeep(oap);
5492    }
5493    break;
5494
5495  // "gj" and "gk" two new funny movement keys -- up and down
5496  // movement based on *screen* line rather than *file* line.
5497  case 'j':
5498  case K_DOWN:
5499    // with 'nowrap' it works just like the normal "j" command.
5500    if (!curwin->w_p_wrap) {
5501      oap->motion_type = kMTLineWise;
5502      i = cursor_down(cap->count1, oap->op_type == OP_NOP);
5503    } else {
5504      i = nv_screengo(oap, FORWARD, cap->count1, false);
5505    }
5506    if (!i) {
5507      clearopbeep(oap);
5508    }
5509    break;
5510
5511  case 'k':
5512  case K_UP:
5513    // with 'nowrap' it works just like the normal "k" command.
5514    if (!curwin->w_p_wrap) {
5515      oap->motion_type = kMTLineWise;
5516      i = cursor_up(cap->count1, oap->op_type == OP_NOP);
5517    } else {
5518      i = nv_screengo(oap, BACKWARD, cap->count1, false);
5519    }
5520    if (!i) {
5521      clearopbeep(oap);
5522    }
5523    break;
5524
5525  // "gJ": join two lines without inserting a space.
5526  case 'J':
5527    nv_join(cap);
5528    break;
5529
5530  // "g0", "g^" : Like "0" and "^" but for screen lines.
5531  // "gm": middle of "g0" and "g$".
5532  case '^':
5533  case '0':
5534  case 'm':
5535  case K_HOME:
5536  case K_KHOME:
5537    nv_g_home_m_cmd(cap);
5538    break;
5539
5540  case 'M':
5541    oap->motion_type = kMTCharWise;
5542    oap->inclusive = false;
5543    i = linetabsize(curwin, curwin->w_cursor.lnum);
5544    if (cap->count0 > 0 && cap->count0 <= 100) {
5545      coladvance(curwin, (colnr_T)(i * cap->count0 / 100));
5546    } else {
5547      coladvance(curwin, (colnr_T)(i / 2));
5548    }
5549    curwin->w_set_curswant = true;
5550    break;
5551
5552  // "g_": to the last non-blank character in the line or <count> lines downward.
5553  case '_':
5554    nv_g_underscore_cmd(cap);
5555    break;
5556
5557  // "g$" : Like "$" but for screen lines.
5558  case '$':
5559  case K_END:
5560  case K_KEND:
5561    nv_g_dollar_cmd(cap);
5562    break;
5563
5564  // "g*" and "g#", like "*" and "#" but without using "\<" and "\>"
5565  case '*':
5566  case '#':
5567#if POUND != '#'
5568  case POUND:           // pound sign (sometimes equal to '#')
5569#endif
5570  case Ctrl_RSB:                // :tag or :tselect for current identifier
5571  case ']':                     // :tselect for current identifier
5572    nv_ident(cap);
5573    break;
5574
5575  // ge and gE: go back to end of word
5576  case 'e':
5577  case 'E':
5578    oap->motion_type = kMTCharWise;
5579    curwin->w_set_curswant = true;
5580    oap->inclusive = true;
5581    if (bckend_word(cap->count1, cap->nchar == 'E', false) == false) {
5582      clearopbeep(oap);
5583    }
5584    break;
5585
5586  // "g CTRL-G": display info about cursor position
5587  case Ctrl_G:
5588    cursor_pos_info(NULL);
5589    break;
5590
5591  // "gi": start Insert at the last position.
5592  case 'i':
5593    nv_gi_cmd(cap);
5594    break;
5595
5596  // "gI": Start insert in column 1.
5597  case 'I':
5598    beginline(0);
5599    if (!checkclearopq(oap)) {
5600      invoke_edit(cap, false, 'g', false);
5601    }
5602    break;
5603
5604  // "gf": goto file, edit file under cursor
5605  // "]f" and "[f": can also be used.
5606  case 'f':
5607  case 'F':
5608    nv_gotofile(cap);
5609    break;
5610
5611  // "g'm" and "g`m": jump to mark without setting pcmark
5612  case '\'':
5613    cap->arg = true;
5614    FALLTHROUGH;
5615  case '`':
5616    nv_gomark(cap);
5617    break;
5618
5619  // "gs": Goto sleep.
5620  case 's':
5621    do_sleep(cap->count1 * 1000, false);
5622    break;
5623
5624  // "ga": Display the ascii value of the character under the
5625  // cursor.    It is displayed in decimal, hex, and octal. -- webb
5626  case 'a':
5627    do_ascii(NULL);
5628    break;
5629
5630  // "g8": Display the bytes used for the UTF-8 character under the
5631  // cursor.    It is displayed in hex.
5632  // "8g8" finds illegal byte sequence.
5633  case '8':
5634    if (cap->count0 == 8) {
5635      utf_find_illegal();
5636    } else {
5637      show_utf8();
5638    }
5639    break;
5640  // "g<": show scrollback text
5641  case '<':
5642    show_sb_text();
5643    break;
5644
5645  // "gg": Goto the first line in file.  With a count it goes to
5646  // that line number like for "G". -- webb
5647  case 'g':
5648    cap->arg = false;
5649    nv_goto(cap);
5650    break;
5651
5652  //  Two-character operators:
5653  //  "gq"       Format text
5654  //  "gw"       Format text and keep cursor position
5655  //  "g~"       Toggle the case of the text.
5656  //  "gu"       Change text to lower case.
5657  //  "gU"       Change text to upper case.
5658  //  "g?"       rot13 encoding
5659  //  "g@"       call 'operatorfunc'
5660  case 'q':
5661  case 'w':
5662    oap->cursor_start = curwin->w_cursor;
5663    FALLTHROUGH;
5664  case '~':
5665  case 'u':
5666  case 'U':
5667  case '?':
5668  case '@':
5669    nv_operator(cap);
5670    break;
5671
5672  // "gd": Find first occurrence of pattern under the cursor in the current function
5673  // "gD": idem, but in the current file.
5674  case 'd':
5675  case 'D':
5676    nv_gd(oap, cap->nchar, cap->count0);
5677    break;
5678
5679  // g<LeftMouse>: jump to mouse-clicked tag, like "CTRL-]".
5680  case K_LEFTMOUSE:
5681    if (do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0)) {
5682      stuffcharReadbuff(Ctrl_RSB);
5683      exec_stuffed(cap);
5684    }
5685    break;
5686
5687  // g<*Mouse> : <C-*mouse>
5688  case K_MIDDLEMOUSE:
5689  case K_MIDDLEDRAG:
5690  case K_MIDDLERELEASE:
5691  case K_LEFTDRAG:
5692  case K_LEFTRELEASE:
5693  case K_MOUSEMOVE:
5694  case K_RIGHTMOUSE:
5695  case K_RIGHTDRAG:
5696  case K_RIGHTRELEASE:
5697  case K_X1MOUSE:
5698  case K_X1DRAG:
5699  case K_X1RELEASE:
5700  case K_X2MOUSE:
5701  case K_X2DRAG:
5702  case K_X2RELEASE:
5703    mod_mask = MOD_MASK_CTRL;
5704    do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0);
5705    break;
5706
5707  case K_IGNORE:
5708    break;
5709
5710  // "gP" and "gp": same as "P" and "p" but leave cursor just after new text
5711  case 'p':
5712  case 'P':
5713    nv_put(cap);
5714    break;
5715
5716  // "go": goto byte count from start of buffer
5717  case 'o':
5718    oap->inclusive = false;
5719    goto_byte(cap->count0);
5720    break;
5721
5722  case ',':
5723    nv_pcmark(cap);
5724    break;
5725
5726  case ';':
5727    cap->count1 = -cap->count1;
5728    nv_pcmark(cap);
5729    break;
5730
5731  case 't':
5732    if (!checkclearop(oap)) {
5733      goto_tabpage(cap->count0);
5734    }
5735    break;
5736  case 'T':
5737    if (!checkclearop(oap)) {
5738      goto_tabpage(-cap->count1);
5739    }
5740    break;
5741
5742  case TAB:
5743    if (!checkclearop(oap) && !goto_tabpage_lastused()) {
5744      clearopbeep(oap);
5745    }
5746    break;
5747
5748  case '+':
5749  case '-':   // "g+" and "g-": undo or redo along the timeline
5750    if (!checkclearopq(oap)) {
5751      undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1,
5752                false, false, false);
5753    }
5754    break;
5755
5756  default:
5757    clearopbeep(oap);
5758    break;
5759  }
5760}
5761
5762/// Handle "o" and "O" commands.
5763static void n_opencmd(cmdarg_T *cap)
5764{
5765  if (checkclearopq(cap->oap)) {
5766    return;
5767  }
5768
5769  if (cap->cmdchar == 'O') {
5770    // Open above the first line of a folded sequence of lines
5771    hasFolding(curwin, curwin->w_cursor.lnum,
5772               &curwin->w_cursor.lnum, NULL);
5773  } else {
5774    // Open below the last line of a folded sequence of lines
5775    hasFolding(curwin, curwin->w_cursor.lnum,
5776               NULL, &curwin->w_cursor.lnum);
5777  }
5778  // trigger TextChangedI for the 'o/O' command
5779  curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
5780  if (u_save(curwin->w_cursor.lnum - (cap->cmdchar == 'O' ? 1 : 0),
5781             curwin->w_cursor.lnum + (cap->cmdchar == 'o' ? 1 : 0))
5782      && open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD,
5783                   has_format_option(kFoOpenComs) ? OPENLINE_DO_COM : 0,
5784                   0, NULL)) {
5785    if (win_cursorline_standout(curwin)) {
5786      // force redraw of cursorline
5787      curwin->w_valid &= ~VALID_CROW;
5788    }
5789    invoke_edit(cap, false, cap->cmdchar, true);
5790  }
5791}
5792
5793/// "." command: redo last change.
5794static void nv_dot(cmdarg_T *cap)
5795{
5796  if (checkclearopq(cap->oap)) {
5797    return;
5798  }
5799
5800  // If "restart_edit" is true, the last but one command is repeated
5801  // instead of the last command (inserting text). This is used for
5802  // CTRL-O <.> in insert mode.
5803  if (start_redo(cap->count0, restart_edit != 0 && Ins.moved == kInsNone) == false) {
5804    clearopbeep(cap->oap);
5805    return;
5806  }
5807  // Execute the redo keys here: the whole replay resolves within this "." command.
5808  exec_stuffed(cap);
5809}
5810
5811/// CTRL-R: undo undo or specify register in select mode
5812static void nv_redo_or_register(cmdarg_T *cap)
5813{
5814  if (Visual.select && Visual.active) {
5815    // Get register name
5816    no_mapping++;
5817    int reg = plain_vgetc();
5818    LANGMAP_ADJUST(reg, true);
5819    no_mapping--;
5820
5821    if (reg == '"') {
5822      // the unnamed register is 0
5823      reg = 0;
5824    }
5825
5826    Visual.select_reg = valid_yank_reg(reg, true) ? reg : 0;
5827    return;
5828  }
5829
5830  if (checkclearopq(cap->oap)) {
5831    return;
5832  }
5833
5834  u_redo(cap->count1);
5835  curwin->w_set_curswant = true;
5836}
5837
5838/// Handle "U" command.
5839static void nv_Undo(cmdarg_T *cap)
5840{
5841  // In Visual mode and typing "gUU" triggers an operator
5842  if (cap->oap->op_type == OP_UPPER || Visual.active) {
5843    // translate "gUU" to "gUgU"
5844    cap->cmdchar = 'g';
5845    cap->nchar = 'U';
5846    nv_operator(cap);
5847    return;
5848  }
5849
5850  if (checkclearopq(cap->oap)) {
5851    return;
5852  }
5853
5854  u_undoline();
5855  curwin->w_set_curswant = true;
5856}
5857
5858/// '~' command: If tilde is not an operator and Visual is off: swap case of a
5859/// single character.
5860static void nv_tilde(cmdarg_T *cap)
5861{
5862  if (!p_to && !Visual.active && cap->oap->op_type != OP_TILDE) {
5863    if (bt_prompt(curbuf) && !prompt_curpos_editable()) {
5864      clearopbeep(cap->oap);
5865      return;
5866    }
5867    n_swapchar(cap);
5868  } else {
5869    nv_operator(cap);
5870  }
5871}
5872
5873/// Handle an operator command.
5874/// The actual work is done by do_pending_operator().
5875static void nv_operator(cmdarg_T *cap)
5876{
5877  int op_type = get_op_type(cap->cmdchar, cap->nchar);
5878
5879  if (bt_prompt(curbuf) && op_is_change(op_type)
5880      && !prompt_curpos_editable()) {
5881    clearopbeep(cap->oap);
5882    return;
5883  }
5884
5885  if (op_type == cap->oap->op_type) {  // double operator ("dd") works on lines
5886    nv_lineop(cap);
5887  } else if (!checkclearop(cap->oap)) {
5888    cap->oap->start = curwin->w_cursor;
5889    cap->oap->op_type = op_type;
5890    set_op_var(op_type);
5891  }
5892}
5893
5894/// Set v:operator to the characters for "optype".
5895static void set_op_var(int optype)
5896{
5897  if (optype == OP_NOP) {
5898    set_vim_var_string(VV_OP, NULL, 0);
5899  } else {
5900    char opchars[3];
5901    int opchar0 = get_op_char(optype);
5902    assert(opchar0 >= 0 && opchar0 <= UCHAR_MAX);
5903    opchars[0] = (char)opchar0;
5904
5905    int opchar1 = get_extra_op_char(optype);
5906    assert(opchar1 >= 0 && opchar1 <= UCHAR_MAX);
5907    opchars[1] = (char)opchar1;
5908
5909    opchars[2] = NUL;
5910    set_vim_var_string(VV_OP, opchars, 2);
5911  }
5912}
5913
5914/// Handle linewise operator "dd", "yy", etc.
5915///
5916/// "_" is a strange motion command that helps make operators more logical.
5917/// It is actually implemented, but not documented in the real Vi.  This motion
5918/// command actually refers to "the current line".  Commands like "dd" and "yy"
5919/// are really an alternate form of "d_" and "y_".  It does accept a count, so
5920/// "d3_" works to delete 3 lines.
5921static void nv_lineop(cmdarg_T *cap)
5922{
5923  cap->oap->motion_type = kMTLineWise;
5924  if (cursor_down(cap->count1 - 1, cap->oap->op_type == OP_NOP) == false) {
5925    clearopbeep(cap->oap);
5926  } else if ((cap->oap->op_type == OP_DELETE
5927              // only with linewise motions
5928              && cap->oap->motion_force != 'v'
5929              && cap->oap->motion_force != Ctrl_V)
5930             || cap->oap->op_type == OP_LSHIFT
5931             || cap->oap->op_type == OP_RSHIFT) {
5932    beginline(BL_SOL | BL_FIX);
5933  } else if (cap->oap->op_type != OP_YANK) {  // 'Y' does not move cursor
5934    beginline(BL_WHITE | BL_FIX);
5935  }
5936}
5937
5938/// <Home> command.
5939static void nv_home(cmdarg_T *cap)
5940{
5941  // CTRL-HOME is like "gg"
5942  if (mod_mask & MOD_MASK_CTRL) {
5943    nv_goto(cap);
5944  } else {
5945    cap->count0 = 1;
5946    nv_pipe(cap);
5947  }
5948  ins_at_eol = false;       // Don't move cursor past eol (only necessary in a
5949                            // one-character line).
5950}
5951
5952/// "|" command.
5953static void nv_pipe(cmdarg_T *cap)
5954{
5955  cap->oap->motion_type = kMTCharWise;
5956  cap->oap->inclusive = false;
5957  // Not using beginline(), the columns to skip for 'smoothscroll' must be
5958  // adjusted for the column we end up in, not for column zero.
5959  curwin->w_cursor.col = 0;
5960  curwin->w_cursor.coladd = 0;
5961  if (cap->count0 > 0) {
5962    coladvance(curwin, (colnr_T)(cap->count0 - 1));
5963    curwin->w_curswant = (colnr_T)(cap->count0 - 1);
5964  } else {
5965    curwin->w_curswant = 0;
5966  }
5967  // keep curswant at the column where we wanted to go, not where
5968  // we ended; differs if line is too short
5969  curwin->w_set_curswant = false;
5970  adjust_skipcol();
5971}
5972
5973/// Handle back-word command "b" and "B".
5974/// cap->arg is 1 for "B"
5975static void nv_bck_word(cmdarg_T *cap)
5976{
5977  cap->oap->motion_type = kMTCharWise;
5978  cap->oap->inclusive = false;
5979  curwin->w_set_curswant = true;
5980  if (bck_word(cap->count1, cap->arg, false) == false) {
5981    clearopbeep(cap->oap);
5982  } else if ((fdo_flags & kOptFdoFlagHor) && KeyTyped && cap->oap->op_type == OP_NOP) {
5983    foldOpenCursor();
5984  }
5985}
5986
5987/// Handle word motion commands "e", "E", "w" and "W".
5988/// cap->arg is true for "E" and "W".
5989static void nv_wordcmd(cmdarg_T *cap)
5990{
5991  int n;
5992  bool word_end;
5993  bool flag = false;
5994  pos_T startpos = curwin->w_cursor;
5995
5996  // Set inclusive for the "E" and "e" command.
5997  if (cap->cmdchar == 'e' || cap->cmdchar == 'E') {
5998    word_end = true;
5999  } else {
6000    word_end = false;
6001  }
6002  cap->oap->inclusive = word_end;
6003
6004  // "cw" and "cW" are a special case.
6005  if (!word_end && cap->oap->op_type == OP_CHANGE) {
6006    n = gchar_cursor();
6007    if (n != NUL && !ascii_iswhite(n)) {
6008      // This is a little strange.  To match what the real Vi does, we
6009      // effectively map "cw" to "ce", and "cW" to "cE", provided that we are
6010      // not on a space or a TAB.  This seems impolite at first, but it's
6011      // really more what we mean when we say "cw".
6012      //
6013      // Another strangeness: When standing on the end of a word "ce" will
6014      // change until the end of the next word, but "cw" will change only one
6015      // character!  This is done by setting "flag".
6016      if (vim_strchr(p_cpo, kCpoChangew) != NULL) {
6017        cap->oap->inclusive = true;
6018        word_end = true;
6019      }
6020      flag = true;
6021    }
6022  }
6023
6024  cap->oap->motion_type = kMTCharWise;
6025  curwin->w_set_curswant = true;
6026  if (word_end) {
6027    n = end_word(cap->count1, cap->arg, flag, false);
6028  } else {
6029    n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP);
6030  }
6031
6032  // Don't leave the cursor on the NUL past the end of line. Unless we
6033  // didn't move it forward.
6034  if (lt(startpos, curwin->w_cursor)) {
6035    adjust_cursor(cap->oap);
6036  }
6037
6038  if (n == false && cap->oap->op_type == OP_NOP) {
6039    clearopbeep(cap->oap);
6040  } else {
6041    adjust_for_sel(cap);
6042    if ((fdo_flags & kOptFdoFlagHor) && KeyTyped && cap->oap->op_type == OP_NOP) {
6043      foldOpenCursor();
6044    }
6045  }
6046}
6047
6048/// Used after a movement command: If the cursor ends up on the NUL after the
6049/// end of the line, may move it back to the last character and make the motion
6050/// inclusive.
6051static void adjust_cursor(oparg_T *oap)
6052{
6053  // The cursor cannot remain on the NUL when:
6054  // - the column is > 0
6055  // - not in Visual mode or 'selection' is "o"
6056  // - 'virtualedit' is not "all" and not "onemore".
6057  if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL
6058      && (!Visual.active || *p_sel == 'o')
6059      && !virtual_active(curwin)
6060      && (get_ve_flags(curwin) & kOptVeFlagOnemore) == 0) {
6061    curwin->w_cursor.col--;
6062    // prevent cursor from moving on the trail byte
6063    mb_adjust_cursor();
6064    oap->inclusive = true;
6065  }
6066}
6067
6068/// "0" and "^" commands.
6069/// cap->arg is the argument for beginline().
6070static void nv_beginline(cmdarg_T *cap)
6071{
6072  cap->oap->motion_type = kMTCharWise;
6073  cap->oap->inclusive = false;
6074  beginline(cap->arg);
6075  if ((fdo_flags & kOptFdoFlagHor) && KeyTyped && cap->oap->op_type == OP_NOP) {
6076    foldOpenCursor();
6077  }
6078  ins_at_eol = false;       // Don't move cursor past eol (only necessary in a
6079                            // one-character line).
6080}
6081
6082/// In exclusive Visual mode, may include the last character.
6083static void adjust_for_sel(cmdarg_T *cap)
6084{
6085  if (Visual.active && cap->oap->inclusive && *p_sel == 'e'
6086      && gchar_cursor() != NUL && lt(Visual.start, curwin->w_cursor)) {
6087    inc_cursor();
6088    cap->oap->inclusive = false;
6089    Visual.select_exclu_adj = true;
6090  }
6091}
6092
6093/// Exclude last character at end of Visual area for 'selection' == "exclusive".
6094/// Should check Visual.mode before calling this.
6095///
6096/// @return  true when backed up to the previous line.
6097bool unadjust_for_sel(void)
6098{
6099  if (*p_sel == 'e' && !equalpos(Visual.start, curwin->w_cursor)) {
6100    return unadjust_for_sel_inner(lt(Visual.start, curwin->w_cursor)
6101                                  ? &curwin->w_cursor : &Visual.start);
6102  }
6103  return false;
6104}
6105
6106/// Move position "*pp" back one character for 'selection' == "exclusive".
6107///
6108/// @return  true when backed up to the previous line.
6109bool unadjust_for_sel_inner(pos_T *pp)
6110{
6111  Visual.select_exclu_adj = false;
6112
6113  if (pp->coladd > 0) {
6114    pp->coladd--;
6115  } else if (pp->col > 0) {
6116    pp->col--;
6117    mark_mb_adjustpos(curbuf, pp);
6118    if (virtual_active(curwin)) {
6119      colnr_T cs, ce;
6120      getvcol(curwin, pp, &cs, NULL, &ce, 0);
6121      pp->coladd = ce - cs;
6122    }
6123  } else if (pp->lnum > 1) {
6124    pp->lnum--;
6125    pp->col = ml_get_len(pp->lnum);
6126    return true;
6127  }
6128
6129  return false;
6130}
6131
6132/// SELECT key in Normal or Visual mode: end of Select mode mapping.
6133static void nv_select(cmdarg_T *cap)
6134{
6135  if (Visual.active) {
6136    Visual.select = true;
6137    Visual.select_reg = 0;
6138  } else if (Visual.reselect) {
6139    cap->nchar = 'v';               // fake "gv" command
6140    cap->arg = true;
6141    nv_g_cmd(cap);
6142  }
6143}
6144
6145/// "G", "gg", CTRL-END, CTRL-HOME.
6146/// cap->arg is true for "G".
6147static void nv_goto(cmdarg_T *cap)
6148{
6149  linenr_T lnum;
6150
6151  if (cap->arg) {
6152    lnum = curbuf->b_ml.ml_line_count;
6153  } else {
6154    lnum = 1;
6155  }
6156  cap->oap->motion_type = kMTLineWise;
6157  setpcmark();
6158
6159  // When a count is given, use it instead of the default lnum
6160  if (cap->count0 != 0) {
6161    lnum = cap->count0;
6162  }
6163  lnum = MIN(MAX(lnum, 1), curbuf->b_ml.ml_line_count);
6164  curwin->w_cursor.lnum = lnum;
6165  beginline(BL_SOL | BL_FIX);
6166  if ((fdo_flags & kOptFdoFlagJump) && KeyTyped && cap->oap->op_type == OP_NOP) {
6167    foldOpenCursor();
6168  }
6169}
6170
6171/// CTRL-\ in Normal mode.
6172static void nv_normal(cmdarg_T *cap)
6173{
6174  if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G) {
6175    clearop(cap->oap);
6176    if (restart_edit != 0 && mode_displayed) {
6177      clear_cmdline = true;                     // unshow mode later
6178    }
6179    restart_edit = 0;
6180    if (Visual.active) {
6181      end_visual_mode();                // stop Visual
6182      redraw_curbuf_later(UPD_INVERTED);
6183    }
6184  } else {
6185    clearopbeep(cap->oap);
6186  }
6187}
6188
6189/// ESC in Normal mode: beep, but don't flush buffers.
6190/// Don't even beep if we are canceling a command.
6191static void nv_esc(cmdarg_T *cap)
6192{
6193  bool no_reason = (cap->oap->op_type == OP_NOP
6194                    && cap->opcount == 0
6195                    && cap->count0 == 0
6196                    && cap->oap->regname == 0);
6197  bool cmdwin_cancel = cap->arg && bt_cmdwin(curbuf);
6198
6199  if (cmdwin_cancel) {
6200    got_int = false;  // CTRL-C cancels cmdwin; don't interrupt autocmds etc.
6201    cmdwin_do_action("cancel");
6202  } else if (cap->arg) {        // true for CTRL-C
6203    if (restart_edit == 0 && !Visual.active && no_reason) {
6204      if (anyBufIsChanged()) {
6205        msg(_("Type  :qa!  and press <Enter> to abandon all changes"
6206              " and exit Nvim"), 0);
6207      } else {
6208        msg(_("Type  :qa  and press <Enter> to exit Nvim"), 0);
6209      }
6210    }
6211
6212    if (restart_edit != 0) {
6213      redraw_mode = true;  // remove "-- (insert) --"
6214    }
6215
6216    restart_edit = 0;
6217  }
6218
6219  if (Visual.active) {
6220    end_visual_mode();          // stop Visual
6221    check_cursor_col(curwin);         // make sure cursor is not beyond EOL
6222    curwin->w_set_curswant = true;
6223    redraw_curbuf_later(UPD_INVERTED);
6224  } else if (no_reason && !cmdwin_cancel) {
6225    vim_beep(kOptBoFlagEsc);
6226  }
6227  clearop(cap->oap);
6228}
6229
6230/// Move the cursor for the "A" command.
6231void set_cursor_for_append_to_line(void)
6232{
6233  curwin->w_set_curswant = true;
6234  if (get_ve_flags(curwin) == kOptVeFlagAll) {
6235    const int save_State = State;
6236    // Pretend Insert mode here to allow the cursor on the
6237    // character past the end of the line
6238    State = MODE_INSERT;
6239    coladvance(curwin, MAXCOL);
6240    State = save_State;
6241  } else {
6242    curwin->w_cursor.col += (colnr_T)strlen(get_cursor_pos_ptr());
6243  }
6244}
6245
6246/// Handle "A", "a", "I", "i" and <Insert> commands.
6247static void nv_edit(cmdarg_T *cap)
6248{
6249  // <Insert> is equal to "i"
6250  if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS) {
6251    cap->cmdchar = 'i';
6252  }
6253
6254  // in Visual mode "A" and "I" are an operator
6255  if (Visual.active && (cap->cmdchar == 'A' || cap->cmdchar == 'I')) {
6256    v_visop(cap);
6257    // in Visual mode and after an operator "a" and "i" are for text objects
6258  } else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i')
6259             && (cap->oap->op_type != OP_NOP || Visual.active)) {
6260    nv_object(cap);
6261  } else if (!curbuf->b_p_ma && !curbuf->terminal) {
6262    emsg(_(e_modifiable));
6263    clearop(cap->oap);
6264  } else if (!checkclearopq(cap->oap)) {
6265    switch (cap->cmdchar) {
6266    case 'A':           // "A"ppend after the line
6267      set_cursor_for_append_to_line();
6268      break;
6269
6270    case 'I':           // "I"nsert before the first non-blank
6271      beginline(BL_WHITE);
6272      break;
6273
6274    case 'a':           // "a"ppend is like "i"nsert on the next character.
6275      // increment coladd when in virtual space, increment the
6276      // column otherwise, also to append after an unprintable char
6277      if (virtual_active(curwin)
6278          && (curwin->w_cursor.coladd > 0
6279              || *get_cursor_pos_ptr() == NUL
6280              || *get_cursor_pos_ptr() == TAB)) {
6281        curwin->w_cursor.coladd++;
6282      } else if (*get_cursor_pos_ptr() != NUL) {
6283        inc_cursor();
6284      }
6285      break;
6286    }
6287
6288    if (curwin->w_cursor.coladd && cap->cmdchar != 'A') {
6289      int save_State = State;
6290
6291      // Pretend Insert mode here to allow the cursor on the
6292      // character past the end of the line
6293      State = MODE_INSERT;
6294      coladvance(curwin, getviscol());
6295      State = save_State;
6296    }
6297
6298    invoke_edit(cap, false, cap->cmdchar, false);
6299  }
6300}
6301
6302/// Invoke edit() and take care of "restart_edit" and the return value.
6303///
6304/// @param repl  "r" or "gr" command
6305static void invoke_edit(cmdarg_T *cap, int repl, int cmd, int startln)
6306{
6307  int restart_edit_save = 0;
6308
6309  // Complicated: When the user types "a<C-O>a" we don't want to do Insert
6310  // mode recursively.  But when doing "a<C-O>." or "a<C-O>rx" we do allow
6311  // it.
6312  if (repl || !stuff_empty()) {
6313    restart_edit_save = restart_edit;
6314  } else {
6315    restart_edit_save = 0;
6316  }
6317
6318  // Always reset "restart_edit", this is not a restarted edit.
6319  restart_edit = 0;
6320
6321  // Reset Changedtick_i, so that TextChangedI will only be triggered for stuff
6322  // from insert mode, for 'o/O' this has already been done in n_opencmd
6323  if (cap->cmdchar != 'O' && cap->cmdchar != 'o') {
6324    curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
6325  }
6326  InsSession session = atom_ins_start(cmd, cap->count1, kVInsNone, false);
6327  bool busy = edit(cmd, startln, cap->count1);
6328  if (busy) {
6329    cap->retval |= CA_COMMAND_BUSY;
6330  }
6331
6332  if (restart_edit == 0) {
6333    restart_edit = restart_edit_save;
6334  }
6335
6336  atom_ins_end(&session, busy);
6337}
6338
6339/// "a" or "i" while an operator is pending or in Visual mode: object motion.
6340static void nv_object(cmdarg_T *cap)
6341{
6342  bool flag;
6343  bool include;
6344
6345  if (cap->cmdchar == 'i') {
6346    include = false;        // "ix" = inner object: exclude white space
6347  } else {
6348    include = true;         // "ax" = an object: include white space
6349  }
6350  // Make sure (), [], {} and <> are in 'matchpairs'
6351  char *mps_save = curbuf->b_p_mps;
6352  curbuf->b_p_mps = "(:),{:},[:],<:>";
6353
6354  switch (cap->nchar) {
6355  case 'w':       // "aw" = a word
6356    flag = current_word(cap->oap, cap->count1, include, false);
6357    break;
6358  case 'W':       // "aW" = a WORD
6359    flag = current_word(cap->oap, cap->count1, include, true);
6360    break;
6361  case 'b':       // "ab" = a braces block
6362  case '(':
6363  case ')':
6364    flag = current_block(cap->oap, cap->count1, include, '(', ')');
6365    break;
6366  case 'B':       // "aB" = a Brackets block
6367  case '{':
6368  case '}':
6369    flag = current_block(cap->oap, cap->count1, include, '{', '}');
6370    break;
6371  case '[':       // "a[" = a [] block
6372  case ']':
6373    flag = current_block(cap->oap, cap->count1, include, '[', ']');
6374    break;
6375  case '<':       // "a<" = a <> block
6376  case '>':
6377    flag = current_block(cap->oap, cap->count1, include, '<', '>');
6378    break;
6379  case 't':       // "at" = a tag block (xml and html)
6380    // Do not adjust oap->end in do_pending_operator()
6381    // otherwise there are different results for 'dit'
6382    // (note leading whitespace in last line):
6383    // 1) <b>      2) <b>
6384    //    foobar      foobar
6385    //    </b>            </b>
6386    cap->retval |= CA_NO_ADJ_OP_END;
6387    flag = current_tagblock(cap->oap, cap->count1, include);
6388    break;
6389  case 'p':       // "ap" = a paragraph
6390    flag = current_par(cap->oap, cap->count1, include, 'p');
6391    break;
6392  case 'l':       // "il" = inner line, "al" = all lines
6393    flag = current_line(cap->oap, include);
6394    break;
6395  case 's':       // "as" = a sentence
6396    flag = current_sent(cap->oap, cap->count1, include);
6397    break;
6398  case '"':       // "a"" = a double quoted string
6399  case '\'':       // "a'" = a single quoted string
6400  case '`':       // "a`" = a backtick quoted string
6401    flag = current_quote(cap->oap, cap->count1, include,
6402                         cap->nchar);
6403    break;
6404  default:
6405    flag = false;
6406    break;
6407  }
6408
6409  curbuf->b_p_mps = mps_save;
6410  if (!flag) {
6411    clearopbeep(cap->oap);
6412  }
6413  adjust_cursor_col();
6414  curwin->w_set_curswant = true;
6415}
6416
6417/// "q" command: Start/stop macro recording.
6418/// "q:", "q/", "q?": cmdwin.
6419/// "[count]q:": interactive Ex-mode.
6420/// "q=": Multicursor "follow".
6421static void nv_q(cmdarg_T *cap)
6422{
6423  if (cap->oap->op_type == OP_FORMAT) {
6424    // "gqq" is the same as "gqgq": format line
6425    cap->cmdchar = 'g';
6426    cap->nchar = 'q';
6427    nv_operator(cap);
6428    return;
6429  }
6430
6431  if (checkclearop(cap->oap)) {
6432    return;
6433  }
6434
6435  if (cap->nchar == '=' && cap->count0 > 2) {
6436    clearopbeep(cap->oap);
6437  } else if (cap->nchar == '=') {  // "1q=" on, "2q=" off.
6438    mc_follow_set(cap->count0 == 0 ? kNone : cap->count0 == 1 ? kTrue : kFalse);
6439  } else if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?') {
6440    if (cmdwin_buf != NULL) {
6441      emsg(_(e_cmdline_window_already_open));
6442      return;
6443    }
6444    if (cap->nchar == ':' && cap->count0 > 0) {
6445      // "[count]q:": interactive Ex mode. E565 on textlock.
6446      do_cmdline_cmd("exmode");
6447      return;
6448    }
6449    bool insert_range = Visual.active && cap->nchar == ':';
6450    char fc[2] = { (char)cap->nchar, 0 };
6451    typval_T tv_args[] = {
6452      { .v_type = VAR_STRING, .vval.v_string = fc },
6453      { .v_type = VAR_STRING, .vval.v_string = insert_range ? "'<,'>" : "" },
6454      { .v_type = VAR_NUMBER, .vval.v_number = insert_range ? 5 : 1 },
6455      { .v_type = VAR_UNKNOWN },
6456    };
6457    nlua_call_typval("vim._core.cmdwin", "open", tv_args, NULL);
6458  } else {
6459    // (stop) recording into a named register, unless executing a
6460    // register.
6461    if (reg_executing == 0 && do_record(cap->nchar) == FAIL) {
6462      clearopbeep(cap->oap);
6463    }
6464  }
6465}
6466
6467/// Handle the "@r" command.
6468static void nv_at(cmdarg_T *cap)
6469{
6470  if (checkclearop(cap->oap)) {
6471    return;
6472  }
6473  if (cap->nchar == '=') {
6474    if (get_expr_register() == NUL) {
6475      return;
6476    }
6477  }
6478  atom_macro_start(cap->nchar);
6479  while (cap->count1-- && !got_int) {
6480    if (do_execreg(cap->nchar, false, false, false) == false) {
6481      clearopbeep(cap->oap);
6482      break;
6483    }
6484    line_breakcheck();
6485  }
6486}
6487
6488/// Handle the CTRL-U and CTRL-D commands.
6489static void nv_halfpage(cmdarg_T *cap)
6490{
6491  if (!checkclearop(cap->oap)) {
6492    pagescroll(cap->cmdchar == Ctrl_D ? FORWARD : BACKWARD, cap->count0, true);
6493  }
6494}
6495
6496/// Handle "J" or "gJ" command.
6497static void nv_join(cmdarg_T *cap)
6498{
6499  if (Visual.active) {  // join the visual lines
6500    nv_operator(cap);
6501    return;
6502  }
6503
6504  if (checkclearop(cap->oap)) {
6505    return;
6506  }
6507
6508  cap->count0 = MAX(cap->count0, 2);  // default for join is two lines!
6509
6510  if (curwin->w_cursor.lnum + cap->count0 - 1 >
6511      curbuf->b_ml.ml_line_count) {
6512    // can't join when on the last line
6513    if (cap->count0 <= 2) {
6514      clearopbeep(cap->oap);
6515      return;
6516    }
6517    cap->count0 = curbuf->b_ml.ml_line_count - curwin->w_cursor.lnum + 1;
6518  }
6519
6520  prep_redo_cmd(cap);
6521  do_join((size_t)cap->count0, cap->nchar == NUL, true, true, true);
6522}
6523
6524/// "P", "gP", "p" and "gp" commands.
6525static void nv_put(cmdarg_T *cap)
6526{
6527  nv_put_opt(cap, false);
6528}
6529
6530/// "P", "gP", "p" and "gp" commands.
6531///
6532/// @param fix_indent  true for "[p", "[P", "]p" and "]P".
6533static void nv_put_opt(cmdarg_T *cap, bool fix_indent)
6534{
6535  yankreg_T *savereg = NULL;
6536  bool empty = false;
6537  bool was_visual = false;
6538  int dir;
6539  int flags = 0;
6540  const int save_fen = curwin->w_p_fen;
6541
6542  if (cap->oap->op_type != OP_NOP) {
6543    // "dp" is ":diffput"
6544    if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p') {
6545      atom_capture_op(cap->oap, cap, false);  // Atom + dot-repeat for "dp".
6546      clearop(cap->oap);
6547      assert(cap->opcount >= 0);
6548      nv_diffgetput(true, (size_t)cap->opcount);
6549    } else {
6550      clearopbeep(cap->oap);
6551    }
6552    return;
6553  }
6554
6555  if (bt_prompt(curbuf) && !prompt_curpos_editable()) {
6556    if (curwin->w_cursor.lnum == curbuf->b_prompt_start.mark.lnum) {
6557      curwin->w_cursor.col = curbuf->b_prompt_start.mark.col;
6558      // Since we've shifted the cursor to the first editable char. We want to
6559      // paste before that.
6560      cap->cmdchar = 'P';
6561    } else {
6562      clearopbeep(cap->oap);
6563      return;
6564    }
6565  }
6566
6567  if (fix_indent) {
6568    dir = (cap->cmdchar == ']' && cap->nchar == 'p')
6569          ? FORWARD : BACKWARD;
6570    flags |= PUT_FIXINDENT;
6571  } else {
6572    dir = (cap->cmdchar == 'P'
6573           || ((cap->cmdchar == 'g' || cap->cmdchar == 'z')
6574               && cap->nchar == 'P')) ? BACKWARD : FORWARD;
6575  }
6576  bool vatom_prepped = false;
6577  if (Visual.active) {
6578    // Visual-mode put: complete the visual atom ("viw" + "p").
6579    vatom_prepped = atom_visual_end((CmdSpec){ .regname = cap->oap->regname, .count = cap->count0,
6580                                               .cmd = cap->cmdchar, .cmd2 = cap->nchar }, true);
6581  }
6582  if (!vatom_prepped) {
6583    prep_redo_cmd(cap);
6584  }
6585  if (cap->cmdchar == 'g') {
6586    flags |= PUT_CURSEND;
6587  } else if (cap->cmdchar == 'z') {
6588    flags |= PUT_BLOCK_INNER;
6589  }
6590
6591  if (Visual.active) {
6592    // Putting in Visual mode: The put text replaces the selected
6593    // text.  First delete the selected text, then put the new text.
6594    // Need to save and restore the registers that the delete
6595    // overwrites if the old contents is being put.
6596    was_visual = true;
6597    int regname = cap->oap->regname;
6598    bool keep_registers = cap->cmdchar == 'P';
6599    // '+' and '*' could be the same selection
6600    bool clipoverwrite = (regname == '+' || regname == '*')
6601                         && (cb_flags & (kOptCbFlagUnnamed | kOptCbFlagUnnamedplus));
6602    if (regname == 0 || regname == '"' || clipoverwrite
6603        || ascii_isdigit(regname) || regname == '-') {
6604      // The delete might overwrite the register we want to put, save it first
6605      savereg = copy_register(regname);
6606    }
6607
6608    // Temporarily disable folding, as deleting a fold marker may cause
6609    // the cursor to be included in a fold.
6610    curwin->w_p_fen = false;
6611
6612    // To place the cursor correctly after a blockwise put, and to leave the
6613    // text in the correct position when putting over a selection with
6614    // 'virtualedit' and past the end of the line, we use the 'c' operator in
6615    // do_put(), which requires the visual selection to still be active.
6616    if (!Visual.active || Visual.mode == 'V' || regname != '.') {
6617      // Now delete the selected text. Avoid messages here.
6618      cap->cmdchar = 'd';
6619      cap->nchar = NUL;
6620      cap->oap->regname = keep_registers ? '_' : NUL;
6621      msg_silent++;
6622      atom_suppress(true);  // internal op: the put atom already cascades
6623      nv_operator(cap);
6624      do_pending_operator(cap, 0, false);
6625      atom_suppress(false);
6626      empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
6627      msg_silent--;
6628
6629      // delete PUT_LINE_BACKWARD;
6630      cap->oap->regname = regname;
6631    }
6632
6633    // When deleted a linewise Visual area, put the register as
6634    // lines to avoid it joined with the next line.  When deletion was
6635    // charwise, split a line when putting lines.
6636    if (Visual.mode == 'V') {
6637      flags |= PUT_LINE;
6638    } else if (Visual.mode == 'v') {
6639      flags |= PUT_LINE_SPLIT;
6640    }
6641    if (Visual.mode == Ctrl_V && dir == FORWARD) {
6642      flags |= PUT_LINE_FORWARD;
6643    }
6644    dir = BACKWARD;
6645    if ((Visual.mode != 'V'
6646         && curwin->w_cursor.col < curbuf->b_op_start.col)
6647        || (Visual.mode == 'V'
6648            && curwin->w_cursor.lnum < curbuf->b_op_start.lnum)) {
6649      // cursor is at the end of the line or end of file, put
6650      // forward.
6651      dir = FORWARD;
6652    }
6653    // May have been reset in do_put().
6654    Visual.active = true;
6655  }
6656  do_put(cap->oap->regname, savereg, dir, cap->count1, flags);
6657
6658  // If a register was saved, free it
6659  if (savereg != NULL) {
6660    free_register(savereg);
6661    xfree(savereg);
6662  }
6663
6664  if (was_visual) {
6665    if (save_fen) {
6666      curwin->w_p_fen = true;
6667    }
6668    // What to reselect with "gv"?  Selecting the just put text seems to
6669    // be the most useful, since the original text was removed.
6670    curbuf->b_visual.vi_start = curbuf->b_op_start;
6671    curbuf->b_visual.vi_end = curbuf->b_op_end;
6672    // need to adjust cursor position
6673    if (*p_sel == 'e') {
6674      inc(&curbuf->b_visual.vi_end);
6675    }
6676  }
6677
6678  // When all lines were selected and deleted do_put() leaves an empty
6679  // line that needs to be deleted now.
6680  if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL) {
6681    ml_delete_flags(curbuf->b_ml.ml_line_count, ML_DEL_MESSAGE);
6682    deleted_lines(curbuf->b_ml.ml_line_count + 1, 1);
6683
6684    // If the cursor was in that line, move it to the end of the last
6685    // line.
6686    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) {
6687      curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6688      coladvance(curwin, MAXCOL);
6689    }
6690  }
6691  auto_format(false, true);
6692}
6693
6694/// "o" and "O" commands.
6695static void nv_open(cmdarg_T *cap)
6696{
6697  // "do" is ":diffget"
6698  if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o') {
6699    atom_capture_op(cap->oap, cap, false);  // Atom + dot-repeat for "do".
6700    clearop(cap->oap);
6701    assert(cap->opcount >= 0);
6702    nv_diffgetput(false, (size_t)cap->opcount);
6703  } else if (Visual.active) {
6704    // switch start and end of visual/
6705    v_swap_corners(cap->cmdchar);
6706  } else if (bt_prompt(curbuf) && curwin->w_cursor.lnum < curbuf->b_prompt_start.mark.lnum) {
6707    clearopbeep(cap->oap);
6708  } else {
6709    n_opencmd(cap);
6710  }
6711}
6712
6713/// Handles K_PASTE_START, repeats pasted text.
6714static void nv_paste(cmdarg_T *cap)
6715{
6716  paste_repeat(cap->count1);
6717}
6718
6719/// Handle an arbitrary event in normal mode
6720static void nv_event(cmdarg_T *cap)
6721{
6722  // Garbage collection should have been executed before blocking for events in
6723  // the `input_get` in `state_enter`, but we also disable it here in case the
6724  // `input_get` branch was not executed (!multiqueue_empty(loop.events), which
6725  // could have `may_garbage_collect` set to true in `normal_check`).
6726  //
6727  // That is because here we may run code that calls `input_get` later
6728  // (`f_confirm` or `get_keystroke` for example), but in these cases it is
6729  // not safe to perform garbage collection because there could be unreferenced
6730  // lists or dicts being used.
6731  may_garbage_collect = false;
6732  bool may_restart = (restart_edit != 0 || Visual.restart_select != 0);
6733  state_handle_k_event();
6734  finish_op = false;
6735  if (may_restart) {
6736    // Tricky: if restart_edit was set before the handler we are in ctrl-o mode,
6737    // but if not, the event should be allowed to trigger :startinsert.
6738    cap->retval |= CA_COMMAND_BUSY;  // don't call edit() or restart Select now
6739  }
6740}
6741
6742/// Executes one MODE_NORMAL command (Normal, Visual, Select and Op-pending, see get_real_state())
6743/// from pending input, outside the main state machine.
6744///
6745/// Called in a loop. A pending op/register travels into the next call via `oap`; a count prefix via
6746/// `opcount` ("3dl" is two calls, one command).
6747///
6748/// @param toplevel  `NormalState.toplevel` (full interactive-command treatment).
6749void normal_cmd(oparg_T *oap, bool toplevel)
6750{
6751  NormalState s;
6752  normal_state_init(&s);
6753  s.toplevel = toplevel;
6754  s.oa = *oap;
6755  normal_prepare(&s);
6756  normal_execute(&s.state, safe_vgetc());
6757  *oap = s.oa;
6758}
6759
6760/// Executes pending readahead now (see "Stuffing", input.c).
6761///
6762/// During "textlock" the stuffed keys are queued instead (main loop). For CmdAtom/multicursor
6763/// purposes, that's fine: if stuff_empty()=false, pending CmdAtom stays open, will collect later.
6764///
6765/// @param cap  The cmd whose translation was stuffed ("x" => "dl"), or NULL (internal stuff).
6766void exec_stuffed(cmdarg_T *cap)
6767{
6768  if (cap != NULL) {
6769    atom_stuff_start(cap);  // Label as one atom.
6770  }
6771  if (text_locked() || curbuf_locked()) {
6772    return;
6773  }
6774  oparg_T oa;
6775  clear_oparg(&oa);
6776  oparg_T *oap = cap != NULL ? cap->oap : &oa;
6777  finish_op = false;
6778  while (!stuff_empty() && !got_int) {
6779    update_topline_cursor();
6780    // Continue the command's operator state.
6781    normal_cmd(oap, true);
6782  }
6783  finish_op = false;
6784  if (cap != NULL && restart_edit != 0) {
6785    // When insert-session-resume is pending (i_CTRL-O), resume happens after next command.
6786    cap->retval |= CA_COMMAND_BUSY;
6787  }
6788}