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