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