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