xref: /vim-8.2.3635/src/normal.c (revision d2ea7cf1)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 /*
10  * normal.c:	Contains the main routine for processing characters in command
11  *		mode.  Communicates closely with the code in ops.c to handle
12  *		the operators.
13  */
14 
15 #include "vim.h"
16 
17 static int	VIsual_mode_orig = NUL;		// saved Visual mode
18 static int	restart_VIsual_select = 0;
19 
20 #ifdef FEAT_EVAL
21 static void	set_vcount_ca(cmdarg_T *cap, int *set_prevcount);
22 #endif
23 static int	nv_compare(const void *s1, const void *s2);
24 static void	unshift_special(cmdarg_T *cap);
25 #ifdef FEAT_CMDL_INFO
26 static void	del_from_showcmd(int);
27 #endif
28 
29 /*
30  * nv_*(): functions called to handle Normal and Visual mode commands.
31  * n_*(): functions called to handle Normal mode commands.
32  * v_*(): functions called to handle Visual mode commands.
33  */
34 static void	nv_ignore(cmdarg_T *cap);
35 static void	nv_nop(cmdarg_T *cap);
36 static void	nv_error(cmdarg_T *cap);
37 static void	nv_help(cmdarg_T *cap);
38 static void	nv_addsub(cmdarg_T *cap);
39 static void	nv_page(cmdarg_T *cap);
40 static void	nv_zet(cmdarg_T *cap);
41 #ifdef FEAT_GUI
42 static void	nv_ver_scrollbar(cmdarg_T *cap);
43 static void	nv_hor_scrollbar(cmdarg_T *cap);
44 #endif
45 #ifdef FEAT_GUI_TABLINE
46 static void	nv_tabline(cmdarg_T *cap);
47 static void	nv_tabmenu(cmdarg_T *cap);
48 #endif
49 static void	nv_exmode(cmdarg_T *cap);
50 static void	nv_colon(cmdarg_T *cap);
51 static void	nv_ctrlg(cmdarg_T *cap);
52 static void	nv_ctrlh(cmdarg_T *cap);
53 static void	nv_clear(cmdarg_T *cap);
54 static void	nv_ctrlo(cmdarg_T *cap);
55 static void	nv_hat(cmdarg_T *cap);
56 static void	nv_Zet(cmdarg_T *cap);
57 static void	nv_ident(cmdarg_T *cap);
58 static void	nv_tagpop(cmdarg_T *cap);
59 static void	nv_scroll(cmdarg_T *cap);
60 static void	nv_right(cmdarg_T *cap);
61 static void	nv_left(cmdarg_T *cap);
62 static void	nv_up(cmdarg_T *cap);
63 static void	nv_down(cmdarg_T *cap);
64 static void	nv_end(cmdarg_T *cap);
65 static void	nv_dollar(cmdarg_T *cap);
66 static void	nv_search(cmdarg_T *cap);
67 static void	nv_next(cmdarg_T *cap);
68 static int	normal_search(cmdarg_T *cap, int dir, char_u *pat, int opt, int *wrapped);
69 static void	nv_csearch(cmdarg_T *cap);
70 static void	nv_brackets(cmdarg_T *cap);
71 static void	nv_percent(cmdarg_T *cap);
72 static void	nv_brace(cmdarg_T *cap);
73 static void	nv_mark(cmdarg_T *cap);
74 static void	nv_findpar(cmdarg_T *cap);
75 static void	nv_undo(cmdarg_T *cap);
76 static void	nv_kundo(cmdarg_T *cap);
77 static void	nv_Replace(cmdarg_T *cap);
78 static void	nv_replace(cmdarg_T *cap);
79 static void	nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos);
80 static void	v_visop(cmdarg_T *cap);
81 static void	nv_subst(cmdarg_T *cap);
82 static void	nv_abbrev(cmdarg_T *cap);
83 static void	nv_optrans(cmdarg_T *cap);
84 static void	nv_gomark(cmdarg_T *cap);
85 static void	nv_pcmark(cmdarg_T *cap);
86 static void	nv_regname(cmdarg_T *cap);
87 static void	nv_visual(cmdarg_T *cap);
88 static void	n_start_visual_mode(int c);
89 static void	nv_window(cmdarg_T *cap);
90 static void	nv_suspend(cmdarg_T *cap);
91 static void	nv_g_cmd(cmdarg_T *cap);
92 static void	nv_dot(cmdarg_T *cap);
93 static void	nv_redo(cmdarg_T *cap);
94 static void	nv_Undo(cmdarg_T *cap);
95 static void	nv_tilde(cmdarg_T *cap);
96 static void	nv_operator(cmdarg_T *cap);
97 #ifdef FEAT_EVAL
98 static void	set_op_var(int optype);
99 #endif
100 static void	nv_lineop(cmdarg_T *cap);
101 static void	nv_home(cmdarg_T *cap);
102 static void	nv_pipe(cmdarg_T *cap);
103 static void	nv_bck_word(cmdarg_T *cap);
104 static void	nv_wordcmd(cmdarg_T *cap);
105 static void	nv_beginline(cmdarg_T *cap);
106 static void	adjust_cursor(oparg_T *oap);
107 static void	adjust_for_sel(cmdarg_T *cap);
108 static void	nv_select(cmdarg_T *cap);
109 static void	nv_goto(cmdarg_T *cap);
110 static void	nv_normal(cmdarg_T *cap);
111 static void	nv_esc(cmdarg_T *oap);
112 static void	nv_edit(cmdarg_T *cap);
113 static void	invoke_edit(cmdarg_T *cap, int repl, int cmd, int startln);
114 #ifdef FEAT_TEXTOBJ
115 static void	nv_object(cmdarg_T *cap);
116 #endif
117 static void	nv_record(cmdarg_T *cap);
118 static void	nv_at(cmdarg_T *cap);
119 static void	nv_halfpage(cmdarg_T *cap);
120 static void	nv_join(cmdarg_T *cap);
121 static void	nv_put(cmdarg_T *cap);
122 static void	nv_put_opt(cmdarg_T *cap, int fix_indent);
123 static void	nv_open(cmdarg_T *cap);
124 #ifdef FEAT_NETBEANS_INTG
125 static void	nv_nbcmd(cmdarg_T *cap);
126 #endif
127 #ifdef FEAT_DND
128 static void	nv_drop(cmdarg_T *cap);
129 #endif
130 static void	nv_cursorhold(cmdarg_T *cap);
131 
132 static char *e_noident = N_("E349: No identifier under cursor");
133 
134 /*
135  * Function to be called for a Normal or Visual mode command.
136  * The argument is a cmdarg_T.
137  */
138 typedef void (*nv_func_T)(cmdarg_T *cap);
139 
140 // Values for cmd_flags.
141 #define NV_NCH	    0x01	  // may need to get a second char
142 #define NV_NCH_NOP  (0x02|NV_NCH) // get second char when no operator pending
143 #define NV_NCH_ALW  (0x04|NV_NCH) // always get a second char
144 #define NV_LANG	    0x08	// second char needs language adjustment
145 
146 #define NV_SS	    0x10	// may start selection
147 #define NV_SSS	    0x20	// may start selection with shift modifier
148 #define NV_STS	    0x40	// may stop selection without shift modif.
149 #define NV_RL	    0x80	// 'rightleft' modifies command
150 #define NV_KEEPREG  0x100	// don't clear regname
151 #define NV_NCW	    0x200	// not allowed in command-line window
152 
153 /*
154  * Generally speaking, every Normal mode command should either clear any
155  * pending operator (with *clearop*()), or set the motion type variable
156  * oap->motion_type.
157  *
158  * When a cursor motion command is made, it is marked as being a character or
159  * line oriented motion.  Then, if an operator is in effect, the operation
160  * becomes character or line oriented accordingly.
161  */
162 
163 /*
164  * This table contains one entry for every Normal or Visual mode command.
165  * The order doesn't matter, init_normal_cmds() will create a sorted index.
166  * It is faster when all keys from zero to '~' are present.
167  */
168 static const struct nv_cmd
169 {
170     int		cmd_char;	// (first) command character
171     nv_func_T   cmd_func;	// function for this command
172     short_u	cmd_flags;	// NV_ flags
173     short	cmd_arg;	// value for ca.arg
174 } nv_cmds[] =
175 {
176     {NUL,	nv_error,	0,			0},
177     {Ctrl_A,	nv_addsub,	0,			0},
178     {Ctrl_B,	nv_page,	NV_STS,			BACKWARD},
179     {Ctrl_C,	nv_esc,		0,			TRUE},
180     {Ctrl_D,	nv_halfpage,	0,			0},
181     {Ctrl_E,	nv_scroll_line,	0,			TRUE},
182     {Ctrl_F,	nv_page,	NV_STS,			FORWARD},
183     {Ctrl_G,	nv_ctrlg,	0,			0},
184     {Ctrl_H,	nv_ctrlh,	0,			0},
185     {Ctrl_I,	nv_pcmark,	0,			0},
186     {NL,	nv_down,	0,			FALSE},
187     {Ctrl_K,	nv_error,	0,			0},
188     {Ctrl_L,	nv_clear,	0,			0},
189     {CAR,	nv_down,	0,			TRUE},
190     {Ctrl_N,	nv_down,	NV_STS,			FALSE},
191     {Ctrl_O,	nv_ctrlo,	0,			0},
192     {Ctrl_P,	nv_up,		NV_STS,			FALSE},
193     {Ctrl_Q,	nv_visual,	0,			FALSE},
194     {Ctrl_R,	nv_redo,	0,			0},
195     {Ctrl_S,	nv_ignore,	0,			0},
196     {Ctrl_T,	nv_tagpop,	NV_NCW,			0},
197     {Ctrl_U,	nv_halfpage,	0,			0},
198     {Ctrl_V,	nv_visual,	0,			FALSE},
199     {'V',	nv_visual,	0,			FALSE},
200     {'v',	nv_visual,	0,			FALSE},
201     {Ctrl_W,	nv_window,	0,			0},
202     {Ctrl_X,	nv_addsub,	0,			0},
203     {Ctrl_Y,	nv_scroll_line,	0,			FALSE},
204     {Ctrl_Z,	nv_suspend,	0,			0},
205     {ESC,	nv_esc,		0,			FALSE},
206     {Ctrl_BSL,	nv_normal,	NV_NCH_ALW,		0},
207     {Ctrl_RSB,	nv_ident,	NV_NCW,			0},
208     {Ctrl_HAT,	nv_hat,		NV_NCW,			0},
209     {Ctrl__,	nv_error,	0,			0},
210     {' ',	nv_right,	0,			0},
211     {'!',	nv_operator,	0,			0},
212     {'"',	nv_regname,	NV_NCH_NOP|NV_KEEPREG,	0},
213     {'#',	nv_ident,	0,			0},
214     {'$',	nv_dollar,	0,			0},
215     {'%',	nv_percent,	0,			0},
216     {'&',	nv_optrans,	0,			0},
217     {'\'',	nv_gomark,	NV_NCH_ALW,		TRUE},
218     {'(',	nv_brace,	0,			BACKWARD},
219     {')',	nv_brace,	0,			FORWARD},
220     {'*',	nv_ident,	0,			0},
221     {'+',	nv_down,	0,			TRUE},
222     {',',	nv_csearch,	0,			TRUE},
223     {'-',	nv_up,		0,			TRUE},
224     {'.',	nv_dot,		NV_KEEPREG,		0},
225     {'/',	nv_search,	0,			FALSE},
226     {'0',	nv_beginline,	0,			0},
227     {'1',	nv_ignore,	0,			0},
228     {'2',	nv_ignore,	0,			0},
229     {'3',	nv_ignore,	0,			0},
230     {'4',	nv_ignore,	0,			0},
231     {'5',	nv_ignore,	0,			0},
232     {'6',	nv_ignore,	0,			0},
233     {'7',	nv_ignore,	0,			0},
234     {'8',	nv_ignore,	0,			0},
235     {'9',	nv_ignore,	0,			0},
236     {':',	nv_colon,	0,			0},
237     {';',	nv_csearch,	0,			FALSE},
238     {'<',	nv_operator,	NV_RL,			0},
239     {'=',	nv_operator,	0,			0},
240     {'>',	nv_operator,	NV_RL,			0},
241     {'?',	nv_search,	0,			FALSE},
242     {'@',	nv_at,		NV_NCH_NOP,		FALSE},
243     {'A',	nv_edit,	0,			0},
244     {'B',	nv_bck_word,	0,			1},
245     {'C',	nv_abbrev,	NV_KEEPREG,		0},
246     {'D',	nv_abbrev,	NV_KEEPREG,		0},
247     {'E',	nv_wordcmd,	0,			TRUE},
248     {'F',	nv_csearch,	NV_NCH_ALW|NV_LANG,	BACKWARD},
249     {'G',	nv_goto,	0,			TRUE},
250     {'H',	nv_scroll,	0,			0},
251     {'I',	nv_edit,	0,			0},
252     {'J',	nv_join,	0,			0},
253     {'K',	nv_ident,	0,			0},
254     {'L',	nv_scroll,	0,			0},
255     {'M',	nv_scroll,	0,			0},
256     {'N',	nv_next,	0,			SEARCH_REV},
257     {'O',	nv_open,	0,			0},
258     {'P',	nv_put,		0,			0},
259     {'Q',	nv_exmode,	NV_NCW,			0},
260     {'R',	nv_Replace,	0,			FALSE},
261     {'S',	nv_subst,	NV_KEEPREG,		0},
262     {'T',	nv_csearch,	NV_NCH_ALW|NV_LANG,	BACKWARD},
263     {'U',	nv_Undo,	0,			0},
264     {'W',	nv_wordcmd,	0,			TRUE},
265     {'X',	nv_abbrev,	NV_KEEPREG,		0},
266     {'Y',	nv_abbrev,	NV_KEEPREG,		0},
267     {'Z',	nv_Zet,		NV_NCH_NOP|NV_NCW,	0},
268     {'[',	nv_brackets,	NV_NCH_ALW,		BACKWARD},
269     {'\\',	nv_error,	0,			0},
270     {']',	nv_brackets,	NV_NCH_ALW,		FORWARD},
271     {'^',	nv_beginline,	0,			BL_WHITE | BL_FIX},
272     {'_',	nv_lineop,	0,			0},
273     {'`',	nv_gomark,	NV_NCH_ALW,		FALSE},
274     {'a',	nv_edit,	NV_NCH,			0},
275     {'b',	nv_bck_word,	0,			0},
276     {'c',	nv_operator,	0,			0},
277     {'d',	nv_operator,	0,			0},
278     {'e',	nv_wordcmd,	0,			FALSE},
279     {'f',	nv_csearch,	NV_NCH_ALW|NV_LANG,	FORWARD},
280     {'g',	nv_g_cmd,	NV_NCH_ALW,		FALSE},
281     {'h',	nv_left,	NV_RL,			0},
282     {'i',	nv_edit,	NV_NCH,			0},
283     {'j',	nv_down,	0,			FALSE},
284     {'k',	nv_up,		0,			FALSE},
285     {'l',	nv_right,	NV_RL,			0},
286     {'m',	nv_mark,	NV_NCH_NOP,		0},
287     {'n',	nv_next,	0,			0},
288     {'o',	nv_open,	0,			0},
289     {'p',	nv_put,		0,			0},
290     {'q',	nv_record,	NV_NCH,			0},
291     {'r',	nv_replace,	NV_NCH_NOP|NV_LANG,	0},
292     {'s',	nv_subst,	NV_KEEPREG,		0},
293     {'t',	nv_csearch,	NV_NCH_ALW|NV_LANG,	FORWARD},
294     {'u',	nv_undo,	0,			0},
295     {'w',	nv_wordcmd,	0,			FALSE},
296     {'x',	nv_abbrev,	NV_KEEPREG,		0},
297     {'y',	nv_operator,	0,			0},
298     {'z',	nv_zet,		NV_NCH_ALW,		0},
299     {'{',	nv_findpar,	0,			BACKWARD},
300     {'|',	nv_pipe,	0,			0},
301     {'}',	nv_findpar,	0,			FORWARD},
302     {'~',	nv_tilde,	0,			0},
303 
304     // pound sign
305     {POUND,	nv_ident,	0,			0},
306     {K_MOUSEUP, nv_mousescroll,	0,			MSCR_UP},
307     {K_MOUSEDOWN, nv_mousescroll, 0,			MSCR_DOWN},
308     {K_MOUSELEFT, nv_mousescroll, 0,			MSCR_LEFT},
309     {K_MOUSERIGHT, nv_mousescroll, 0,			MSCR_RIGHT},
310     {K_LEFTMOUSE, nv_mouse,	0,			0},
311     {K_LEFTMOUSE_NM, nv_mouse,	0,			0},
312     {K_LEFTDRAG, nv_mouse,	0,			0},
313     {K_LEFTRELEASE, nv_mouse,	0,			0},
314     {K_LEFTRELEASE_NM, nv_mouse, 0,			0},
315     {K_MOUSEMOVE, nv_mouse,	0,			0},
316     {K_MIDDLEMOUSE, nv_mouse,	0,			0},
317     {K_MIDDLEDRAG, nv_mouse,	0,			0},
318     {K_MIDDLERELEASE, nv_mouse,	0,			0},
319     {K_RIGHTMOUSE, nv_mouse,	0,			0},
320     {K_RIGHTDRAG, nv_mouse,	0,			0},
321     {K_RIGHTRELEASE, nv_mouse,	0,			0},
322     {K_X1MOUSE, nv_mouse,	0,			0},
323     {K_X1DRAG, nv_mouse,	0,			0},
324     {K_X1RELEASE, nv_mouse,	0,			0},
325     {K_X2MOUSE, nv_mouse,	0,			0},
326     {K_X2DRAG, nv_mouse,	0,			0},
327     {K_X2RELEASE, nv_mouse,	0,			0},
328     {K_IGNORE,	nv_ignore,	NV_KEEPREG,		0},
329     {K_NOP,	nv_nop,		0,			0},
330     {K_INS,	nv_edit,	0,			0},
331     {K_KINS,	nv_edit,	0,			0},
332     {K_BS,	nv_ctrlh,	0,			0},
333     {K_UP,	nv_up,		NV_SSS|NV_STS,		FALSE},
334     {K_S_UP,	nv_page,	NV_SS,			BACKWARD},
335     {K_DOWN,	nv_down,	NV_SSS|NV_STS,		FALSE},
336     {K_S_DOWN,	nv_page,	NV_SS,			FORWARD},
337     {K_LEFT,	nv_left,	NV_SSS|NV_STS|NV_RL,	0},
338     {K_S_LEFT,	nv_bck_word,	NV_SS|NV_RL,		0},
339     {K_C_LEFT,	nv_bck_word,	NV_SSS|NV_RL|NV_STS,	1},
340     {K_RIGHT,	nv_right,	NV_SSS|NV_STS|NV_RL,	0},
341     {K_S_RIGHT,	nv_wordcmd,	NV_SS|NV_RL,		FALSE},
342     {K_C_RIGHT,	nv_wordcmd,	NV_SSS|NV_RL|NV_STS,	TRUE},
343     {K_PAGEUP,	nv_page,	NV_SSS|NV_STS,		BACKWARD},
344     {K_KPAGEUP,	nv_page,	NV_SSS|NV_STS,		BACKWARD},
345     {K_PAGEDOWN, nv_page,	NV_SSS|NV_STS,		FORWARD},
346     {K_KPAGEDOWN, nv_page,	NV_SSS|NV_STS,		FORWARD},
347     {K_END,	nv_end,		NV_SSS|NV_STS,		FALSE},
348     {K_KEND,	nv_end,		NV_SSS|NV_STS,		FALSE},
349     {K_S_END,	nv_end,		NV_SS,			FALSE},
350     {K_C_END,	nv_end,		NV_SSS|NV_STS,		TRUE},
351     {K_HOME,	nv_home,	NV_SSS|NV_STS,		0},
352     {K_KHOME,	nv_home,	NV_SSS|NV_STS,		0},
353     {K_S_HOME,	nv_home,	NV_SS,			0},
354     {K_C_HOME,	nv_goto,	NV_SSS|NV_STS,		FALSE},
355     {K_DEL,	nv_abbrev,	0,			0},
356     {K_KDEL,	nv_abbrev,	0,			0},
357     {K_UNDO,	nv_kundo,	0,			0},
358     {K_HELP,	nv_help,	NV_NCW,			0},
359     {K_F1,	nv_help,	NV_NCW,			0},
360     {K_XF1,	nv_help,	NV_NCW,			0},
361     {K_SELECT,	nv_select,	0,			0},
362 #ifdef FEAT_GUI
363     {K_VER_SCROLLBAR, nv_ver_scrollbar, 0,		0},
364     {K_HOR_SCROLLBAR, nv_hor_scrollbar, 0,		0},
365 #endif
366 #ifdef FEAT_GUI_TABLINE
367     {K_TABLINE, nv_tabline,	0,			0},
368     {K_TABMENU, nv_tabmenu,	0,			0},
369 #endif
370 #ifdef FEAT_NETBEANS_INTG
371     {K_F21,	nv_nbcmd,	NV_NCH_ALW,		0},
372 #endif
373 #ifdef FEAT_DND
374     {K_DROP,	nv_drop,	NV_STS,			0},
375 #endif
376     {K_CURSORHOLD, nv_cursorhold, NV_KEEPREG,		0},
377     {K_PS,	nv_edit,	0,			0},
378     {K_COMMAND,	nv_colon,	0,			0},
379 };
380 
381 // Number of commands in nv_cmds[].
382 #define NV_CMDS_SIZE (sizeof(nv_cmds) / sizeof(struct nv_cmd))
383 
384 // Sorted index of commands in nv_cmds[].
385 static short nv_cmd_idx[NV_CMDS_SIZE];
386 
387 // The highest index for which
388 // nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char]
389 static int nv_max_linear;
390 
391 /*
392  * Compare functions for qsort() below, that checks the command character
393  * through the index in nv_cmd_idx[].
394  */
395     static int
396 nv_compare(const void *s1, const void *s2)
397 {
398     int		c1, c2;
399 
400     // The commands are sorted on absolute value.
401     c1 = nv_cmds[*(const short *)s1].cmd_char;
402     c2 = nv_cmds[*(const short *)s2].cmd_char;
403     if (c1 < 0)
404 	c1 = -c1;
405     if (c2 < 0)
406 	c2 = -c2;
407     return c1 - c2;
408 }
409 
410 /*
411  * Initialize the nv_cmd_idx[] table.
412  */
413     void
414 init_normal_cmds(void)
415 {
416     int		i;
417 
418     // Fill the index table with a one to one relation.
419     for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
420 	nv_cmd_idx[i] = i;
421 
422     // Sort the commands by the command character.
423     qsort((void *)&nv_cmd_idx, (size_t)NV_CMDS_SIZE, sizeof(short), nv_compare);
424 
425     // Find the first entry that can't be indexed by the command character.
426     for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
427 	if (i != nv_cmds[nv_cmd_idx[i]].cmd_char)
428 	    break;
429     nv_max_linear = i - 1;
430 }
431 
432 /*
433  * Search for a command in the commands table.
434  * Returns -1 for invalid command.
435  */
436     static int
437 find_command(int cmdchar)
438 {
439     int		i;
440     int		idx;
441     int		top, bot;
442     int		c;
443 
444     // A multi-byte character is never a command.
445     if (cmdchar >= 0x100)
446 	return -1;
447 
448     // We use the absolute value of the character.  Special keys have a
449     // negative value, but are sorted on their absolute value.
450     if (cmdchar < 0)
451 	cmdchar = -cmdchar;
452 
453     // If the character is in the first part: The character is the index into
454     // nv_cmd_idx[].
455     if (cmdchar <= nv_max_linear)
456 	return nv_cmd_idx[cmdchar];
457 
458     // Perform a binary search.
459     bot = nv_max_linear + 1;
460     top = NV_CMDS_SIZE - 1;
461     idx = -1;
462     while (bot <= top)
463     {
464 	i = (top + bot) / 2;
465 	c = nv_cmds[nv_cmd_idx[i]].cmd_char;
466 	if (c < 0)
467 	    c = -c;
468 	if (cmdchar == c)
469 	{
470 	    idx = nv_cmd_idx[i];
471 	    break;
472 	}
473 	if (cmdchar > c)
474 	    bot = i + 1;
475 	else
476 	    top = i - 1;
477     }
478     return idx;
479 }
480 
481 /*
482  * Execute a command in Normal mode.
483  */
484     void
485 normal_cmd(
486     oparg_T	*oap,
487     int		toplevel UNUSED)	// TRUE when called from main()
488 {
489     cmdarg_T	ca;			// command arguments
490     int		c;
491     int		ctrl_w = FALSE;		// got CTRL-W command
492     int		old_col = curwin->w_curswant;
493 #ifdef FEAT_CMDL_INFO
494     int		need_flushbuf;		// need to call out_flush()
495 #endif
496     pos_T	old_pos;		// cursor position before command
497     int		mapped_len;
498     static int	old_mapped_len = 0;
499     int		idx;
500 #ifdef FEAT_EVAL
501     int		set_prevcount = FALSE;
502 #endif
503     int		save_did_cursorhold = did_cursorhold;
504 
505     CLEAR_FIELD(ca);	// also resets ca.retval
506     ca.oap = oap;
507 
508     // Use a count remembered from before entering an operator.  After typing
509     // "3d" we return from normal_cmd() and come back here, the "3" is
510     // remembered in "opcount".
511     ca.opcount = opcount;
512 
513     /*
514      * If there is an operator pending, then the command we take this time
515      * will terminate it. Finish_op tells us to finish the operation before
516      * returning this time (unless the operation was cancelled).
517      */
518 #ifdef CURSOR_SHAPE
519     c = finish_op;
520 #endif
521     finish_op = (oap->op_type != OP_NOP);
522 #ifdef CURSOR_SHAPE
523     if (finish_op != c)
524     {
525 	ui_cursor_shape();		// may show different cursor shape
526 # ifdef FEAT_MOUSESHAPE
527 	update_mouseshape(-1);
528 # endif
529     }
530 #endif
531 
532     // When not finishing an operator and no register name typed, reset the
533     // count.
534     if (!finish_op && !oap->regname)
535     {
536 	ca.opcount = 0;
537 #ifdef FEAT_EVAL
538 	set_prevcount = TRUE;
539 #endif
540     }
541 
542     // Restore counts from before receiving K_CURSORHOLD.  This means after
543     // typing "3", handling K_CURSORHOLD and then typing "2" we get "32", not
544     // "3 * 2".
545     if (oap->prev_opcount > 0 || oap->prev_count0 > 0)
546     {
547 	ca.opcount = oap->prev_opcount;
548 	ca.count0 = oap->prev_count0;
549 	oap->prev_opcount = 0;
550 	oap->prev_count0 = 0;
551     }
552 
553     mapped_len = typebuf_maplen();
554 
555     State = NORMAL_BUSY;
556 #ifdef USE_ON_FLY_SCROLL
557     dont_scroll = FALSE;	// allow scrolling here
558 #endif
559 
560 #ifdef FEAT_EVAL
561     // Set v:count here, when called from main() and not a stuffed
562     // command, so that v:count can be used in an expression mapping
563     // when there is no count. Do set it for redo.
564     if (toplevel && readbuf1_empty())
565 	set_vcount_ca(&ca, &set_prevcount);
566 #endif
567 
568     /*
569      * Get the command character from the user.
570      */
571     c = safe_vgetc();
572     LANGMAP_ADJUST(c, get_real_state() != SELECTMODE);
573 
574     /*
575      * If a mapping was started in Visual or Select mode, remember the length
576      * of the mapping.  This is used below to not return to Insert mode for as
577      * long as the mapping is being executed.
578      */
579     if (restart_edit == 0)
580 	old_mapped_len = 0;
581     else if (old_mapped_len
582 		|| (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0))
583 	old_mapped_len = typebuf_maplen();
584 
585     if (c == NUL)
586 	c = K_ZERO;
587 
588     /*
589      * In Select mode, typed text replaces the selection.
590      */
591     if (VIsual_active
592 	    && VIsual_select
593 	    && (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER))
594     {
595 	// Fake a "c"hange command.  When "restart_edit" is set (e.g., because
596 	// 'insertmode' is set) fake a "d"elete command, Insert mode will
597 	// restart automatically.
598 	// Insert the typed character in the typeahead buffer, so that it can
599 	// be mapped in Insert mode.  Required for ":lmap" to work.
600 	ins_char_typebuf(vgetc_char, vgetc_mod_mask);
601 	if (restart_edit != 0)
602 	    c = 'd';
603 	else
604 	    c = 'c';
605 	msg_nowait = TRUE;	// don't delay going to insert mode
606 	old_mapped_len = 0;	// do go to Insert mode
607     }
608 
609 #ifdef FEAT_CMDL_INFO
610     need_flushbuf = add_to_showcmd(c);
611 #endif
612 
613 getcount:
614     if (!(VIsual_active && VIsual_select))
615     {
616 	/*
617 	 * Handle a count before a command and compute ca.count0.
618 	 * Note that '0' is a command and not the start of a count, but it's
619 	 * part of a count after other digits.
620 	 */
621 	while (    (c >= '1' && c <= '9')
622 		|| (ca.count0 != 0 && (c == K_DEL || c == K_KDEL || c == '0')))
623 	{
624 	    if (c == K_DEL || c == K_KDEL)
625 	    {
626 		ca.count0 /= 10;
627 #ifdef FEAT_CMDL_INFO
628 		del_from_showcmd(4);	// delete the digit and ~@%
629 #endif
630 	    }
631 	    else
632 		ca.count0 = ca.count0 * 10 + (c - '0');
633 	    if (ca.count0 < 0)	    // 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 #ifdef FEAT_FOLDING
2977 		// "zF": create fold command
2978 		// "zf": create fold operator
2979     case 'F':
2980     case 'f':   if (foldManualAllowed(TRUE))
2981 		{
2982 		    cap->nchar = 'f';
2983 		    nv_operator(cap);
2984 		    curwin->w_p_fen = TRUE;
2985 
2986 		    // "zF" is like "zfzf"
2987 		    if (nchar == 'F' && cap->oap->op_type == OP_FOLD)
2988 		    {
2989 			nv_operator(cap);
2990 			finish_op = TRUE;
2991 		    }
2992 		}
2993 		else
2994 		    clearopbeep(cap->oap);
2995 		break;
2996 
2997 		// "zd": delete fold at cursor
2998 		// "zD": delete fold at cursor recursively
2999     case 'd':
3000     case 'D':	if (foldManualAllowed(FALSE))
3001 		{
3002 		    if (VIsual_active)
3003 			nv_operator(cap);
3004 		    else
3005 			deleteFold(curwin->w_cursor.lnum,
3006 				  curwin->w_cursor.lnum, nchar == 'D', FALSE);
3007 		}
3008 		break;
3009 
3010 		// "zE": erase all folds
3011     case 'E':	if (foldmethodIsManual(curwin))
3012 		{
3013 		    clearFolding(curwin);
3014 		    changed_window_setting();
3015 		}
3016 		else if (foldmethodIsMarker(curwin))
3017 		    deleteFold((linenr_T)1, curbuf->b_ml.ml_line_count,
3018 								 TRUE, FALSE);
3019 		else
3020 		    emsg(_("E352: Cannot erase folds with current 'foldmethod'"));
3021 		break;
3022 
3023 		// "zn": fold none: reset 'foldenable'
3024     case 'n':	curwin->w_p_fen = FALSE;
3025 		break;
3026 
3027 		// "zN": fold Normal: set 'foldenable'
3028     case 'N':	curwin->w_p_fen = TRUE;
3029 		break;
3030 
3031 		// "zi": invert folding: toggle 'foldenable'
3032     case 'i':	curwin->w_p_fen = !curwin->w_p_fen;
3033 		break;
3034 
3035 		// "za": open closed fold or close open fold at cursor
3036     case 'a':	if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
3037 		    openFold(curwin->w_cursor.lnum, cap->count1);
3038 		else
3039 		{
3040 		    closeFold(curwin->w_cursor.lnum, cap->count1);
3041 		    curwin->w_p_fen = TRUE;
3042 		}
3043 		break;
3044 
3045 		// "zA": open fold at cursor recursively
3046     case 'A':	if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
3047 		    openFoldRecurse(curwin->w_cursor.lnum);
3048 		else
3049 		{
3050 		    closeFoldRecurse(curwin->w_cursor.lnum);
3051 		    curwin->w_p_fen = TRUE;
3052 		}
3053 		break;
3054 
3055 		// "zo": open fold at cursor or Visual area
3056     case 'o':	if (VIsual_active)
3057 		    nv_operator(cap);
3058 		else
3059 		    openFold(curwin->w_cursor.lnum, cap->count1);
3060 		break;
3061 
3062 		// "zO": open fold recursively
3063     case 'O':	if (VIsual_active)
3064 		    nv_operator(cap);
3065 		else
3066 		    openFoldRecurse(curwin->w_cursor.lnum);
3067 		break;
3068 
3069 		// "zc": close fold at cursor or Visual area
3070     case 'c':	if (VIsual_active)
3071 		    nv_operator(cap);
3072 		else
3073 		    closeFold(curwin->w_cursor.lnum, cap->count1);
3074 		curwin->w_p_fen = TRUE;
3075 		break;
3076 
3077 		// "zC": close fold recursively
3078     case 'C':	if (VIsual_active)
3079 		    nv_operator(cap);
3080 		else
3081 		    closeFoldRecurse(curwin->w_cursor.lnum);
3082 		curwin->w_p_fen = TRUE;
3083 		break;
3084 
3085 		// "zv": open folds at the cursor
3086     case 'v':	foldOpenCursor();
3087 		break;
3088 
3089 		// "zx": re-apply 'foldlevel' and open folds at the cursor
3090     case 'x':	curwin->w_p_fen = TRUE;
3091 		curwin->w_foldinvalid = TRUE;	// recompute folds
3092 		newFoldLevel();			// update right now
3093 		foldOpenCursor();
3094 		break;
3095 
3096 		// "zX": undo manual opens/closes, re-apply 'foldlevel'
3097     case 'X':	curwin->w_p_fen = TRUE;
3098 		curwin->w_foldinvalid = TRUE;	// recompute folds
3099 		old_fdl = -1;			// force an update
3100 		break;
3101 
3102 		// "zm": fold more
3103     case 'm':	if (curwin->w_p_fdl > 0)
3104 		{
3105 		    curwin->w_p_fdl -= cap->count1;
3106 		    if (curwin->w_p_fdl < 0)
3107 			curwin->w_p_fdl = 0;
3108 		}
3109 		old_fdl = -1;		// force an update
3110 		curwin->w_p_fen = TRUE;
3111 		break;
3112 
3113 		// "zM": close all folds
3114     case 'M':	curwin->w_p_fdl = 0;
3115 		old_fdl = -1;		// force an update
3116 		curwin->w_p_fen = TRUE;
3117 		break;
3118 
3119 		// "zr": reduce folding
3120     case 'r':	curwin->w_p_fdl += cap->count1;
3121 		{
3122 		    int d = getDeepestNesting();
3123 
3124 		    if (curwin->w_p_fdl >= d)
3125 			curwin->w_p_fdl = d;
3126 		}
3127 		break;
3128 
3129 		// "zR": open all folds
3130     case 'R':	curwin->w_p_fdl = getDeepestNesting();
3131 		old_fdl = -1;		// force an update
3132 		break;
3133 
3134     case 'j':	// "zj" move to next fold downwards
3135     case 'k':	// "zk" move to next fold upwards
3136 		if (foldMoveTo(TRUE, nchar == 'j' ? FORWARD : BACKWARD,
3137 							  cap->count1) == FAIL)
3138 		    clearopbeep(cap->oap);
3139 		break;
3140 
3141 #endif // FEAT_FOLDING
3142 
3143 #ifdef FEAT_SPELL
3144     case 'u':	// "zug" and "zuw": undo "zg" and "zw"
3145 		++no_mapping;
3146 		++allow_keys;   // no mapping for nchar, but allow key codes
3147 		nchar = plain_vgetc();
3148 		LANGMAP_ADJUST(nchar, TRUE);
3149 		--no_mapping;
3150 		--allow_keys;
3151 #ifdef FEAT_CMDL_INFO
3152 		(void)add_to_showcmd(nchar);
3153 #endif
3154 		if (vim_strchr((char_u *)"gGwW", nchar) == NULL)
3155 		{
3156 		    clearopbeep(cap->oap);
3157 		    break;
3158 		}
3159 		undo = TRUE;
3160 		// FALLTHROUGH
3161 
3162     case 'g':	// "zg": add good word to word list
3163     case 'w':	// "zw": add wrong word to word list
3164     case 'G':	// "zG": add good word to temp word list
3165     case 'W':	// "zW": add wrong word to temp word list
3166 		{
3167 		    char_u  *ptr = NULL;
3168 		    int	    len;
3169 
3170 		    if (checkclearop(cap->oap))
3171 			break;
3172 		    if (VIsual_active && get_visual_text(cap, &ptr, &len)
3173 								      == FAIL)
3174 			return;
3175 		    if (ptr == NULL)
3176 		    {
3177 			pos_T	pos = curwin->w_cursor;
3178 
3179 			// Find bad word under the cursor.  When 'spell' is
3180 			// off this fails and find_ident_under_cursor() is
3181 			// used below.
3182 			emsg_off++;
3183 			len = spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL);
3184 			emsg_off--;
3185 			if (len != 0 && curwin->w_cursor.col <= pos.col)
3186 			    ptr = ml_get_pos(&curwin->w_cursor);
3187 			curwin->w_cursor = pos;
3188 		    }
3189 
3190 		    if (ptr == NULL && (len = find_ident_under_cursor(&ptr,
3191 							    FIND_IDENT)) == 0)
3192 			return;
3193 		    spell_add_word(ptr, len, nchar == 'w' || nchar == 'W'
3194 					      ? SPELL_ADD_BAD : SPELL_ADD_GOOD,
3195 					    (nchar == 'G' || nchar == 'W')
3196 						       ? 0 : (int)cap->count1,
3197 					    undo);
3198 		}
3199 		break;
3200 
3201     case '=':	// "z=": suggestions for a badly spelled word
3202 		if (!checkclearop(cap->oap))
3203 		    spell_suggest((int)cap->count0);
3204 		break;
3205 #endif
3206 
3207     default:	clearopbeep(cap->oap);
3208     }
3209 
3210 #ifdef FEAT_FOLDING
3211     // Redraw when 'foldenable' changed
3212     if (old_fen != curwin->w_p_fen)
3213     {
3214 # ifdef FEAT_DIFF
3215 	win_T	    *wp;
3216 
3217 	if (foldmethodIsDiff(curwin) && curwin->w_p_scb)
3218 	{
3219 	    // Adjust 'foldenable' in diff-synced windows.
3220 	    FOR_ALL_WINDOWS(wp)
3221 	    {
3222 		if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb)
3223 		{
3224 		    wp->w_p_fen = curwin->w_p_fen;
3225 		    changed_window_setting_win(wp);
3226 		}
3227 	    }
3228 	}
3229 # endif
3230 	changed_window_setting();
3231     }
3232 
3233     // Redraw when 'foldlevel' changed.
3234     if (old_fdl != curwin->w_p_fdl)
3235 	newFoldLevel();
3236 #endif
3237 }
3238 
3239 #ifdef FEAT_GUI
3240 /*
3241  * Vertical scrollbar movement.
3242  */
3243     static void
3244 nv_ver_scrollbar(cmdarg_T *cap)
3245 {
3246     if (cap->oap->op_type != OP_NOP)
3247 	clearopbeep(cap->oap);
3248 
3249     // Even if an operator was pending, we still want to scroll
3250     gui_do_scroll();
3251 }
3252 
3253 /*
3254  * Horizontal scrollbar movement.
3255  */
3256     static void
3257 nv_hor_scrollbar(cmdarg_T *cap)
3258 {
3259     if (cap->oap->op_type != OP_NOP)
3260 	clearopbeep(cap->oap);
3261 
3262     // Even if an operator was pending, we still want to scroll
3263     gui_do_horiz_scroll(scrollbar_value, FALSE);
3264 }
3265 #endif
3266 
3267 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
3268 /*
3269  * Click in GUI tab.
3270  */
3271     static void
3272 nv_tabline(cmdarg_T *cap)
3273 {
3274     if (cap->oap->op_type != OP_NOP)
3275 	clearopbeep(cap->oap);
3276 
3277     // Even if an operator was pending, we still want to jump tabs.
3278     goto_tabpage(current_tab);
3279 }
3280 
3281 /*
3282  * Selected item in tab line menu.
3283  */
3284     static void
3285 nv_tabmenu(cmdarg_T *cap)
3286 {
3287     if (cap->oap->op_type != OP_NOP)
3288 	clearopbeep(cap->oap);
3289 
3290     // Even if an operator was pending, we still want to jump tabs.
3291     handle_tabmenu();
3292 }
3293 
3294 /*
3295  * Handle selecting an item of the GUI tab line menu.
3296  * Used in Normal and Insert mode.
3297  */
3298     void
3299 handle_tabmenu(void)
3300 {
3301     switch (current_tabmenu)
3302     {
3303 	case TABLINE_MENU_CLOSE:
3304 	    if (current_tab == 0)
3305 		do_cmdline_cmd((char_u *)"tabclose");
3306 	    else
3307 	    {
3308 		vim_snprintf((char *)IObuff, IOSIZE, "tabclose %d",
3309 								 current_tab);
3310 		do_cmdline_cmd(IObuff);
3311 	    }
3312 	    break;
3313 
3314 	case TABLINE_MENU_NEW:
3315 	    if (current_tab == 0)
3316 		do_cmdline_cmd((char_u *)"$tabnew");
3317 	    else
3318 	    {
3319 		vim_snprintf((char *)IObuff, IOSIZE, "%dtabnew",
3320 							     current_tab - 1);
3321 		do_cmdline_cmd(IObuff);
3322 	    }
3323 	    break;
3324 
3325 	case TABLINE_MENU_OPEN:
3326 	    if (current_tab == 0)
3327 		do_cmdline_cmd((char_u *)"browse $tabnew");
3328 	    else
3329 	    {
3330 		vim_snprintf((char *)IObuff, IOSIZE, "browse %dtabnew",
3331 							     current_tab - 1);
3332 		do_cmdline_cmd(IObuff);
3333 	    }
3334 	    break;
3335     }
3336 }
3337 #endif
3338 
3339 /*
3340  * "Q" command.
3341  */
3342     static void
3343 nv_exmode(cmdarg_T *cap)
3344 {
3345     /*
3346      * Ignore 'Q' in Visual mode, just give a beep.
3347      */
3348     if (VIsual_active)
3349 	vim_beep(BO_EX);
3350     else if (!checkclearop(cap->oap))
3351 	do_exmode(FALSE);
3352 }
3353 
3354 /*
3355  * Handle a ":" command.
3356  */
3357     static void
3358 nv_colon(cmdarg_T *cap)
3359 {
3360     int	old_p_im;
3361     int	cmd_result;
3362     int	is_cmdkey = cap->cmdchar == K_COMMAND;
3363 
3364     if (VIsual_active && !is_cmdkey)
3365 	nv_operator(cap);
3366     else
3367     {
3368 	if (cap->oap->op_type != OP_NOP)
3369 	{
3370 	    // Using ":" as a movement is characterwise exclusive.
3371 	    cap->oap->motion_type = MCHAR;
3372 	    cap->oap->inclusive = FALSE;
3373 	}
3374 	else if (cap->count0 && !is_cmdkey)
3375 	{
3376 	    // translate "count:" into ":.,.+(count - 1)"
3377 	    stuffcharReadbuff('.');
3378 	    if (cap->count0 > 1)
3379 	    {
3380 		stuffReadbuff((char_u *)",.+");
3381 		stuffnumReadbuff((long)cap->count0 - 1L);
3382 	    }
3383 	}
3384 
3385 	// When typing, don't type below an old message
3386 	if (KeyTyped)
3387 	    compute_cmdrow();
3388 
3389 	old_p_im = p_im;
3390 
3391 	// get a command line and execute it
3392 	cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL,
3393 			    cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0);
3394 
3395 	// If 'insertmode' changed, enter or exit Insert mode
3396 	if (p_im != old_p_im)
3397 	{
3398 	    if (p_im)
3399 		restart_edit = 'i';
3400 	    else
3401 		restart_edit = 0;
3402 	}
3403 
3404 	if (cmd_result == FAIL)
3405 	    // The Ex command failed, do not execute the operator.
3406 	    clearop(cap->oap);
3407 	else if (cap->oap->op_type != OP_NOP
3408 		&& (cap->oap->start.lnum > curbuf->b_ml.ml_line_count
3409 		    || cap->oap->start.col >
3410 			       (colnr_T)STRLEN(ml_get(cap->oap->start.lnum))
3411 		    || did_emsg
3412 		    ))
3413 	    // The start of the operator has become invalid by the Ex command.
3414 	    clearopbeep(cap->oap);
3415     }
3416 }
3417 
3418 /*
3419  * Handle CTRL-G command.
3420  */
3421     static void
3422 nv_ctrlg(cmdarg_T *cap)
3423 {
3424     if (VIsual_active)	// toggle Selection/Visual mode
3425     {
3426 	VIsual_select = !VIsual_select;
3427 	showmode();
3428     }
3429     else if (!checkclearop(cap->oap))
3430 	// print full name if count given or :cd used
3431 	fileinfo((int)cap->count0, FALSE, TRUE);
3432 }
3433 
3434 /*
3435  * Handle CTRL-H <Backspace> command.
3436  */
3437     static void
3438 nv_ctrlh(cmdarg_T *cap)
3439 {
3440     if (VIsual_active && VIsual_select)
3441     {
3442 	cap->cmdchar = 'x';	// BS key behaves like 'x' in Select mode
3443 	v_visop(cap);
3444     }
3445     else
3446 	nv_left(cap);
3447 }
3448 
3449 /*
3450  * CTRL-L: clear screen and redraw.
3451  */
3452     static void
3453 nv_clear(cmdarg_T *cap)
3454 {
3455     if (!checkclearop(cap->oap))
3456     {
3457 #ifdef FEAT_SYN_HL
3458 	// Clear all syntax states to force resyncing.
3459 	syn_stack_free_all(curwin->w_s);
3460 # ifdef FEAT_RELTIME
3461 	{
3462 	    win_T *wp;
3463 
3464 	    FOR_ALL_WINDOWS(wp)
3465 		wp->w_s->b_syn_slow = FALSE;
3466 	}
3467 # endif
3468 #endif
3469 	redraw_later(CLEAR);
3470 #if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3471 # ifdef VIMDLL
3472 	if (!gui.in_use)
3473 # endif
3474 	    resize_console_buf();
3475 #endif
3476     }
3477 }
3478 
3479 /*
3480  * CTRL-O: In Select mode: switch to Visual mode for one command.
3481  * Otherwise: Go to older pcmark.
3482  */
3483     static void
3484 nv_ctrlo(cmdarg_T *cap)
3485 {
3486     if (VIsual_active && VIsual_select)
3487     {
3488 	VIsual_select = FALSE;
3489 	showmode();
3490 	restart_VIsual_select = 2;	// restart Select mode later
3491     }
3492     else
3493     {
3494 	cap->count1 = -cap->count1;
3495 	nv_pcmark(cap);
3496     }
3497 }
3498 
3499 /*
3500  * CTRL-^ command, short for ":e #".  Works even when the alternate buffer is
3501  * not named.
3502  */
3503     static void
3504 nv_hat(cmdarg_T *cap)
3505 {
3506     if (!checkclearopq(cap->oap))
3507 	(void)buflist_getfile((int)cap->count0, (linenr_T)0,
3508 						GETF_SETMARK|GETF_ALT, FALSE);
3509 }
3510 
3511 /*
3512  * "Z" commands.
3513  */
3514     static void
3515 nv_Zet(cmdarg_T *cap)
3516 {
3517     if (!checkclearopq(cap->oap))
3518     {
3519 	switch (cap->nchar)
3520 	{
3521 			// "ZZ": equivalent to ":x".
3522 	    case 'Z':	do_cmdline_cmd((char_u *)"x");
3523 			break;
3524 
3525 			// "ZQ": equivalent to ":q!" (Elvis compatible).
3526 	    case 'Q':	do_cmdline_cmd((char_u *)"q!");
3527 			break;
3528 
3529 	    default:	clearopbeep(cap->oap);
3530 	}
3531     }
3532 }
3533 
3534 /*
3535  * Call nv_ident() as if "c1" was used, with "c2" as next character.
3536  */
3537     void
3538 do_nv_ident(int c1, int c2)
3539 {
3540     oparg_T	oa;
3541     cmdarg_T	ca;
3542 
3543     clear_oparg(&oa);
3544     CLEAR_FIELD(ca);
3545     ca.oap = &oa;
3546     ca.cmdchar = c1;
3547     ca.nchar = c2;
3548     nv_ident(&ca);
3549 }
3550 
3551 /*
3552  * Handle the commands that use the word under the cursor.
3553  * [g] CTRL-]	:ta to current identifier
3554  * [g] 'K'	run program for current identifier
3555  * [g] '*'	/ to current identifier or string
3556  * [g] '#'	? to current identifier or string
3557  *  g  ']'	:tselect for current identifier
3558  */
3559     static void
3560 nv_ident(cmdarg_T *cap)
3561 {
3562     char_u	*ptr = NULL;
3563     char_u	*buf;
3564     unsigned	buflen;
3565     char_u	*newbuf;
3566     char_u	*p;
3567     char_u	*kp;		// value of 'keywordprg'
3568     int		kp_help;	// 'keywordprg' is ":he"
3569     int		kp_ex;		// 'keywordprg' starts with ":"
3570     int		n = 0;		// init for GCC
3571     int		cmdchar;
3572     int		g_cmd;		// "g" command
3573     int		tag_cmd = FALSE;
3574     char_u	*aux_ptr;
3575     int		isman;
3576     int		isman_s;
3577 
3578     if (cap->cmdchar == 'g')	// "g*", "g#", "g]" and "gCTRL-]"
3579     {
3580 	cmdchar = cap->nchar;
3581 	g_cmd = TRUE;
3582     }
3583     else
3584     {
3585 	cmdchar = cap->cmdchar;
3586 	g_cmd = FALSE;
3587     }
3588 
3589     if (cmdchar == POUND)	// the pound sign, '#' for English keyboards
3590 	cmdchar = '#';
3591 
3592     /*
3593      * The "]", "CTRL-]" and "K" commands accept an argument in Visual mode.
3594      */
3595     if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K')
3596     {
3597 	if (VIsual_active && get_visual_text(cap, &ptr, &n) == FAIL)
3598 	    return;
3599 	if (checkclearopq(cap->oap))
3600 	    return;
3601     }
3602 
3603     if (ptr == NULL && (n = find_ident_under_cursor(&ptr,
3604 		    (cmdchar == '*' || cmdchar == '#')
3605 				 ? FIND_IDENT|FIND_STRING : FIND_IDENT)) == 0)
3606     {
3607 	clearop(cap->oap);
3608 	return;
3609     }
3610 
3611     // Allocate buffer to put the command in.  Inserting backslashes can
3612     // double the length of the word.  p_kp / curbuf->b_p_kp could be added
3613     // and some numbers.
3614     kp = (*curbuf->b_p_kp == NUL ? p_kp : curbuf->b_p_kp);
3615     kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0
3616 						 || STRCMP(kp, ":help") == 0);
3617     if (kp_help && *skipwhite(ptr) == NUL)
3618     {
3619 	emsg(_(e_noident));	 // found white space only
3620 	return;
3621     }
3622     kp_ex = (*kp == ':');
3623     buflen = (unsigned)(n * 2 + 30 + STRLEN(kp));
3624     buf = alloc(buflen);
3625     if (buf == NULL)
3626 	return;
3627     buf[0] = NUL;
3628 
3629     switch (cmdchar)
3630     {
3631 	case '*':
3632 	case '#':
3633 	    /*
3634 	     * Put cursor at start of word, makes search skip the word
3635 	     * under the cursor.
3636 	     * Call setpcmark() first, so "*``" puts the cursor back where
3637 	     * it was.
3638 	     */
3639 	    setpcmark();
3640 	    curwin->w_cursor.col = (colnr_T) (ptr - ml_get_curline());
3641 
3642 	    if (!g_cmd && vim_iswordp(ptr))
3643 		STRCPY(buf, "\\<");
3644 	    no_smartcase = TRUE;	// don't use 'smartcase' now
3645 	    break;
3646 
3647 	case 'K':
3648 	    if (kp_help)
3649 		STRCPY(buf, "he! ");
3650 	    else if (kp_ex)
3651 	    {
3652 		if (cap->count0 != 0)
3653 		    vim_snprintf((char *)buf, buflen, "%s %ld",
3654 							     kp, cap->count0);
3655 		else
3656 		    STRCPY(buf, kp);
3657 		STRCAT(buf, " ");
3658 	    }
3659 	    else
3660 	    {
3661 		// An external command will probably use an argument starting
3662 		// with "-" as an option.  To avoid trouble we skip the "-".
3663 		while (*ptr == '-' && n > 0)
3664 		{
3665 		    ++ptr;
3666 		    --n;
3667 		}
3668 		if (n == 0)
3669 		{
3670 		    emsg(_(e_noident));	 // found dashes only
3671 		    vim_free(buf);
3672 		    return;
3673 		}
3674 
3675 		// When a count is given, turn it into a range.  Is this
3676 		// really what we want?
3677 		isman = (STRCMP(kp, "man") == 0);
3678 		isman_s = (STRCMP(kp, "man -s") == 0);
3679 		if (cap->count0 != 0 && !(isman || isman_s))
3680 		    sprintf((char *)buf, ".,.+%ld", cap->count0 - 1);
3681 
3682 		STRCAT(buf, "! ");
3683 		if (cap->count0 == 0 && isman_s)
3684 		    STRCAT(buf, "man");
3685 		else
3686 		    STRCAT(buf, kp);
3687 		STRCAT(buf, " ");
3688 		if (cap->count0 != 0 && (isman || isman_s))
3689 		{
3690 		    sprintf((char *)buf + STRLEN(buf), "%ld", cap->count0);
3691 		    STRCAT(buf, " ");
3692 		}
3693 	    }
3694 	    break;
3695 
3696 	case ']':
3697 	    tag_cmd = TRUE;
3698 #ifdef FEAT_CSCOPE
3699 	    if (p_cst)
3700 		STRCPY(buf, "cstag ");
3701 	    else
3702 #endif
3703 		STRCPY(buf, "ts ");
3704 	    break;
3705 
3706 	default:
3707 	    tag_cmd = TRUE;
3708 	    if (curbuf->b_help)
3709 		STRCPY(buf, "he! ");
3710 	    else
3711 	    {
3712 		if (g_cmd)
3713 		    STRCPY(buf, "tj ");
3714 		else if (cap->count0 == 0)
3715 		    STRCPY(buf, "ta ");
3716 		else
3717 		    sprintf((char *)buf, ":%ldta ", cap->count0);
3718 	    }
3719     }
3720 
3721     /*
3722      * Now grab the chars in the identifier
3723      */
3724     if (cmdchar == 'K' && !kp_help)
3725     {
3726 	ptr = vim_strnsave(ptr, n);
3727 	if (kp_ex)
3728 	    // Escape the argument properly for an Ex command
3729 	    p = vim_strsave_fnameescape(ptr, FALSE);
3730 	else
3731 	    // Escape the argument properly for a shell command
3732 	    p = vim_strsave_shellescape(ptr, TRUE, TRUE);
3733 	vim_free(ptr);
3734 	if (p == NULL)
3735 	{
3736 	    vim_free(buf);
3737 	    return;
3738 	}
3739 	newbuf = vim_realloc(buf, STRLEN(buf) + STRLEN(p) + 1);
3740 	if (newbuf == NULL)
3741 	{
3742 	    vim_free(buf);
3743 	    vim_free(p);
3744 	    return;
3745 	}
3746 	buf = newbuf;
3747 	STRCAT(buf, p);
3748 	vim_free(p);
3749     }
3750     else
3751     {
3752 	if (cmdchar == '*')
3753 	    aux_ptr = (char_u *)(magic_isset() ? "/.*~[^$\\" : "/^$\\");
3754 	else if (cmdchar == '#')
3755 	    aux_ptr = (char_u *)(magic_isset() ? "/?.*~[^$\\" : "/?^$\\");
3756 	else if (tag_cmd)
3757 	{
3758 	    if (curbuf->b_help)
3759 		// ":help" handles unescaped argument
3760 		aux_ptr = (char_u *)"";
3761 	    else
3762 		aux_ptr = (char_u *)"\\|\"\n[";
3763 	}
3764 	else
3765 	    aux_ptr = (char_u *)"\\|\"\n*?[";
3766 
3767 	p = buf + STRLEN(buf);
3768 	while (n-- > 0)
3769 	{
3770 	    // put a backslash before \ and some others
3771 	    if (vim_strchr(aux_ptr, *ptr) != NULL)
3772 		*p++ = '\\';
3773 	    // When current byte is a part of multibyte character, copy all
3774 	    // bytes of that character.
3775 	    if (has_mbyte)
3776 	    {
3777 		int i;
3778 		int len = (*mb_ptr2len)(ptr) - 1;
3779 
3780 		for (i = 0; i < len && n >= 1; ++i, --n)
3781 		    *p++ = *ptr++;
3782 	    }
3783 	    *p++ = *ptr++;
3784 	}
3785 	*p = NUL;
3786     }
3787 
3788     /*
3789      * Execute the command.
3790      */
3791     if (cmdchar == '*' || cmdchar == '#')
3792     {
3793 	if (!g_cmd && (has_mbyte
3794 		    ? vim_iswordp(mb_prevptr(ml_get_curline(), ptr))
3795 		    : vim_iswordc(ptr[-1])))
3796 	    STRCAT(buf, "\\>");
3797 
3798 	// put pattern in search history
3799 	init_history();
3800 	add_to_history(HIST_SEARCH, buf, TRUE, NUL);
3801 
3802 	(void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0, NULL);
3803     }
3804     else
3805     {
3806 	g_tag_at_cursor = TRUE;
3807 	do_cmdline_cmd(buf);
3808 	g_tag_at_cursor = FALSE;
3809     }
3810 
3811     vim_free(buf);
3812 }
3813 
3814 /*
3815  * Get visually selected text, within one line only.
3816  * Returns FAIL if more than one line selected.
3817  */
3818     int
3819 get_visual_text(
3820     cmdarg_T	*cap,
3821     char_u	**pp,	    // return: start of selected text
3822     int		*lenp)	    // return: length of selected text
3823 {
3824     if (VIsual_mode != 'V')
3825 	unadjust_for_sel();
3826     if (VIsual.lnum != curwin->w_cursor.lnum)
3827     {
3828 	if (cap != NULL)
3829 	    clearopbeep(cap->oap);
3830 	return FAIL;
3831     }
3832     if (VIsual_mode == 'V')
3833     {
3834 	*pp = ml_get_curline();
3835 	*lenp = (int)STRLEN(*pp);
3836     }
3837     else
3838     {
3839 	if (LT_POS(curwin->w_cursor, VIsual))
3840 	{
3841 	    *pp = ml_get_pos(&curwin->w_cursor);
3842 	    *lenp = VIsual.col - curwin->w_cursor.col + 1;
3843 	}
3844 	else
3845 	{
3846 	    *pp = ml_get_pos(&VIsual);
3847 	    *lenp = curwin->w_cursor.col - VIsual.col + 1;
3848 	}
3849 	if (has_mbyte)
3850 	    // Correct the length to include the whole last character.
3851 	    *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
3852     }
3853     reset_VIsual_and_resel();
3854     return OK;
3855 }
3856 
3857 /*
3858  * CTRL-T: backwards in tag stack
3859  */
3860     static void
3861 nv_tagpop(cmdarg_T *cap)
3862 {
3863     if (!checkclearopq(cap->oap))
3864 	do_tag((char_u *)"", DT_POP, (int)cap->count1, FALSE, TRUE);
3865 }
3866 
3867 /*
3868  * Handle scrolling command 'H', 'L' and 'M'.
3869  */
3870     static void
3871 nv_scroll(cmdarg_T *cap)
3872 {
3873     int		used = 0;
3874     long	n;
3875 #ifdef FEAT_FOLDING
3876     linenr_T	lnum;
3877 #endif
3878     int		half;
3879 
3880     cap->oap->motion_type = MLINE;
3881     setpcmark();
3882 
3883     if (cap->cmdchar == 'L')
3884     {
3885 	validate_botline();	    // make sure curwin->w_botline is valid
3886 	curwin->w_cursor.lnum = curwin->w_botline - 1;
3887 	if (cap->count1 - 1 >= curwin->w_cursor.lnum)
3888 	    curwin->w_cursor.lnum = 1;
3889 	else
3890 	{
3891 #ifdef FEAT_FOLDING
3892 	    if (hasAnyFolding(curwin))
3893 	    {
3894 		// Count a fold for one screen line.
3895 		for (n = cap->count1 - 1; n > 0
3896 			    && curwin->w_cursor.lnum > curwin->w_topline; --n)
3897 		{
3898 		    (void)hasFolding(curwin->w_cursor.lnum,
3899 						&curwin->w_cursor.lnum, NULL);
3900 		    --curwin->w_cursor.lnum;
3901 		}
3902 	    }
3903 	    else
3904 #endif
3905 		curwin->w_cursor.lnum -= cap->count1 - 1;
3906 	}
3907     }
3908     else
3909     {
3910 	if (cap->cmdchar == 'M')
3911 	{
3912 #ifdef FEAT_DIFF
3913 	    // Don't count filler lines above the window.
3914 	    used -= diff_check_fill(curwin, curwin->w_topline)
3915 							  - curwin->w_topfill;
3916 #endif
3917 	    validate_botline();	    // make sure w_empty_rows is valid
3918 	    half = (curwin->w_height - curwin->w_empty_rows + 1) / 2;
3919 	    for (n = 0; curwin->w_topline + n < curbuf->b_ml.ml_line_count; ++n)
3920 	    {
3921 #ifdef FEAT_DIFF
3922 		// Count half he number of filler lines to be "below this
3923 		// line" and half to be "above the next line".
3924 		if (n > 0 && used + diff_check_fill(curwin, curwin->w_topline
3925 							     + n) / 2 >= half)
3926 		{
3927 		    --n;
3928 		    break;
3929 		}
3930 #endif
3931 		used += plines(curwin->w_topline + n);
3932 		if (used >= half)
3933 		    break;
3934 #ifdef FEAT_FOLDING
3935 		if (hasFolding(curwin->w_topline + n, NULL, &lnum))
3936 		    n = lnum - curwin->w_topline;
3937 #endif
3938 	    }
3939 	    if (n > 0 && used > curwin->w_height)
3940 		--n;
3941 	}
3942 	else // (cap->cmdchar == 'H')
3943 	{
3944 	    n = cap->count1 - 1;
3945 #ifdef FEAT_FOLDING
3946 	    if (hasAnyFolding(curwin))
3947 	    {
3948 		// Count a fold for one screen line.
3949 		lnum = curwin->w_topline;
3950 		while (n-- > 0 && lnum < curwin->w_botline - 1)
3951 		{
3952 		    (void)hasFolding(lnum, NULL, &lnum);
3953 		    ++lnum;
3954 		}
3955 		n = lnum - curwin->w_topline;
3956 	    }
3957 #endif
3958 	}
3959 	curwin->w_cursor.lnum = curwin->w_topline + n;
3960 	if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
3961 	    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3962     }
3963 
3964     // Correct for 'so', except when an operator is pending.
3965     if (cap->oap->op_type == OP_NOP)
3966 	cursor_correct();
3967     beginline(BL_SOL | BL_FIX);
3968 }
3969 
3970 /*
3971  * Cursor right commands.
3972  */
3973     static void
3974 nv_right(cmdarg_T *cap)
3975 {
3976     long	n;
3977     int		past_line;
3978 
3979     if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
3980     {
3981 	// <C-Right> and <S-Right> move a word or WORD right
3982 	if (mod_mask & MOD_MASK_CTRL)
3983 	    cap->arg = TRUE;
3984 	nv_wordcmd(cap);
3985 	return;
3986     }
3987 
3988     cap->oap->motion_type = MCHAR;
3989     cap->oap->inclusive = FALSE;
3990     past_line = (VIsual_active && *p_sel != 'o');
3991 
3992     /*
3993      * In virtual edit mode, there's no such thing as "past_line", as lines
3994      * are (theoretically) infinitely long.
3995      */
3996     if (virtual_active())
3997 	past_line = 0;
3998 
3999     for (n = cap->count1; n > 0; --n)
4000     {
4001 	if ((!past_line && oneright() == FAIL)
4002 		|| (past_line && *ml_get_cursor() == NUL)
4003 		)
4004 	{
4005 	    /*
4006 	     *	  <Space> wraps to next line if 'whichwrap' has 's'.
4007 	     *	      'l' wraps to next line if 'whichwrap' has 'l'.
4008 	     * CURS_RIGHT wraps to next line if 'whichwrap' has '>'.
4009 	     */
4010 	    if (       ((cap->cmdchar == ' '
4011 			    && vim_strchr(p_ww, 's') != NULL)
4012 			|| (cap->cmdchar == 'l'
4013 			    && vim_strchr(p_ww, 'l') != NULL)
4014 			|| (cap->cmdchar == K_RIGHT
4015 			    && vim_strchr(p_ww, '>') != NULL))
4016 		    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
4017 	    {
4018 		// When deleting we also count the NL as a character.
4019 		// Set cap->oap->inclusive when last char in the line is
4020 		// included, move to next line after that
4021 		if (	   cap->oap->op_type != OP_NOP
4022 			&& !cap->oap->inclusive
4023 			&& !LINEEMPTY(curwin->w_cursor.lnum))
4024 		    cap->oap->inclusive = TRUE;
4025 		else
4026 		{
4027 		    ++curwin->w_cursor.lnum;
4028 		    curwin->w_cursor.col = 0;
4029 		    curwin->w_cursor.coladd = 0;
4030 		    curwin->w_set_curswant = TRUE;
4031 		    cap->oap->inclusive = FALSE;
4032 		}
4033 		continue;
4034 	    }
4035 	    if (cap->oap->op_type == OP_NOP)
4036 	    {
4037 		// Only beep and flush if not moved at all
4038 		if (n == cap->count1)
4039 		    beep_flush();
4040 	    }
4041 	    else
4042 	    {
4043 		if (!LINEEMPTY(curwin->w_cursor.lnum))
4044 		    cap->oap->inclusive = TRUE;
4045 	    }
4046 	    break;
4047 	}
4048 	else if (past_line)
4049 	{
4050 	    curwin->w_set_curswant = TRUE;
4051 	    if (virtual_active())
4052 		oneright();
4053 	    else
4054 	    {
4055 		if (has_mbyte)
4056 		    curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
4057 		else
4058 		    ++curwin->w_cursor.col;
4059 	    }
4060 	}
4061     }
4062 #ifdef FEAT_FOLDING
4063     if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped
4064 					       && cap->oap->op_type == OP_NOP)
4065 	foldOpenCursor();
4066 #endif
4067 }
4068 
4069 /*
4070  * Cursor left commands.
4071  *
4072  * Returns TRUE when operator end should not be adjusted.
4073  */
4074     static void
4075 nv_left(cmdarg_T *cap)
4076 {
4077     long	n;
4078 
4079     if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
4080     {
4081 	// <C-Left> and <S-Left> move a word or WORD left
4082 	if (mod_mask & MOD_MASK_CTRL)
4083 	    cap->arg = 1;
4084 	nv_bck_word(cap);
4085 	return;
4086     }
4087 
4088     cap->oap->motion_type = MCHAR;
4089     cap->oap->inclusive = FALSE;
4090     for (n = cap->count1; n > 0; --n)
4091     {
4092 	if (oneleft() == FAIL)
4093 	{
4094 	    // <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'.
4095 	    //		 'h' wraps to previous line if 'whichwrap' has 'h'.
4096 	    //	   CURS_LEFT wraps to previous line if 'whichwrap' has '<'.
4097 	    if (       (((cap->cmdchar == K_BS
4098 				|| cap->cmdchar == Ctrl_H)
4099 			    && vim_strchr(p_ww, 'b') != NULL)
4100 			|| (cap->cmdchar == 'h'
4101 			    && vim_strchr(p_ww, 'h') != NULL)
4102 			|| (cap->cmdchar == K_LEFT
4103 			    && vim_strchr(p_ww, '<') != NULL))
4104 		    && curwin->w_cursor.lnum > 1)
4105 	    {
4106 		--(curwin->w_cursor.lnum);
4107 		coladvance((colnr_T)MAXCOL);
4108 		curwin->w_set_curswant = TRUE;
4109 
4110 		// When the NL before the first char has to be deleted we
4111 		// put the cursor on the NUL after the previous line.
4112 		// This is a very special case, be careful!
4113 		// Don't adjust op_end now, otherwise it won't work.
4114 		if (	   (cap->oap->op_type == OP_DELETE
4115 			    || cap->oap->op_type == OP_CHANGE)
4116 			&& !LINEEMPTY(curwin->w_cursor.lnum))
4117 		{
4118 		    char_u *cp = ml_get_cursor();
4119 
4120 		    if (*cp != NUL)
4121 		    {
4122 			if (has_mbyte)
4123 			    curwin->w_cursor.col += (*mb_ptr2len)(cp);
4124 			else
4125 			    ++curwin->w_cursor.col;
4126 		    }
4127 		    cap->retval |= CA_NO_ADJ_OP_END;
4128 		}
4129 		continue;
4130 	    }
4131 	    // Only beep and flush if not moved at all
4132 	    else if (cap->oap->op_type == OP_NOP && n == cap->count1)
4133 		beep_flush();
4134 	    break;
4135 	}
4136     }
4137 #ifdef FEAT_FOLDING
4138     if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped
4139 					       && cap->oap->op_type == OP_NOP)
4140 	foldOpenCursor();
4141 #endif
4142 }
4143 
4144 /*
4145  * Cursor up commands.
4146  * cap->arg is TRUE for "-": Move cursor to first non-blank.
4147  */
4148     static void
4149 nv_up(cmdarg_T *cap)
4150 {
4151     if (mod_mask & MOD_MASK_SHIFT)
4152     {
4153 	// <S-Up> is page up
4154 	cap->arg = BACKWARD;
4155 	nv_page(cap);
4156     }
4157     else
4158     {
4159 	cap->oap->motion_type = MLINE;
4160 	if (cursor_up(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
4161 	    clearopbeep(cap->oap);
4162 	else if (cap->arg)
4163 	    beginline(BL_WHITE | BL_FIX);
4164     }
4165 }
4166 
4167 /*
4168  * Cursor down commands.
4169  * cap->arg is TRUE for CR and "+": Move cursor to first non-blank.
4170  */
4171     static void
4172 nv_down(cmdarg_T *cap)
4173 {
4174     if (mod_mask & MOD_MASK_SHIFT)
4175     {
4176 	// <S-Down> is page down
4177 	cap->arg = FORWARD;
4178 	nv_page(cap);
4179     }
4180 #if defined(FEAT_QUICKFIX)
4181     // Quickfix window only: view the result under the cursor.
4182     else if (bt_quickfix(curbuf) && cap->cmdchar == CAR)
4183 	qf_view_result(FALSE);
4184 #endif
4185     else
4186     {
4187 #ifdef FEAT_CMDWIN
4188 	// In the cmdline window a <CR> executes the command.
4189 	if (cmdwin_type != 0 && cap->cmdchar == CAR)
4190 	    cmdwin_result = CAR;
4191 	else
4192 #endif
4193 #ifdef FEAT_JOB_CHANNEL
4194 	// In a prompt buffer a <CR> in the last line invokes the callback.
4195 	if (bt_prompt(curbuf) && cap->cmdchar == CAR
4196 		       && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
4197 	{
4198 	    invoke_prompt_callback();
4199 	    if (restart_edit == 0)
4200 		restart_edit = 'a';
4201 	}
4202 	else
4203 #endif
4204 	{
4205 	    cap->oap->motion_type = MLINE;
4206 	    if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
4207 		clearopbeep(cap->oap);
4208 	    else if (cap->arg)
4209 		beginline(BL_WHITE | BL_FIX);
4210 	}
4211     }
4212 }
4213 
4214 #ifdef FEAT_SEARCHPATH
4215 /*
4216  * Grab the file name under the cursor and edit it.
4217  */
4218     static void
4219 nv_gotofile(cmdarg_T *cap)
4220 {
4221     char_u	*ptr;
4222     linenr_T	lnum = -1;
4223 
4224     if (text_locked())
4225     {
4226 	clearopbeep(cap->oap);
4227 	text_locked_msg();
4228 	return;
4229     }
4230     if (curbuf_locked())
4231     {
4232 	clearop(cap->oap);
4233 	return;
4234     }
4235 #ifdef FEAT_PROP_POPUP
4236     if (ERROR_IF_TERM_POPUP_WINDOW)
4237 	return;
4238 #endif
4239 
4240     ptr = grab_file_name(cap->count1, &lnum);
4241 
4242     if (ptr != NULL)
4243     {
4244 	// do autowrite if necessary
4245 	if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !buf_hide(curbuf))
4246 	    (void)autowrite(curbuf, FALSE);
4247 	setpcmark();
4248 	if (do_ecmd(0, ptr, NULL, NULL, ECMD_LAST,
4249 				buf_hide(curbuf) ? ECMD_HIDE : 0, curwin) == OK
4250 		&& cap->nchar == 'F' && lnum >= 0)
4251 	{
4252 	    curwin->w_cursor.lnum = lnum;
4253 	    check_cursor_lnum();
4254 	    beginline(BL_SOL | BL_FIX);
4255 	}
4256 	vim_free(ptr);
4257     }
4258     else
4259 	clearop(cap->oap);
4260 }
4261 #endif
4262 
4263 /*
4264  * <End> command: to end of current line or last line.
4265  */
4266     static void
4267 nv_end(cmdarg_T *cap)
4268 {
4269     if (cap->arg || (mod_mask & MOD_MASK_CTRL))	// CTRL-END = goto last line
4270     {
4271 	cap->arg = TRUE;
4272 	nv_goto(cap);
4273 	cap->count1 = 1;		// to end of current line
4274     }
4275     nv_dollar(cap);
4276 }
4277 
4278 /*
4279  * Handle the "$" command.
4280  */
4281     static void
4282 nv_dollar(cmdarg_T *cap)
4283 {
4284     cap->oap->motion_type = MCHAR;
4285     cap->oap->inclusive = TRUE;
4286     // In virtual mode when off the edge of a line and an operator
4287     // is pending (whew!) keep the cursor where it is.
4288     // Otherwise, send it to the end of the line.
4289     if (!virtual_active() || gchar_cursor() != NUL
4290 					       || cap->oap->op_type == OP_NOP)
4291 	curwin->w_curswant = MAXCOL;	// so we stay at the end
4292     if (cursor_down((long)(cap->count1 - 1),
4293 					 cap->oap->op_type == OP_NOP) == FAIL)
4294 	clearopbeep(cap->oap);
4295 #ifdef FEAT_FOLDING
4296     else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
4297 	foldOpenCursor();
4298 #endif
4299 }
4300 
4301 /*
4302  * Implementation of '?' and '/' commands.
4303  * If cap->arg is TRUE don't set PC mark.
4304  */
4305     static void
4306 nv_search(cmdarg_T *cap)
4307 {
4308     oparg_T	*oap = cap->oap;
4309     pos_T	save_cursor = curwin->w_cursor;
4310 
4311     if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13)
4312     {
4313 	// Translate "g??" to "g?g?"
4314 	cap->cmdchar = 'g';
4315 	cap->nchar = '?';
4316 	nv_operator(cap);
4317 	return;
4318     }
4319 
4320     // When using 'incsearch' the cursor may be moved to set a different search
4321     // start position.
4322     cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0, TRUE);
4323 
4324     if (cap->searchbuf == NULL)
4325     {
4326 	clearop(oap);
4327 	return;
4328     }
4329 
4330     (void)normal_search(cap, cap->cmdchar, cap->searchbuf,
4331 			(cap->arg || !EQUAL_POS(save_cursor, curwin->w_cursor))
4332 						      ? 0 : SEARCH_MARK, NULL);
4333 }
4334 
4335 /*
4336  * Handle "N" and "n" commands.
4337  * cap->arg is SEARCH_REV for "N", 0 for "n".
4338  */
4339     static void
4340 nv_next(cmdarg_T *cap)
4341 {
4342     pos_T   old = curwin->w_cursor;
4343     int	    wrapped = FALSE;
4344     int	    i = normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, &wrapped);
4345 
4346     if (i == 1 && !wrapped && EQUAL_POS(old, curwin->w_cursor))
4347     {
4348 	// Avoid getting stuck on the current cursor position, which can
4349 	// happen when an offset is given and the cursor is on the last char
4350 	// in the buffer: Repeat with count + 1.
4351 	cap->count1 += 1;
4352 	(void)normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg, NULL);
4353 	cap->count1 -= 1;
4354     }
4355 }
4356 
4357 /*
4358  * Search for "pat" in direction "dir" ('/' or '?', 0 for repeat).
4359  * Uses only cap->count1 and cap->oap from "cap".
4360  * Return 0 for failure, 1 for found, 2 for found and line offset added.
4361  */
4362     static int
4363 normal_search(
4364     cmdarg_T	*cap,
4365     int		dir,
4366     char_u	*pat,
4367     int		opt,		// extra flags for do_search()
4368     int		*wrapped)
4369 {
4370     int		i;
4371     searchit_arg_T sia;
4372 
4373     cap->oap->motion_type = MCHAR;
4374     cap->oap->inclusive = FALSE;
4375     cap->oap->use_reg_one = TRUE;
4376     curwin->w_set_curswant = TRUE;
4377 
4378     CLEAR_FIELD(sia);
4379     i = do_search(cap->oap, dir, dir, pat, cap->count1,
4380 			    opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, &sia);
4381     if (wrapped != NULL)
4382 	*wrapped = sia.sa_wrapped;
4383     if (i == 0)
4384 	clearop(cap->oap);
4385     else
4386     {
4387 	if (i == 2)
4388 	    cap->oap->motion_type = MLINE;
4389 	curwin->w_cursor.coladd = 0;
4390 #ifdef FEAT_FOLDING
4391 	if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
4392 	    foldOpenCursor();
4393 #endif
4394     }
4395 
4396     // "/$" will put the cursor after the end of the line, may need to
4397     // correct that here
4398     check_cursor();
4399     return i;
4400 }
4401 
4402 /*
4403  * Character search commands.
4404  * cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', TRUE for
4405  * ',' and FALSE for ';'.
4406  * cap->nchar is NUL for ',' and ';' (repeat the search)
4407  */
4408     static void
4409 nv_csearch(cmdarg_T *cap)
4410 {
4411     int		t_cmd;
4412 
4413     if (cap->cmdchar == 't' || cap->cmdchar == 'T')
4414 	t_cmd = TRUE;
4415     else
4416 	t_cmd = FALSE;
4417 
4418     cap->oap->motion_type = MCHAR;
4419     if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == FAIL)
4420 	clearopbeep(cap->oap);
4421     else
4422     {
4423 	curwin->w_set_curswant = TRUE;
4424 	// Include a Tab for "tx" and for "dfx".
4425 	if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD
4426 		&& (t_cmd || cap->oap->op_type != OP_NOP))
4427 	{
4428 	    colnr_T	scol, ecol;
4429 
4430 	    getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
4431 	    curwin->w_cursor.coladd = ecol - scol;
4432 	}
4433 	else
4434 	    curwin->w_cursor.coladd = 0;
4435 	adjust_for_sel(cap);
4436 #ifdef FEAT_FOLDING
4437 	if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
4438 	    foldOpenCursor();
4439 #endif
4440     }
4441 }
4442 
4443 /*
4444  * "[" and "]" commands.
4445  * cap->arg is BACKWARD for "[" and FORWARD for "]".
4446  */
4447     static void
4448 nv_brackets(cmdarg_T *cap)
4449 {
4450     pos_T	new_pos = {0, 0, 0};
4451     pos_T	prev_pos;
4452     pos_T	*pos = NULL;	    // init for GCC
4453     pos_T	old_pos;	    // cursor position before command
4454     int		flag;
4455     long	n;
4456     int		findc;
4457     int		c;
4458 
4459     cap->oap->motion_type = MCHAR;
4460     cap->oap->inclusive = FALSE;
4461     old_pos = curwin->w_cursor;
4462     curwin->w_cursor.coladd = 0;    // TODO: don't do this for an error.
4463 
4464 #ifdef FEAT_SEARCHPATH
4465     /*
4466      * "[f" or "]f" : Edit file under the cursor (same as "gf")
4467      */
4468     if (cap->nchar == 'f')
4469 	nv_gotofile(cap);
4470     else
4471 #endif
4472 
4473 #ifdef FEAT_FIND_ID
4474     /*
4475      * Find the occurrence(s) of the identifier or define under cursor
4476      * in current and included files or jump to the first occurrence.
4477      *
4478      *			search	     list	    jump
4479      *		      fwd   bwd    fwd	 bwd	 fwd	bwd
4480      * identifier     "]i"  "[i"   "]I"  "[I"	"]^I"  "[^I"
4481      * define	      "]d"  "[d"   "]D"  "[D"	"]^D"  "[^D"
4482      */
4483     if (vim_strchr((char_u *)
4484 # ifdef EBCDIC
4485 		"iI\005dD\067",
4486 # else
4487 		"iI\011dD\004",
4488 # endif
4489 		cap->nchar) != NULL)
4490     {
4491 	char_u	*ptr;
4492 	int	len;
4493 
4494 	if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
4495 	    clearop(cap->oap);
4496 	else
4497 	{
4498 	    find_pattern_in_path(ptr, 0, len, TRUE,
4499 		cap->count0 == 0 ? !isupper(cap->nchar) : FALSE,
4500 		((cap->nchar & 0xf) == ('d' & 0xf)) ?  FIND_DEFINE : FIND_ANY,
4501 		cap->count1,
4502 		isupper(cap->nchar) ? ACTION_SHOW_ALL :
4503 			    islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO,
4504 		cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1,
4505 		(linenr_T)MAXLNUM);
4506 	    curwin->w_set_curswant = TRUE;
4507 	}
4508     }
4509     else
4510 #endif
4511 
4512     /*
4513      * "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')'
4514      * "[#", "]#": go to start/end of Nth innermost #if..#endif construct.
4515      * "[/", "[*", "]/", "]*": go to Nth comment start/end.
4516      * "[m" or "]m" search for prev/next start of (Java) method.
4517      * "[M" or "]M" search for prev/next end of (Java) method.
4518      */
4519     if (  (cap->cmdchar == '['
4520 		&& vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL)
4521 	    || (cap->cmdchar == ']'
4522 		&& vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL))
4523     {
4524 	if (cap->nchar == '*')
4525 	    cap->nchar = '/';
4526 	prev_pos.lnum = 0;
4527 	if (cap->nchar == 'm' || cap->nchar == 'M')
4528 	{
4529 	    if (cap->cmdchar == '[')
4530 		findc = '{';
4531 	    else
4532 		findc = '}';
4533 	    n = 9999;
4534 	}
4535 	else
4536 	{
4537 	    findc = cap->nchar;
4538 	    n = cap->count1;
4539 	}
4540 	for ( ; n > 0; --n)
4541 	{
4542 	    if ((pos = findmatchlimit(cap->oap, findc,
4543 		(cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL)
4544 	    {
4545 		if (new_pos.lnum == 0)	// nothing found
4546 		{
4547 		    if (cap->nchar != 'm' && cap->nchar != 'M')
4548 			clearopbeep(cap->oap);
4549 		}
4550 		else
4551 		    pos = &new_pos;	// use last one found
4552 		break;
4553 	    }
4554 	    prev_pos = new_pos;
4555 	    curwin->w_cursor = *pos;
4556 	    new_pos = *pos;
4557 	}
4558 	curwin->w_cursor = old_pos;
4559 
4560 	/*
4561 	 * Handle "[m", "]m", "[M" and "[M".  The findmatchlimit() only
4562 	 * brought us to the match for "[m" and "]M" when inside a method.
4563 	 * Try finding the '{' or '}' we want to be at.
4564 	 * Also repeat for the given count.
4565 	 */
4566 	if (cap->nchar == 'm' || cap->nchar == 'M')
4567 	{
4568 	    // norm is TRUE for "]M" and "[m"
4569 	    int	    norm = ((findc == '{') == (cap->nchar == 'm'));
4570 
4571 	    n = cap->count1;
4572 	    // found a match: we were inside a method
4573 	    if (prev_pos.lnum != 0)
4574 	    {
4575 		pos = &prev_pos;
4576 		curwin->w_cursor = prev_pos;
4577 		if (norm)
4578 		    --n;
4579 	    }
4580 	    else
4581 		pos = NULL;
4582 	    while (n > 0)
4583 	    {
4584 		for (;;)
4585 		{
4586 		    if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0)
4587 		    {
4588 			// if not found anything, that's an error
4589 			if (pos == NULL)
4590 			    clearopbeep(cap->oap);
4591 			n = 0;
4592 			break;
4593 		    }
4594 		    c = gchar_cursor();
4595 		    if (c == '{' || c == '}')
4596 		    {
4597 			// Must have found end/start of class: use it.
4598 			// Or found the place to be at.
4599 			if ((c == findc && norm) || (n == 1 && !norm))
4600 			{
4601 			    new_pos = curwin->w_cursor;
4602 			    pos = &new_pos;
4603 			    n = 0;
4604 			}
4605 			// if no match found at all, we started outside of the
4606 			// class and we're inside now.  Just go on.
4607 			else if (new_pos.lnum == 0)
4608 			{
4609 			    new_pos = curwin->w_cursor;
4610 			    pos = &new_pos;
4611 			}
4612 			// found start/end of other method: go to match
4613 			else if ((pos = findmatchlimit(cap->oap, findc,
4614 			    (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD,
4615 								  0)) == NULL)
4616 			    n = 0;
4617 			else
4618 			    curwin->w_cursor = *pos;
4619 			break;
4620 		    }
4621 		}
4622 		--n;
4623 	    }
4624 	    curwin->w_cursor = old_pos;
4625 	    if (pos == NULL && new_pos.lnum != 0)
4626 		clearopbeep(cap->oap);
4627 	}
4628 	if (pos != NULL)
4629 	{
4630 	    setpcmark();
4631 	    curwin->w_cursor = *pos;
4632 	    curwin->w_set_curswant = TRUE;
4633 #ifdef FEAT_FOLDING
4634 	    if ((fdo_flags & FDO_BLOCK) && KeyTyped
4635 					       && cap->oap->op_type == OP_NOP)
4636 		foldOpenCursor();
4637 #endif
4638 	}
4639     }
4640 
4641     /*
4642      * "[[", "[]", "]]" and "][": move to start or end of function
4643      */
4644     else if (cap->nchar == '[' || cap->nchar == ']')
4645     {
4646 	if (cap->nchar == cap->cmdchar)		    // "]]" or "[["
4647 	    flag = '{';
4648 	else
4649 	    flag = '}';		    // "][" or "[]"
4650 
4651 	curwin->w_set_curswant = TRUE;
4652 	/*
4653 	 * Imitate strange Vi behaviour: When using "]]" with an operator
4654 	 * we also stop at '}'.
4655 	 */
4656 	if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag,
4657 	      (cap->oap->op_type != OP_NOP
4658 				      && cap->arg == FORWARD && flag == '{')))
4659 	    clearopbeep(cap->oap);
4660 	else
4661 	{
4662 	    if (cap->oap->op_type == OP_NOP)
4663 		beginline(BL_WHITE | BL_FIX);
4664 #ifdef FEAT_FOLDING
4665 	    if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
4666 		foldOpenCursor();
4667 #endif
4668 	}
4669     }
4670 
4671     /*
4672      * "[p", "[P", "]P" and "]p": put with indent adjustment
4673      */
4674     else if (cap->nchar == 'p' || cap->nchar == 'P')
4675     {
4676 	nv_put_opt(cap, TRUE);
4677     }
4678 
4679     /*
4680      * "['", "[`", "]'" and "]`": jump to next mark
4681      */
4682     else if (cap->nchar == '\'' || cap->nchar == '`')
4683     {
4684 	pos = &curwin->w_cursor;
4685 	for (n = cap->count1; n > 0; --n)
4686 	{
4687 	    prev_pos = *pos;
4688 	    pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD,
4689 							  cap->nchar == '\'');
4690 	    if (pos == NULL)
4691 		break;
4692 	}
4693 	if (pos == NULL)
4694 	    pos = &prev_pos;
4695 	nv_cursormark(cap, cap->nchar == '\'', pos);
4696     }
4697 
4698     /*
4699      * [ or ] followed by a middle mouse click: put selected text with
4700      * indent adjustment.  Any other button just does as usual.
4701      */
4702     else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE)
4703     {
4704 	(void)do_mouse(cap->oap, cap->nchar,
4705 		       (cap->cmdchar == ']') ? FORWARD : BACKWARD,
4706 		       cap->count1, PUT_FIXINDENT);
4707     }
4708 
4709 #ifdef FEAT_FOLDING
4710     /*
4711      * "[z" and "]z": move to start or end of open fold.
4712      */
4713     else if (cap->nchar == 'z')
4714     {
4715 	if (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD,
4716 							 cap->count1) == FAIL)
4717 	    clearopbeep(cap->oap);
4718     }
4719 #endif
4720 
4721 #ifdef FEAT_DIFF
4722     /*
4723      * "[c" and "]c": move to next or previous diff-change.
4724      */
4725     else if (cap->nchar == 'c')
4726     {
4727 	if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD,
4728 							 cap->count1) == FAIL)
4729 	    clearopbeep(cap->oap);
4730     }
4731 #endif
4732 
4733 #ifdef FEAT_SPELL
4734     /*
4735      * "[s", "[S", "]s" and "]S": move to next spell error.
4736      */
4737     else if (cap->nchar == 's' || cap->nchar == 'S')
4738     {
4739 	setpcmark();
4740 	for (n = 0; n < cap->count1; ++n)
4741 	    if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD,
4742 			  cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0)
4743 	    {
4744 		clearopbeep(cap->oap);
4745 		break;
4746 	    }
4747 	    else
4748 		curwin->w_set_curswant = TRUE;
4749 # ifdef FEAT_FOLDING
4750 	if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
4751 	    foldOpenCursor();
4752 # endif
4753     }
4754 #endif
4755 
4756     // Not a valid cap->nchar.
4757     else
4758 	clearopbeep(cap->oap);
4759 }
4760 
4761 /*
4762  * Handle Normal mode "%" command.
4763  */
4764     static void
4765 nv_percent(cmdarg_T *cap)
4766 {
4767     pos_T	*pos;
4768 #if defined(FEAT_FOLDING)
4769     linenr_T	lnum = curwin->w_cursor.lnum;
4770 #endif
4771 
4772     cap->oap->inclusive = TRUE;
4773     if (cap->count0)	    // {cnt}% : goto {cnt} percentage in file
4774     {
4775 	if (cap->count0 > 100)
4776 	    clearopbeep(cap->oap);
4777 	else
4778 	{
4779 	    cap->oap->motion_type = MLINE;
4780 	    setpcmark();
4781 	    // Round up, so 'normal 100%' always jumps at the line line.
4782 	    // Beyond 21474836 lines, (ml_line_count * 100 + 99) would
4783 	    // overflow on 32-bits, so use a formula with less accuracy
4784 	    // to avoid overflows.
4785 	    if (curbuf->b_ml.ml_line_count >= 21474836)
4786 		curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99L)
4787 							 / 100L * cap->count0;
4788 	    else
4789 		curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count *
4790 						    cap->count0 + 99L) / 100L;
4791 	    if (curwin->w_cursor.lnum < 1)
4792 		curwin->w_cursor.lnum = 1;
4793 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
4794 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4795 	    beginline(BL_SOL | BL_FIX);
4796 	}
4797     }
4798     else		    // "%" : go to matching paren
4799     {
4800 	cap->oap->motion_type = MCHAR;
4801 	cap->oap->use_reg_one = TRUE;
4802 	if ((pos = findmatch(cap->oap, NUL)) == NULL)
4803 	    clearopbeep(cap->oap);
4804 	else
4805 	{
4806 	    setpcmark();
4807 	    curwin->w_cursor = *pos;
4808 	    curwin->w_set_curswant = TRUE;
4809 	    curwin->w_cursor.coladd = 0;
4810 	    adjust_for_sel(cap);
4811 	}
4812     }
4813 #ifdef FEAT_FOLDING
4814     if (cap->oap->op_type == OP_NOP
4815 	    && lnum != curwin->w_cursor.lnum
4816 	    && (fdo_flags & FDO_PERCENT)
4817 	    && KeyTyped)
4818 	foldOpenCursor();
4819 #endif
4820 }
4821 
4822 /*
4823  * Handle "(" and ")" commands.
4824  * cap->arg is BACKWARD for "(" and FORWARD for ")".
4825  */
4826     static void
4827 nv_brace(cmdarg_T *cap)
4828 {
4829     cap->oap->motion_type = MCHAR;
4830     cap->oap->use_reg_one = TRUE;
4831     // The motion used to be inclusive for "(", but that is not what Vi does.
4832     cap->oap->inclusive = FALSE;
4833     curwin->w_set_curswant = TRUE;
4834 
4835     if (findsent(cap->arg, cap->count1) == FAIL)
4836 	clearopbeep(cap->oap);
4837     else
4838     {
4839 	// Don't leave the cursor on the NUL past end of line.
4840 	adjust_cursor(cap->oap);
4841 	curwin->w_cursor.coladd = 0;
4842 #ifdef FEAT_FOLDING
4843 	if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
4844 	    foldOpenCursor();
4845 #endif
4846     }
4847 }
4848 
4849 /*
4850  * "m" command: Mark a position.
4851  */
4852     static void
4853 nv_mark(cmdarg_T *cap)
4854 {
4855     if (!checkclearop(cap->oap))
4856     {
4857 	if (setmark(cap->nchar) == FAIL)
4858 	    clearopbeep(cap->oap);
4859     }
4860 }
4861 
4862 /*
4863  * "{" and "}" commands.
4864  * cmd->arg is BACKWARD for "{" and FORWARD for "}".
4865  */
4866     static void
4867 nv_findpar(cmdarg_T *cap)
4868 {
4869     cap->oap->motion_type = MCHAR;
4870     cap->oap->inclusive = FALSE;
4871     cap->oap->use_reg_one = TRUE;
4872     curwin->w_set_curswant = TRUE;
4873     if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, FALSE))
4874 	clearopbeep(cap->oap);
4875     else
4876     {
4877 	curwin->w_cursor.coladd = 0;
4878 #ifdef FEAT_FOLDING
4879 	if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
4880 	    foldOpenCursor();
4881 #endif
4882     }
4883 }
4884 
4885 /*
4886  * "u" command: Undo or make lower case.
4887  */
4888     static void
4889 nv_undo(cmdarg_T *cap)
4890 {
4891     if (cap->oap->op_type == OP_LOWER || VIsual_active)
4892     {
4893 	// translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu"
4894 	cap->cmdchar = 'g';
4895 	cap->nchar = 'u';
4896 	nv_operator(cap);
4897     }
4898     else
4899 	nv_kundo(cap);
4900 }
4901 
4902 /*
4903  * <Undo> command.
4904  */
4905     static void
4906 nv_kundo(cmdarg_T *cap)
4907 {
4908     if (!checkclearopq(cap->oap))
4909     {
4910 #ifdef FEAT_JOB_CHANNEL
4911 	if (bt_prompt(curbuf))
4912 	{
4913 	    clearopbeep(cap->oap);
4914 	    return;
4915 	}
4916 #endif
4917 	u_undo((int)cap->count1);
4918 	curwin->w_set_curswant = TRUE;
4919     }
4920 }
4921 
4922 /*
4923  * Handle the "r" command.
4924  */
4925     static void
4926 nv_replace(cmdarg_T *cap)
4927 {
4928     char_u	*ptr;
4929     int		had_ctrl_v;
4930     long	n;
4931 
4932     if (checkclearop(cap->oap))
4933 	return;
4934 #ifdef FEAT_JOB_CHANNEL
4935     if (bt_prompt(curbuf) && !prompt_curpos_editable())
4936     {
4937 	clearopbeep(cap->oap);
4938 	return;
4939     }
4940 #endif
4941 
4942     // get another character
4943     if (cap->nchar == Ctrl_V)
4944     {
4945 	had_ctrl_v = Ctrl_V;
4946 	cap->nchar = get_literal(FALSE);
4947 	// Don't redo a multibyte character with CTRL-V.
4948 	if (cap->nchar > DEL)
4949 	    had_ctrl_v = NUL;
4950     }
4951     else
4952 	had_ctrl_v = NUL;
4953 
4954     // Abort if the character is a special key.
4955     if (IS_SPECIAL(cap->nchar))
4956     {
4957 	clearopbeep(cap->oap);
4958 	return;
4959     }
4960 
4961     // Visual mode "r"
4962     if (VIsual_active)
4963     {
4964 	if (got_int)
4965 	    reset_VIsual();
4966 	if (had_ctrl_v)
4967 	{
4968 	    // Use a special (negative) number to make a difference between a
4969 	    // literal CR or NL and a line break.
4970 	    if (cap->nchar == CAR)
4971 		cap->nchar = REPLACE_CR_NCHAR;
4972 	    else if (cap->nchar == NL)
4973 		cap->nchar = REPLACE_NL_NCHAR;
4974 	}
4975 	nv_operator(cap);
4976 	return;
4977     }
4978 
4979     // Break tabs, etc.
4980     if (virtual_active())
4981     {
4982 	if (u_save_cursor() == FAIL)
4983 	    return;
4984 	if (gchar_cursor() == NUL)
4985 	{
4986 	    // Add extra space and put the cursor on the first one.
4987 	    coladvance_force((colnr_T)(getviscol() + cap->count1));
4988 	    curwin->w_cursor.col -= cap->count1;
4989 	}
4990 	else if (gchar_cursor() == TAB)
4991 	    coladvance_force(getviscol());
4992     }
4993 
4994     // Abort if not enough characters to replace.
4995     ptr = ml_get_cursor();
4996     if (STRLEN(ptr) < (unsigned)cap->count1
4997 	    || (has_mbyte && mb_charlen(ptr) < cap->count1))
4998     {
4999 	clearopbeep(cap->oap);
5000 	return;
5001     }
5002 
5003     /*
5004      * Replacing with a TAB is done by edit() when it is complicated because
5005      * 'expandtab' or 'smarttab' is set.  CTRL-V TAB inserts a literal TAB.
5006      * Other characters are done below to avoid problems with things like
5007      * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC).
5008      */
5009     if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta))
5010     {
5011 	stuffnumReadbuff(cap->count1);
5012 	stuffcharReadbuff('R');
5013 	stuffcharReadbuff('\t');
5014 	stuffcharReadbuff(ESC);
5015 	return;
5016     }
5017 
5018     // save line for undo
5019     if (u_save_cursor() == FAIL)
5020 	return;
5021 
5022     if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n'))
5023     {
5024 	/*
5025 	 * Replace character(s) by a single newline.
5026 	 * Strange vi behaviour: Only one newline is inserted.
5027 	 * Delete the characters here.
5028 	 * Insert the newline with an insert command, takes care of
5029 	 * autoindent.	The insert command depends on being on the last
5030 	 * character of a line or not.
5031 	 */
5032 	(void)del_chars(cap->count1, FALSE);	// delete the characters
5033 	stuffcharReadbuff('\r');
5034 	stuffcharReadbuff(ESC);
5035 
5036 	// Give 'r' to edit(), to get the redo command right.
5037 	invoke_edit(cap, TRUE, 'r', FALSE);
5038     }
5039     else
5040     {
5041 	prep_redo(cap->oap->regname, cap->count1,
5042 				       NUL, 'r', NUL, had_ctrl_v, cap->nchar);
5043 
5044 	curbuf->b_op_start = curwin->w_cursor;
5045 	if (has_mbyte)
5046 	{
5047 	    int		old_State = State;
5048 
5049 	    if (cap->ncharC1 != 0)
5050 		AppendCharToRedobuff(cap->ncharC1);
5051 	    if (cap->ncharC2 != 0)
5052 		AppendCharToRedobuff(cap->ncharC2);
5053 
5054 	    // This is slow, but it handles replacing a single-byte with a
5055 	    // multi-byte and the other way around.  Also handles adding
5056 	    // composing characters for utf-8.
5057 	    for (n = cap->count1; n > 0; --n)
5058 	    {
5059 		State = REPLACE;
5060 		if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
5061 		{
5062 		    int c = ins_copychar(curwin->w_cursor.lnum
5063 					   + (cap->nchar == Ctrl_Y ? -1 : 1));
5064 		    if (c != NUL)
5065 			ins_char(c);
5066 		    else
5067 			// will be decremented further down
5068 			++curwin->w_cursor.col;
5069 		}
5070 		else
5071 		    ins_char(cap->nchar);
5072 		State = old_State;
5073 		if (cap->ncharC1 != 0)
5074 		    ins_char(cap->ncharC1);
5075 		if (cap->ncharC2 != 0)
5076 		    ins_char(cap->ncharC2);
5077 	    }
5078 	}
5079 	else
5080 	{
5081 	    /*
5082 	     * Replace the characters within one line.
5083 	     */
5084 	    for (n = cap->count1; n > 0; --n)
5085 	    {
5086 		/*
5087 		 * Get ptr again, because u_save and/or showmatch() will have
5088 		 * released the line.  At the same time we let know that the
5089 		 * line will be changed.
5090 		 */
5091 		ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);
5092 		if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
5093 		{
5094 		  int c = ins_copychar(curwin->w_cursor.lnum
5095 					   + (cap->nchar == Ctrl_Y ? -1 : 1));
5096 		  if (c != NUL)
5097 		    ptr[curwin->w_cursor.col] = c;
5098 		}
5099 		else
5100 		    ptr[curwin->w_cursor.col] = cap->nchar;
5101 		if (p_sm && msg_silent == 0)
5102 		    showmatch(cap->nchar);
5103 		++curwin->w_cursor.col;
5104 	    }
5105 #ifdef FEAT_NETBEANS_INTG
5106 	    if (netbeans_active())
5107 	    {
5108 		colnr_T  start = (colnr_T)(curwin->w_cursor.col - cap->count1);
5109 
5110 		netbeans_removed(curbuf, curwin->w_cursor.lnum, start,
5111 							   (long)cap->count1);
5112 		netbeans_inserted(curbuf, curwin->w_cursor.lnum, start,
5113 					       &ptr[start], (int)cap->count1);
5114 	    }
5115 #endif
5116 
5117 	    // mark the buffer as changed and prepare for displaying
5118 	    changed_bytes(curwin->w_cursor.lnum,
5119 			       (colnr_T)(curwin->w_cursor.col - cap->count1));
5120 	}
5121 	--curwin->w_cursor.col;	    // cursor on the last replaced char
5122 	// if the character on the left of the current cursor is a multi-byte
5123 	// character, move two characters left
5124 	if (has_mbyte)
5125 	    mb_adjust_cursor();
5126 	curbuf->b_op_end = curwin->w_cursor;
5127 	curwin->w_set_curswant = TRUE;
5128 	set_last_insert(cap->nchar);
5129     }
5130 }
5131 
5132 /*
5133  * 'o': Exchange start and end of Visual area.
5134  * 'O': same, but in block mode exchange left and right corners.
5135  */
5136     static void
5137 v_swap_corners(int cmdchar)
5138 {
5139     pos_T	old_cursor;
5140     colnr_T	left, right;
5141 
5142     if (cmdchar == 'O' && VIsual_mode == Ctrl_V)
5143     {
5144 	old_cursor = curwin->w_cursor;
5145 	getvcols(curwin, &old_cursor, &VIsual, &left, &right);
5146 	curwin->w_cursor.lnum = VIsual.lnum;
5147 	coladvance(left);
5148 	VIsual = curwin->w_cursor;
5149 
5150 	curwin->w_cursor.lnum = old_cursor.lnum;
5151 	curwin->w_curswant = right;
5152 	// 'selection "exclusive" and cursor at right-bottom corner: move it
5153 	// right one column
5154 	if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e')
5155 	    ++curwin->w_curswant;
5156 	coladvance(curwin->w_curswant);
5157 	if (curwin->w_cursor.col == old_cursor.col
5158 		&& (!virtual_active()
5159 		    || curwin->w_cursor.coladd == old_cursor.coladd))
5160 	{
5161 	    curwin->w_cursor.lnum = VIsual.lnum;
5162 	    if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e')
5163 		++right;
5164 	    coladvance(right);
5165 	    VIsual = curwin->w_cursor;
5166 
5167 	    curwin->w_cursor.lnum = old_cursor.lnum;
5168 	    coladvance(left);
5169 	    curwin->w_curswant = left;
5170 	}
5171     }
5172     else
5173     {
5174 	old_cursor = curwin->w_cursor;
5175 	curwin->w_cursor = VIsual;
5176 	VIsual = old_cursor;
5177 	curwin->w_set_curswant = TRUE;
5178     }
5179 }
5180 
5181 /*
5182  * "R" (cap->arg is FALSE) and "gR" (cap->arg is TRUE).
5183  */
5184     static void
5185 nv_Replace(cmdarg_T *cap)
5186 {
5187     if (VIsual_active)		// "R" is replace lines
5188     {
5189 	cap->cmdchar = 'c';
5190 	cap->nchar = NUL;
5191 	VIsual_mode_orig = VIsual_mode; // remember original area for gv
5192 	VIsual_mode = 'V';
5193 	nv_operator(cap);
5194     }
5195     else if (!checkclearopq(cap->oap))
5196     {
5197 	if (!curbuf->b_p_ma)
5198 	    emsg(_(e_modifiable));
5199 	else
5200 	{
5201 	    if (virtual_active())
5202 		coladvance(getviscol());
5203 	    invoke_edit(cap, FALSE, cap->arg ? 'V' : 'R', FALSE);
5204 	}
5205     }
5206 }
5207 
5208 /*
5209  * "gr".
5210  */
5211     static void
5212 nv_vreplace(cmdarg_T *cap)
5213 {
5214     if (VIsual_active)
5215     {
5216 	cap->cmdchar = 'r';
5217 	cap->nchar = cap->extra_char;
5218 	nv_replace(cap);	// Do same as "r" in Visual mode for now
5219     }
5220     else if (!checkclearopq(cap->oap))
5221     {
5222 	if (!curbuf->b_p_ma)
5223 	    emsg(_(e_modifiable));
5224 	else
5225 	{
5226 	    if (cap->extra_char == Ctrl_V)	// get another character
5227 		cap->extra_char = get_literal(FALSE);
5228 	    stuffcharReadbuff(cap->extra_char);
5229 	    stuffcharReadbuff(ESC);
5230 	    if (virtual_active())
5231 		coladvance(getviscol());
5232 	    invoke_edit(cap, TRUE, 'v', FALSE);
5233 	}
5234     }
5235 }
5236 
5237 /*
5238  * Swap case for "~" command, when it does not work like an operator.
5239  */
5240     static void
5241 n_swapchar(cmdarg_T *cap)
5242 {
5243     long	n;
5244     pos_T	startpos;
5245     int		did_change = 0;
5246 #ifdef FEAT_NETBEANS_INTG
5247     pos_T	pos;
5248     char_u	*ptr;
5249     int		count;
5250 #endif
5251 
5252     if (checkclearopq(cap->oap))
5253 	return;
5254 
5255     if (LINEEMPTY(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL)
5256     {
5257 	clearopbeep(cap->oap);
5258 	return;
5259     }
5260 
5261     prep_redo_cmd(cap);
5262 
5263     if (u_save_cursor() == FAIL)
5264 	return;
5265 
5266     startpos = curwin->w_cursor;
5267 #ifdef FEAT_NETBEANS_INTG
5268     pos = startpos;
5269 #endif
5270     for (n = cap->count1; n > 0; --n)
5271     {
5272 	did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor);
5273 	inc_cursor();
5274 	if (gchar_cursor() == NUL)
5275 	{
5276 	    if (vim_strchr(p_ww, '~') != NULL
5277 		    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
5278 	    {
5279 #ifdef FEAT_NETBEANS_INTG
5280 		if (netbeans_active())
5281 		{
5282 		    if (did_change)
5283 		    {
5284 			ptr = ml_get(pos.lnum);
5285 			count = (int)STRLEN(ptr) - pos.col;
5286 			netbeans_removed(curbuf, pos.lnum, pos.col,
5287 								 (long)count);
5288 			netbeans_inserted(curbuf, pos.lnum, pos.col,
5289 							&ptr[pos.col], count);
5290 		    }
5291 		    pos.col = 0;
5292 		    pos.lnum++;
5293 		}
5294 #endif
5295 		++curwin->w_cursor.lnum;
5296 		curwin->w_cursor.col = 0;
5297 		if (n > 1)
5298 		{
5299 		    if (u_savesub(curwin->w_cursor.lnum) == FAIL)
5300 			break;
5301 		    u_clearline();
5302 		}
5303 	    }
5304 	    else
5305 		break;
5306 	}
5307     }
5308 #ifdef FEAT_NETBEANS_INTG
5309     if (did_change && netbeans_active())
5310     {
5311 	ptr = ml_get(pos.lnum);
5312 	count = curwin->w_cursor.col - pos.col;
5313 	netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
5314 	netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count);
5315     }
5316 #endif
5317 
5318 
5319     check_cursor();
5320     curwin->w_set_curswant = TRUE;
5321     if (did_change)
5322     {
5323 	changed_lines(startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1,
5324 									  0L);
5325 	curbuf->b_op_start = startpos;
5326 	curbuf->b_op_end = curwin->w_cursor;
5327 	if (curbuf->b_op_end.col > 0)
5328 	    --curbuf->b_op_end.col;
5329     }
5330 }
5331 
5332 /*
5333  * Move cursor to mark.
5334  */
5335     static void
5336 nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos)
5337 {
5338     if (check_mark(pos) == FAIL)
5339 	clearop(cap->oap);
5340     else
5341     {
5342 	if (cap->cmdchar == '\''
5343 		|| cap->cmdchar == '`'
5344 		|| cap->cmdchar == '['
5345 		|| cap->cmdchar == ']')
5346 	    setpcmark();
5347 	curwin->w_cursor = *pos;
5348 	if (flag)
5349 	    beginline(BL_WHITE | BL_FIX);
5350 	else
5351 	    check_cursor();
5352     }
5353     cap->oap->motion_type = flag ? MLINE : MCHAR;
5354     if (cap->cmdchar == '`')
5355 	cap->oap->use_reg_one = TRUE;
5356     cap->oap->inclusive = FALSE;		// ignored if not MCHAR
5357     curwin->w_set_curswant = TRUE;
5358 }
5359 
5360 /*
5361  * Handle commands that are operators in Visual mode.
5362  */
5363     static void
5364 v_visop(cmdarg_T *cap)
5365 {
5366     static char_u trans[] = "YyDdCcxdXdAAIIrr";
5367 
5368     // Uppercase means linewise, except in block mode, then "D" deletes till
5369     // the end of the line, and "C" replaces till EOL
5370     if (isupper(cap->cmdchar))
5371     {
5372 	if (VIsual_mode != Ctrl_V)
5373 	{
5374 	    VIsual_mode_orig = VIsual_mode;
5375 	    VIsual_mode = 'V';
5376 	}
5377 	else if (cap->cmdchar == 'C' || cap->cmdchar == 'D')
5378 	    curwin->w_curswant = MAXCOL;
5379     }
5380     cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1);
5381     nv_operator(cap);
5382 }
5383 
5384 /*
5385  * "s" and "S" commands.
5386  */
5387     static void
5388 nv_subst(cmdarg_T *cap)
5389 {
5390 #ifdef FEAT_TERMINAL
5391     // When showing output of term_dumpdiff() swap the top and bottom.
5392     if (term_swap_diff() == OK)
5393 	return;
5394 #endif
5395 #ifdef FEAT_JOB_CHANNEL
5396     if (bt_prompt(curbuf) && !prompt_curpos_editable())
5397     {
5398 	clearopbeep(cap->oap);
5399 	return;
5400     }
5401 #endif
5402     if (VIsual_active)	// "vs" and "vS" are the same as "vc"
5403     {
5404 	if (cap->cmdchar == 'S')
5405 	{
5406 	    VIsual_mode_orig = VIsual_mode;
5407 	    VIsual_mode = 'V';
5408 	}
5409 	cap->cmdchar = 'c';
5410 	nv_operator(cap);
5411     }
5412     else
5413 	nv_optrans(cap);
5414 }
5415 
5416 /*
5417  * Abbreviated commands.
5418  */
5419     static void
5420 nv_abbrev(cmdarg_T *cap)
5421 {
5422     if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL)
5423 	cap->cmdchar = 'x';		// DEL key behaves like 'x'
5424 
5425     // in Visual mode these commands are operators
5426     if (VIsual_active)
5427 	v_visop(cap);
5428     else
5429 	nv_optrans(cap);
5430 }
5431 
5432 /*
5433  * Translate a command into another command.
5434  */
5435     static void
5436 nv_optrans(cmdarg_T *cap)
5437 {
5438     static char_u *(ar[8]) = {(char_u *)"dl", (char_u *)"dh",
5439 			      (char_u *)"d$", (char_u *)"c$",
5440 			      (char_u *)"cl", (char_u *)"cc",
5441 			      (char_u *)"yy", (char_u *)":s\r"};
5442     static char_u *str = (char_u *)"xXDCsSY&";
5443 
5444     if (!checkclearopq(cap->oap))
5445     {
5446 	// In Vi "2D" doesn't delete the next line.  Can't translate it
5447 	// either, because "2." should also not use the count.
5448 	if (cap->cmdchar == 'D' && vim_strchr(p_cpo, CPO_HASH) != NULL)
5449 	{
5450 	    cap->oap->start = curwin->w_cursor;
5451 	    cap->oap->op_type = OP_DELETE;
5452 #ifdef FEAT_EVAL
5453 	    set_op_var(OP_DELETE);
5454 #endif
5455 	    cap->count1 = 1;
5456 	    nv_dollar(cap);
5457 	    finish_op = TRUE;
5458 	    ResetRedobuff();
5459 	    AppendCharToRedobuff('D');
5460 	}
5461 	else
5462 	{
5463 	    if (cap->count0)
5464 		stuffnumReadbuff(cap->count0);
5465 	    stuffReadbuff(ar[(int)(vim_strchr(str, cap->cmdchar) - str)]);
5466 	}
5467     }
5468     cap->opcount = 0;
5469 }
5470 
5471 /*
5472  * "'" and "`" commands.  Also for "g'" and "g`".
5473  * cap->arg is TRUE for "'" and "g'".
5474  */
5475     static void
5476 nv_gomark(cmdarg_T *cap)
5477 {
5478     pos_T	*pos;
5479     int		c;
5480 #ifdef FEAT_FOLDING
5481     pos_T	old_cursor = curwin->w_cursor;
5482     int		old_KeyTyped = KeyTyped;    // getting file may reset it
5483 #endif
5484 
5485     if (cap->cmdchar == 'g')
5486 	c = cap->extra_char;
5487     else
5488 	c = cap->nchar;
5489     pos = getmark(c, (cap->oap->op_type == OP_NOP));
5490     if (pos == (pos_T *)-1)	    // jumped to other file
5491     {
5492 	if (cap->arg)
5493 	{
5494 	    check_cursor_lnum();
5495 	    beginline(BL_WHITE | BL_FIX);
5496 	}
5497 	else
5498 	    check_cursor();
5499     }
5500     else
5501 	nv_cursormark(cap, cap->arg, pos);
5502 
5503     // May need to clear the coladd that a mark includes.
5504     if (!virtual_active())
5505 	curwin->w_cursor.coladd = 0;
5506     check_cursor_col();
5507 #ifdef FEAT_FOLDING
5508     if (cap->oap->op_type == OP_NOP
5509 	    && pos != NULL
5510 	    && (pos == (pos_T *)-1 || !EQUAL_POS(old_cursor, *pos))
5511 	    && (fdo_flags & FDO_MARK)
5512 	    && old_KeyTyped)
5513 	foldOpenCursor();
5514 #endif
5515 }
5516 
5517 /*
5518  * Handle CTRL-O, CTRL-I, "g;", "g," and "CTRL-Tab" commands.
5519  */
5520     static void
5521 nv_pcmark(cmdarg_T *cap)
5522 {
5523 #ifdef FEAT_JUMPLIST
5524     pos_T	*pos;
5525 # ifdef FEAT_FOLDING
5526     linenr_T	lnum = curwin->w_cursor.lnum;
5527     int		old_KeyTyped = KeyTyped;    // getting file may reset it
5528 # endif
5529 
5530     if (!checkclearopq(cap->oap))
5531     {
5532 	if (cap->cmdchar == TAB && mod_mask == MOD_MASK_CTRL)
5533 	{
5534 	    if (goto_tabpage_lastused() == FAIL)
5535 		clearopbeep(cap->oap);
5536 	    return;
5537 	}
5538 	if (cap->cmdchar == 'g')
5539 	    pos = movechangelist((int)cap->count1);
5540 	else
5541 	    pos = movemark((int)cap->count1);
5542 	if (pos == (pos_T *)-1)		// jump to other file
5543 	{
5544 	    curwin->w_set_curswant = TRUE;
5545 	    check_cursor();
5546 	}
5547 	else if (pos != NULL)		    // can jump
5548 	    nv_cursormark(cap, FALSE, pos);
5549 	else if (cap->cmdchar == 'g')
5550 	{
5551 	    if (curbuf->b_changelistlen == 0)
5552 		emsg(_("E664: changelist is empty"));
5553 	    else if (cap->count1 < 0)
5554 		emsg(_("E662: At start of changelist"));
5555 	    else
5556 		emsg(_("E663: At end of changelist"));
5557 	}
5558 	else
5559 	    clearopbeep(cap->oap);
5560 # ifdef FEAT_FOLDING
5561 	if (cap->oap->op_type == OP_NOP
5562 		&& (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum)
5563 		&& (fdo_flags & FDO_MARK)
5564 		&& old_KeyTyped)
5565 	    foldOpenCursor();
5566 # endif
5567     }
5568 #else
5569     clearopbeep(cap->oap);
5570 #endif
5571 }
5572 
5573 /*
5574  * Handle '"' command.
5575  */
5576     static void
5577 nv_regname(cmdarg_T *cap)
5578 {
5579     if (checkclearop(cap->oap))
5580 	return;
5581 #ifdef FEAT_EVAL
5582     if (cap->nchar == '=')
5583 	cap->nchar = get_expr_register();
5584 #endif
5585     if (cap->nchar != NUL && valid_yank_reg(cap->nchar, FALSE))
5586     {
5587 	cap->oap->regname = cap->nchar;
5588 	cap->opcount = cap->count0;	// remember count before '"'
5589 #ifdef FEAT_EVAL
5590 	set_reg_var(cap->oap->regname);
5591 #endif
5592     }
5593     else
5594 	clearopbeep(cap->oap);
5595 }
5596 
5597 /*
5598  * Handle "v", "V" and "CTRL-V" commands.
5599  * Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg
5600  * is TRUE.
5601  * Handle CTRL-Q just like CTRL-V.
5602  */
5603     static void
5604 nv_visual(cmdarg_T *cap)
5605 {
5606     if (cap->cmdchar == Ctrl_Q)
5607 	cap->cmdchar = Ctrl_V;
5608 
5609     // 'v', 'V' and CTRL-V can be used while an operator is pending to make it
5610     // characterwise, linewise, or blockwise.
5611     if (cap->oap->op_type != OP_NOP)
5612     {
5613 	motion_force = cap->oap->motion_force = cap->cmdchar;
5614 	finish_op = FALSE;	// operator doesn't finish now but later
5615 	return;
5616     }
5617 
5618     VIsual_select = cap->arg;
5619     if (VIsual_active)	    // change Visual mode
5620     {
5621 	if (VIsual_mode == cap->cmdchar)    // stop visual mode
5622 	    end_visual_mode();
5623 	else				    // toggle char/block mode
5624 	{				    //	   or char/line mode
5625 	    VIsual_mode = cap->cmdchar;
5626 	    showmode();
5627 	}
5628 	redraw_curbuf_later(INVERTED);	    // update the inversion
5629     }
5630     else		    // start Visual mode
5631     {
5632 	check_visual_highlight();
5633 	if (cap->count0 > 0 && resel_VIsual_mode != NUL)
5634 	{
5635 	    // use previously selected part
5636 	    VIsual = curwin->w_cursor;
5637 
5638 	    VIsual_active = TRUE;
5639 	    VIsual_reselect = TRUE;
5640 	    if (!cap->arg)
5641 		// start Select mode when 'selectmode' contains "cmd"
5642 		may_start_select('c');
5643 	    setmouse();
5644 	    if (p_smd && msg_silent == 0)
5645 		redraw_cmdline = TRUE;	    // show visual mode later
5646 	    /*
5647 	     * For V and ^V, we multiply the number of lines even if there
5648 	     * was only one -- webb
5649 	     */
5650 	    if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1)
5651 	    {
5652 		curwin->w_cursor.lnum +=
5653 				    resel_VIsual_line_count * cap->count0 - 1;
5654 		if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
5655 		    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5656 	    }
5657 	    VIsual_mode = resel_VIsual_mode;
5658 	    if (VIsual_mode == 'v')
5659 	    {
5660 		if (resel_VIsual_line_count <= 1)
5661 		{
5662 		    validate_virtcol();
5663 		    curwin->w_curswant = curwin->w_virtcol
5664 					+ resel_VIsual_vcol * cap->count0 - 1;
5665 		}
5666 		else
5667 		    curwin->w_curswant = resel_VIsual_vcol;
5668 		coladvance(curwin->w_curswant);
5669 	    }
5670 	    if (resel_VIsual_vcol == MAXCOL)
5671 	    {
5672 		curwin->w_curswant = MAXCOL;
5673 		coladvance((colnr_T)MAXCOL);
5674 	    }
5675 	    else if (VIsual_mode == Ctrl_V)
5676 	    {
5677 		validate_virtcol();
5678 		curwin->w_curswant = curwin->w_virtcol
5679 					+ resel_VIsual_vcol * cap->count0 - 1;
5680 		coladvance(curwin->w_curswant);
5681 	    }
5682 	    else
5683 		curwin->w_set_curswant = TRUE;
5684 	    redraw_curbuf_later(INVERTED);	// show the inversion
5685 	}
5686 	else
5687 	{
5688 	    if (!cap->arg)
5689 		// start Select mode when 'selectmode' contains "cmd"
5690 		may_start_select('c');
5691 	    n_start_visual_mode(cap->cmdchar);
5692 	    if (VIsual_mode != 'V' && *p_sel == 'e')
5693 		++cap->count1;  // include one more char
5694 	    if (cap->count0 > 0 && --cap->count1 > 0)
5695 	    {
5696 		// With a count select that many characters or lines.
5697 		if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V)
5698 		    nv_right(cap);
5699 		else if (VIsual_mode == 'V')
5700 		    nv_down(cap);
5701 	    }
5702 	}
5703     }
5704 }
5705 
5706 /*
5707  * Start selection for Shift-movement keys.
5708  */
5709     void
5710 start_selection(void)
5711 {
5712     // if 'selectmode' contains "key", start Select mode
5713     may_start_select('k');
5714     n_start_visual_mode('v');
5715 }
5716 
5717 /*
5718  * Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu.
5719  */
5720     void
5721 may_start_select(int c)
5722 {
5723     VIsual_select = (stuff_empty() && typebuf_typed()
5724 		    && (vim_strchr(p_slm, c) != NULL));
5725 }
5726 
5727 /*
5728  * Start Visual mode "c".
5729  * Should set VIsual_select before calling this.
5730  */
5731     static void
5732 n_start_visual_mode(int c)
5733 {
5734 #ifdef FEAT_CONCEAL
5735     // Check for redraw before changing the state.
5736     conceal_check_cursor_line();
5737 #endif
5738 
5739     VIsual_mode = c;
5740     VIsual_active = TRUE;
5741     VIsual_reselect = TRUE;
5742 
5743     // Corner case: the 0 position in a tab may change when going into
5744     // virtualedit.  Recalculate curwin->w_cursor to avoid bad highlighting.
5745     if (c == Ctrl_V && (ve_flags & VE_BLOCK) && gchar_cursor() == TAB)
5746     {
5747 	validate_virtcol();
5748 	coladvance(curwin->w_virtcol);
5749     }
5750     VIsual = curwin->w_cursor;
5751 
5752 #ifdef FEAT_FOLDING
5753     foldAdjustVisual();
5754 #endif
5755 
5756     setmouse();
5757 #ifdef FEAT_CONCEAL
5758     // Check for redraw after changing the state.
5759     conceal_check_cursor_line();
5760 #endif
5761 
5762     if (p_smd && msg_silent == 0)
5763 	redraw_cmdline = TRUE;	// show visual mode later
5764 #ifdef FEAT_CLIPBOARD
5765     // Make sure the clipboard gets updated.  Needed because start and
5766     // end may still be the same, and the selection needs to be owned
5767     clip_star.vmode = NUL;
5768 #endif
5769 
5770     // Only need to redraw this line, unless still need to redraw an old
5771     // Visual area (when 'lazyredraw' is set).
5772     if (curwin->w_redr_type < INVERTED)
5773     {
5774 	curwin->w_old_cursor_lnum = curwin->w_cursor.lnum;
5775 	curwin->w_old_visual_lnum = curwin->w_cursor.lnum;
5776     }
5777 }
5778 
5779 
5780 /*
5781  * CTRL-W: Window commands
5782  */
5783     static void
5784 nv_window(cmdarg_T *cap)
5785 {
5786     if (cap->nchar == ':')
5787     {
5788 	// "CTRL-W :" is the same as typing ":"; useful in a terminal window
5789 	cap->cmdchar = ':';
5790 	cap->nchar = NUL;
5791 	nv_colon(cap);
5792     }
5793     else if (!checkclearop(cap->oap))
5794 	do_window(cap->nchar, cap->count0, NUL); // everything is in window.c
5795 }
5796 
5797 /*
5798  * CTRL-Z: Suspend
5799  */
5800     static void
5801 nv_suspend(cmdarg_T *cap)
5802 {
5803     clearop(cap->oap);
5804     if (VIsual_active)
5805 	end_visual_mode();		// stop Visual mode
5806     do_cmdline_cmd((char_u *)"stop");
5807 }
5808 
5809 /*
5810  * Commands starting with "g".
5811  */
5812     static void
5813 nv_g_cmd(cmdarg_T *cap)
5814 {
5815     oparg_T	*oap = cap->oap;
5816     pos_T	tpos;
5817     int		i;
5818     int		flag = FALSE;
5819 
5820     switch (cap->nchar)
5821     {
5822     case Ctrl_A:
5823     case Ctrl_X:
5824 #ifdef MEM_PROFILE
5825     /*
5826      * "g^A": dump log of used memory.
5827      */
5828 	if (!VIsual_active && cap->nchar == Ctrl_A)
5829 	    vim_mem_profile_dump();
5830 	else
5831 #endif
5832     /*
5833      * "g^A/g^X": sequentially increment visually selected region
5834      */
5835 	     if (VIsual_active)
5836 	{
5837 	    cap->arg = TRUE;
5838 	    cap->cmdchar = cap->nchar;
5839 	    cap->nchar = NUL;
5840 	    nv_addsub(cap);
5841 	}
5842 	else
5843 	    clearopbeep(oap);
5844 	break;
5845 
5846     /*
5847      * "gR": Enter virtual replace mode.
5848      */
5849     case 'R':
5850 	cap->arg = TRUE;
5851 	nv_Replace(cap);
5852 	break;
5853 
5854     case 'r':
5855 	nv_vreplace(cap);
5856 	break;
5857 
5858     case '&':
5859 	do_cmdline_cmd((char_u *)"%s//~/&");
5860 	break;
5861 
5862     /*
5863      * "gv": Reselect the previous Visual area.  If Visual already active,
5864      *	     exchange previous and current Visual area.
5865      */
5866     case 'v':
5867 	if (checkclearop(oap))
5868 	    break;
5869 
5870 	if (	   curbuf->b_visual.vi_start.lnum == 0
5871 		|| curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count
5872 		|| curbuf->b_visual.vi_end.lnum == 0)
5873 	    beep_flush();
5874 	else
5875 	{
5876 	    // set w_cursor to the start of the Visual area, tpos to the end
5877 	    if (VIsual_active)
5878 	    {
5879 		i = VIsual_mode;
5880 		VIsual_mode = curbuf->b_visual.vi_mode;
5881 		curbuf->b_visual.vi_mode = i;
5882 # ifdef FEAT_EVAL
5883 		curbuf->b_visual_mode_eval = i;
5884 # endif
5885 		i = curwin->w_curswant;
5886 		curwin->w_curswant = curbuf->b_visual.vi_curswant;
5887 		curbuf->b_visual.vi_curswant = i;
5888 
5889 		tpos = curbuf->b_visual.vi_end;
5890 		curbuf->b_visual.vi_end = curwin->w_cursor;
5891 		curwin->w_cursor = curbuf->b_visual.vi_start;
5892 		curbuf->b_visual.vi_start = VIsual;
5893 	    }
5894 	    else
5895 	    {
5896 		VIsual_mode = curbuf->b_visual.vi_mode;
5897 		curwin->w_curswant = curbuf->b_visual.vi_curswant;
5898 		tpos = curbuf->b_visual.vi_end;
5899 		curwin->w_cursor = curbuf->b_visual.vi_start;
5900 	    }
5901 
5902 	    VIsual_active = TRUE;
5903 	    VIsual_reselect = TRUE;
5904 
5905 	    // Set Visual to the start and w_cursor to the end of the Visual
5906 	    // area.  Make sure they are on an existing character.
5907 	    check_cursor();
5908 	    VIsual = curwin->w_cursor;
5909 	    curwin->w_cursor = tpos;
5910 	    check_cursor();
5911 	    update_topline();
5912 	    /*
5913 	     * When called from normal "g" command: start Select mode when
5914 	     * 'selectmode' contains "cmd".  When called for K_SELECT, always
5915 	     * start Select mode.
5916 	     */
5917 	    if (cap->arg)
5918 		VIsual_select = TRUE;
5919 	    else
5920 		may_start_select('c');
5921 	    setmouse();
5922 #ifdef FEAT_CLIPBOARD
5923 	    // Make sure the clipboard gets updated.  Needed because start and
5924 	    // end are still the same, and the selection needs to be owned
5925 	    clip_star.vmode = NUL;
5926 #endif
5927 	    redraw_curbuf_later(INVERTED);
5928 	    showmode();
5929 	}
5930 	break;
5931     /*
5932      * "gV": Don't reselect the previous Visual area after a Select mode
5933      *	     mapping of menu.
5934      */
5935     case 'V':
5936 	VIsual_reselect = FALSE;
5937 	break;
5938 
5939     /*
5940      * "gh":  start Select mode.
5941      * "gH":  start Select line mode.
5942      * "g^H": start Select block mode.
5943      */
5944     case K_BS:
5945 	cap->nchar = Ctrl_H;
5946 	// FALLTHROUGH
5947     case 'h':
5948     case 'H':
5949     case Ctrl_H:
5950 # ifdef EBCDIC
5951 	// EBCDIC: 'v'-'h' != '^v'-'^h'
5952 	if (cap->nchar == Ctrl_H)
5953 	    cap->cmdchar = Ctrl_V;
5954 	else
5955 # endif
5956 	cap->cmdchar = cap->nchar + ('v' - 'h');
5957 	cap->arg = TRUE;
5958 	nv_visual(cap);
5959 	break;
5960 
5961     // "gn", "gN" visually select next/previous search match
5962     // "gn" selects next match
5963     // "gN" selects previous match
5964     case 'N':
5965     case 'n':
5966 	if (!current_search(cap->count1, cap->nchar == 'n'))
5967 	    clearopbeep(oap);
5968 	break;
5969 
5970     /*
5971      * "gj" and "gk" two new funny movement keys -- up and down
5972      * movement based on *screen* line rather than *file* line.
5973      */
5974     case 'j':
5975     case K_DOWN:
5976 	// with 'nowrap' it works just like the normal "j" command.
5977 	if (!curwin->w_p_wrap)
5978 	{
5979 	    oap->motion_type = MLINE;
5980 	    i = cursor_down(cap->count1, oap->op_type == OP_NOP);
5981 	}
5982 	else
5983 	    i = nv_screengo(oap, FORWARD, cap->count1);
5984 	if (i == FAIL)
5985 	    clearopbeep(oap);
5986 	break;
5987 
5988     case 'k':
5989     case K_UP:
5990 	// with 'nowrap' it works just like the normal "k" command.
5991 	if (!curwin->w_p_wrap)
5992 	{
5993 	    oap->motion_type = MLINE;
5994 	    i = cursor_up(cap->count1, oap->op_type == OP_NOP);
5995 	}
5996 	else
5997 	    i = nv_screengo(oap, BACKWARD, cap->count1);
5998 	if (i == FAIL)
5999 	    clearopbeep(oap);
6000 	break;
6001 
6002     /*
6003      * "gJ": join two lines without inserting a space.
6004      */
6005     case 'J':
6006 	nv_join(cap);
6007 	break;
6008 
6009     /*
6010      * "g0", "g^" and "g$": Like "0", "^" and "$" but for screen lines.
6011      * "gm": middle of "g0" and "g$".
6012      */
6013     case '^':
6014 	flag = TRUE;
6015 	// FALLTHROUGH
6016 
6017     case '0':
6018     case 'm':
6019     case K_HOME:
6020     case K_KHOME:
6021 	oap->motion_type = MCHAR;
6022 	oap->inclusive = FALSE;
6023 	if (curwin->w_p_wrap && curwin->w_width != 0)
6024 	{
6025 	    int		width1 = curwin->w_width - curwin_col_off();
6026 	    int		width2 = width1 + curwin_col_off2();
6027 
6028 	    validate_virtcol();
6029 	    i = 0;
6030 	    if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0)
6031 		i = (curwin->w_virtcol - width1) / width2 * width2 + width1;
6032 	}
6033 	else
6034 	    i = curwin->w_leftcol;
6035 	// Go to the middle of the screen line.  When 'number' or
6036 	// 'relativenumber' is on and lines are wrapping the middle can be more
6037 	// to the left.
6038 	if (cap->nchar == 'm')
6039 	    i += (curwin->w_width - curwin_col_off()
6040 		    + ((curwin->w_p_wrap && i > 0)
6041 			? curwin_col_off2() : 0)) / 2;
6042 	coladvance((colnr_T)i);
6043 	if (flag)
6044 	{
6045 	    do
6046 		i = gchar_cursor();
6047 	    while (VIM_ISWHITE(i) && oneright() == OK);
6048 	    curwin->w_valid &= ~VALID_WCOL;
6049 	}
6050 	curwin->w_set_curswant = TRUE;
6051 	break;
6052 
6053     case 'M':
6054 	{
6055 	    char_u  *ptr = ml_get_curline();
6056 
6057 	    oap->motion_type = MCHAR;
6058 	    oap->inclusive = FALSE;
6059 	    if (has_mbyte)
6060 		i = mb_string2cells(ptr, (int)STRLEN(ptr));
6061 	    else
6062 		i = (int)STRLEN(ptr);
6063 	    if (cap->count0 > 0 && cap->count0 <= 100)
6064 		coladvance((colnr_T)(i * cap->count0 / 100));
6065 	    else
6066 		coladvance((colnr_T)(i / 2));
6067 	    curwin->w_set_curswant = TRUE;
6068 	}
6069 	break;
6070 
6071     case '_':
6072 	// "g_": to the last non-blank character in the line or <count> lines
6073 	// downward.
6074 	cap->oap->motion_type = MCHAR;
6075 	cap->oap->inclusive = TRUE;
6076 	curwin->w_curswant = MAXCOL;
6077 	if (cursor_down((long)(cap->count1 - 1),
6078 					 cap->oap->op_type == OP_NOP) == FAIL)
6079 	    clearopbeep(cap->oap);
6080 	else
6081 	{
6082 	    char_u  *ptr = ml_get_curline();
6083 
6084 	    // In Visual mode we may end up after the line.
6085 	    if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL)
6086 		--curwin->w_cursor.col;
6087 
6088 	    // Decrease the cursor column until it's on a non-blank.
6089 	    while (curwin->w_cursor.col > 0
6090 				    && VIM_ISWHITE(ptr[curwin->w_cursor.col]))
6091 		--curwin->w_cursor.col;
6092 	    curwin->w_set_curswant = TRUE;
6093 	    adjust_for_sel(cap);
6094 	}
6095 	break;
6096 
6097     case '$':
6098     case K_END:
6099     case K_KEND:
6100 	{
6101 	    int col_off = curwin_col_off();
6102 
6103 	    oap->motion_type = MCHAR;
6104 	    oap->inclusive = TRUE;
6105 	    if (curwin->w_p_wrap && curwin->w_width != 0)
6106 	    {
6107 		curwin->w_curswant = MAXCOL;    // so we stay at the end
6108 		if (cap->count1 == 1)
6109 		{
6110 		    int		width1 = curwin->w_width - col_off;
6111 		    int		width2 = width1 + curwin_col_off2();
6112 
6113 		    validate_virtcol();
6114 		    i = width1 - 1;
6115 		    if (curwin->w_virtcol >= (colnr_T)width1)
6116 			i += ((curwin->w_virtcol - width1) / width2 + 1)
6117 								     * width2;
6118 		    coladvance((colnr_T)i);
6119 
6120 		    // Make sure we stick in this column.
6121 		    validate_virtcol();
6122 		    curwin->w_curswant = curwin->w_virtcol;
6123 		    curwin->w_set_curswant = FALSE;
6124 		    if (curwin->w_cursor.col > 0 && curwin->w_p_wrap)
6125 		    {
6126 			/*
6127 			 * Check for landing on a character that got split at
6128 			 * the end of the line.  We do not want to advance to
6129 			 * the next screen line.
6130 			 */
6131 			if (curwin->w_virtcol > (colnr_T)i)
6132 			    --curwin->w_cursor.col;
6133 		    }
6134 		}
6135 		else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == FAIL)
6136 		    clearopbeep(oap);
6137 	    }
6138 	    else
6139 	    {
6140 		if (cap->count1 > 1)
6141 		    // if it fails, let the cursor still move to the last char
6142 		    (void)cursor_down(cap->count1 - 1, FALSE);
6143 
6144 		i = curwin->w_leftcol + curwin->w_width - col_off - 1;
6145 		coladvance((colnr_T)i);
6146 
6147 		// if the character doesn't fit move one back
6148 		if (curwin->w_cursor.col > 0
6149 				       && (*mb_ptr2cells)(ml_get_cursor()) > 1)
6150 		{
6151 		    colnr_T vcol;
6152 
6153 		    getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &vcol);
6154 		    if (vcol >= curwin->w_leftcol + curwin->w_width - col_off)
6155 			--curwin->w_cursor.col;
6156 		}
6157 
6158 		// Make sure we stick in this column.
6159 		validate_virtcol();
6160 		curwin->w_curswant = curwin->w_virtcol;
6161 		curwin->w_set_curswant = FALSE;
6162 	    }
6163 	}
6164 	break;
6165 
6166     /*
6167      * "g*" and "g#", like "*" and "#" but without using "\<" and "\>"
6168      */
6169     case '*':
6170     case '#':
6171 #if POUND != '#'
6172     case POUND:		// pound sign (sometimes equal to '#')
6173 #endif
6174     case Ctrl_RSB:		// :tag or :tselect for current identifier
6175     case ']':			// :tselect for current identifier
6176 	nv_ident(cap);
6177 	break;
6178 
6179     /*
6180      * ge and gE: go back to end of word
6181      */
6182     case 'e':
6183     case 'E':
6184 	oap->motion_type = MCHAR;
6185 	curwin->w_set_curswant = TRUE;
6186 	oap->inclusive = TRUE;
6187 	if (bckend_word(cap->count1, cap->nchar == 'E', FALSE) == FAIL)
6188 	    clearopbeep(oap);
6189 	break;
6190 
6191     /*
6192      * "g CTRL-G": display info about cursor position
6193      */
6194     case Ctrl_G:
6195 	cursor_pos_info(NULL);
6196 	break;
6197 
6198     /*
6199      * "gi": start Insert at the last position.
6200      */
6201     case 'i':
6202 	if (curbuf->b_last_insert.lnum != 0)
6203 	{
6204 	    curwin->w_cursor = curbuf->b_last_insert;
6205 	    check_cursor_lnum();
6206 	    i = (int)STRLEN(ml_get_curline());
6207 	    if (curwin->w_cursor.col > (colnr_T)i)
6208 	    {
6209 		if (virtual_active())
6210 		    curwin->w_cursor.coladd += curwin->w_cursor.col - i;
6211 		curwin->w_cursor.col = i;
6212 	    }
6213 	}
6214 	cap->cmdchar = 'i';
6215 	nv_edit(cap);
6216 	break;
6217 
6218     /*
6219      * "gI": Start insert in column 1.
6220      */
6221     case 'I':
6222 	beginline(0);
6223 	if (!checkclearopq(oap))
6224 	    invoke_edit(cap, FALSE, 'g', FALSE);
6225 	break;
6226 
6227 #ifdef FEAT_SEARCHPATH
6228     /*
6229      * "gf": goto file, edit file under cursor
6230      * "]f" and "[f": can also be used.
6231      */
6232     case 'f':
6233     case 'F':
6234 	nv_gotofile(cap);
6235 	break;
6236 #endif
6237 
6238 	// "g'm" and "g`m": jump to mark without setting pcmark
6239     case '\'':
6240 	cap->arg = TRUE;
6241 	// FALLTHROUGH
6242     case '`':
6243 	nv_gomark(cap);
6244 	break;
6245 
6246     /*
6247      * "gs": Goto sleep.
6248      */
6249     case 's':
6250 	do_sleep(cap->count1 * 1000L, FALSE);
6251 	break;
6252 
6253     /*
6254      * "ga": Display the ascii value of the character under the
6255      * cursor.	It is displayed in decimal, hex, and octal. -- webb
6256      */
6257     case 'a':
6258 	do_ascii(NULL);
6259 	break;
6260 
6261     /*
6262      * "g8": Display the bytes used for the UTF-8 character under the
6263      * cursor.	It is displayed in hex.
6264      * "8g8" finds illegal byte sequence.
6265      */
6266     case '8':
6267 	if (cap->count0 == 8)
6268 	    utf_find_illegal();
6269 	else
6270 	    show_utf8();
6271 	break;
6272 
6273     // "g<": show scrollback text
6274     case '<':
6275 	show_sb_text();
6276 	break;
6277 
6278     /*
6279      * "gg": Goto the first line in file.  With a count it goes to
6280      * that line number like for "G". -- webb
6281      */
6282     case 'g':
6283 	cap->arg = FALSE;
6284 	nv_goto(cap);
6285 	break;
6286 
6287     /*
6288      *	 Two-character operators:
6289      *	 "gq"	    Format text
6290      *	 "gw"	    Format text and keep cursor position
6291      *	 "g~"	    Toggle the case of the text.
6292      *	 "gu"	    Change text to lower case.
6293      *	 "gU"	    Change text to upper case.
6294      *   "g?"	    rot13 encoding
6295      *   "g@"	    call 'operatorfunc'
6296      */
6297     case 'q':
6298     case 'w':
6299 	oap->cursor_start = curwin->w_cursor;
6300 	// FALLTHROUGH
6301     case '~':
6302     case 'u':
6303     case 'U':
6304     case '?':
6305     case '@':
6306 	nv_operator(cap);
6307 	break;
6308 
6309     /*
6310      * "gd": Find first occurrence of pattern under the cursor in the
6311      *	 current function
6312      * "gD": idem, but in the current file.
6313      */
6314     case 'd':
6315     case 'D':
6316 	nv_gd(oap, cap->nchar, (int)cap->count0);
6317 	break;
6318 
6319     /*
6320      * g<*Mouse> : <C-*mouse>
6321      */
6322     case K_MIDDLEMOUSE:
6323     case K_MIDDLEDRAG:
6324     case K_MIDDLERELEASE:
6325     case K_LEFTMOUSE:
6326     case K_LEFTDRAG:
6327     case K_LEFTRELEASE:
6328     case K_MOUSEMOVE:
6329     case K_RIGHTMOUSE:
6330     case K_RIGHTDRAG:
6331     case K_RIGHTRELEASE:
6332     case K_X1MOUSE:
6333     case K_X1DRAG:
6334     case K_X1RELEASE:
6335     case K_X2MOUSE:
6336     case K_X2DRAG:
6337     case K_X2RELEASE:
6338 	mod_mask = MOD_MASK_CTRL;
6339 	(void)do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0);
6340 	break;
6341 
6342     case K_IGNORE:
6343 	break;
6344 
6345     /*
6346      * "gP" and "gp": same as "P" and "p" but leave cursor just after new text
6347      */
6348     case 'p':
6349     case 'P':
6350 	nv_put(cap);
6351 	break;
6352 
6353 #ifdef FEAT_BYTEOFF
6354     // "go": goto byte count from start of buffer
6355     case 'o':
6356 	goto_byte(cap->count0);
6357 	break;
6358 #endif
6359 
6360     // "gQ": improved Ex mode
6361     case 'Q':
6362 	if (text_locked())
6363 	{
6364 	    clearopbeep(cap->oap);
6365 	    text_locked_msg();
6366 	    break;
6367 	}
6368 
6369 	if (!checkclearopq(oap))
6370 	    do_exmode(TRUE);
6371 	break;
6372 
6373 #ifdef FEAT_JUMPLIST
6374     case ',':
6375 	nv_pcmark(cap);
6376 	break;
6377 
6378     case ';':
6379 	cap->count1 = -cap->count1;
6380 	nv_pcmark(cap);
6381 	break;
6382 #endif
6383 
6384     case 't':
6385 	if (!checkclearop(oap))
6386 	    goto_tabpage((int)cap->count0);
6387 	break;
6388     case 'T':
6389 	if (!checkclearop(oap))
6390 	    goto_tabpage(-(int)cap->count1);
6391 	break;
6392 
6393     case TAB:
6394 	if (!checkclearop(oap) && goto_tabpage_lastused() == FAIL)
6395 	    clearopbeep(oap);
6396 	break;
6397 
6398     case '+':
6399     case '-': // "g+" and "g-": undo or redo along the timeline
6400 	if (!checkclearopq(oap))
6401 	    undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1,
6402 							 FALSE, FALSE, FALSE);
6403 	break;
6404 
6405     default:
6406 	clearopbeep(oap);
6407 	break;
6408     }
6409 }
6410 
6411 /*
6412  * Handle "o" and "O" commands.
6413  */
6414     static void
6415 n_opencmd(cmdarg_T *cap)
6416 {
6417 #ifdef FEAT_CONCEAL
6418     linenr_T	oldline = curwin->w_cursor.lnum;
6419 #endif
6420 
6421     if (!checkclearopq(cap->oap))
6422     {
6423 #ifdef FEAT_FOLDING
6424 	if (cap->cmdchar == 'O')
6425 	    // Open above the first line of a folded sequence of lines
6426 	    (void)hasFolding(curwin->w_cursor.lnum,
6427 						&curwin->w_cursor.lnum, NULL);
6428 	else
6429 	    // Open below the last line of a folded sequence of lines
6430 	    (void)hasFolding(curwin->w_cursor.lnum,
6431 						NULL, &curwin->w_cursor.lnum);
6432 #endif
6433 	if (u_save((linenr_T)(curwin->w_cursor.lnum -
6434 					       (cap->cmdchar == 'O' ? 1 : 0)),
6435 		   (linenr_T)(curwin->w_cursor.lnum +
6436 					       (cap->cmdchar == 'o' ? 1 : 0))
6437 		       ) == OK
6438 		&& open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD,
6439 			 has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM : 0,
6440 								      0) == OK)
6441 	{
6442 #ifdef FEAT_CONCEAL
6443 	    if (curwin->w_p_cole > 0 && oldline != curwin->w_cursor.lnum)
6444 		redrawWinline(curwin, oldline);
6445 #endif
6446 #ifdef FEAT_SYN_HL
6447 	    if (curwin->w_p_cul)
6448 		// force redraw of cursorline
6449 		curwin->w_valid &= ~VALID_CROW;
6450 #endif
6451 	    // When '#' is in 'cpoptions' ignore the count.
6452 	    if (vim_strchr(p_cpo, CPO_HASH) != NULL)
6453 		cap->count1 = 1;
6454 	    invoke_edit(cap, FALSE, cap->cmdchar, TRUE);
6455 	}
6456     }
6457 }
6458 
6459 /*
6460  * "." command: redo last change.
6461  */
6462     static void
6463 nv_dot(cmdarg_T *cap)
6464 {
6465     if (!checkclearopq(cap->oap))
6466     {
6467 	/*
6468 	 * If "restart_edit" is TRUE, the last but one command is repeated
6469 	 * instead of the last command (inserting text). This is used for
6470 	 * CTRL-O <.> in insert mode.
6471 	 */
6472 	if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == FAIL)
6473 	    clearopbeep(cap->oap);
6474     }
6475 }
6476 
6477 /*
6478  * CTRL-R: undo undo
6479  */
6480     static void
6481 nv_redo(cmdarg_T *cap)
6482 {
6483     if (!checkclearopq(cap->oap))
6484     {
6485 	u_redo((int)cap->count1);
6486 	curwin->w_set_curswant = TRUE;
6487     }
6488 }
6489 
6490 /*
6491  * Handle "U" command.
6492  */
6493     static void
6494 nv_Undo(cmdarg_T *cap)
6495 {
6496     // In Visual mode and typing "gUU" triggers an operator
6497     if (cap->oap->op_type == OP_UPPER || VIsual_active)
6498     {
6499 	// translate "gUU" to "gUgU"
6500 	cap->cmdchar = 'g';
6501 	cap->nchar = 'U';
6502 	nv_operator(cap);
6503     }
6504     else if (!checkclearopq(cap->oap))
6505     {
6506 	u_undoline();
6507 	curwin->w_set_curswant = TRUE;
6508     }
6509 }
6510 
6511 /*
6512  * '~' command: If tilde is not an operator and Visual is off: swap case of a
6513  * single character.
6514  */
6515     static void
6516 nv_tilde(cmdarg_T *cap)
6517 {
6518     if (!p_to && !VIsual_active && cap->oap->op_type != OP_TILDE)
6519     {
6520 #ifdef FEAT_JOB_CHANNEL
6521 	if (bt_prompt(curbuf) && !prompt_curpos_editable())
6522 	{
6523 	    clearopbeep(cap->oap);
6524 	    return;
6525 	}
6526 #endif
6527 	n_swapchar(cap);
6528     }
6529     else
6530 	nv_operator(cap);
6531 }
6532 
6533 /*
6534  * Handle an operator command.
6535  * The actual work is done by do_pending_operator().
6536  */
6537     static void
6538 nv_operator(cmdarg_T *cap)
6539 {
6540     int	    op_type;
6541 
6542     op_type = get_op_type(cap->cmdchar, cap->nchar);
6543 #ifdef FEAT_JOB_CHANNEL
6544     if (bt_prompt(curbuf) && op_is_change(op_type) && !prompt_curpos_editable())
6545     {
6546 	clearopbeep(cap->oap);
6547 	return;
6548     }
6549 #endif
6550 
6551     if (op_type == cap->oap->op_type)	    // double operator works on lines
6552 	nv_lineop(cap);
6553     else if (!checkclearop(cap->oap))
6554     {
6555 	cap->oap->start = curwin->w_cursor;
6556 	cap->oap->op_type = op_type;
6557 #ifdef FEAT_EVAL
6558 	set_op_var(op_type);
6559 #endif
6560     }
6561 }
6562 
6563 #ifdef FEAT_EVAL
6564 /*
6565  * Set v:operator to the characters for "optype".
6566  */
6567     static void
6568 set_op_var(int optype)
6569 {
6570     char_u	opchars[3];
6571 
6572     if (optype == OP_NOP)
6573 	set_vim_var_string(VV_OP, NULL, 0);
6574     else
6575     {
6576 	opchars[0] = get_op_char(optype);
6577 	opchars[1] = get_extra_op_char(optype);
6578 	opchars[2] = NUL;
6579 	set_vim_var_string(VV_OP, opchars, -1);
6580     }
6581 }
6582 #endif
6583 
6584 /*
6585  * Handle linewise operator "dd", "yy", etc.
6586  *
6587  * "_" is is a strange motion command that helps make operators more logical.
6588  * It is actually implemented, but not documented in the real Vi.  This motion
6589  * command actually refers to "the current line".  Commands like "dd" and "yy"
6590  * are really an alternate form of "d_" and "y_".  It does accept a count, so
6591  * "d3_" works to delete 3 lines.
6592  */
6593     static void
6594 nv_lineop(cmdarg_T *cap)
6595 {
6596     cap->oap->motion_type = MLINE;
6597     if (cursor_down(cap->count1 - 1L, cap->oap->op_type == OP_NOP) == FAIL)
6598 	clearopbeep(cap->oap);
6599     else if (  (cap->oap->op_type == OP_DELETE // only with linewise motions
6600 		&& cap->oap->motion_force != 'v'
6601 		&& cap->oap->motion_force != Ctrl_V)
6602 	    || cap->oap->op_type == OP_LSHIFT
6603 	    || cap->oap->op_type == OP_RSHIFT)
6604 	beginline(BL_SOL | BL_FIX);
6605     else if (cap->oap->op_type != OP_YANK)	// 'Y' does not move cursor
6606 	beginline(BL_WHITE | BL_FIX);
6607 }
6608 
6609 /*
6610  * <Home> command.
6611  */
6612     static void
6613 nv_home(cmdarg_T *cap)
6614 {
6615     // CTRL-HOME is like "gg"
6616     if (mod_mask & MOD_MASK_CTRL)
6617 	nv_goto(cap);
6618     else
6619     {
6620 	cap->count0 = 1;
6621 	nv_pipe(cap);
6622     }
6623     ins_at_eol = FALSE;	    // Don't move cursor past eol (only necessary in a
6624 			    // one-character line).
6625 }
6626 
6627 /*
6628  * "|" command.
6629  */
6630     static void
6631 nv_pipe(cmdarg_T *cap)
6632 {
6633     cap->oap->motion_type = MCHAR;
6634     cap->oap->inclusive = FALSE;
6635     beginline(0);
6636     if (cap->count0 > 0)
6637     {
6638 	coladvance((colnr_T)(cap->count0 - 1));
6639 	curwin->w_curswant = (colnr_T)(cap->count0 - 1);
6640     }
6641     else
6642 	curwin->w_curswant = 0;
6643     // keep curswant at the column where we wanted to go, not where
6644     // we ended; differs if line is too short
6645     curwin->w_set_curswant = FALSE;
6646 }
6647 
6648 /*
6649  * Handle back-word command "b" and "B".
6650  * cap->arg is 1 for "B"
6651  */
6652     static void
6653 nv_bck_word(cmdarg_T *cap)
6654 {
6655     cap->oap->motion_type = MCHAR;
6656     cap->oap->inclusive = FALSE;
6657     curwin->w_set_curswant = TRUE;
6658     if (bck_word(cap->count1, cap->arg, FALSE) == FAIL)
6659 	clearopbeep(cap->oap);
6660 #ifdef FEAT_FOLDING
6661     else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6662 	foldOpenCursor();
6663 #endif
6664 }
6665 
6666 /*
6667  * Handle word motion commands "e", "E", "w" and "W".
6668  * cap->arg is TRUE for "E" and "W".
6669  */
6670     static void
6671 nv_wordcmd(cmdarg_T *cap)
6672 {
6673     int		n;
6674     int		word_end;
6675     int		flag = FALSE;
6676     pos_T	startpos = curwin->w_cursor;
6677 
6678     /*
6679      * Set inclusive for the "E" and "e" command.
6680      */
6681     if (cap->cmdchar == 'e' || cap->cmdchar == 'E')
6682 	word_end = TRUE;
6683     else
6684 	word_end = FALSE;
6685     cap->oap->inclusive = word_end;
6686 
6687     /*
6688      * "cw" and "cW" are a special case.
6689      */
6690     if (!word_end && cap->oap->op_type == OP_CHANGE)
6691     {
6692 	n = gchar_cursor();
6693 	if (n != NUL)			// not an empty line
6694 	{
6695 	    if (VIM_ISWHITE(n))
6696 	    {
6697 		/*
6698 		 * Reproduce a funny Vi behaviour: "cw" on a blank only
6699 		 * changes one character, not all blanks until the start of
6700 		 * the next word.  Only do this when the 'w' flag is included
6701 		 * in 'cpoptions'.
6702 		 */
6703 		if (cap->count1 == 1 && vim_strchr(p_cpo, CPO_CW) != NULL)
6704 		{
6705 		    cap->oap->inclusive = TRUE;
6706 		    cap->oap->motion_type = MCHAR;
6707 		    return;
6708 		}
6709 	    }
6710 	    else
6711 	    {
6712 		/*
6713 		 * This is a little strange. To match what the real Vi does,
6714 		 * we effectively map 'cw' to 'ce', and 'cW' to 'cE', provided
6715 		 * that we are not on a space or a TAB.  This seems impolite
6716 		 * at first, but it's really more what we mean when we say
6717 		 * 'cw'.
6718 		 * Another strangeness: When standing on the end of a word
6719 		 * "ce" will change until the end of the next word, but "cw"
6720 		 * will change only one character! This is done by setting
6721 		 * flag.
6722 		 */
6723 		cap->oap->inclusive = TRUE;
6724 		word_end = TRUE;
6725 		flag = TRUE;
6726 	    }
6727 	}
6728     }
6729 
6730     cap->oap->motion_type = MCHAR;
6731     curwin->w_set_curswant = TRUE;
6732     if (word_end)
6733 	n = end_word(cap->count1, cap->arg, flag, FALSE);
6734     else
6735 	n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP);
6736 
6737     // Don't leave the cursor on the NUL past the end of line. Unless we
6738     // didn't move it forward.
6739     if (LT_POS(startpos, curwin->w_cursor))
6740 	adjust_cursor(cap->oap);
6741 
6742     if (n == FAIL && cap->oap->op_type == OP_NOP)
6743 	clearopbeep(cap->oap);
6744     else
6745     {
6746 	adjust_for_sel(cap);
6747 #ifdef FEAT_FOLDING
6748 	if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6749 	    foldOpenCursor();
6750 #endif
6751     }
6752 }
6753 
6754 /*
6755  * Used after a movement command: If the cursor ends up on the NUL after the
6756  * end of the line, may move it back to the last character and make the motion
6757  * inclusive.
6758  */
6759     static void
6760 adjust_cursor(oparg_T *oap)
6761 {
6762     // The cursor cannot remain on the NUL when:
6763     // - the column is > 0
6764     // - not in Visual mode or 'selection' is "o"
6765     // - 'virtualedit' is not "all" and not "onemore".
6766     if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL
6767 		&& (!VIsual_active || *p_sel == 'o')
6768 		&& !virtual_active() && (ve_flags & VE_ONEMORE) == 0)
6769     {
6770 	--curwin->w_cursor.col;
6771 	// prevent cursor from moving on the trail byte
6772 	if (has_mbyte)
6773 	    mb_adjust_cursor();
6774 	oap->inclusive = TRUE;
6775     }
6776 }
6777 
6778 /*
6779  * "0" and "^" commands.
6780  * cap->arg is the argument for beginline().
6781  */
6782     static void
6783 nv_beginline(cmdarg_T *cap)
6784 {
6785     cap->oap->motion_type = MCHAR;
6786     cap->oap->inclusive = FALSE;
6787     beginline(cap->arg);
6788 #ifdef FEAT_FOLDING
6789     if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6790 	foldOpenCursor();
6791 #endif
6792     ins_at_eol = FALSE;	    // Don't move cursor past eol (only necessary in a
6793 			    // one-character line).
6794 }
6795 
6796 /*
6797  * In exclusive Visual mode, may include the last character.
6798  */
6799     static void
6800 adjust_for_sel(cmdarg_T *cap)
6801 {
6802     if (VIsual_active && cap->oap->inclusive && *p_sel == 'e'
6803 	    && gchar_cursor() != NUL && LT_POS(VIsual, curwin->w_cursor))
6804     {
6805 	if (has_mbyte)
6806 	    inc_cursor();
6807 	else
6808 	    ++curwin->w_cursor.col;
6809 	cap->oap->inclusive = FALSE;
6810     }
6811 }
6812 
6813 /*
6814  * Exclude last character at end of Visual area for 'selection' == "exclusive".
6815  * Should check VIsual_mode before calling this.
6816  * Returns TRUE when backed up to the previous line.
6817  */
6818     int
6819 unadjust_for_sel(void)
6820 {
6821     pos_T	*pp;
6822 
6823     if (*p_sel == 'e' && !EQUAL_POS(VIsual, curwin->w_cursor))
6824     {
6825 	if (LT_POS(VIsual, curwin->w_cursor))
6826 	    pp = &curwin->w_cursor;
6827 	else
6828 	    pp = &VIsual;
6829 	if (pp->coladd > 0)
6830 	    --pp->coladd;
6831 	else
6832 	if (pp->col > 0)
6833 	{
6834 	    --pp->col;
6835 	    mb_adjustpos(curbuf, pp);
6836 	}
6837 	else if (pp->lnum > 1)
6838 	{
6839 	    --pp->lnum;
6840 	    pp->col = (colnr_T)STRLEN(ml_get(pp->lnum));
6841 	    return TRUE;
6842 	}
6843     }
6844     return FALSE;
6845 }
6846 
6847 /*
6848  * SELECT key in Normal or Visual mode: end of Select mode mapping.
6849  */
6850     static void
6851 nv_select(cmdarg_T *cap)
6852 {
6853     if (VIsual_active)
6854 	VIsual_select = TRUE;
6855     else if (VIsual_reselect)
6856     {
6857 	cap->nchar = 'v';	    // fake "gv" command
6858 	cap->arg = TRUE;
6859 	nv_g_cmd(cap);
6860     }
6861 }
6862 
6863 
6864 /*
6865  * "G", "gg", CTRL-END, CTRL-HOME.
6866  * cap->arg is TRUE for "G".
6867  */
6868     static void
6869 nv_goto(cmdarg_T *cap)
6870 {
6871     linenr_T	lnum;
6872 
6873     if (cap->arg)
6874 	lnum = curbuf->b_ml.ml_line_count;
6875     else
6876 	lnum = 1L;
6877     cap->oap->motion_type = MLINE;
6878     setpcmark();
6879 
6880     // When a count is given, use it instead of the default lnum
6881     if (cap->count0 != 0)
6882 	lnum = cap->count0;
6883     if (lnum < 1L)
6884 	lnum = 1L;
6885     else if (lnum > curbuf->b_ml.ml_line_count)
6886 	lnum = curbuf->b_ml.ml_line_count;
6887     curwin->w_cursor.lnum = lnum;
6888     beginline(BL_SOL | BL_FIX);
6889 #ifdef FEAT_FOLDING
6890     if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP)
6891 	foldOpenCursor();
6892 #endif
6893 }
6894 
6895 /*
6896  * CTRL-\ in Normal mode.
6897  */
6898     static void
6899 nv_normal(cmdarg_T *cap)
6900 {
6901     if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G)
6902     {
6903 	clearop(cap->oap);
6904 	if (restart_edit != 0 && mode_displayed)
6905 	    clear_cmdline = TRUE;		// unshow mode later
6906 	restart_edit = 0;
6907 #ifdef FEAT_CMDWIN
6908 	if (cmdwin_type != 0)
6909 	    cmdwin_result = Ctrl_C;
6910 #endif
6911 	if (VIsual_active)
6912 	{
6913 	    end_visual_mode();		// stop Visual
6914 	    redraw_curbuf_later(INVERTED);
6915 	}
6916 	// CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set.
6917 	if (cap->nchar == Ctrl_G && p_im)
6918 	    restart_edit = 'a';
6919     }
6920     else
6921 	clearopbeep(cap->oap);
6922 }
6923 
6924 /*
6925  * ESC in Normal mode: beep, but don't flush buffers.
6926  * Don't even beep if we are canceling a command.
6927  */
6928     static void
6929 nv_esc(cmdarg_T *cap)
6930 {
6931     int		no_reason;
6932 
6933     no_reason = (cap->oap->op_type == OP_NOP
6934 		&& cap->opcount == 0
6935 		&& cap->count0 == 0
6936 		&& cap->oap->regname == 0
6937 		&& !p_im);
6938 
6939     if (cap->arg)		// TRUE for CTRL-C
6940     {
6941 	if (restart_edit == 0
6942 #ifdef FEAT_CMDWIN
6943 		&& cmdwin_type == 0
6944 #endif
6945 		&& !VIsual_active
6946 		&& no_reason)
6947 	{
6948 	    if (anyBufIsChanged())
6949 		msg(_("Type  :qa!  and press <Enter> to abandon all changes and exit Vim"));
6950 	    else
6951 		msg(_("Type  :qa  and press <Enter> to exit Vim"));
6952 	}
6953 
6954 	// Don't reset "restart_edit" when 'insertmode' is set, it won't be
6955 	// set again below when halfway a mapping.
6956 	if (!p_im)
6957 	    restart_edit = 0;
6958 #ifdef FEAT_CMDWIN
6959 	if (cmdwin_type != 0)
6960 	{
6961 	    cmdwin_result = K_IGNORE;
6962 	    got_int = FALSE;	// don't stop executing autocommands et al.
6963 	    return;
6964 	}
6965 #endif
6966     }
6967 #ifdef FEAT_CMDWIN
6968     else if (cmdwin_type != 0 && ex_normal_busy)
6969     {
6970 	// When :normal runs out of characters while in the command line window
6971 	// vgetorpeek() will return ESC.  Exit the cmdline window to break the
6972 	// loop.
6973 	cmdwin_result = K_IGNORE;
6974 	return;
6975     }
6976 #endif
6977 
6978     if (VIsual_active)
6979     {
6980 	end_visual_mode();	// stop Visual
6981 	check_cursor_col();	// make sure cursor is not beyond EOL
6982 	curwin->w_set_curswant = TRUE;
6983 	redraw_curbuf_later(INVERTED);
6984     }
6985     else if (no_reason)
6986 	vim_beep(BO_ESC);
6987     clearop(cap->oap);
6988 
6989     // A CTRL-C is often used at the start of a menu.  When 'insertmode' is
6990     // set return to Insert mode afterwards.
6991     if (restart_edit == 0 && goto_im() && ex_normal_busy == 0)
6992 	restart_edit = 'a';
6993 }
6994 
6995 /*
6996  * Move the cursor for the "A" command.
6997  */
6998     void
6999 set_cursor_for_append_to_line(void)
7000 {
7001     curwin->w_set_curswant = TRUE;
7002     if (ve_flags == VE_ALL)
7003     {
7004 	int save_State = State;
7005 
7006 	// Pretend Insert mode here to allow the cursor on the
7007 	// character past the end of the line
7008 	State = INSERT;
7009 	coladvance((colnr_T)MAXCOL);
7010 	State = save_State;
7011     }
7012     else
7013 	curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
7014 }
7015 
7016 /*
7017  * Handle "A", "a", "I", "i" and <Insert> commands.
7018  * Also handle K_PS, start bracketed paste.
7019  */
7020     static void
7021 nv_edit(cmdarg_T *cap)
7022 {
7023     // <Insert> is equal to "i"
7024     if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS)
7025 	cap->cmdchar = 'i';
7026 
7027     // in Visual mode "A" and "I" are an operator
7028     if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I'))
7029     {
7030 #ifdef FEAT_TERMINAL
7031 	if (term_in_normal_mode())
7032 	{
7033 	    end_visual_mode();
7034 	    clearop(cap->oap);
7035 	    term_enter_job_mode();
7036 	    return;
7037 	}
7038 #endif
7039 	v_visop(cap);
7040     }
7041 
7042     // in Visual mode and after an operator "a" and "i" are for text objects
7043     else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i')
7044 	    && (cap->oap->op_type != OP_NOP || VIsual_active))
7045     {
7046 #ifdef FEAT_TEXTOBJ
7047 	nv_object(cap);
7048 #else
7049 	clearopbeep(cap->oap);
7050 #endif
7051     }
7052 #ifdef FEAT_TERMINAL
7053     else if (term_in_normal_mode())
7054     {
7055 	clearop(cap->oap);
7056 	term_enter_job_mode();
7057 	return;
7058     }
7059 #endif
7060     else if (!curbuf->b_p_ma && !p_im)
7061     {
7062 	// Only give this error when 'insertmode' is off.
7063 	emsg(_(e_modifiable));
7064 	clearop(cap->oap);
7065 	if (cap->cmdchar == K_PS)
7066 	    // drop the pasted text
7067 	    bracketed_paste(PASTE_INSERT, TRUE, NULL);
7068     }
7069     else if (cap->cmdchar == K_PS && VIsual_active)
7070     {
7071 	pos_T old_pos = curwin->w_cursor;
7072 	pos_T old_visual = VIsual;
7073 
7074 	// In Visual mode the selected text is deleted.
7075 	if (VIsual_mode == 'V' || curwin->w_cursor.lnum != VIsual.lnum)
7076 	{
7077 	    shift_delete_registers();
7078 	    cap->oap->regname = '1';
7079 	}
7080 	else
7081 	    cap->oap->regname = '-';
7082 	cap->cmdchar = 'd';
7083 	cap->nchar = NUL;
7084 	nv_operator(cap);
7085 	do_pending_operator(cap, 0, FALSE);
7086 	cap->cmdchar = K_PS;
7087 
7088 	// When the last char in the line was deleted then append. Detect this
7089 	// by checking if the cursor moved to before the Visual area.
7090 	if (*ml_get_cursor() != NUL && LT_POS(curwin->w_cursor, old_pos)
7091 				       && LT_POS(curwin->w_cursor, old_visual))
7092 	    inc_cursor();
7093 
7094 	// Insert to replace the deleted text with the pasted text.
7095 	invoke_edit(cap, FALSE, cap->cmdchar, FALSE);
7096     }
7097     else if (!checkclearopq(cap->oap))
7098     {
7099 	switch (cap->cmdchar)
7100 	{
7101 	    case 'A':	// "A"ppend after the line
7102 		set_cursor_for_append_to_line();
7103 		break;
7104 
7105 	    case 'I':	// "I"nsert before the first non-blank
7106 		if (vim_strchr(p_cpo, CPO_INSEND) == NULL)
7107 		    beginline(BL_WHITE);
7108 		else
7109 		    beginline(BL_WHITE|BL_FIX);
7110 		break;
7111 
7112 	    case K_PS:
7113 		// Bracketed paste works like "a"ppend, unless the cursor is in
7114 		// the first column, then it inserts.
7115 		if (curwin->w_cursor.col == 0)
7116 		    break;
7117 		// FALLTHROUGH
7118 
7119 	    case 'a':	// "a"ppend is like "i"nsert on the next character.
7120 		// increment coladd when in virtual space, increment the
7121 		// column otherwise, also to append after an unprintable char
7122 		if (virtual_active()
7123 			&& (curwin->w_cursor.coladd > 0
7124 			    || *ml_get_cursor() == NUL
7125 			    || *ml_get_cursor() == TAB))
7126 		    curwin->w_cursor.coladd++;
7127 		else if (*ml_get_cursor() != NUL)
7128 		    inc_cursor();
7129 		break;
7130 	}
7131 
7132 	if (curwin->w_cursor.coladd && cap->cmdchar != 'A')
7133 	{
7134 	    int save_State = State;
7135 
7136 	    // Pretend Insert mode here to allow the cursor on the
7137 	    // character past the end of the line
7138 	    State = INSERT;
7139 	    coladvance(getviscol());
7140 	    State = save_State;
7141 	}
7142 
7143 	invoke_edit(cap, FALSE, cap->cmdchar, FALSE);
7144     }
7145     else if (cap->cmdchar == K_PS)
7146 	// drop the pasted text
7147 	bracketed_paste(PASTE_INSERT, TRUE, NULL);
7148 }
7149 
7150 /*
7151  * Invoke edit() and take care of "restart_edit" and the return value.
7152  */
7153     static void
7154 invoke_edit(
7155     cmdarg_T	*cap,
7156     int		repl,		// "r" or "gr" command
7157     int		cmd,
7158     int		startln)
7159 {
7160     int		restart_edit_save = 0;
7161 
7162     // Complicated: When the user types "a<C-O>a" we don't want to do Insert
7163     // mode recursively.  But when doing "a<C-O>." or "a<C-O>rx" we do allow
7164     // it.
7165     if (repl || !stuff_empty())
7166 	restart_edit_save = restart_edit;
7167     else
7168 	restart_edit_save = 0;
7169 
7170     // Always reset "restart_edit", this is not a restarted edit.
7171     restart_edit = 0;
7172 
7173     if (edit(cmd, startln, cap->count1))
7174 	cap->retval |= CA_COMMAND_BUSY;
7175 
7176     if (restart_edit == 0)
7177 	restart_edit = restart_edit_save;
7178 }
7179 
7180 #ifdef FEAT_TEXTOBJ
7181 /*
7182  * "a" or "i" while an operator is pending or in Visual mode: object motion.
7183  */
7184     static void
7185 nv_object(
7186     cmdarg_T	*cap)
7187 {
7188     int		flag;
7189     int		include;
7190     char_u	*mps_save;
7191 
7192     if (cap->cmdchar == 'i')
7193 	include = FALSE;    // "ix" = inner object: exclude white space
7194     else
7195 	include = TRUE;	    // "ax" = an object: include white space
7196 
7197     // Make sure (), [], {} and <> are in 'matchpairs'
7198     mps_save = curbuf->b_p_mps;
7199     curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>";
7200 
7201     switch (cap->nchar)
7202     {
7203 	case 'w': // "aw" = a word
7204 		flag = current_word(cap->oap, cap->count1, include, FALSE);
7205 		break;
7206 	case 'W': // "aW" = a WORD
7207 		flag = current_word(cap->oap, cap->count1, include, TRUE);
7208 		break;
7209 	case 'b': // "ab" = a braces block
7210 	case '(':
7211 	case ')':
7212 		flag = current_block(cap->oap, cap->count1, include, '(', ')');
7213 		break;
7214 	case 'B': // "aB" = a Brackets block
7215 	case '{':
7216 	case '}':
7217 		flag = current_block(cap->oap, cap->count1, include, '{', '}');
7218 		break;
7219 	case '[': // "a[" = a [] block
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 't': // "at" = a tag block (xml and html)
7228 		// Do not adjust oap->end in do_pending_operator()
7229 		// otherwise there are different results for 'dit'
7230 		// (note leading whitespace in last line):
7231 		// 1) <b>      2) <b>
7232 		//    foobar      foobar
7233 		//    </b>            </b>
7234 		cap->retval |= CA_NO_ADJ_OP_END;
7235 		flag = current_tagblock(cap->oap, cap->count1, include);
7236 		break;
7237 	case 'p': // "ap" = a paragraph
7238 		flag = current_par(cap->oap, cap->count1, include, 'p');
7239 		break;
7240 	case 's': // "as" = a sentence
7241 		flag = current_sent(cap->oap, cap->count1, include);
7242 		break;
7243 	case '"': // "a"" = a double quoted string
7244 	case '\'': // "a'" = a single quoted string
7245 	case '`': // "a`" = a backtick quoted string
7246 		flag = current_quote(cap->oap, cap->count1, include,
7247 								  cap->nchar);
7248 		break;
7249 #if 0	// TODO
7250 	case 'S': // "aS" = a section
7251 	case 'f': // "af" = a filename
7252 	case 'u': // "au" = a URL
7253 #endif
7254 	default:
7255 		flag = FAIL;
7256 		break;
7257     }
7258 
7259     curbuf->b_p_mps = mps_save;
7260     if (flag == FAIL)
7261 	clearopbeep(cap->oap);
7262     adjust_cursor_col();
7263     curwin->w_set_curswant = TRUE;
7264 }
7265 #endif
7266 
7267 /*
7268  * "q" command: Start/stop recording.
7269  * "q:", "q/", "q?": edit command-line in command-line window.
7270  */
7271     static void
7272 nv_record(cmdarg_T *cap)
7273 {
7274     if (cap->oap->op_type == OP_FORMAT)
7275     {
7276 	// "gqq" is the same as "gqgq": format line
7277 	cap->cmdchar = 'g';
7278 	cap->nchar = 'q';
7279 	nv_operator(cap);
7280     }
7281     else if (!checkclearop(cap->oap))
7282     {
7283 #ifdef FEAT_CMDWIN
7284 	if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?')
7285 	{
7286 	    stuffcharReadbuff(cap->nchar);
7287 	    stuffcharReadbuff(K_CMDWIN);
7288 	}
7289 	else
7290 #endif
7291 	    // (stop) recording into a named register, unless executing a
7292 	    // register
7293 	    if (reg_executing == 0 && do_record(cap->nchar) == FAIL)
7294 		clearopbeep(cap->oap);
7295     }
7296 }
7297 
7298 /*
7299  * Handle the "@r" command.
7300  */
7301     static void
7302 nv_at(cmdarg_T *cap)
7303 {
7304     if (checkclearop(cap->oap))
7305 	return;
7306 #ifdef FEAT_EVAL
7307     if (cap->nchar == '=')
7308     {
7309 	if (get_expr_register() == NUL)
7310 	    return;
7311     }
7312 #endif
7313     while (cap->count1-- && !got_int)
7314     {
7315 	if (do_execreg(cap->nchar, FALSE, FALSE, FALSE) == FAIL)
7316 	{
7317 	    clearopbeep(cap->oap);
7318 	    break;
7319 	}
7320 	line_breakcheck();
7321     }
7322 }
7323 
7324 /*
7325  * Handle the CTRL-U and CTRL-D commands.
7326  */
7327     static void
7328 nv_halfpage(cmdarg_T *cap)
7329 {
7330     if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1)
7331 	    || (cap->cmdchar == Ctrl_D
7332 		&& curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count))
7333 	clearopbeep(cap->oap);
7334     else if (!checkclearop(cap->oap))
7335 	halfpage(cap->cmdchar == Ctrl_D, cap->count0);
7336 }
7337 
7338 /*
7339  * Handle "J" or "gJ" command.
7340  */
7341     static void
7342 nv_join(cmdarg_T *cap)
7343 {
7344     if (VIsual_active)	// join the visual lines
7345 	nv_operator(cap);
7346     else if (!checkclearop(cap->oap))
7347     {
7348 	if (cap->count0 <= 1)
7349 	    cap->count0 = 2;	    // default for join is two lines!
7350 	if (curwin->w_cursor.lnum + cap->count0 - 1 >
7351 						   curbuf->b_ml.ml_line_count)
7352 	{
7353 	    // can't join when on the last line
7354 	    if (cap->count0 <= 2)
7355 	    {
7356 		clearopbeep(cap->oap);
7357 		return;
7358 	    }
7359 	    cap->count0 = curbuf->b_ml.ml_line_count
7360 						  - curwin->w_cursor.lnum + 1;
7361 	}
7362 
7363 	prep_redo(cap->oap->regname, cap->count0,
7364 				     NUL, cap->cmdchar, NUL, NUL, cap->nchar);
7365 	(void)do_join(cap->count0, cap->nchar == NUL, TRUE, TRUE, TRUE);
7366     }
7367 }
7368 
7369 /*
7370  * "P", "gP", "p" and "gp" commands.
7371  */
7372     static void
7373 nv_put(cmdarg_T *cap)
7374 {
7375     nv_put_opt(cap, FALSE);
7376 }
7377 
7378 /*
7379  * "P", "gP", "p" and "gp" commands.
7380  * "fix_indent" is TRUE for "[p", "[P", "]p" and "]P".
7381  */
7382     static void
7383 nv_put_opt(cmdarg_T *cap, int fix_indent)
7384 {
7385     int		regname = 0;
7386     void	*reg1 = NULL, *reg2 = NULL;
7387     int		empty = FALSE;
7388     int		was_visual = FALSE;
7389     int		dir;
7390     int		flags = 0;
7391 
7392     if (cap->oap->op_type != OP_NOP)
7393     {
7394 #ifdef FEAT_DIFF
7395 	// "dp" is ":diffput"
7396 	if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p')
7397 	{
7398 	    clearop(cap->oap);
7399 	    nv_diffgetput(TRUE, cap->opcount);
7400 	}
7401 	else
7402 #endif
7403 	clearopbeep(cap->oap);
7404     }
7405 #ifdef FEAT_JOB_CHANNEL
7406     else if (bt_prompt(curbuf) && !prompt_curpos_editable())
7407     {
7408 	clearopbeep(cap->oap);
7409     }
7410 #endif
7411     else
7412     {
7413 	if (fix_indent)
7414 	{
7415 	    dir = (cap->cmdchar == ']' && cap->nchar == 'p')
7416 							 ? FORWARD : BACKWARD;
7417 	    flags |= PUT_FIXINDENT;
7418 	}
7419 	else
7420 	    dir = (cap->cmdchar == 'P'
7421 				 || (cap->cmdchar == 'g' && cap->nchar == 'P'))
7422 							 ? BACKWARD : FORWARD;
7423 	prep_redo_cmd(cap);
7424 	if (cap->cmdchar == 'g')
7425 	    flags |= PUT_CURSEND;
7426 
7427 	if (VIsual_active)
7428 	{
7429 	    // Putting in Visual mode: The put text replaces the selected
7430 	    // text.  First delete the selected text, then put the new text.
7431 	    // Need to save and restore the registers that the delete
7432 	    // overwrites if the old contents is being put.
7433 	    was_visual = TRUE;
7434 	    regname = cap->oap->regname;
7435 #ifdef FEAT_CLIPBOARD
7436 	    adjust_clip_reg(&regname);
7437 #endif
7438 	   if (regname == 0 || regname == '"'
7439 				     || VIM_ISDIGIT(regname) || regname == '-'
7440 #ifdef FEAT_CLIPBOARD
7441 		    || (clip_unnamed && (regname == '*' || regname == '+'))
7442 #endif
7443 
7444 		    )
7445 	    {
7446 		// The delete is going to overwrite the register we want to
7447 		// put, save it first.
7448 		reg1 = get_register(regname, TRUE);
7449 	    }
7450 
7451 	    // Now delete the selected text. Avoid messages here.
7452 	    cap->cmdchar = 'd';
7453 	    cap->nchar = NUL;
7454 	    cap->oap->regname = NUL;
7455 	    ++msg_silent;
7456 	    nv_operator(cap);
7457 	    do_pending_operator(cap, 0, FALSE);
7458 	    empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
7459 	    --msg_silent;
7460 
7461 	    // delete PUT_LINE_BACKWARD;
7462 	    cap->oap->regname = regname;
7463 
7464 	    if (reg1 != NULL)
7465 	    {
7466 		// Delete probably changed the register we want to put, save
7467 		// it first. Then put back what was there before the delete.
7468 		reg2 = get_register(regname, FALSE);
7469 		put_register(regname, reg1);
7470 	    }
7471 
7472 	    // When deleted a linewise Visual area, put the register as
7473 	    // lines to avoid it joined with the next line.  When deletion was
7474 	    // characterwise, split a line when putting lines.
7475 	    if (VIsual_mode == 'V')
7476 		flags |= PUT_LINE;
7477 	    else if (VIsual_mode == 'v')
7478 		flags |= PUT_LINE_SPLIT;
7479 	    if (VIsual_mode == Ctrl_V && dir == FORWARD)
7480 		flags |= PUT_LINE_FORWARD;
7481 	    dir = BACKWARD;
7482 	    if ((VIsual_mode != 'V'
7483 			&& curwin->w_cursor.col < curbuf->b_op_start.col)
7484 		    || (VIsual_mode == 'V'
7485 			&& curwin->w_cursor.lnum < curbuf->b_op_start.lnum))
7486 		// cursor is at the end of the line or end of file, put
7487 		// forward.
7488 		dir = FORWARD;
7489 	    // May have been reset in do_put().
7490 	    VIsual_active = TRUE;
7491 	}
7492 	do_put(cap->oap->regname, NULL, dir, cap->count1, flags);
7493 
7494 	// If a register was saved, put it back now.
7495 	if (reg2 != NULL)
7496 	    put_register(regname, reg2);
7497 
7498 	// What to reselect with "gv"?  Selecting the just put text seems to
7499 	// be the most useful, since the original text was removed.
7500 	if (was_visual)
7501 	{
7502 	    curbuf->b_visual.vi_start = curbuf->b_op_start;
7503 	    curbuf->b_visual.vi_end = curbuf->b_op_end;
7504 	    // need to adjust cursor position
7505 	    if (*p_sel == 'e')
7506 		inc(&curbuf->b_visual.vi_end);
7507 	}
7508 
7509 	// When all lines were selected and deleted do_put() leaves an empty
7510 	// line that needs to be deleted now.
7511 	if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL)
7512 	{
7513 	    ml_delete_flags(curbuf->b_ml.ml_line_count, ML_DEL_MESSAGE);
7514 	    deleted_lines(curbuf->b_ml.ml_line_count + 1, 1);
7515 
7516 	    // If the cursor was in that line, move it to the end of the last
7517 	    // line.
7518 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
7519 	    {
7520 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7521 		coladvance((colnr_T)MAXCOL);
7522 	    }
7523 	}
7524 	auto_format(FALSE, TRUE);
7525     }
7526 }
7527 
7528 /*
7529  * "o" and "O" commands.
7530  */
7531     static void
7532 nv_open(cmdarg_T *cap)
7533 {
7534 #ifdef FEAT_DIFF
7535     // "do" is ":diffget"
7536     if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o')
7537     {
7538 	clearop(cap->oap);
7539 	nv_diffgetput(FALSE, cap->opcount);
7540     }
7541     else
7542 #endif
7543     if (VIsual_active)  // switch start and end of visual
7544 	v_swap_corners(cap->cmdchar);
7545 #ifdef FEAT_JOB_CHANNEL
7546     else if (bt_prompt(curbuf))
7547 	clearopbeep(cap->oap);
7548 #endif
7549     else
7550 	n_opencmd(cap);
7551 }
7552 
7553 #ifdef FEAT_NETBEANS_INTG
7554     static void
7555 nv_nbcmd(cmdarg_T *cap)
7556 {
7557     netbeans_keycommand(cap->nchar);
7558 }
7559 #endif
7560 
7561 #ifdef FEAT_DND
7562     static void
7563 nv_drop(cmdarg_T *cap UNUSED)
7564 {
7565     do_put('~', NULL, BACKWARD, 1L, PUT_CURSEND);
7566 }
7567 #endif
7568 
7569 /*
7570  * Trigger CursorHold event.
7571  * When waiting for a character for 'updatetime' K_CURSORHOLD is put in the
7572  * input buffer.  "did_cursorhold" is set to avoid retriggering.
7573  */
7574     static void
7575 nv_cursorhold(cmdarg_T *cap)
7576 {
7577     apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf);
7578     did_cursorhold = TRUE;
7579     cap->retval |= CA_COMMAND_BUSY;	// don't call edit() now
7580 }
7581