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