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