xref: /vim-8.2.3635/src/normal.c (revision abfa9efb)
1 /* vi:set ts=8 sts=4 sw=4:
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 /*
18  * The Visual area is remembered for reselection.
19  */
20 static int	resel_VIsual_mode = NUL;	/* 'v', 'V', or Ctrl-V */
21 static linenr_T	resel_VIsual_line_count;	/* number of lines */
22 static colnr_T	resel_VIsual_vcol;		/* nr of cols or end col */
23 static int	VIsual_mode_orig = NUL;		/* saved Visual mode */
24 
25 static int	restart_VIsual_select = 0;
26 
27 #ifdef FEAT_EVAL
28 static void	set_vcount_ca __ARGS((cmdarg_T *cap, int *set_prevcount));
29 #endif
30 static int
31 #ifdef __BORLANDC__
32     _RTLENTRYF
33 #endif
34 		nv_compare __ARGS((const void *s1, const void *s2));
35 static int	find_command __ARGS((int cmdchar));
36 static void	op_colon __ARGS((oparg_T *oap));
37 static void	op_function __ARGS((oparg_T *oap));
38 #if defined(FEAT_MOUSE)
39 static void	find_start_of_word __ARGS((pos_T *));
40 static void	find_end_of_word __ARGS((pos_T *));
41 static int	get_mouse_class __ARGS((char_u *p));
42 #endif
43 static void	prep_redo_cmd __ARGS((cmdarg_T *cap));
44 static void	prep_redo __ARGS((int regname, long, int, int, int, int, int));
45 static int	checkclearop __ARGS((oparg_T *oap));
46 static int	checkclearopq __ARGS((oparg_T *oap));
47 static void	clearop __ARGS((oparg_T *oap));
48 static void	clearopbeep __ARGS((oparg_T *oap));
49 static void	unshift_special __ARGS((cmdarg_T *cap));
50 static void	may_clear_cmdline __ARGS((void));
51 #ifdef FEAT_CMDL_INFO
52 static void	del_from_showcmd __ARGS((int));
53 #endif
54 
55 /*
56  * nv_*(): functions called to handle Normal and Visual mode commands.
57  * n_*(): functions called to handle Normal mode commands.
58  * v_*(): functions called to handle Visual mode commands.
59  */
60 static void	nv_ignore __ARGS((cmdarg_T *cap));
61 static void	nv_nop __ARGS((cmdarg_T *cap));
62 static void	nv_error __ARGS((cmdarg_T *cap));
63 static void	nv_help __ARGS((cmdarg_T *cap));
64 static void	nv_addsub __ARGS((cmdarg_T *cap));
65 static void	nv_page __ARGS((cmdarg_T *cap));
66 static void	nv_gd __ARGS((oparg_T *oap, int nchar, int thisblock));
67 static int	nv_screengo __ARGS((oparg_T *oap, int dir, long dist));
68 #ifdef FEAT_MOUSE
69 static void	nv_mousescroll __ARGS((cmdarg_T *cap));
70 static void	nv_mouse __ARGS((cmdarg_T *cap));
71 #endif
72 static void	nv_scroll_line __ARGS((cmdarg_T *cap));
73 static void	nv_zet __ARGS((cmdarg_T *cap));
74 #ifdef FEAT_GUI
75 static void	nv_ver_scrollbar __ARGS((cmdarg_T *cap));
76 static void	nv_hor_scrollbar __ARGS((cmdarg_T *cap));
77 #endif
78 #ifdef FEAT_GUI_TABLINE
79 static void	nv_tabline __ARGS((cmdarg_T *cap));
80 static void	nv_tabmenu __ARGS((cmdarg_T *cap));
81 #endif
82 static void	nv_exmode __ARGS((cmdarg_T *cap));
83 static void	nv_colon __ARGS((cmdarg_T *cap));
84 static void	nv_ctrlg __ARGS((cmdarg_T *cap));
85 static void	nv_ctrlh __ARGS((cmdarg_T *cap));
86 static void	nv_clear __ARGS((cmdarg_T *cap));
87 static void	nv_ctrlo __ARGS((cmdarg_T *cap));
88 static void	nv_hat __ARGS((cmdarg_T *cap));
89 static void	nv_Zet __ARGS((cmdarg_T *cap));
90 static void	nv_ident __ARGS((cmdarg_T *cap));
91 static void	nv_tagpop __ARGS((cmdarg_T *cap));
92 static void	nv_scroll __ARGS((cmdarg_T *cap));
93 static void	nv_right __ARGS((cmdarg_T *cap));
94 static void	nv_left __ARGS((cmdarg_T *cap));
95 static void	nv_up __ARGS((cmdarg_T *cap));
96 static void	nv_down __ARGS((cmdarg_T *cap));
97 #ifdef FEAT_SEARCHPATH
98 static void	nv_gotofile __ARGS((cmdarg_T *cap));
99 #endif
100 static void	nv_end __ARGS((cmdarg_T *cap));
101 static void	nv_dollar __ARGS((cmdarg_T *cap));
102 static void	nv_search __ARGS((cmdarg_T *cap));
103 static void	nv_next __ARGS((cmdarg_T *cap));
104 static int	normal_search __ARGS((cmdarg_T *cap, int dir, char_u *pat, int opt));
105 static void	nv_csearch __ARGS((cmdarg_T *cap));
106 static void	nv_brackets __ARGS((cmdarg_T *cap));
107 static void	nv_percent __ARGS((cmdarg_T *cap));
108 static void	nv_brace __ARGS((cmdarg_T *cap));
109 static void	nv_mark __ARGS((cmdarg_T *cap));
110 static void	nv_findpar __ARGS((cmdarg_T *cap));
111 static void	nv_undo __ARGS((cmdarg_T *cap));
112 static void	nv_kundo __ARGS((cmdarg_T *cap));
113 static void	nv_Replace __ARGS((cmdarg_T *cap));
114 #ifdef FEAT_VREPLACE
115 static void	nv_vreplace __ARGS((cmdarg_T *cap));
116 #endif
117 static void	v_swap_corners __ARGS((int cmdchar));
118 static void	nv_replace __ARGS((cmdarg_T *cap));
119 static void	n_swapchar __ARGS((cmdarg_T *cap));
120 static void	nv_cursormark __ARGS((cmdarg_T *cap, int flag, pos_T *pos));
121 static void	v_visop __ARGS((cmdarg_T *cap));
122 static void	nv_subst __ARGS((cmdarg_T *cap));
123 static void	nv_abbrev __ARGS((cmdarg_T *cap));
124 static void	nv_optrans __ARGS((cmdarg_T *cap));
125 static void	nv_gomark __ARGS((cmdarg_T *cap));
126 static void	nv_pcmark __ARGS((cmdarg_T *cap));
127 static void	nv_regname __ARGS((cmdarg_T *cap));
128 static void	nv_visual __ARGS((cmdarg_T *cap));
129 static void	n_start_visual_mode __ARGS((int c));
130 static void	nv_window __ARGS((cmdarg_T *cap));
131 static void	nv_suspend __ARGS((cmdarg_T *cap));
132 static void	nv_g_cmd __ARGS((cmdarg_T *cap));
133 static void	n_opencmd __ARGS((cmdarg_T *cap));
134 static void	nv_dot __ARGS((cmdarg_T *cap));
135 static void	nv_redo __ARGS((cmdarg_T *cap));
136 static void	nv_Undo __ARGS((cmdarg_T *cap));
137 static void	nv_tilde __ARGS((cmdarg_T *cap));
138 static void	nv_operator __ARGS((cmdarg_T *cap));
139 #ifdef FEAT_EVAL
140 static void	set_op_var __ARGS((int optype));
141 #endif
142 static void	nv_lineop __ARGS((cmdarg_T *cap));
143 static void	nv_home __ARGS((cmdarg_T *cap));
144 static void	nv_pipe __ARGS((cmdarg_T *cap));
145 static void	nv_bck_word __ARGS((cmdarg_T *cap));
146 static void	nv_wordcmd __ARGS((cmdarg_T *cap));
147 static void	nv_beginline __ARGS((cmdarg_T *cap));
148 static void	adjust_cursor __ARGS((oparg_T *oap));
149 static void	adjust_for_sel __ARGS((cmdarg_T *cap));
150 static int	unadjust_for_sel __ARGS((void));
151 static void	nv_select __ARGS((cmdarg_T *cap));
152 static void	nv_goto __ARGS((cmdarg_T *cap));
153 static void	nv_normal __ARGS((cmdarg_T *cap));
154 static void	nv_esc __ARGS((cmdarg_T *oap));
155 static void	nv_edit __ARGS((cmdarg_T *cap));
156 static void	invoke_edit __ARGS((cmdarg_T *cap, int repl, int cmd, int startln));
157 #ifdef FEAT_TEXTOBJ
158 static void	nv_object __ARGS((cmdarg_T *cap));
159 #endif
160 static void	nv_record __ARGS((cmdarg_T *cap));
161 static void	nv_at __ARGS((cmdarg_T *cap));
162 static void	nv_halfpage __ARGS((cmdarg_T *cap));
163 static void	nv_join __ARGS((cmdarg_T *cap));
164 static void	nv_put __ARGS((cmdarg_T *cap));
165 static void	nv_open __ARGS((cmdarg_T *cap));
166 #ifdef FEAT_SNIFF
167 static void	nv_sniff __ARGS((cmdarg_T *cap));
168 #endif
169 #ifdef FEAT_NETBEANS_INTG
170 static void	nv_nbcmd __ARGS((cmdarg_T *cap));
171 #endif
172 #ifdef FEAT_DND
173 static void	nv_drop __ARGS((cmdarg_T *cap));
174 #endif
175 #ifdef FEAT_AUTOCMD
176 static void	nv_cursorhold __ARGS((cmdarg_T *cap));
177 #endif
178 static void	get_op_vcol __ARGS((oparg_T *oap, colnr_T col, int initial));
179 
180 static char *e_noident = N_("E349: No identifier under cursor");
181 
182 /*
183  * Function to be called for a Normal or Visual mode command.
184  * The argument is a cmdarg_T.
185  */
186 typedef void (*nv_func_T) __ARGS((cmdarg_T *cap));
187 
188 /* Values for cmd_flags. */
189 #define NV_NCH	    0x01	  /* may need to get a second char */
190 #define NV_NCH_NOP  (0x02|NV_NCH) /* get second char when no operator pending */
191 #define NV_NCH_ALW  (0x04|NV_NCH) /* always get a second char */
192 #define NV_LANG	    0x08	/* second char needs language adjustment */
193 
194 #define NV_SS	    0x10	/* may start selection */
195 #define NV_SSS	    0x20	/* may start selection with shift modifier */
196 #define NV_STS	    0x40	/* may stop selection without shift modif. */
197 #define NV_RL	    0x80	/* 'rightleft' modifies command */
198 #define NV_KEEPREG  0x100	/* don't clear regname */
199 #define NV_NCW	    0x200	/* not allowed in command-line window */
200 
201 /*
202  * Generally speaking, every Normal mode command should either clear any
203  * pending operator (with *clearop*()), or set the motion type variable
204  * oap->motion_type.
205  *
206  * When a cursor motion command is made, it is marked as being a character or
207  * line oriented motion.  Then, if an operator is in effect, the operation
208  * becomes character or line oriented accordingly.
209  */
210 
211 /*
212  * This table contains one entry for every Normal or Visual mode command.
213  * The order doesn't matter, init_normal_cmds() will create a sorted index.
214  * It is faster when all keys from zero to '~' are present.
215  */
216 static const struct nv_cmd
217 {
218     int		cmd_char;	/* (first) command character */
219     nv_func_T   cmd_func;	/* function for this command */
220     short_u	cmd_flags;	/* NV_ flags */
221     short	cmd_arg;	/* value for ca.arg */
222 } nv_cmds[] =
223 {
224     {NUL,	nv_error,	0,			0},
225     {Ctrl_A,	nv_addsub,	0,			0},
226     {Ctrl_B,	nv_page,	NV_STS,			BACKWARD},
227     {Ctrl_C,	nv_esc,		0,			TRUE},
228     {Ctrl_D,	nv_halfpage,	0,			0},
229     {Ctrl_E,	nv_scroll_line,	0,			TRUE},
230     {Ctrl_F,	nv_page,	NV_STS,			FORWARD},
231     {Ctrl_G,	nv_ctrlg,	0,			0},
232     {Ctrl_H,	nv_ctrlh,	0,			0},
233     {Ctrl_I,	nv_pcmark,	0,			0},
234     {NL,	nv_down,	0,			FALSE},
235     {Ctrl_K,	nv_error,	0,			0},
236     {Ctrl_L,	nv_clear,	0,			0},
237     {Ctrl_M,	nv_down,	0,			TRUE},
238     {Ctrl_N,	nv_down,	NV_STS,			FALSE},
239     {Ctrl_O,	nv_ctrlo,	0,			0},
240     {Ctrl_P,	nv_up,		NV_STS,			FALSE},
241     {Ctrl_Q,	nv_visual,	0,			FALSE},
242     {Ctrl_R,	nv_redo,	0,			0},
243     {Ctrl_S,	nv_ignore,	0,			0},
244     {Ctrl_T,	nv_tagpop,	NV_NCW,			0},
245     {Ctrl_U,	nv_halfpage,	0,			0},
246     {Ctrl_V,	nv_visual,	0,			FALSE},
247     {'V',	nv_visual,	0,			FALSE},
248     {'v',	nv_visual,	0,			FALSE},
249     {Ctrl_W,	nv_window,	0,			0},
250     {Ctrl_X,	nv_addsub,	0,			0},
251     {Ctrl_Y,	nv_scroll_line,	0,			FALSE},
252     {Ctrl_Z,	nv_suspend,	0,			0},
253     {ESC,	nv_esc,		0,			FALSE},
254     {Ctrl_BSL,	nv_normal,	NV_NCH_ALW,		0},
255     {Ctrl_RSB,	nv_ident,	NV_NCW,			0},
256     {Ctrl_HAT,	nv_hat,		NV_NCW,			0},
257     {Ctrl__,	nv_error,	0,			0},
258     {' ',	nv_right,	0,			0},
259     {'!',	nv_operator,	0,			0},
260     {'"',	nv_regname,	NV_NCH_NOP|NV_KEEPREG,	0},
261     {'#',	nv_ident,	0,			0},
262     {'$',	nv_dollar,	0,			0},
263     {'%',	nv_percent,	0,			0},
264     {'&',	nv_optrans,	0,			0},
265     {'\'',	nv_gomark,	NV_NCH_ALW,		TRUE},
266     {'(',	nv_brace,	0,			BACKWARD},
267     {')',	nv_brace,	0,			FORWARD},
268     {'*',	nv_ident,	0,			0},
269     {'+',	nv_down,	0,			TRUE},
270     {',',	nv_csearch,	0,			TRUE},
271     {'-',	nv_up,		0,			TRUE},
272     {'.',	nv_dot,		NV_KEEPREG,		0},
273     {'/',	nv_search,	0,			FALSE},
274     {'0',	nv_beginline,	0,			0},
275     {'1',	nv_ignore,	0,			0},
276     {'2',	nv_ignore,	0,			0},
277     {'3',	nv_ignore,	0,			0},
278     {'4',	nv_ignore,	0,			0},
279     {'5',	nv_ignore,	0,			0},
280     {'6',	nv_ignore,	0,			0},
281     {'7',	nv_ignore,	0,			0},
282     {'8',	nv_ignore,	0,			0},
283     {'9',	nv_ignore,	0,			0},
284     {':',	nv_colon,	0,			0},
285     {';',	nv_csearch,	0,			FALSE},
286     {'<',	nv_operator,	NV_RL,			0},
287     {'=',	nv_operator,	0,			0},
288     {'>',	nv_operator,	NV_RL,			0},
289     {'?',	nv_search,	0,			FALSE},
290     {'@',	nv_at,		NV_NCH_NOP,		FALSE},
291     {'A',	nv_edit,	0,			0},
292     {'B',	nv_bck_word,	0,			1},
293     {'C',	nv_abbrev,	NV_KEEPREG,		0},
294     {'D',	nv_abbrev,	NV_KEEPREG,		0},
295     {'E',	nv_wordcmd,	0,			TRUE},
296     {'F',	nv_csearch,	NV_NCH_ALW|NV_LANG,	BACKWARD},
297     {'G',	nv_goto,	0,			TRUE},
298     {'H',	nv_scroll,	0,			0},
299     {'I',	nv_edit,	0,			0},
300     {'J',	nv_join,	0,			0},
301     {'K',	nv_ident,	0,			0},
302     {'L',	nv_scroll,	0,			0},
303     {'M',	nv_scroll,	0,			0},
304     {'N',	nv_next,	0,			SEARCH_REV},
305     {'O',	nv_open,	0,			0},
306     {'P',	nv_put,		0,			0},
307     {'Q',	nv_exmode,	NV_NCW,			0},
308     {'R',	nv_Replace,	0,			FALSE},
309     {'S',	nv_subst,	NV_KEEPREG,		0},
310     {'T',	nv_csearch,	NV_NCH_ALW|NV_LANG,	BACKWARD},
311     {'U',	nv_Undo,	0,			0},
312     {'W',	nv_wordcmd,	0,			TRUE},
313     {'X',	nv_abbrev,	NV_KEEPREG,		0},
314     {'Y',	nv_abbrev,	NV_KEEPREG,		0},
315     {'Z',	nv_Zet,		NV_NCH_NOP|NV_NCW,	0},
316     {'[',	nv_brackets,	NV_NCH_ALW,		BACKWARD},
317     {'\\',	nv_error,	0,			0},
318     {']',	nv_brackets,	NV_NCH_ALW,		FORWARD},
319     {'^',	nv_beginline,	0,			BL_WHITE | BL_FIX},
320     {'_',	nv_lineop,	0,			0},
321     {'`',	nv_gomark,	NV_NCH_ALW,		FALSE},
322     {'a',	nv_edit,	NV_NCH,			0},
323     {'b',	nv_bck_word,	0,			0},
324     {'c',	nv_operator,	0,			0},
325     {'d',	nv_operator,	0,			0},
326     {'e',	nv_wordcmd,	0,			FALSE},
327     {'f',	nv_csearch,	NV_NCH_ALW|NV_LANG,	FORWARD},
328     {'g',	nv_g_cmd,	NV_NCH_ALW,		FALSE},
329     {'h',	nv_left,	NV_RL,			0},
330     {'i',	nv_edit,	NV_NCH,			0},
331     {'j',	nv_down,	0,			FALSE},
332     {'k',	nv_up,		0,			FALSE},
333     {'l',	nv_right,	NV_RL,			0},
334     {'m',	nv_mark,	NV_NCH_NOP,		0},
335     {'n',	nv_next,	0,			0},
336     {'o',	nv_open,	0,			0},
337     {'p',	nv_put,		0,			0},
338     {'q',	nv_record,	NV_NCH,			0},
339     {'r',	nv_replace,	NV_NCH_NOP|NV_LANG,	0},
340     {'s',	nv_subst,	NV_KEEPREG,		0},
341     {'t',	nv_csearch,	NV_NCH_ALW|NV_LANG,	FORWARD},
342     {'u',	nv_undo,	0,			0},
343     {'w',	nv_wordcmd,	0,			FALSE},
344     {'x',	nv_abbrev,	NV_KEEPREG,		0},
345     {'y',	nv_operator,	0,			0},
346     {'z',	nv_zet,		NV_NCH_ALW,		0},
347     {'{',	nv_findpar,	0,			BACKWARD},
348     {'|',	nv_pipe,	0,			0},
349     {'}',	nv_findpar,	0,			FORWARD},
350     {'~',	nv_tilde,	0,			0},
351 
352     /* pound sign */
353     {POUND,	nv_ident,	0,			0},
354 #ifdef FEAT_MOUSE
355     {K_MOUSEUP, nv_mousescroll,	0,			MSCR_UP},
356     {K_MOUSEDOWN, nv_mousescroll, 0,			MSCR_DOWN},
357     {K_MOUSELEFT, nv_mousescroll, 0,			MSCR_LEFT},
358     {K_MOUSERIGHT, nv_mousescroll, 0,			MSCR_RIGHT},
359     {K_LEFTMOUSE, nv_mouse,	0,			0},
360     {K_LEFTMOUSE_NM, nv_mouse,	0,			0},
361     {K_LEFTDRAG, nv_mouse,	0,			0},
362     {K_LEFTRELEASE, nv_mouse,	0,			0},
363     {K_LEFTRELEASE_NM, nv_mouse, 0,			0},
364     {K_MIDDLEMOUSE, nv_mouse,	0,			0},
365     {K_MIDDLEDRAG, nv_mouse,	0,			0},
366     {K_MIDDLERELEASE, nv_mouse,	0,			0},
367     {K_RIGHTMOUSE, nv_mouse,	0,			0},
368     {K_RIGHTDRAG, nv_mouse,	0,			0},
369     {K_RIGHTRELEASE, nv_mouse,	0,			0},
370     {K_X1MOUSE, nv_mouse,	0,			0},
371     {K_X1DRAG, nv_mouse,	0,			0},
372     {K_X1RELEASE, nv_mouse,	0,			0},
373     {K_X2MOUSE, nv_mouse,	0,			0},
374     {K_X2DRAG, nv_mouse,	0,			0},
375     {K_X2RELEASE, nv_mouse,	0,			0},
376 #endif
377     {K_IGNORE,	nv_ignore,	NV_KEEPREG,		0},
378     {K_NOP,	nv_nop,		0,			0},
379     {K_INS,	nv_edit,	0,			0},
380     {K_KINS,	nv_edit,	0,			0},
381     {K_BS,	nv_ctrlh,	0,			0},
382     {K_UP,	nv_up,		NV_SSS|NV_STS,		FALSE},
383     {K_S_UP,	nv_page,	NV_SS,			BACKWARD},
384     {K_DOWN,	nv_down,	NV_SSS|NV_STS,		FALSE},
385     {K_S_DOWN,	nv_page,	NV_SS,			FORWARD},
386     {K_LEFT,	nv_left,	NV_SSS|NV_STS|NV_RL,	0},
387     {K_S_LEFT,	nv_bck_word,	NV_SS|NV_RL,		0},
388     {K_C_LEFT,	nv_bck_word,	NV_SSS|NV_RL|NV_STS,	1},
389     {K_RIGHT,	nv_right,	NV_SSS|NV_STS|NV_RL,	0},
390     {K_S_RIGHT,	nv_wordcmd,	NV_SS|NV_RL,		FALSE},
391     {K_C_RIGHT,	nv_wordcmd,	NV_SSS|NV_RL|NV_STS,	TRUE},
392     {K_PAGEUP,	nv_page,	NV_SSS|NV_STS,		BACKWARD},
393     {K_KPAGEUP,	nv_page,	NV_SSS|NV_STS,		BACKWARD},
394     {K_PAGEDOWN, nv_page,	NV_SSS|NV_STS,		FORWARD},
395     {K_KPAGEDOWN, nv_page,	NV_SSS|NV_STS,		FORWARD},
396     {K_END,	nv_end,		NV_SSS|NV_STS,		FALSE},
397     {K_KEND,	nv_end,		NV_SSS|NV_STS,		FALSE},
398     {K_S_END,	nv_end,		NV_SS,			FALSE},
399     {K_C_END,	nv_end,		NV_SSS|NV_STS,		TRUE},
400     {K_HOME,	nv_home,	NV_SSS|NV_STS,		0},
401     {K_KHOME,	nv_home,	NV_SSS|NV_STS,		0},
402     {K_S_HOME,	nv_home,	NV_SS,			0},
403     {K_C_HOME,	nv_goto,	NV_SSS|NV_STS,		FALSE},
404     {K_DEL,	nv_abbrev,	0,			0},
405     {K_KDEL,	nv_abbrev,	0,			0},
406     {K_UNDO,	nv_kundo,	0,			0},
407     {K_HELP,	nv_help,	NV_NCW,			0},
408     {K_F1,	nv_help,	NV_NCW,			0},
409     {K_XF1,	nv_help,	NV_NCW,			0},
410     {K_SELECT,	nv_select,	0,			0},
411 #ifdef FEAT_GUI
412     {K_VER_SCROLLBAR, nv_ver_scrollbar, 0,		0},
413     {K_HOR_SCROLLBAR, nv_hor_scrollbar, 0,		0},
414 #endif
415 #ifdef FEAT_GUI_TABLINE
416     {K_TABLINE, nv_tabline,	0,			0},
417     {K_TABMENU, nv_tabmenu,	0,			0},
418 #endif
419 #ifdef FEAT_FKMAP
420     {K_F8,	farsi_fkey,	0,			0},
421     {K_F9,	farsi_fkey,	0,			0},
422 #endif
423 #ifdef FEAT_SNIFF
424     {K_SNIFF,	nv_sniff,	0,			0},
425 #endif
426 #ifdef FEAT_NETBEANS_INTG
427     {K_F21,	nv_nbcmd,	NV_NCH_ALW,		0},
428 #endif
429 #ifdef FEAT_DND
430     {K_DROP,	nv_drop,	NV_STS,			0},
431 #endif
432 #ifdef FEAT_AUTOCMD
433     {K_CURSORHOLD, nv_cursorhold, NV_KEEPREG,		0},
434 #endif
435 };
436 
437 /* Number of commands in nv_cmds[]. */
438 #define NV_CMDS_SIZE (sizeof(nv_cmds) / sizeof(struct nv_cmd))
439 
440 /* Sorted index of commands in nv_cmds[]. */
441 static short nv_cmd_idx[NV_CMDS_SIZE];
442 
443 /* The highest index for which
444  * nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char] */
445 static int nv_max_linear;
446 
447 /*
448  * Compare functions for qsort() below, that checks the command character
449  * through the index in nv_cmd_idx[].
450  */
451     static int
452 #ifdef __BORLANDC__
453 _RTLENTRYF
454 #endif
455 nv_compare(s1, s2)
456     const void	*s1;
457     const void	*s2;
458 {
459     int		c1, c2;
460 
461     /* The commands are sorted on absolute value. */
462     c1 = nv_cmds[*(const short *)s1].cmd_char;
463     c2 = nv_cmds[*(const short *)s2].cmd_char;
464     if (c1 < 0)
465 	c1 = -c1;
466     if (c2 < 0)
467 	c2 = -c2;
468     return c1 - c2;
469 }
470 
471 /*
472  * Initialize the nv_cmd_idx[] table.
473  */
474     void
475 init_normal_cmds()
476 {
477     int		i;
478 
479     /* Fill the index table with a one to one relation. */
480     for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
481 	nv_cmd_idx[i] = i;
482 
483     /* Sort the commands by the command character.  */
484     qsort((void *)&nv_cmd_idx, (size_t)NV_CMDS_SIZE, sizeof(short), nv_compare);
485 
486     /* Find the first entry that can't be indexed by the command character. */
487     for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
488 	if (i != nv_cmds[nv_cmd_idx[i]].cmd_char)
489 	    break;
490     nv_max_linear = i - 1;
491 }
492 
493 /*
494  * Search for a command in the commands table.
495  * Returns -1 for invalid command.
496  */
497     static int
498 find_command(cmdchar)
499     int		cmdchar;
500 {
501     int		i;
502     int		idx;
503     int		top, bot;
504     int		c;
505 
506 #ifdef FEAT_MBYTE
507     /* A multi-byte character is never a command. */
508     if (cmdchar >= 0x100)
509 	return -1;
510 #endif
511 
512     /* We use the absolute value of the character.  Special keys have a
513      * negative value, but are sorted on their absolute value. */
514     if (cmdchar < 0)
515 	cmdchar = -cmdchar;
516 
517     /* If the character is in the first part: The character is the index into
518      * nv_cmd_idx[]. */
519     if (cmdchar <= nv_max_linear)
520 	return nv_cmd_idx[cmdchar];
521 
522     /* Perform a binary search. */
523     bot = nv_max_linear + 1;
524     top = NV_CMDS_SIZE - 1;
525     idx = -1;
526     while (bot <= top)
527     {
528 	i = (top + bot) / 2;
529 	c = nv_cmds[nv_cmd_idx[i]].cmd_char;
530 	if (c < 0)
531 	    c = -c;
532 	if (cmdchar == c)
533 	{
534 	    idx = nv_cmd_idx[i];
535 	    break;
536 	}
537 	if (cmdchar > c)
538 	    bot = i + 1;
539 	else
540 	    top = i - 1;
541     }
542     return idx;
543 }
544 
545 /*
546  * Execute a command in Normal mode.
547  */
548     void
549 normal_cmd(oap, toplevel)
550     oparg_T	*oap;
551     int		toplevel UNUSED;	/* TRUE when called from main() */
552 {
553     cmdarg_T	ca;			/* command arguments */
554     int		c;
555     int		ctrl_w = FALSE;		/* got CTRL-W command */
556     int		old_col = curwin->w_curswant;
557 #ifdef FEAT_CMDL_INFO
558     int		need_flushbuf;		/* need to call out_flush() */
559 #endif
560     pos_T	old_pos;		/* cursor position before command */
561     int		mapped_len;
562     static int	old_mapped_len = 0;
563     int		idx;
564 #ifdef FEAT_EVAL
565     int		set_prevcount = FALSE;
566 #endif
567 
568     vim_memset(&ca, 0, sizeof(ca));	/* also resets ca.retval */
569     ca.oap = oap;
570 
571     /* Use a count remembered from before entering an operator.  After typing
572      * "3d" we return from normal_cmd() and come back here, the "3" is
573      * remembered in "opcount". */
574     ca.opcount = opcount;
575 
576 #ifdef FEAT_SNIFF
577     want_sniff_request = sniff_connected;
578 #endif
579 
580     /*
581      * If there is an operator pending, then the command we take this time
582      * will terminate it. Finish_op tells us to finish the operation before
583      * returning this time (unless the operation was cancelled).
584      */
585 #ifdef CURSOR_SHAPE
586     c = finish_op;
587 #endif
588     finish_op = (oap->op_type != OP_NOP);
589 #ifdef CURSOR_SHAPE
590     if (finish_op != c)
591     {
592 	ui_cursor_shape();		/* may show different cursor shape */
593 # ifdef FEAT_MOUSESHAPE
594 	update_mouseshape(-1);
595 # endif
596     }
597 #endif
598 
599     /* When not finishing an operator and no register name typed, reset the
600      * count. */
601     if (!finish_op && !oap->regname)
602     {
603 	ca.opcount = 0;
604 #ifdef FEAT_EVAL
605 	set_prevcount = TRUE;
606 #endif
607     }
608 
609 #ifdef FEAT_AUTOCMD
610     /* Restore counts from before receiving K_CURSORHOLD.  This means after
611      * typing "3", handling K_CURSORHOLD and then typing "2" we get "32", not
612      * "3 * 2". */
613     if (oap->prev_opcount > 0 || oap->prev_count0 > 0)
614     {
615 	ca.opcount = oap->prev_opcount;
616 	ca.count0 = oap->prev_count0;
617 	oap->prev_opcount = 0;
618 	oap->prev_count0 = 0;
619     }
620 #endif
621 
622     mapped_len = typebuf_maplen();
623 
624     State = NORMAL_BUSY;
625 #ifdef USE_ON_FLY_SCROLL
626     dont_scroll = FALSE;	/* allow scrolling here */
627 #endif
628 
629 #ifdef FEAT_EVAL
630     /* Set v:count here, when called from main() and not a stuffed
631      * command, so that v:count can be used in an expression mapping
632      * when there is no count. Do set it for redo. */
633     if (toplevel && readbuf1_empty())
634 	set_vcount_ca(&ca, &set_prevcount);
635 #endif
636 
637     /*
638      * Get the command character from the user.
639      */
640     c = safe_vgetc();
641     LANGMAP_ADJUST(c, TRUE);
642 
643     /*
644      * If a mapping was started in Visual or Select mode, remember the length
645      * of the mapping.  This is used below to not return to Insert mode for as
646      * long as the mapping is being executed.
647      */
648     if (restart_edit == 0)
649 	old_mapped_len = 0;
650     else if (old_mapped_len
651 		|| (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0))
652 	old_mapped_len = typebuf_maplen();
653 
654     if (c == NUL)
655 	c = K_ZERO;
656 
657     /*
658      * In Select mode, typed text replaces the selection.
659      */
660     if (VIsual_active
661 	    && VIsual_select
662 	    && (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER))
663     {
664 	/* Fake a "c"hange command.  When "restart_edit" is set (e.g., because
665 	 * 'insertmode' is set) fake a "d"elete command, Insert mode will
666 	 * restart automatically.
667 	 * Insert the typed character in the typeahead buffer, so that it can
668 	 * be mapped in Insert mode.  Required for ":lmap" to work. */
669 	ins_char_typebuf(c);
670 	if (restart_edit != 0)
671 	    c = 'd';
672 	else
673 	    c = 'c';
674 	msg_nowait = TRUE;	/* don't delay going to insert mode */
675 	old_mapped_len = 0;	/* do go to Insert mode */
676     }
677 
678 #ifdef FEAT_CMDL_INFO
679     need_flushbuf = add_to_showcmd(c);
680 #endif
681 
682 getcount:
683     if (!(VIsual_active && VIsual_select))
684     {
685 	/*
686 	 * Handle a count before a command and compute ca.count0.
687 	 * Note that '0' is a command and not the start of a count, but it's
688 	 * part of a count after other digits.
689 	 */
690 	while (    (c >= '1' && c <= '9')
691 		|| (ca.count0 != 0 && (c == K_DEL || c == K_KDEL || c == '0')))
692 	{
693 	    if (c == K_DEL || c == K_KDEL)
694 	    {
695 		ca.count0 /= 10;
696 #ifdef FEAT_CMDL_INFO
697 		del_from_showcmd(4);	/* delete the digit and ~@% */
698 #endif
699 	    }
700 	    else
701 		ca.count0 = ca.count0 * 10 + (c - '0');
702 	    if (ca.count0 < 0)	    /* got too large! */
703 		ca.count0 = 999999999L;
704 #ifdef FEAT_EVAL
705 	    /* Set v:count here, when called from main() and not a stuffed
706 	     * command, so that v:count can be used in an expression mapping
707 	     * right after the count. Do set it for redo. */
708 	    if (toplevel && readbuf1_empty())
709 		set_vcount_ca(&ca, &set_prevcount);
710 #endif
711 	    if (ctrl_w)
712 	    {
713 		++no_mapping;
714 		++allow_keys;		/* no mapping for nchar, but keys */
715 	    }
716 	    ++no_zero_mapping;		/* don't map zero here */
717 	    c = plain_vgetc();
718 	    LANGMAP_ADJUST(c, TRUE);
719 	    --no_zero_mapping;
720 	    if (ctrl_w)
721 	    {
722 		--no_mapping;
723 		--allow_keys;
724 	    }
725 #ifdef FEAT_CMDL_INFO
726 	    need_flushbuf |= add_to_showcmd(c);
727 #endif
728 	}
729 
730 	/*
731 	 * If we got CTRL-W there may be a/another count
732 	 */
733 	if (c == Ctrl_W && !ctrl_w && oap->op_type == OP_NOP)
734 	{
735 	    ctrl_w = TRUE;
736 	    ca.opcount = ca.count0;	/* remember first count */
737 	    ca.count0 = 0;
738 	    ++no_mapping;
739 	    ++allow_keys;		/* no mapping for nchar, but keys */
740 	    c = plain_vgetc();		/* get next character */
741 	    LANGMAP_ADJUST(c, TRUE);
742 	    --no_mapping;
743 	    --allow_keys;
744 #ifdef FEAT_CMDL_INFO
745 	    need_flushbuf |= add_to_showcmd(c);
746 #endif
747 	    goto getcount;		/* jump back */
748 	}
749     }
750 
751 #ifdef FEAT_AUTOCMD
752     if (c == K_CURSORHOLD)
753     {
754 	/* Save the count values so that ca.opcount and ca.count0 are exactly
755 	 * the same when coming back here after handling K_CURSORHOLD. */
756 	oap->prev_opcount = ca.opcount;
757 	oap->prev_count0 = ca.count0;
758     }
759     else
760 #endif
761 	if (ca.opcount != 0)
762     {
763 	/*
764 	 * If we're in the middle of an operator (including after entering a
765 	 * yank buffer with '"') AND we had a count before the operator, then
766 	 * that count overrides the current value of ca.count0.
767 	 * What this means effectively, is that commands like "3dw" get turned
768 	 * into "d3w" which makes things fall into place pretty neatly.
769 	 * If you give a count before AND after the operator, they are
770 	 * multiplied.
771 	 */
772 	if (ca.count0)
773 	    ca.count0 *= ca.opcount;
774 	else
775 	    ca.count0 = ca.opcount;
776     }
777 
778     /*
779      * Always remember the count.  It will be set to zero (on the next call,
780      * above) when there is no pending operator.
781      * When called from main(), save the count for use by the "count" built-in
782      * variable.
783      */
784     ca.opcount = ca.count0;
785     ca.count1 = (ca.count0 == 0 ? 1 : ca.count0);
786 
787 #ifdef FEAT_EVAL
788     /*
789      * Only set v:count when called from main() and not a stuffed command.
790      * Do set it for redo.
791      */
792     if (toplevel && readbuf1_empty())
793 	set_vcount(ca.count0, ca.count1, set_prevcount);
794 #endif
795 
796     /*
797      * Find the command character in the table of commands.
798      * For CTRL-W we already got nchar when looking for a count.
799      */
800     if (ctrl_w)
801     {
802 	ca.nchar = c;
803 	ca.cmdchar = Ctrl_W;
804     }
805     else
806 	ca.cmdchar = c;
807     idx = find_command(ca.cmdchar);
808     if (idx < 0)
809     {
810 	/* Not a known command: beep. */
811 	clearopbeep(oap);
812 	goto normal_end;
813     }
814 
815     if (text_locked() && (nv_cmds[idx].cmd_flags & NV_NCW))
816     {
817 	/* This command is not allowed while editing a cmdline: beep. */
818 	clearopbeep(oap);
819 	text_locked_msg();
820 	goto normal_end;
821     }
822 #ifdef FEAT_AUTOCMD
823     if ((nv_cmds[idx].cmd_flags & NV_NCW) && curbuf_locked())
824 	goto normal_end;
825 #endif
826 
827     /*
828      * In Visual/Select mode, a few keys are handled in a special way.
829      */
830     if (VIsual_active)
831     {
832 	/* when 'keymodel' contains "stopsel" may stop Select/Visual mode */
833 	if (km_stopsel
834 		&& (nv_cmds[idx].cmd_flags & NV_STS)
835 		&& !(mod_mask & MOD_MASK_SHIFT))
836 	{
837 	    end_visual_mode();
838 	    redraw_curbuf_later(INVERTED);
839 	}
840 
841 	/* Keys that work different when 'keymodel' contains "startsel" */
842 	if (km_startsel)
843 	{
844 	    if (nv_cmds[idx].cmd_flags & NV_SS)
845 	    {
846 		unshift_special(&ca);
847 		idx = find_command(ca.cmdchar);
848 		if (idx < 0)
849 		{
850 		    /* Just in case */
851 		    clearopbeep(oap);
852 		    goto normal_end;
853 		}
854 	    }
855 	    else if ((nv_cmds[idx].cmd_flags & NV_SSS)
856 					       && (mod_mask & MOD_MASK_SHIFT))
857 	    {
858 		mod_mask &= ~MOD_MASK_SHIFT;
859 	    }
860 	}
861     }
862 
863 #ifdef FEAT_RIGHTLEFT
864     if (curwin->w_p_rl && KeyTyped && !KeyStuffed
865 					  && (nv_cmds[idx].cmd_flags & NV_RL))
866     {
867 	/* Invert horizontal movements and operations.  Only when typed by the
868 	 * user directly, not when the result of a mapping or "x" translated
869 	 * to "dl". */
870 	switch (ca.cmdchar)
871 	{
872 	    case 'l':	    ca.cmdchar = 'h'; break;
873 	    case K_RIGHT:   ca.cmdchar = K_LEFT; break;
874 	    case K_S_RIGHT: ca.cmdchar = K_S_LEFT; break;
875 	    case K_C_RIGHT: ca.cmdchar = K_C_LEFT; break;
876 	    case 'h':	    ca.cmdchar = 'l'; break;
877 	    case K_LEFT:    ca.cmdchar = K_RIGHT; break;
878 	    case K_S_LEFT:  ca.cmdchar = K_S_RIGHT; break;
879 	    case K_C_LEFT:  ca.cmdchar = K_C_RIGHT; break;
880 	    case '>':	    ca.cmdchar = '<'; break;
881 	    case '<':	    ca.cmdchar = '>'; break;
882 	}
883 	idx = find_command(ca.cmdchar);
884     }
885 #endif
886 
887     /*
888      * Get an additional character if we need one.
889      */
890     if ((nv_cmds[idx].cmd_flags & NV_NCH)
891 	    && (((nv_cmds[idx].cmd_flags & NV_NCH_NOP) == NV_NCH_NOP
892 		    && oap->op_type == OP_NOP)
893 		|| (nv_cmds[idx].cmd_flags & NV_NCH_ALW) == NV_NCH_ALW
894 		|| (ca.cmdchar == 'q'
895 		    && oap->op_type == OP_NOP
896 		    && !Recording
897 		    && !Exec_reg)
898 		|| ((ca.cmdchar == 'a' || ca.cmdchar == 'i')
899 		    && (oap->op_type != OP_NOP || VIsual_active))))
900     {
901 	int	*cp;
902 	int	repl = FALSE;	/* get character for replace mode */
903 	int	lit = FALSE;	/* get extra character literally */
904 	int	langmap_active = FALSE;    /* using :lmap mappings */
905 	int	lang;		/* getting a text character */
906 #ifdef USE_IM_CONTROL
907 	int	save_smd;	/* saved value of p_smd */
908 #endif
909 
910 	++no_mapping;
911 	++allow_keys;		/* no mapping for nchar, but allow key codes */
912 #ifdef FEAT_AUTOCMD
913 	/* Don't generate a CursorHold event here, most commands can't handle
914 	 * it, e.g., nv_replace(), nv_csearch(). */
915 	did_cursorhold = TRUE;
916 #endif
917 	if (ca.cmdchar == 'g')
918 	{
919 	    /*
920 	     * For 'g' get the next character now, so that we can check for
921 	     * "gr", "g'" and "g`".
922 	     */
923 	    ca.nchar = plain_vgetc();
924 	    LANGMAP_ADJUST(ca.nchar, TRUE);
925 #ifdef FEAT_CMDL_INFO
926 	    need_flushbuf |= add_to_showcmd(ca.nchar);
927 #endif
928 	    if (ca.nchar == 'r' || ca.nchar == '\'' || ca.nchar == '`'
929 						       || ca.nchar == Ctrl_BSL)
930 	    {
931 		cp = &ca.extra_char;	/* need to get a third character */
932 		if (ca.nchar != 'r')
933 		    lit = TRUE;			/* get it literally */
934 		else
935 		    repl = TRUE;		/* get it in replace mode */
936 	    }
937 	    else
938 		cp = NULL;		/* no third character needed */
939 	}
940 	else
941 	{
942 	    if (ca.cmdchar == 'r')		/* get it in replace mode */
943 		repl = TRUE;
944 	    cp = &ca.nchar;
945 	}
946 	lang = (repl || (nv_cmds[idx].cmd_flags & NV_LANG));
947 
948 	/*
949 	 * Get a second or third character.
950 	 */
951 	if (cp != NULL)
952 	{
953 #ifdef CURSOR_SHAPE
954 	    if (repl)
955 	    {
956 		State = REPLACE;	/* pretend Replace mode */
957 		ui_cursor_shape();	/* show different cursor shape */
958 	    }
959 #endif
960 	    if (lang && curbuf->b_p_iminsert == B_IMODE_LMAP)
961 	    {
962 		/* Allow mappings defined with ":lmap". */
963 		--no_mapping;
964 		--allow_keys;
965 		if (repl)
966 		    State = LREPLACE;
967 		else
968 		    State = LANGMAP;
969 		langmap_active = TRUE;
970 	    }
971 #ifdef USE_IM_CONTROL
972 	    save_smd = p_smd;
973 	    p_smd = FALSE;	/* Don't let the IM code show the mode here */
974 	    if (lang && curbuf->b_p_iminsert == B_IMODE_IM)
975 		im_set_active(TRUE);
976 #endif
977 
978 	    *cp = plain_vgetc();
979 
980 	    if (langmap_active)
981 	    {
982 		/* Undo the decrement done above */
983 		++no_mapping;
984 		++allow_keys;
985 		State = NORMAL_BUSY;
986 	    }
987 #ifdef USE_IM_CONTROL
988 	    if (lang)
989 	    {
990 		if (curbuf->b_p_iminsert != B_IMODE_LMAP)
991 		    im_save_status(&curbuf->b_p_iminsert);
992 		im_set_active(FALSE);
993 	    }
994 	    p_smd = save_smd;
995 #endif
996 #ifdef CURSOR_SHAPE
997 	    State = NORMAL_BUSY;
998 #endif
999 #ifdef FEAT_CMDL_INFO
1000 	    need_flushbuf |= add_to_showcmd(*cp);
1001 #endif
1002 
1003 	    if (!lit)
1004 	    {
1005 #ifdef FEAT_DIGRAPHS
1006 		/* Typing CTRL-K gets a digraph. */
1007 		if (*cp == Ctrl_K
1008 			&& ((nv_cmds[idx].cmd_flags & NV_LANG)
1009 			    || cp == &ca.extra_char)
1010 			&& vim_strchr(p_cpo, CPO_DIGRAPH) == NULL)
1011 		{
1012 		    c = get_digraph(FALSE);
1013 		    if (c > 0)
1014 		    {
1015 			*cp = c;
1016 # ifdef FEAT_CMDL_INFO
1017 			/* Guessing how to update showcmd here... */
1018 			del_from_showcmd(3);
1019 			need_flushbuf |= add_to_showcmd(*cp);
1020 # endif
1021 		    }
1022 		}
1023 #endif
1024 
1025 		/* adjust chars > 127, except after "tTfFr" commands */
1026 		LANGMAP_ADJUST(*cp, !lang);
1027 #ifdef FEAT_RIGHTLEFT
1028 		/* adjust Hebrew mapped char */
1029 		if (p_hkmap && lang && KeyTyped)
1030 		    *cp = hkmap(*cp);
1031 # ifdef FEAT_FKMAP
1032 		/* adjust Farsi mapped char */
1033 		if (p_fkmap && lang && KeyTyped)
1034 		    *cp = fkmap(*cp);
1035 # endif
1036 #endif
1037 	    }
1038 
1039 	    /*
1040 	     * When the next character is CTRL-\ a following CTRL-N means the
1041 	     * command is aborted and we go to Normal mode.
1042 	     */
1043 	    if (cp == &ca.extra_char
1044 		    && ca.nchar == Ctrl_BSL
1045 		    && (ca.extra_char == Ctrl_N || ca.extra_char == Ctrl_G))
1046 	    {
1047 		ca.cmdchar = Ctrl_BSL;
1048 		ca.nchar = ca.extra_char;
1049 		idx = find_command(ca.cmdchar);
1050 	    }
1051 	    else if ((ca.nchar == 'n' || ca.nchar == 'N') && ca.cmdchar == 'g')
1052 		ca.oap->op_type = get_op_type(*cp, NUL);
1053 	    else if (*cp == Ctrl_BSL)
1054 	    {
1055 		long towait = (p_ttm >= 0 ? p_ttm : p_tm);
1056 
1057 		/* There is a busy wait here when typing "f<C-\>" and then
1058 		 * something different from CTRL-N.  Can't be avoided. */
1059 		while ((c = vpeekc()) <= 0 && towait > 0L)
1060 		{
1061 		    do_sleep(towait > 50L ? 50L : towait);
1062 		    towait -= 50L;
1063 		}
1064 		if (c > 0)
1065 		{
1066 		    c = plain_vgetc();
1067 		    if (c != Ctrl_N && c != Ctrl_G)
1068 			vungetc(c);
1069 		    else
1070 		    {
1071 			ca.cmdchar = Ctrl_BSL;
1072 			ca.nchar = c;
1073 			idx = find_command(ca.cmdchar);
1074 		    }
1075 		}
1076 	    }
1077 
1078 #ifdef FEAT_MBYTE
1079 	    /* When getting a text character and the next character is a
1080 	     * multi-byte character, it could be a composing character.
1081 	     * However, don't wait for it to arrive. Also, do enable mapping,
1082 	     * because if it's put back with vungetc() it's too late to apply
1083 	     * mapping. */
1084 	    --no_mapping;
1085 	    while (enc_utf8 && lang && (c = vpeekc()) > 0
1086 				 && (c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1))
1087 	    {
1088 		c = plain_vgetc();
1089 		if (!utf_iscomposing(c))
1090 		{
1091 		    vungetc(c);		/* it wasn't, put it back */
1092 		    break;
1093 		}
1094 		else if (ca.ncharC1 == 0)
1095 		    ca.ncharC1 = c;
1096 		else
1097 		    ca.ncharC2 = c;
1098 	    }
1099 	    ++no_mapping;
1100 #endif
1101 	}
1102 	--no_mapping;
1103 	--allow_keys;
1104     }
1105 
1106 #ifdef FEAT_CMDL_INFO
1107     /*
1108      * Flush the showcmd characters onto the screen so we can see them while
1109      * the command is being executed.  Only do this when the shown command was
1110      * actually displayed, otherwise this will slow down a lot when executing
1111      * mappings.
1112      */
1113     if (need_flushbuf)
1114 	out_flush();
1115 #endif
1116 #ifdef FEAT_AUTOCMD
1117     if (ca.cmdchar != K_IGNORE)
1118 	did_cursorhold = FALSE;
1119 #endif
1120 
1121     State = NORMAL;
1122 
1123     if (ca.nchar == ESC)
1124     {
1125 	clearop(oap);
1126 	if (restart_edit == 0 && goto_im())
1127 	    restart_edit = 'a';
1128 	goto normal_end;
1129     }
1130 
1131     if (ca.cmdchar != K_IGNORE)
1132     {
1133 	msg_didout = FALSE;    /* don't scroll screen up for normal command */
1134 	msg_col = 0;
1135     }
1136 
1137     old_pos = curwin->w_cursor;		/* remember where cursor was */
1138 
1139     /* When 'keymodel' contains "startsel" some keys start Select/Visual
1140      * mode. */
1141     if (!VIsual_active && km_startsel)
1142     {
1143 	if (nv_cmds[idx].cmd_flags & NV_SS)
1144 	{
1145 	    start_selection();
1146 	    unshift_special(&ca);
1147 	    idx = find_command(ca.cmdchar);
1148 	}
1149 	else if ((nv_cmds[idx].cmd_flags & NV_SSS)
1150 					   && (mod_mask & MOD_MASK_SHIFT))
1151 	{
1152 	    start_selection();
1153 	    mod_mask &= ~MOD_MASK_SHIFT;
1154 	}
1155     }
1156 
1157     /*
1158      * Execute the command!
1159      * Call the command function found in the commands table.
1160      */
1161     ca.arg = nv_cmds[idx].cmd_arg;
1162     (nv_cmds[idx].cmd_func)(&ca);
1163 
1164     /*
1165      * If we didn't start or finish an operator, reset oap->regname, unless we
1166      * need it later.
1167      */
1168     if (!finish_op
1169 	    && !oap->op_type
1170 	    && (idx < 0 || !(nv_cmds[idx].cmd_flags & NV_KEEPREG)))
1171     {
1172 	clearop(oap);
1173 #ifdef FEAT_EVAL
1174 	{
1175 	    int regname = 0;
1176 
1177 	    /* Adjust the register according to 'clipboard', so that when
1178 	     * "unnamed" is present it becomes '*' or '+' instead of '"'. */
1179 # ifdef FEAT_CLIPBOARD
1180 	    adjust_clip_reg(&regname);
1181 # endif
1182 	    set_reg_var(regname);
1183 	}
1184 #endif
1185     }
1186 
1187     /* Get the length of mapped chars again after typing a count, second
1188      * character or "z333<cr>". */
1189     if (old_mapped_len > 0)
1190 	old_mapped_len = typebuf_maplen();
1191 
1192     /*
1193      * If an operation is pending, handle it...
1194      */
1195     do_pending_operator(&ca, old_col, FALSE);
1196 
1197     /*
1198      * Wait for a moment when a message is displayed that will be overwritten
1199      * by the mode message.
1200      * In Visual mode and with "^O" in Insert mode, a short message will be
1201      * overwritten by the mode message.  Wait a bit, until a key is hit.
1202      * In Visual mode, it's more important to keep the Visual area updated
1203      * than keeping a message (e.g. from a /pat search).
1204      * Only do this if the command was typed, not from a mapping.
1205      * Don't wait when emsg_silent is non-zero.
1206      * Also wait a bit after an error message, e.g. for "^O:".
1207      * Don't redraw the screen, it would remove the message.
1208      */
1209     if (       ((p_smd
1210 		    && msg_silent == 0
1211 		    && (restart_edit != 0
1212 			|| (VIsual_active
1213 			    && old_pos.lnum == curwin->w_cursor.lnum
1214 			    && old_pos.col == curwin->w_cursor.col)
1215 		       )
1216 		    && (clear_cmdline
1217 			|| redraw_cmdline)
1218 		    && (msg_didout || (msg_didany && msg_scroll))
1219 		    && !msg_nowait
1220 		    && KeyTyped)
1221 		|| (restart_edit != 0
1222 		    && !VIsual_active
1223 		    && (msg_scroll
1224 			|| emsg_on_display)))
1225 	    && oap->regname == 0
1226 	    && !(ca.retval & CA_COMMAND_BUSY)
1227 	    && stuff_empty()
1228 	    && typebuf_typed()
1229 	    && emsg_silent == 0
1230 	    && !did_wait_return
1231 	    && oap->op_type == OP_NOP)
1232     {
1233 	int	save_State = State;
1234 
1235 	/* Draw the cursor with the right shape here */
1236 	if (restart_edit != 0)
1237 	    State = INSERT;
1238 
1239 	/* If need to redraw, and there is a "keep_msg", redraw before the
1240 	 * delay */
1241 	if (must_redraw && keep_msg != NULL && !emsg_on_display)
1242 	{
1243 	    char_u	*kmsg;
1244 
1245 	    kmsg = keep_msg;
1246 	    keep_msg = NULL;
1247 	    /* showmode() will clear keep_msg, but we want to use it anyway */
1248 	    update_screen(0);
1249 	    /* now reset it, otherwise it's put in the history again */
1250 	    keep_msg = kmsg;
1251 	    msg_attr(kmsg, keep_msg_attr);
1252 	    vim_free(kmsg);
1253 	}
1254 	setcursor();
1255 	cursor_on();
1256 	out_flush();
1257 	if (msg_scroll || emsg_on_display)
1258 	    ui_delay(1000L, TRUE);	/* wait at least one second */
1259 	ui_delay(3000L, FALSE);		/* wait up to three seconds */
1260 	State = save_State;
1261 
1262 	msg_scroll = FALSE;
1263 	emsg_on_display = FALSE;
1264     }
1265 
1266     /*
1267      * Finish up after executing a Normal mode command.
1268      */
1269 normal_end:
1270 
1271     msg_nowait = FALSE;
1272 
1273     /* Reset finish_op, in case it was set */
1274 #ifdef CURSOR_SHAPE
1275     c = finish_op;
1276 #endif
1277     finish_op = FALSE;
1278 #ifdef CURSOR_SHAPE
1279     /* Redraw the cursor with another shape, if we were in Operator-pending
1280      * mode or did a replace command. */
1281     if (c || ca.cmdchar == 'r')
1282     {
1283 	ui_cursor_shape();		/* may show different cursor shape */
1284 # ifdef FEAT_MOUSESHAPE
1285 	update_mouseshape(-1);
1286 # endif
1287     }
1288 #endif
1289 
1290 #ifdef FEAT_CMDL_INFO
1291     if (oap->op_type == OP_NOP && oap->regname == 0
1292 # ifdef FEAT_AUTOCMD
1293 	    && ca.cmdchar != K_CURSORHOLD
1294 # endif
1295 	    )
1296 	clear_showcmd();
1297 #endif
1298 
1299     checkpcmark();		/* check if we moved since setting pcmark */
1300     vim_free(ca.searchbuf);
1301 
1302 #ifdef FEAT_MBYTE
1303     if (has_mbyte)
1304 	mb_adjust_cursor();
1305 #endif
1306 
1307 #ifdef FEAT_SCROLLBIND
1308     if (curwin->w_p_scb && toplevel)
1309     {
1310 	validate_cursor();	/* may need to update w_leftcol */
1311 	do_check_scrollbind(TRUE);
1312     }
1313 #endif
1314 
1315 #ifdef FEAT_CURSORBIND
1316     if (curwin->w_p_crb && toplevel)
1317     {
1318 	validate_cursor();	/* may need to update w_leftcol */
1319 	do_check_cursorbind();
1320     }
1321 #endif
1322 
1323     /*
1324      * May restart edit(), if we got here with CTRL-O in Insert mode (but not
1325      * if still inside a mapping that started in Visual mode).
1326      * May switch from Visual to Select mode after CTRL-O command.
1327      */
1328     if (       oap->op_type == OP_NOP
1329 	    && ((restart_edit != 0 && !VIsual_active && old_mapped_len == 0)
1330 		|| restart_VIsual_select == 1)
1331 	    && !(ca.retval & CA_COMMAND_BUSY)
1332 	    && stuff_empty()
1333 	    && oap->regname == 0)
1334     {
1335 	if (restart_VIsual_select == 1)
1336 	{
1337 	    VIsual_select = TRUE;
1338 	    showmode();
1339 	    restart_VIsual_select = 0;
1340 	}
1341 	if (restart_edit != 0 && !VIsual_active && old_mapped_len == 0)
1342 	    (void)edit(restart_edit, FALSE, 1L);
1343     }
1344 
1345     if (restart_VIsual_select == 2)
1346 	restart_VIsual_select = 1;
1347 
1348     /* Save count before an operator for next time. */
1349     opcount = ca.opcount;
1350 }
1351 
1352 #ifdef FEAT_EVAL
1353 /*
1354  * Set v:count and v:count1 according to "cap".
1355  * Set v:prevcount only when "set_prevcount" is TRUE.
1356  */
1357     static void
1358 set_vcount_ca(cap, set_prevcount)
1359     cmdarg_T	*cap;
1360     int		*set_prevcount;
1361 {
1362     long count = cap->count0;
1363 
1364     /* multiply with cap->opcount the same way as above */
1365     if (cap->opcount != 0)
1366 	count = cap->opcount * (count == 0 ? 1 : count);
1367     set_vcount(count, count == 0 ? 1 : count, *set_prevcount);
1368     *set_prevcount = FALSE;  /* only set v:prevcount once */
1369 }
1370 #endif
1371 
1372 /*
1373  * Handle an operator after visual mode or when the movement is finished
1374  */
1375     void
1376 do_pending_operator(cap, old_col, gui_yank)
1377     cmdarg_T	*cap;
1378     int		old_col;
1379     int		gui_yank;
1380 {
1381     oparg_T	*oap = cap->oap;
1382     pos_T	old_cursor;
1383     int		empty_region_error;
1384     int		restart_edit_save;
1385 #ifdef FEAT_LINEBREAK
1386     int		lbr_saved = curwin->w_p_lbr;
1387 #endif
1388 
1389     /* The visual area is remembered for redo */
1390     static int	    redo_VIsual_mode = NUL; /* 'v', 'V', or Ctrl-V */
1391     static linenr_T redo_VIsual_line_count; /* number of lines */
1392     static colnr_T  redo_VIsual_vcol;	    /* number of cols or end column */
1393     static long	    redo_VIsual_count;	    /* count for Visual operator */
1394     static int	    redo_VIsual_arg;	    /* extra argument */
1395 #ifdef FEAT_VIRTUALEDIT
1396     int		    include_line_break = FALSE;
1397 #endif
1398 
1399 #if defined(FEAT_CLIPBOARD)
1400     /*
1401      * Yank the visual area into the GUI selection register before we operate
1402      * on it and lose it forever.
1403      * Don't do it if a specific register was specified, so that ""x"*P works.
1404      * This could call do_pending_operator() recursively, but that's OK
1405      * because gui_yank will be TRUE for the nested call.
1406      */
1407     if ((clip_star.available || clip_plus.available)
1408 	    && oap->op_type != OP_NOP
1409 	    && !gui_yank
1410 	    && VIsual_active
1411 	    && !redo_VIsual_busy
1412 	    && oap->regname == 0)
1413 	clip_auto_select();
1414 #endif
1415     old_cursor = curwin->w_cursor;
1416 
1417     /*
1418      * If an operation is pending, handle it...
1419      */
1420     if ((finish_op || VIsual_active) && oap->op_type != OP_NOP)
1421     {
1422 #ifdef FEAT_LINEBREAK
1423 	/* Avoid a problem with unwanted linebreaks in block mode. */
1424 	if (curwin->w_p_lbr)
1425 	    curwin->w_valid &= ~VALID_VIRTCOL;
1426 	curwin->w_p_lbr = FALSE;
1427 #endif
1428 	oap->is_VIsual = VIsual_active;
1429 	if (oap->motion_force == 'V')
1430 	    oap->motion_type = MLINE;
1431 	else if (oap->motion_force == 'v')
1432 	{
1433 	    /* If the motion was linewise, "inclusive" will not have been set.
1434 	     * Use "exclusive" to be consistent.  Makes "dvj" work nice. */
1435 	    if (oap->motion_type == MLINE)
1436 		oap->inclusive = FALSE;
1437 	    /* If the motion already was characterwise, toggle "inclusive" */
1438 	    else if (oap->motion_type == MCHAR)
1439 		oap->inclusive = !oap->inclusive;
1440 	    oap->motion_type = MCHAR;
1441 	}
1442 	else if (oap->motion_force == Ctrl_V)
1443 	{
1444 	    /* Change line- or characterwise motion into Visual block mode. */
1445 	    VIsual_active = TRUE;
1446 	    VIsual = oap->start;
1447 	    VIsual_mode = Ctrl_V;
1448 	    VIsual_select = FALSE;
1449 	    VIsual_reselect = FALSE;
1450 	}
1451 
1452 	/* Only redo yank when 'y' flag is in 'cpoptions'. */
1453 	/* Never redo "zf" (define fold). */
1454 	if ((vim_strchr(p_cpo, CPO_YANK) != NULL || oap->op_type != OP_YANK)
1455 		&& ((!VIsual_active || oap->motion_force)
1456 		    /* Also redo Operator-pending Visual mode mappings */
1457 		    || (VIsual_active && cap->cmdchar == ':'
1458 						 && oap->op_type != OP_COLON))
1459 		&& cap->cmdchar != 'D'
1460 #ifdef FEAT_FOLDING
1461 		&& oap->op_type != OP_FOLD
1462 		&& oap->op_type != OP_FOLDOPEN
1463 		&& oap->op_type != OP_FOLDOPENREC
1464 		&& oap->op_type != OP_FOLDCLOSE
1465 		&& oap->op_type != OP_FOLDCLOSEREC
1466 		&& oap->op_type != OP_FOLDDEL
1467 		&& oap->op_type != OP_FOLDDELREC
1468 #endif
1469 		)
1470 	{
1471 	    prep_redo(oap->regname, cap->count0,
1472 		    get_op_char(oap->op_type), get_extra_op_char(oap->op_type),
1473 		    oap->motion_force, cap->cmdchar, cap->nchar);
1474 	    if (cap->cmdchar == '/' || cap->cmdchar == '?') /* was a search */
1475 	    {
1476 		/*
1477 		 * If 'cpoptions' does not contain 'r', insert the search
1478 		 * pattern to really repeat the same command.
1479 		 */
1480 		if (vim_strchr(p_cpo, CPO_REDO) == NULL)
1481 		    AppendToRedobuffLit(cap->searchbuf, -1);
1482 		AppendToRedobuff(NL_STR);
1483 	    }
1484 	    else if (cap->cmdchar == ':')
1485 	    {
1486 		/* do_cmdline() has stored the first typed line in
1487 		 * "repeat_cmdline".  When several lines are typed repeating
1488 		 * won't be possible. */
1489 		if (repeat_cmdline == NULL)
1490 		    ResetRedobuff();
1491 		else
1492 		{
1493 		    AppendToRedobuffLit(repeat_cmdline, -1);
1494 		    AppendToRedobuff(NL_STR);
1495 		    vim_free(repeat_cmdline);
1496 		    repeat_cmdline = NULL;
1497 		}
1498 	    }
1499 	}
1500 
1501 	if (redo_VIsual_busy)
1502 	{
1503 	    /* Redo of an operation on a Visual area. Use the same size from
1504 	     * redo_VIsual_line_count and redo_VIsual_vcol. */
1505 	    oap->start = curwin->w_cursor;
1506 	    curwin->w_cursor.lnum += redo_VIsual_line_count - 1;
1507 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
1508 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
1509 	    VIsual_mode = redo_VIsual_mode;
1510 	    if (redo_VIsual_vcol == MAXCOL || VIsual_mode == 'v')
1511 	    {
1512 		if (VIsual_mode == 'v')
1513 		{
1514 		    if (redo_VIsual_line_count <= 1)
1515 		    {
1516 			validate_virtcol();
1517 			curwin->w_curswant =
1518 				     curwin->w_virtcol + redo_VIsual_vcol - 1;
1519 		    }
1520 		    else
1521 			curwin->w_curswant = redo_VIsual_vcol;
1522 		}
1523 		else
1524 		{
1525 		    curwin->w_curswant = MAXCOL;
1526 		}
1527 		coladvance(curwin->w_curswant);
1528 	    }
1529 	    cap->count0 = redo_VIsual_count;
1530 	    if (redo_VIsual_count != 0)
1531 		cap->count1 = redo_VIsual_count;
1532 	    else
1533 		cap->count1 = 1;
1534 	}
1535 	else if (VIsual_active)
1536 	{
1537 	    if (!gui_yank)
1538 	    {
1539 		/* Save the current VIsual area for '< and '> marks, and "gv" */
1540 		curbuf->b_visual.vi_start = VIsual;
1541 		curbuf->b_visual.vi_end = curwin->w_cursor;
1542 		curbuf->b_visual.vi_mode = VIsual_mode;
1543 		if (VIsual_mode_orig != NUL)
1544 		{
1545 		    curbuf->b_visual.vi_mode = VIsual_mode_orig;
1546 		    VIsual_mode_orig = NUL;
1547 		}
1548 		curbuf->b_visual.vi_curswant = curwin->w_curswant;
1549 # ifdef FEAT_EVAL
1550 		curbuf->b_visual_mode_eval = VIsual_mode;
1551 # endif
1552 	    }
1553 
1554 	    /* In Select mode, a linewise selection is operated upon like a
1555 	     * characterwise selection.
1556 	     * Special case: gH<Del> deletes the last line. */
1557 	    if (VIsual_select && VIsual_mode == 'V'
1558 					    && cap->oap->op_type != OP_DELETE)
1559 	    {
1560 		if (lt(VIsual, curwin->w_cursor))
1561 		{
1562 		    VIsual.col = 0;
1563 		    curwin->w_cursor.col =
1564 			       (colnr_T)STRLEN(ml_get(curwin->w_cursor.lnum));
1565 		}
1566 		else
1567 		{
1568 		    curwin->w_cursor.col = 0;
1569 		    VIsual.col = (colnr_T)STRLEN(ml_get(VIsual.lnum));
1570 		}
1571 		VIsual_mode = 'v';
1572 	    }
1573 	    /* If 'selection' is "exclusive", backup one character for
1574 	     * charwise selections. */
1575 	    else if (VIsual_mode == 'v')
1576 	    {
1577 # ifdef FEAT_VIRTUALEDIT
1578 		include_line_break =
1579 # endif
1580 		    unadjust_for_sel();
1581 	    }
1582 
1583 	    oap->start = VIsual;
1584 	    if (VIsual_mode == 'V')
1585 		oap->start.col = 0;
1586 	}
1587 
1588 	/*
1589 	 * Set oap->start to the first position of the operated text, oap->end
1590 	 * to the end of the operated text.  w_cursor is equal to oap->start.
1591 	 */
1592 	if (lt(oap->start, curwin->w_cursor))
1593 	{
1594 #ifdef FEAT_FOLDING
1595 	    /* Include folded lines completely. */
1596 	    if (!VIsual_active)
1597 	    {
1598 		if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL))
1599 		    oap->start.col = 0;
1600 		if (hasFolding(curwin->w_cursor.lnum, NULL,
1601 						      &curwin->w_cursor.lnum))
1602 		    curwin->w_cursor.col = (colnr_T)STRLEN(ml_get_curline());
1603 	    }
1604 #endif
1605 	    oap->end = curwin->w_cursor;
1606 	    curwin->w_cursor = oap->start;
1607 
1608 	    /* w_virtcol may have been updated; if the cursor goes back to its
1609 	     * previous position w_virtcol becomes invalid and isn't updated
1610 	     * automatically. */
1611 	    curwin->w_valid &= ~VALID_VIRTCOL;
1612 	}
1613 	else
1614 	{
1615 #ifdef FEAT_FOLDING
1616 	    /* Include folded lines completely. */
1617 	    if (!VIsual_active && oap->motion_type == MLINE)
1618 	    {
1619 		if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum,
1620 									NULL))
1621 		    curwin->w_cursor.col = 0;
1622 		if (hasFolding(oap->start.lnum, NULL, &oap->start.lnum))
1623 		    oap->start.col = (colnr_T)STRLEN(ml_get(oap->start.lnum));
1624 	    }
1625 #endif
1626 	    oap->end = oap->start;
1627 	    oap->start = curwin->w_cursor;
1628 	}
1629 
1630 	oap->line_count = oap->end.lnum - oap->start.lnum + 1;
1631 
1632 #ifdef FEAT_VIRTUALEDIT
1633 	/* Set "virtual_op" before resetting VIsual_active. */
1634 	virtual_op = virtual_active();
1635 #endif
1636 
1637 	if (VIsual_active || redo_VIsual_busy)
1638 	{
1639 	    get_op_vcol(oap, redo_VIsual_vcol, TRUE);
1640 
1641 	    if (!redo_VIsual_busy && !gui_yank)
1642 	    {
1643 		/*
1644 		 * Prepare to reselect and redo Visual: this is based on the
1645 		 * size of the Visual text
1646 		 */
1647 		resel_VIsual_mode = VIsual_mode;
1648 		if (curwin->w_curswant == MAXCOL)
1649 		    resel_VIsual_vcol = MAXCOL;
1650 		else
1651 		{
1652 		    if (VIsual_mode != Ctrl_V)
1653 			getvvcol(curwin, &(oap->end),
1654 						  NULL, NULL, &oap->end_vcol);
1655 		    if (VIsual_mode == Ctrl_V || oap->line_count <= 1)
1656 		    {
1657 			if (VIsual_mode != Ctrl_V)
1658 			    getvvcol(curwin, &(oap->start),
1659 						&oap->start_vcol, NULL, NULL);
1660 			resel_VIsual_vcol = oap->end_vcol - oap->start_vcol + 1;
1661 		    }
1662 		    else
1663 			resel_VIsual_vcol = oap->end_vcol;
1664 		}
1665 		resel_VIsual_line_count = oap->line_count;
1666 	    }
1667 
1668 	    /* can't redo yank (unless 'y' is in 'cpoptions') and ":" */
1669 	    if ((vim_strchr(p_cpo, CPO_YANK) != NULL || oap->op_type != OP_YANK)
1670 		    && oap->op_type != OP_COLON
1671 #ifdef FEAT_FOLDING
1672 		    && oap->op_type != OP_FOLD
1673 		    && oap->op_type != OP_FOLDOPEN
1674 		    && oap->op_type != OP_FOLDOPENREC
1675 		    && oap->op_type != OP_FOLDCLOSE
1676 		    && oap->op_type != OP_FOLDCLOSEREC
1677 		    && oap->op_type != OP_FOLDDEL
1678 		    && oap->op_type != OP_FOLDDELREC
1679 #endif
1680 		    && oap->motion_force == NUL
1681 		    )
1682 	    {
1683 		/* Prepare for redoing.  Only use the nchar field for "r",
1684 		 * otherwise it might be the second char of the operator. */
1685 		if (cap->cmdchar == 'g' && (cap->nchar == 'n'
1686 							|| cap->nchar == 'N'))
1687 		    prep_redo(oap->regname, cap->count0,
1688 			    get_op_char(oap->op_type), get_extra_op_char(oap->op_type),
1689 			    oap->motion_force, cap->cmdchar, cap->nchar);
1690 		else if (cap->cmdchar != ':')
1691 		    prep_redo(oap->regname, 0L, NUL, 'v',
1692 					get_op_char(oap->op_type),
1693 					get_extra_op_char(oap->op_type),
1694 					oap->op_type == OP_REPLACE
1695 							  ? cap->nchar : NUL);
1696 		if (!redo_VIsual_busy)
1697 		{
1698 		    redo_VIsual_mode = resel_VIsual_mode;
1699 		    redo_VIsual_vcol = resel_VIsual_vcol;
1700 		    redo_VIsual_line_count = resel_VIsual_line_count;
1701 		    redo_VIsual_count = cap->count0;
1702 		    redo_VIsual_arg = cap->arg;
1703 		}
1704 	    }
1705 
1706 	    /*
1707 	     * oap->inclusive defaults to TRUE.
1708 	     * If oap->end is on a NUL (empty line) oap->inclusive becomes
1709 	     * FALSE.  This makes "d}P" and "v}dP" work the same.
1710 	     */
1711 	    if (oap->motion_force == NUL || oap->motion_type == MLINE)
1712 		oap->inclusive = TRUE;
1713 	    if (VIsual_mode == 'V')
1714 		oap->motion_type = MLINE;
1715 	    else
1716 	    {
1717 		oap->motion_type = MCHAR;
1718 		if (VIsual_mode != Ctrl_V && *ml_get_pos(&(oap->end)) == NUL
1719 #ifdef FEAT_VIRTUALEDIT
1720 			&& (include_line_break || !virtual_op)
1721 #endif
1722 			)
1723 		{
1724 		    oap->inclusive = FALSE;
1725 		    /* Try to include the newline, unless it's an operator
1726 		     * that works on lines only. */
1727 		    if (*p_sel != 'o'
1728 			    && !op_on_lines(oap->op_type)
1729 			    && oap->end.lnum < curbuf->b_ml.ml_line_count)
1730 		    {
1731 			++oap->end.lnum;
1732 			oap->end.col = 0;
1733 #ifdef FEAT_VIRTUALEDIT
1734 			oap->end.coladd = 0;
1735 #endif
1736 			++oap->line_count;
1737 		    }
1738 		}
1739 	    }
1740 
1741 	    redo_VIsual_busy = FALSE;
1742 
1743 	    /*
1744 	     * Switch Visual off now, so screen updating does
1745 	     * not show inverted text when the screen is redrawn.
1746 	     * With OP_YANK and sometimes with OP_COLON and OP_FILTER there is
1747 	     * no screen redraw, so it is done here to remove the inverted
1748 	     * part.
1749 	     */
1750 	    if (!gui_yank)
1751 	    {
1752 		VIsual_active = FALSE;
1753 #ifdef FEAT_MOUSE
1754 		setmouse();
1755 		mouse_dragging = 0;
1756 #endif
1757 		may_clear_cmdline();
1758 		if ((oap->op_type == OP_YANK
1759 			    || oap->op_type == OP_COLON
1760 			    || oap->op_type == OP_FUNCTION
1761 			    || oap->op_type == OP_FILTER)
1762 			&& oap->motion_force == NUL)
1763 		{
1764 #ifdef FEAT_LINEBREAK
1765 		    /* make sure redrawing is correct */
1766 		    curwin->w_p_lbr = lbr_saved;
1767 #endif
1768 		    redraw_curbuf_later(INVERTED);
1769 		}
1770 	    }
1771 	}
1772 
1773 #ifdef FEAT_MBYTE
1774 	/* Include the trailing byte of a multi-byte char. */
1775 	if (has_mbyte && oap->inclusive)
1776 	{
1777 	    int		l;
1778 
1779 	    l = (*mb_ptr2len)(ml_get_pos(&oap->end));
1780 	    if (l > 1)
1781 		oap->end.col += l - 1;
1782 	}
1783 #endif
1784 	curwin->w_set_curswant = TRUE;
1785 
1786 	/*
1787 	 * oap->empty is set when start and end are the same.  The inclusive
1788 	 * flag affects this too, unless yanking and the end is on a NUL.
1789 	 */
1790 	oap->empty = (oap->motion_type == MCHAR
1791 		    && (!oap->inclusive
1792 			|| (oap->op_type == OP_YANK
1793 			    && gchar_pos(&oap->end) == NUL))
1794 		    && equalpos(oap->start, oap->end)
1795 #ifdef FEAT_VIRTUALEDIT
1796 		    && !(virtual_op && oap->start.coladd != oap->end.coladd)
1797 #endif
1798 		    );
1799 	/*
1800 	 * For delete, change and yank, it's an error to operate on an
1801 	 * empty region, when 'E' included in 'cpoptions' (Vi compatible).
1802 	 */
1803 	empty_region_error = (oap->empty
1804 				&& vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL);
1805 
1806 	/* Force a redraw when operating on an empty Visual region, when
1807 	 * 'modifiable is off or creating a fold. */
1808 	if (oap->is_VIsual && (oap->empty || !curbuf->b_p_ma
1809 #ifdef FEAT_FOLDING
1810 		    || oap->op_type == OP_FOLD
1811 #endif
1812 		    ))
1813 	{
1814 #ifdef FEAT_LINEBREAK
1815 	    curwin->w_p_lbr = lbr_saved;
1816 #endif
1817 	    redraw_curbuf_later(INVERTED);
1818 	}
1819 
1820 	/*
1821 	 * If the end of an operator is in column one while oap->motion_type
1822 	 * is MCHAR and oap->inclusive is FALSE, we put op_end after the last
1823 	 * character in the previous line. If op_start is on or before the
1824 	 * first non-blank in the line, the operator becomes linewise
1825 	 * (strange, but that's the way vi does it).
1826 	 */
1827 	if (	   oap->motion_type == MCHAR
1828 		&& oap->inclusive == FALSE
1829 		&& !(cap->retval & CA_NO_ADJ_OP_END)
1830 		&& oap->end.col == 0
1831 		&& (!oap->is_VIsual || *p_sel == 'o')
1832 		&& !oap->block_mode
1833 		&& oap->line_count > 1)
1834 	{
1835 	    oap->end_adjusted = TRUE;	    /* remember that we did this */
1836 	    --oap->line_count;
1837 	    --oap->end.lnum;
1838 	    if (inindent(0))
1839 		oap->motion_type = MLINE;
1840 	    else
1841 	    {
1842 		oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
1843 		if (oap->end.col)
1844 		{
1845 		    --oap->end.col;
1846 		    oap->inclusive = TRUE;
1847 		}
1848 	    }
1849 	}
1850 	else
1851 	    oap->end_adjusted = FALSE;
1852 
1853 	switch (oap->op_type)
1854 	{
1855 	case OP_LSHIFT:
1856 	case OP_RSHIFT:
1857 	    op_shift(oap, TRUE, oap->is_VIsual ? (int)cap->count1 : 1);
1858 	    auto_format(FALSE, TRUE);
1859 	    break;
1860 
1861 	case OP_JOIN_NS:
1862 	case OP_JOIN:
1863 	    if (oap->line_count < 2)
1864 		oap->line_count = 2;
1865 	    if (curwin->w_cursor.lnum + oap->line_count - 1 >
1866 						   curbuf->b_ml.ml_line_count)
1867 		beep_flush();
1868 	    else
1869 	    {
1870 		(void)do_join(oap->line_count, oap->op_type == OP_JOIN,
1871 							    TRUE, TRUE, TRUE);
1872 		auto_format(FALSE, TRUE);
1873 	    }
1874 	    break;
1875 
1876 	case OP_DELETE:
1877 	    VIsual_reselect = FALSE;	    /* don't reselect now */
1878 	    if (empty_region_error)
1879 	    {
1880 		vim_beep(BO_OPER);
1881 		CancelRedo();
1882 	    }
1883 	    else
1884 	    {
1885 		(void)op_delete(oap);
1886 		if (oap->motion_type == MLINE && has_format_option(FO_AUTO))
1887 		    u_save_cursor();	    /* cursor line wasn't saved yet */
1888 		auto_format(FALSE, TRUE);
1889 	    }
1890 	    break;
1891 
1892 	case OP_YANK:
1893 	    if (empty_region_error)
1894 	    {
1895 		if (!gui_yank)
1896 		{
1897 		    vim_beep(BO_OPER);
1898 		    CancelRedo();
1899 		}
1900 	    }
1901 	    else
1902 	    {
1903 #ifdef FEAT_LINEBREAK
1904 		curwin->w_p_lbr = lbr_saved;
1905 #endif
1906 		(void)op_yank(oap, FALSE, !gui_yank);
1907 	    }
1908 	    check_cursor_col();
1909 	    break;
1910 
1911 	case OP_CHANGE:
1912 	    VIsual_reselect = FALSE;	    /* don't reselect now */
1913 	    if (empty_region_error)
1914 	    {
1915 		vim_beep(BO_OPER);
1916 		CancelRedo();
1917 	    }
1918 	    else
1919 	    {
1920 		/* This is a new edit command, not a restart.  Need to
1921 		 * remember it to make 'insertmode' work with mappings for
1922 		 * Visual mode.  But do this only once and not when typed and
1923 		 * 'insertmode' isn't set. */
1924 		if (p_im || !KeyTyped)
1925 		    restart_edit_save = restart_edit;
1926 		else
1927 		    restart_edit_save = 0;
1928 		restart_edit = 0;
1929 #ifdef FEAT_LINEBREAK
1930 		/* Restore linebreak, so that when the user edits it looks as
1931 		 * before. */
1932 		if (curwin->w_p_lbr != lbr_saved)
1933 		{
1934 		    curwin->w_p_lbr = lbr_saved;
1935 		    get_op_vcol(oap, redo_VIsual_mode, FALSE);
1936 		}
1937 #endif
1938 		/* Reset finish_op now, don't want it set inside edit(). */
1939 		finish_op = FALSE;
1940 		if (op_change(oap))	/* will call edit() */
1941 		    cap->retval |= CA_COMMAND_BUSY;
1942 		if (restart_edit == 0)
1943 		    restart_edit = restart_edit_save;
1944 	    }
1945 	    break;
1946 
1947 	case OP_FILTER:
1948 	    if (vim_strchr(p_cpo, CPO_FILTER) != NULL)
1949 		AppendToRedobuff((char_u *)"!\r");  /* use any last used !cmd */
1950 	    else
1951 		bangredo = TRUE;    /* do_bang() will put cmd in redo buffer */
1952 
1953 	case OP_INDENT:
1954 	case OP_COLON:
1955 
1956 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
1957 	    /*
1958 	     * If 'equalprg' is empty, do the indenting internally.
1959 	     */
1960 	    if (oap->op_type == OP_INDENT && *get_equalprg() == NUL)
1961 	    {
1962 # ifdef FEAT_LISP
1963 		if (curbuf->b_p_lisp)
1964 		{
1965 		    op_reindent(oap, get_lisp_indent);
1966 		    break;
1967 		}
1968 # endif
1969 # ifdef FEAT_CINDENT
1970 		op_reindent(oap,
1971 #  ifdef FEAT_EVAL
1972 			*curbuf->b_p_inde != NUL ? get_expr_indent :
1973 #  endif
1974 			    get_c_indent);
1975 		break;
1976 # endif
1977 	    }
1978 #endif
1979 
1980 	    op_colon(oap);
1981 	    break;
1982 
1983 	case OP_TILDE:
1984 	case OP_UPPER:
1985 	case OP_LOWER:
1986 	case OP_ROT13:
1987 	    if (empty_region_error)
1988 	    {
1989 		vim_beep(BO_OPER);
1990 		CancelRedo();
1991 	    }
1992 	    else
1993 		op_tilde(oap);
1994 	    check_cursor_col();
1995 	    break;
1996 
1997 	case OP_FORMAT:
1998 #if defined(FEAT_EVAL)
1999 	    if (*curbuf->b_p_fex != NUL)
2000 		op_formatexpr(oap);	/* use expression */
2001 	    else
2002 #endif
2003 		if (*p_fp != NUL)
2004 		op_colon(oap);		/* use external command */
2005 	    else
2006 		op_format(oap, FALSE);	/* use internal function */
2007 	    break;
2008 
2009 	case OP_FORMAT2:
2010 	    op_format(oap, TRUE);	/* use internal function */
2011 	    break;
2012 
2013 	case OP_FUNCTION:
2014 	    op_function(oap);		/* call 'operatorfunc' */
2015 	    break;
2016 
2017 	case OP_INSERT:
2018 	case OP_APPEND:
2019 	    VIsual_reselect = FALSE;	/* don't reselect now */
2020 #ifdef FEAT_VISUALEXTRA
2021 	    if (empty_region_error)
2022 	    {
2023 		vim_beep(BO_OPER);
2024 		CancelRedo();
2025 	    }
2026 	    else
2027 	    {
2028 		/* This is a new edit command, not a restart.  Need to
2029 		 * remember it to make 'insertmode' work with mappings for
2030 		 * Visual mode.  But do this only once. */
2031 		restart_edit_save = restart_edit;
2032 		restart_edit = 0;
2033 #ifdef FEAT_LINEBREAK
2034 		/* Restore linebreak, so that when the user edits it looks as
2035 		 * before. */
2036 		if (curwin->w_p_lbr != lbr_saved)
2037 		{
2038 		    curwin->w_p_lbr = lbr_saved;
2039 		    get_op_vcol(oap, redo_VIsual_mode, FALSE);
2040 		}
2041 #endif
2042 		op_insert(oap, cap->count1);
2043 #ifdef FEAT_LINEBREAK
2044 		/* Reset linebreak, so that formatting works correctly. */
2045 		curwin->w_p_lbr = FALSE;
2046 #endif
2047 
2048 		/* TODO: when inserting in several lines, should format all
2049 		 * the lines. */
2050 		auto_format(FALSE, TRUE);
2051 
2052 		if (restart_edit == 0)
2053 		    restart_edit = restart_edit_save;
2054 	    }
2055 #else
2056 	    vim_beep(BO_OPER);
2057 #endif
2058 	    break;
2059 
2060 	case OP_REPLACE:
2061 	    VIsual_reselect = FALSE;	/* don't reselect now */
2062 #ifdef FEAT_VISUALEXTRA
2063 	    if (empty_region_error)
2064 #endif
2065 	    {
2066 		vim_beep(BO_OPER);
2067 		CancelRedo();
2068 	    }
2069 #ifdef FEAT_VISUALEXTRA
2070 	    else
2071 	    {
2072 # ifdef FEAT_LINEBREAK
2073 		/* Restore linebreak, so that when the user edits it looks as
2074 		 * before. */
2075 		if (curwin->w_p_lbr != lbr_saved)
2076 		{
2077 		    curwin->w_p_lbr = lbr_saved;
2078 		    get_op_vcol(oap, redo_VIsual_mode, FALSE);
2079 		}
2080 # endif
2081 		op_replace(oap, cap->nchar);
2082 	    }
2083 #endif
2084 	    break;
2085 
2086 #ifdef FEAT_FOLDING
2087 	case OP_FOLD:
2088 	    VIsual_reselect = FALSE;	/* don't reselect now */
2089 	    foldCreate(oap->start.lnum, oap->end.lnum);
2090 	    break;
2091 
2092 	case OP_FOLDOPEN:
2093 	case OP_FOLDOPENREC:
2094 	case OP_FOLDCLOSE:
2095 	case OP_FOLDCLOSEREC:
2096 	    VIsual_reselect = FALSE;	/* don't reselect now */
2097 	    opFoldRange(oap->start.lnum, oap->end.lnum,
2098 		    oap->op_type == OP_FOLDOPEN
2099 					    || oap->op_type == OP_FOLDOPENREC,
2100 		    oap->op_type == OP_FOLDOPENREC
2101 					  || oap->op_type == OP_FOLDCLOSEREC,
2102 					  oap->is_VIsual);
2103 	    break;
2104 
2105 	case OP_FOLDDEL:
2106 	case OP_FOLDDELREC:
2107 	    VIsual_reselect = FALSE;	/* don't reselect now */
2108 	    deleteFold(oap->start.lnum, oap->end.lnum,
2109 			       oap->op_type == OP_FOLDDELREC, oap->is_VIsual);
2110 	    break;
2111 #endif
2112 	case OP_NR_ADD:
2113 	case OP_NR_SUB:
2114 	    if (empty_region_error)
2115 	    {
2116 		vim_beep(BO_OPER);
2117 		CancelRedo();
2118 	    }
2119 	    else
2120 	    {
2121 		VIsual_active = TRUE;
2122 #ifdef FEAT_LINEBREAK
2123 		curwin->w_p_lbr = lbr_saved;
2124 #endif
2125 		op_addsub(oap, cap->count1, redo_VIsual_arg);
2126 		VIsual_active = FALSE;
2127 	    }
2128 	    check_cursor_col();
2129 	    break;
2130 	default:
2131 	    clearopbeep(oap);
2132 	}
2133 #ifdef FEAT_VIRTUALEDIT
2134 	virtual_op = MAYBE;
2135 #endif
2136 	if (!gui_yank)
2137 	{
2138 	    /*
2139 	     * if 'sol' not set, go back to old column for some commands
2140 	     */
2141 	    if (!p_sol && oap->motion_type == MLINE && !oap->end_adjusted
2142 		    && (oap->op_type == OP_LSHIFT || oap->op_type == OP_RSHIFT
2143 						|| oap->op_type == OP_DELETE))
2144 	    {
2145 #ifdef FEAT_LINEBREAK
2146 		curwin->w_p_lbr = FALSE;
2147 #endif
2148 		coladvance(curwin->w_curswant = old_col);
2149 	    }
2150 	}
2151 	else
2152 	{
2153 	    curwin->w_cursor = old_cursor;
2154 	}
2155 	oap->block_mode = FALSE;
2156 	clearop(oap);
2157     }
2158 #ifdef FEAT_LINEBREAK
2159     curwin->w_p_lbr = lbr_saved;
2160 #endif
2161 }
2162 
2163 /*
2164  * Handle indent and format operators and visual mode ":".
2165  */
2166     static void
2167 op_colon(oap)
2168     oparg_T	*oap;
2169 {
2170     stuffcharReadbuff(':');
2171     if (oap->is_VIsual)
2172 	stuffReadbuff((char_u *)"'<,'>");
2173     else
2174     {
2175 	/*
2176 	 * Make the range look nice, so it can be repeated.
2177 	 */
2178 	if (oap->start.lnum == curwin->w_cursor.lnum)
2179 	    stuffcharReadbuff('.');
2180 	else
2181 	    stuffnumReadbuff((long)oap->start.lnum);
2182 	if (oap->end.lnum != oap->start.lnum)
2183 	{
2184 	    stuffcharReadbuff(',');
2185 	    if (oap->end.lnum == curwin->w_cursor.lnum)
2186 		stuffcharReadbuff('.');
2187 	    else if (oap->end.lnum == curbuf->b_ml.ml_line_count)
2188 		stuffcharReadbuff('$');
2189 	    else if (oap->start.lnum == curwin->w_cursor.lnum)
2190 	    {
2191 		stuffReadbuff((char_u *)".+");
2192 		stuffnumReadbuff((long)oap->line_count - 1);
2193 	    }
2194 	    else
2195 		stuffnumReadbuff((long)oap->end.lnum);
2196 	}
2197     }
2198     if (oap->op_type != OP_COLON)
2199 	stuffReadbuff((char_u *)"!");
2200     if (oap->op_type == OP_INDENT)
2201     {
2202 #ifndef FEAT_CINDENT
2203 	if (*get_equalprg() == NUL)
2204 	    stuffReadbuff((char_u *)"indent");
2205 	else
2206 #endif
2207 	    stuffReadbuff(get_equalprg());
2208 	stuffReadbuff((char_u *)"\n");
2209     }
2210     else if (oap->op_type == OP_FORMAT)
2211     {
2212 	if (*p_fp == NUL)
2213 	    stuffReadbuff((char_u *)"fmt");
2214 	else
2215 	    stuffReadbuff(p_fp);
2216 	stuffReadbuff((char_u *)"\n']");
2217     }
2218 
2219     /*
2220      * do_cmdline() does the rest
2221      */
2222 }
2223 
2224 /*
2225  * Handle the "g@" operator: call 'operatorfunc'.
2226  */
2227     static void
2228 op_function(oap)
2229     oparg_T	*oap UNUSED;
2230 {
2231 #ifdef FEAT_EVAL
2232     char_u	*(argv[1]);
2233 # ifdef FEAT_VIRTUALEDIT
2234     int		save_virtual_op = virtual_op;
2235 # endif
2236 
2237     if (*p_opfunc == NUL)
2238 	EMSG(_("E774: 'operatorfunc' is empty"));
2239     else
2240     {
2241 	/* Set '[ and '] marks to text to be operated on. */
2242 	curbuf->b_op_start = oap->start;
2243 	curbuf->b_op_end = oap->end;
2244 	if (oap->motion_type != MLINE && !oap->inclusive)
2245 	    /* Exclude the end position. */
2246 	    decl(&curbuf->b_op_end);
2247 
2248 	if (oap->block_mode)
2249 	    argv[0] = (char_u *)"block";
2250 	else if (oap->motion_type == MLINE)
2251 	    argv[0] = (char_u *)"line";
2252 	else
2253 	    argv[0] = (char_u *)"char";
2254 
2255 # ifdef FEAT_VIRTUALEDIT
2256 	/* Reset virtual_op so that 'virtualedit' can be changed in the
2257 	 * function. */
2258 	virtual_op = MAYBE;
2259 # endif
2260 
2261 	(void)call_func_retnr(p_opfunc, 1, argv, FALSE);
2262 
2263 # ifdef FEAT_VIRTUALEDIT
2264 	virtual_op = save_virtual_op;
2265 # endif
2266     }
2267 #else
2268     EMSG(_("E775: Eval feature not available"));
2269 #endif
2270 }
2271 
2272 #if defined(FEAT_MOUSE) || defined(PROTO)
2273 /*
2274  * Do the appropriate action for the current mouse click in the current mode.
2275  * Not used for Command-line mode.
2276  *
2277  * Normal Mode:
2278  * event	 modi-	position      visual	   change   action
2279  *		 fier	cursor			   window
2280  * left press	  -	yes	    end		    yes
2281  * left press	  C	yes	    end		    yes	    "^]" (2)
2282  * left press	  S	yes	    end		    yes	    "*" (2)
2283  * left drag	  -	yes	start if moved	    no
2284  * left relse	  -	yes	start if moved	    no
2285  * middle press	  -	yes	 if not active	    no	    put register
2286  * middle press	  -	yes	 if active	    no	    yank and put
2287  * right press	  -	yes	start or extend	    yes
2288  * right press	  S	yes	no change	    yes	    "#" (2)
2289  * right drag	  -	yes	extend		    no
2290  * right relse	  -	yes	extend		    no
2291  *
2292  * Insert or Replace Mode:
2293  * event	 modi-	position      visual	   change   action
2294  *		 fier	cursor			   window
2295  * left press	  -	yes	(cannot be active)  yes
2296  * left press	  C	yes	(cannot be active)  yes	    "CTRL-O^]" (2)
2297  * left press	  S	yes	(cannot be active)  yes	    "CTRL-O*" (2)
2298  * left drag	  -	yes	start or extend (1) no	    CTRL-O (1)
2299  * left relse	  -	yes	start or extend (1) no	    CTRL-O (1)
2300  * middle press	  -	no	(cannot be active)  no	    put register
2301  * right press	  -	yes	start or extend	    yes	    CTRL-O
2302  * right press	  S	yes	(cannot be active)  yes	    "CTRL-O#" (2)
2303  *
2304  * (1) only if mouse pointer moved since press
2305  * (2) only if click is in same buffer
2306  *
2307  * Return TRUE if start_arrow() should be called for edit mode.
2308  */
2309     int
2310 do_mouse(oap, c, dir, count, fixindent)
2311     oparg_T	*oap;		/* operator argument, can be NULL */
2312     int		c;		/* K_LEFTMOUSE, etc */
2313     int		dir;		/* Direction to 'put' if necessary */
2314     long	count;
2315     int		fixindent;	/* PUT_FIXINDENT if fixing indent necessary */
2316 {
2317     static int	do_always = FALSE;	/* ignore 'mouse' setting next time */
2318     static int	got_click = FALSE;	/* got a click some time back */
2319 
2320     int		which_button;	/* MOUSE_LEFT, _MIDDLE or _RIGHT */
2321     int		is_click;	/* If FALSE it's a drag or release event */
2322     int		is_drag;	/* If TRUE it's a drag event */
2323     int		jump_flags = 0;	/* flags for jump_to_mouse() */
2324     pos_T	start_visual;
2325     int		moved;		/* Has cursor moved? */
2326     int		in_status_line;	/* mouse in status line */
2327 #ifdef FEAT_WINDOWS
2328     static int	in_tab_line = FALSE; /* mouse clicked in tab line */
2329 #endif
2330 #ifdef FEAT_VERTSPLIT
2331     int		in_sep_line;	/* mouse in vertical separator line */
2332 #endif
2333     int		c1, c2;
2334 #if defined(FEAT_FOLDING)
2335     pos_T	save_cursor;
2336 #endif
2337     win_T	*old_curwin = curwin;
2338     static pos_T orig_cursor;
2339     colnr_T	leftcol, rightcol;
2340     pos_T	end_visual;
2341     int		diff;
2342     int		old_active = VIsual_active;
2343     int		old_mode = VIsual_mode;
2344     int		regname;
2345 
2346 #if defined(FEAT_FOLDING)
2347     save_cursor = curwin->w_cursor;
2348 #endif
2349 
2350     /*
2351      * When GUI is active, always recognize mouse events, otherwise:
2352      * - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.
2353      * - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.
2354      * - For command line and insert mode 'mouse' is checked before calling
2355      *	 do_mouse().
2356      */
2357     if (do_always)
2358 	do_always = FALSE;
2359     else
2360 #ifdef FEAT_GUI
2361 	if (!gui.in_use)
2362 #endif
2363 	{
2364 	    if (VIsual_active)
2365 	    {
2366 		if (!mouse_has(MOUSE_VISUAL))
2367 		    return FALSE;
2368 	    }
2369 	    else if (State == NORMAL && !mouse_has(MOUSE_NORMAL))
2370 		return FALSE;
2371 	}
2372 
2373     for (;;)
2374     {
2375 	which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
2376 	if (is_drag)
2377 	{
2378 	    /* If the next character is the same mouse event then use that
2379 	     * one. Speeds up dragging the status line. */
2380 	    if (vpeekc() != NUL)
2381 	    {
2382 		int nc;
2383 		int save_mouse_row = mouse_row;
2384 		int save_mouse_col = mouse_col;
2385 
2386 		/* Need to get the character, peeking doesn't get the actual
2387 		 * one. */
2388 		nc = safe_vgetc();
2389 		if (c == nc)
2390 		    continue;
2391 		vungetc(nc);
2392 		mouse_row = save_mouse_row;
2393 		mouse_col = save_mouse_col;
2394 	    }
2395 	}
2396 	break;
2397     }
2398 
2399 #ifdef FEAT_MOUSESHAPE
2400     /* May have stopped dragging the status or separator line.  The pointer is
2401      * most likely still on the status or separator line. */
2402     if (!is_drag && drag_status_line)
2403     {
2404 	drag_status_line = FALSE;
2405 	update_mouseshape(SHAPE_IDX_STATUS);
2406     }
2407 # ifdef FEAT_VERTSPLIT
2408     if (!is_drag && drag_sep_line)
2409     {
2410 	drag_sep_line = FALSE;
2411 	update_mouseshape(SHAPE_IDX_VSEP);
2412     }
2413 # endif
2414 #endif
2415 
2416     /*
2417      * Ignore drag and release events if we didn't get a click.
2418      */
2419     if (is_click)
2420 	got_click = TRUE;
2421     else
2422     {
2423 	if (!got_click)			/* didn't get click, ignore */
2424 	    return FALSE;
2425 	if (!is_drag)			/* release, reset got_click */
2426 	{
2427 	    got_click = FALSE;
2428 #ifdef FEAT_WINDOWS
2429 	    if (in_tab_line)
2430 	    {
2431 		in_tab_line = FALSE;
2432 		return FALSE;
2433 	    }
2434 #endif
2435 	}
2436     }
2437 
2438     /*
2439      * CTRL right mouse button does CTRL-T
2440      */
2441     if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)
2442     {
2443 	if (State & INSERT)
2444 	    stuffcharReadbuff(Ctrl_O);
2445 	if (count > 1)
2446 	    stuffnumReadbuff(count);
2447 	stuffcharReadbuff(Ctrl_T);
2448 	got_click = FALSE;		/* ignore drag&release now */
2449 	return FALSE;
2450     }
2451 
2452     /*
2453      * CTRL only works with left mouse button
2454      */
2455     if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)
2456 	return FALSE;
2457 
2458     /*
2459      * When a modifier is down, ignore drag and release events, as well as
2460      * multiple clicks and the middle mouse button.
2461      * Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
2462      */
2463     if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
2464 							     | MOD_MASK_META))
2465 	    && (!is_click
2466 		|| (mod_mask & MOD_MASK_MULTI_CLICK)
2467 		|| which_button == MOUSE_MIDDLE)
2468 	    && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
2469 		&& mouse_model_popup()
2470 		&& which_button == MOUSE_LEFT)
2471 	    && !((mod_mask & MOD_MASK_ALT)
2472 		&& !mouse_model_popup()
2473 		&& which_button == MOUSE_RIGHT)
2474 	    )
2475 	return FALSE;
2476 
2477     /*
2478      * If the button press was used as the movement command for an operator
2479      * (eg "d<MOUSE>"), or it is the middle button that is held down, ignore
2480      * drag/release events.
2481      */
2482     if (!is_click && which_button == MOUSE_MIDDLE)
2483 	return FALSE;
2484 
2485     if (oap != NULL)
2486 	regname = oap->regname;
2487     else
2488 	regname = 0;
2489 
2490     /*
2491      * Middle mouse button does a 'put' of the selected text
2492      */
2493     if (which_button == MOUSE_MIDDLE)
2494     {
2495 	if (State == NORMAL)
2496 	{
2497 	    /*
2498 	     * If an operator was pending, we don't know what the user wanted
2499 	     * to do. Go back to normal mode: Clear the operator and beep().
2500 	     */
2501 	    if (oap != NULL && oap->op_type != OP_NOP)
2502 	    {
2503 		clearopbeep(oap);
2504 		return FALSE;
2505 	    }
2506 
2507 	    /*
2508 	     * If visual was active, yank the highlighted text and put it
2509 	     * before the mouse pointer position.
2510 	     * In Select mode replace the highlighted text with the clipboard.
2511 	     */
2512 	    if (VIsual_active)
2513 	    {
2514 		if (VIsual_select)
2515 		{
2516 		    stuffcharReadbuff(Ctrl_G);
2517 		    stuffReadbuff((char_u *)"\"+p");
2518 		}
2519 		else
2520 		{
2521 		    stuffcharReadbuff('y');
2522 		    stuffcharReadbuff(K_MIDDLEMOUSE);
2523 		}
2524 		do_always = TRUE;	/* ignore 'mouse' setting next time */
2525 		return FALSE;
2526 	    }
2527 	    /*
2528 	     * The rest is below jump_to_mouse()
2529 	     */
2530 	}
2531 
2532 	else if ((State & INSERT) == 0)
2533 	    return FALSE;
2534 
2535 	/*
2536 	 * Middle click in insert mode doesn't move the mouse, just insert the
2537 	 * contents of a register.  '.' register is special, can't insert that
2538 	 * with do_put().
2539 	 * Also paste at the cursor if the current mode isn't in 'mouse' (only
2540 	 * happens for the GUI).
2541 	 */
2542 	if ((State & INSERT) || !mouse_has(MOUSE_NORMAL))
2543 	{
2544 	    if (regname == '.')
2545 		insert_reg(regname, TRUE);
2546 	    else
2547 	    {
2548 #ifdef FEAT_CLIPBOARD
2549 		if (clip_star.available && regname == 0)
2550 		    regname = '*';
2551 #endif
2552 		if ((State & REPLACE_FLAG) && !yank_register_mline(regname))
2553 		    insert_reg(regname, TRUE);
2554 		else
2555 		{
2556 		    do_put(regname, BACKWARD, 1L, fixindent | PUT_CURSEND);
2557 
2558 		    /* Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r */
2559 		    AppendCharToRedobuff(Ctrl_R);
2560 		    AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);
2561 		    AppendCharToRedobuff(regname == 0 ? '"' : regname);
2562 		}
2563 	    }
2564 	    return FALSE;
2565 	}
2566     }
2567 
2568     /* When dragging or button-up stay in the same window. */
2569     if (!is_click)
2570 	jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;
2571 
2572     start_visual.lnum = 0;
2573 
2574 #ifdef FEAT_WINDOWS
2575     /* Check for clicking in the tab page line. */
2576     if (mouse_row == 0 && firstwin->w_winrow > 0)
2577     {
2578 	if (is_drag)
2579 	{
2580 	    if (in_tab_line)
2581 	    {
2582 		c1 = TabPageIdxs[mouse_col];
2583 		tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)
2584 								? c1 - 1 : c1);
2585 	    }
2586 	    return FALSE;
2587 	}
2588 
2589 	/* click in a tab selects that tab page */
2590 	if (is_click
2591 # ifdef FEAT_CMDWIN
2592 		&& cmdwin_type == 0
2593 # endif
2594 		&& mouse_col < Columns)
2595 	{
2596 	    in_tab_line = TRUE;
2597 	    c1 = TabPageIdxs[mouse_col];
2598 	    if (c1 >= 0)
2599 	    {
2600 		if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
2601 		{
2602 		    /* double click opens new page */
2603 		    end_visual_mode();
2604 		    tabpage_new();
2605 		    tabpage_move(c1 == 0 ? 9999 : c1 - 1);
2606 		}
2607 		else
2608 		{
2609 		    /* Go to specified tab page, or next one if not clicking
2610 		     * on a label. */
2611 		    goto_tabpage(c1);
2612 
2613 		    /* It's like clicking on the status line of a window. */
2614 		    if (curwin != old_curwin)
2615 			end_visual_mode();
2616 		}
2617 	    }
2618 	    else if (c1 < 0)
2619 	    {
2620 		tabpage_T	*tp;
2621 
2622 		/* Close the current or specified tab page. */
2623 		if (c1 == -999)
2624 		    tp = curtab;
2625 		else
2626 		    tp = find_tabpage(-c1);
2627 		if (tp == curtab)
2628 		{
2629 		    if (first_tabpage->tp_next != NULL)
2630 			tabpage_close(FALSE);
2631 		}
2632 		else if (tp != NULL)
2633 		    tabpage_close_other(tp, FALSE);
2634 	    }
2635 	}
2636 	return TRUE;
2637     }
2638     else if (is_drag && in_tab_line)
2639     {
2640 	c1 = TabPageIdxs[mouse_col];
2641 	tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
2642 	return FALSE;
2643     }
2644 
2645 #endif
2646 
2647     /*
2648      * When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
2649      * right button up   -> pop-up menu
2650      * shift-left button -> right button
2651      * alt-left button   -> alt-right button
2652      */
2653     if (mouse_model_popup())
2654     {
2655 	if (which_button == MOUSE_RIGHT
2656 			    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
2657 	{
2658 	    /*
2659 	     * NOTE: Ignore right button down and drag mouse events.
2660 	     * Windows only shows the popup menu on the button up event.
2661 	     */
2662 #if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
2663 			  || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2664 	    if (!is_click)
2665 		return FALSE;
2666 #endif
2667 #if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN)
2668 	    if (is_click || is_drag)
2669 		return FALSE;
2670 #endif
2671 #if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
2672 	    || defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN) \
2673 	    || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_PHOTON)
2674 	    if (gui.in_use)
2675 	    {
2676 		jump_flags = 0;
2677 		if (STRCMP(p_mousem, "popup_setpos") == 0)
2678 		{
2679 		    /* First set the cursor position before showing the popup
2680 		     * menu. */
2681 		    if (VIsual_active)
2682 		    {
2683 			pos_T    m_pos;
2684 
2685 			/*
2686 			 * set MOUSE_MAY_STOP_VIS if we are outside the
2687 			 * selection or the current window (might have false
2688 			 * negative here)
2689 			 */
2690 			if (mouse_row < W_WINROW(curwin)
2691 			     || mouse_row
2692 				      > (W_WINROW(curwin) + curwin->w_height))
2693 			    jump_flags = MOUSE_MAY_STOP_VIS;
2694 			else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)
2695 			    jump_flags = MOUSE_MAY_STOP_VIS;
2696 			else
2697 			{
2698 			    if ((lt(curwin->w_cursor, VIsual)
2699 					&& (lt(m_pos, curwin->w_cursor)
2700 					    || lt(VIsual, m_pos)))
2701 				    || (lt(VIsual, curwin->w_cursor)
2702 					&& (lt(m_pos, VIsual)
2703 					    || lt(curwin->w_cursor, m_pos))))
2704 			    {
2705 				jump_flags = MOUSE_MAY_STOP_VIS;
2706 			    }
2707 			    else if (VIsual_mode == Ctrl_V)
2708 			    {
2709 				getvcols(curwin, &curwin->w_cursor, &VIsual,
2710 							 &leftcol, &rightcol);
2711 				getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);
2712 				if (m_pos.col < leftcol || m_pos.col > rightcol)
2713 				    jump_flags = MOUSE_MAY_STOP_VIS;
2714 			    }
2715 			}
2716 		    }
2717 		    else
2718 			jump_flags = MOUSE_MAY_STOP_VIS;
2719 		}
2720 		if (jump_flags)
2721 		{
2722 		    jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
2723 		    update_curbuf(VIsual_active ? INVERTED : VALID);
2724 		    setcursor();
2725 		    out_flush();    /* Update before showing popup menu */
2726 		}
2727 # ifdef FEAT_MENU
2728 		gui_show_popupmenu();
2729 # endif
2730 		return (jump_flags & CURSOR_MOVED) != 0;
2731 	    }
2732 	    else
2733 		return FALSE;
2734 #else
2735 	    return FALSE;
2736 #endif
2737 	}
2738 	if (which_button == MOUSE_LEFT
2739 				&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))
2740 	{
2741 	    which_button = MOUSE_RIGHT;
2742 	    mod_mask &= ~MOD_MASK_SHIFT;
2743 	}
2744     }
2745 
2746     if ((State & (NORMAL | INSERT))
2747 			    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
2748     {
2749 	if (which_button == MOUSE_LEFT)
2750 	{
2751 	    if (is_click)
2752 	    {
2753 		/* stop Visual mode for a left click in a window, but not when
2754 		 * on a status line */
2755 		if (VIsual_active)
2756 		    jump_flags |= MOUSE_MAY_STOP_VIS;
2757 	    }
2758 	    else if (mouse_has(MOUSE_VISUAL))
2759 		jump_flags |= MOUSE_MAY_VIS;
2760 	}
2761 	else if (which_button == MOUSE_RIGHT)
2762 	{
2763 	    if (is_click && VIsual_active)
2764 	    {
2765 		/*
2766 		 * Remember the start and end of visual before moving the
2767 		 * cursor.
2768 		 */
2769 		if (lt(curwin->w_cursor, VIsual))
2770 		{
2771 		    start_visual = curwin->w_cursor;
2772 		    end_visual = VIsual;
2773 		}
2774 		else
2775 		{
2776 		    start_visual = VIsual;
2777 		    end_visual = curwin->w_cursor;
2778 		}
2779 	    }
2780 	    jump_flags |= MOUSE_FOCUS;
2781 	    if (mouse_has(MOUSE_VISUAL))
2782 		jump_flags |= MOUSE_MAY_VIS;
2783 	}
2784     }
2785 
2786     /*
2787      * If an operator is pending, ignore all drags and releases until the
2788      * next mouse click.
2789      */
2790     if (!is_drag && oap != NULL && oap->op_type != OP_NOP)
2791     {
2792 	got_click = FALSE;
2793 	oap->motion_type = MCHAR;
2794     }
2795 
2796     /* When releasing the button let jump_to_mouse() know. */
2797     if (!is_click && !is_drag)
2798 	jump_flags |= MOUSE_RELEASED;
2799 
2800     /*
2801      * JUMP!
2802      */
2803     jump_flags = jump_to_mouse(jump_flags,
2804 			oap == NULL ? NULL : &(oap->inclusive), which_button);
2805     moved = (jump_flags & CURSOR_MOVED);
2806     in_status_line = (jump_flags & IN_STATUS_LINE);
2807 #ifdef FEAT_VERTSPLIT
2808     in_sep_line = (jump_flags & IN_SEP_LINE);
2809 #endif
2810 
2811 #ifdef FEAT_NETBEANS_INTG
2812     if (isNetbeansBuffer(curbuf)
2813 			    && !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))
2814     {
2815 	int key = KEY2TERMCAP1(c);
2816 
2817 	if (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE
2818 					       || key == (int)KE_RIGHTRELEASE)
2819 	    netbeans_button_release(which_button);
2820     }
2821 #endif
2822 
2823     /* When jumping to another window, clear a pending operator.  That's a bit
2824      * friendlier than beeping and not jumping to that window. */
2825     if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)
2826 	clearop(oap);
2827 
2828 #ifdef FEAT_FOLDING
2829     if (mod_mask == 0
2830 	    && !is_drag
2831 	    && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
2832 	    && which_button == MOUSE_LEFT)
2833     {
2834 	/* open or close a fold at this line */
2835 	if (jump_flags & MOUSE_FOLD_OPEN)
2836 	    openFold(curwin->w_cursor.lnum, 1L);
2837 	else
2838 	    closeFold(curwin->w_cursor.lnum, 1L);
2839 	/* don't move the cursor if still in the same window */
2840 	if (curwin == old_curwin)
2841 	    curwin->w_cursor = save_cursor;
2842     }
2843 #endif
2844 
2845 #if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)
2846     if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)
2847     {
2848 	clip_modeless(which_button, is_click, is_drag);
2849 	return FALSE;
2850     }
2851 #endif
2852 
2853     /* Set global flag that we are extending the Visual area with mouse
2854      * dragging; temporarily minimize 'scrolloff'. */
2855     if (VIsual_active && is_drag && p_so)
2856     {
2857 	/* In the very first line, allow scrolling one line */
2858 	if (mouse_row == 0)
2859 	    mouse_dragging = 2;
2860 	else
2861 	    mouse_dragging = 1;
2862     }
2863 
2864     /* When dragging the mouse above the window, scroll down. */
2865     if (is_drag && mouse_row < 0 && !in_status_line)
2866     {
2867 	scroll_redraw(FALSE, 1L);
2868 	mouse_row = 0;
2869     }
2870 
2871     if (start_visual.lnum)		/* right click in visual mode */
2872     {
2873        /* When ALT is pressed make Visual mode blockwise. */
2874        if (mod_mask & MOD_MASK_ALT)
2875 	   VIsual_mode = Ctrl_V;
2876 
2877 	/*
2878 	 * In Visual-block mode, divide the area in four, pick up the corner
2879 	 * that is in the quarter that the cursor is in.
2880 	 */
2881 	if (VIsual_mode == Ctrl_V)
2882 	{
2883 	    getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);
2884 	    if (curwin->w_curswant > (leftcol + rightcol) / 2)
2885 		end_visual.col = leftcol;
2886 	    else
2887 		end_visual.col = rightcol;
2888 	    if (curwin->w_cursor.lnum >=
2889 				    (start_visual.lnum + end_visual.lnum) / 2)
2890 		end_visual.lnum = start_visual.lnum;
2891 
2892 	    /* move VIsual to the right column */
2893 	    start_visual = curwin->w_cursor;	    /* save the cursor pos */
2894 	    curwin->w_cursor = end_visual;
2895 	    coladvance(end_visual.col);
2896 	    VIsual = curwin->w_cursor;
2897 	    curwin->w_cursor = start_visual;	    /* restore the cursor */
2898 	}
2899 	else
2900 	{
2901 	    /*
2902 	     * If the click is before the start of visual, change the start.
2903 	     * If the click is after the end of visual, change the end.  If
2904 	     * the click is inside the visual, change the closest side.
2905 	     */
2906 	    if (lt(curwin->w_cursor, start_visual))
2907 		VIsual = end_visual;
2908 	    else if (lt(end_visual, curwin->w_cursor))
2909 		VIsual = start_visual;
2910 	    else
2911 	    {
2912 		/* In the same line, compare column number */
2913 		if (end_visual.lnum == start_visual.lnum)
2914 		{
2915 		    if (curwin->w_cursor.col - start_visual.col >
2916 				    end_visual.col - curwin->w_cursor.col)
2917 			VIsual = start_visual;
2918 		    else
2919 			VIsual = end_visual;
2920 		}
2921 
2922 		/* In different lines, compare line number */
2923 		else
2924 		{
2925 		    diff = (curwin->w_cursor.lnum - start_visual.lnum) -
2926 				(end_visual.lnum - curwin->w_cursor.lnum);
2927 
2928 		    if (diff > 0)		/* closest to end */
2929 			VIsual = start_visual;
2930 		    else if (diff < 0)	/* closest to start */
2931 			VIsual = end_visual;
2932 		    else			/* in the middle line */
2933 		    {
2934 			if (curwin->w_cursor.col <
2935 					(start_visual.col + end_visual.col) / 2)
2936 			    VIsual = end_visual;
2937 			else
2938 			    VIsual = start_visual;
2939 		    }
2940 		}
2941 	    }
2942 	}
2943     }
2944     /*
2945      * If Visual mode started in insert mode, execute "CTRL-O"
2946      */
2947     else if ((State & INSERT) && VIsual_active)
2948 	stuffcharReadbuff(Ctrl_O);
2949 
2950     /*
2951      * Middle mouse click: Put text before cursor.
2952      */
2953     if (which_button == MOUSE_MIDDLE)
2954     {
2955 #ifdef FEAT_CLIPBOARD
2956 	if (clip_star.available && regname == 0)
2957 	    regname = '*';
2958 #endif
2959 	if (yank_register_mline(regname))
2960 	{
2961 	    if (mouse_past_bottom)
2962 		dir = FORWARD;
2963 	}
2964 	else if (mouse_past_eol)
2965 	    dir = FORWARD;
2966 
2967 	if (fixindent)
2968 	{
2969 	    c1 = (dir == BACKWARD) ? '[' : ']';
2970 	    c2 = 'p';
2971 	}
2972 	else
2973 	{
2974 	    c1 = (dir == FORWARD) ? 'p' : 'P';
2975 	    c2 = NUL;
2976 	}
2977 	prep_redo(regname, count, NUL, c1, NUL, c2, NUL);
2978 
2979 	/*
2980 	 * Remember where the paste started, so in edit() Insstart can be set
2981 	 * to this position
2982 	 */
2983 	if (restart_edit != 0)
2984 	    where_paste_started = curwin->w_cursor;
2985 	do_put(regname, dir, count, fixindent | PUT_CURSEND);
2986     }
2987 
2988 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
2989     /*
2990      * Ctrl-Mouse click or double click in a quickfix window jumps to the
2991      * error under the mouse pointer.
2992      */
2993     else if (((mod_mask & MOD_MASK_CTRL)
2994 		|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
2995 	    && bt_quickfix(curbuf))
2996     {
2997 	if (State & INSERT)
2998 	    stuffcharReadbuff(Ctrl_O);
2999 	if (curwin->w_llist_ref == NULL)	/* quickfix window */
3000 	    stuffReadbuff((char_u *)":.cc\n");
3001 	else					/* location list window */
3002 	    stuffReadbuff((char_u *)":.ll\n");
3003 	got_click = FALSE;		/* ignore drag&release now */
3004     }
3005 #endif
3006 
3007     /*
3008      * Ctrl-Mouse click (or double click in a help window) jumps to the tag
3009      * under the mouse pointer.
3010      */
3011     else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help
3012 		     && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))
3013     {
3014 	if (State & INSERT)
3015 	    stuffcharReadbuff(Ctrl_O);
3016 	stuffcharReadbuff(Ctrl_RSB);
3017 	got_click = FALSE;		/* ignore drag&release now */
3018     }
3019 
3020     /*
3021      * Shift-Mouse click searches for the next occurrence of the word under
3022      * the mouse pointer
3023      */
3024     else if ((mod_mask & MOD_MASK_SHIFT))
3025     {
3026 	if ((State & INSERT) || (VIsual_active && VIsual_select))
3027 	    stuffcharReadbuff(Ctrl_O);
3028 	if (which_button == MOUSE_LEFT)
3029 	    stuffcharReadbuff('*');
3030 	else	/* MOUSE_RIGHT */
3031 	    stuffcharReadbuff('#');
3032     }
3033 
3034     /* Handle double clicks, unless on status line */
3035     else if (in_status_line)
3036     {
3037 #ifdef FEAT_MOUSESHAPE
3038 	if ((is_drag || is_click) && !drag_status_line)
3039 	{
3040 	    drag_status_line = TRUE;
3041 	    update_mouseshape(-1);
3042 	}
3043 #endif
3044     }
3045 #ifdef FEAT_VERTSPLIT
3046     else if (in_sep_line)
3047     {
3048 # ifdef FEAT_MOUSESHAPE
3049 	if ((is_drag || is_click) && !drag_sep_line)
3050 	{
3051 	    drag_sep_line = TRUE;
3052 	    update_mouseshape(-1);
3053 	}
3054 # endif
3055     }
3056 #endif
3057     else if ((mod_mask & MOD_MASK_MULTI_CLICK) && (State & (NORMAL | INSERT))
3058 	     && mouse_has(MOUSE_VISUAL))
3059     {
3060 	if (is_click || !VIsual_active)
3061 	{
3062 	    if (VIsual_active)
3063 		orig_cursor = VIsual;
3064 	    else
3065 	    {
3066 		check_visual_highlight();
3067 		VIsual = curwin->w_cursor;
3068 		orig_cursor = VIsual;
3069 		VIsual_active = TRUE;
3070 		VIsual_reselect = TRUE;
3071 		/* start Select mode if 'selectmode' contains "mouse" */
3072 		may_start_select('o');
3073 		setmouse();
3074 	    }
3075 	    if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
3076 	    {
3077 		/* Double click with ALT pressed makes it blockwise. */
3078 		if (mod_mask & MOD_MASK_ALT)
3079 		    VIsual_mode = Ctrl_V;
3080 		else
3081 		    VIsual_mode = 'v';
3082 	    }
3083 	    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)
3084 		VIsual_mode = 'V';
3085 	    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)
3086 		VIsual_mode = Ctrl_V;
3087 #ifdef FEAT_CLIPBOARD
3088 	    /* Make sure the clipboard gets updated.  Needed because start and
3089 	     * end may still be the same, and the selection needs to be owned */
3090 	    clip_star.vmode = NUL;
3091 #endif
3092 	}
3093 	/*
3094 	 * A double click selects a word or a block.
3095 	 */
3096 	if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
3097 	{
3098 	    pos_T	*pos = NULL;
3099 	    int		gc;
3100 
3101 	    if (is_click)
3102 	    {
3103 		/* If the character under the cursor (skipping white space) is
3104 		 * not a word character, try finding a match and select a (),
3105 		 * {}, [], #if/#endif, etc. block. */
3106 		end_visual = curwin->w_cursor;
3107 		while (gc = gchar_pos(&end_visual), vim_iswhite(gc))
3108 		    inc(&end_visual);
3109 		if (oap != NULL)
3110 		    oap->motion_type = MCHAR;
3111 		if (oap != NULL
3112 			&& VIsual_mode == 'v'
3113 			&& !vim_iswordc(gchar_pos(&end_visual))
3114 			&& equalpos(curwin->w_cursor, VIsual)
3115 			&& (pos = findmatch(oap, NUL)) != NULL)
3116 		{
3117 		    curwin->w_cursor = *pos;
3118 		    if (oap->motion_type == MLINE)
3119 			VIsual_mode = 'V';
3120 		    else if (*p_sel == 'e')
3121 		    {
3122 			if (lt(curwin->w_cursor, VIsual))
3123 			    ++VIsual.col;
3124 			else
3125 			    ++curwin->w_cursor.col;
3126 		    }
3127 		}
3128 	    }
3129 
3130 	    if (pos == NULL && (is_click || is_drag))
3131 	    {
3132 		/* When not found a match or when dragging: extend to include
3133 		 * a word. */
3134 		if (lt(curwin->w_cursor, orig_cursor))
3135 		{
3136 		    find_start_of_word(&curwin->w_cursor);
3137 		    find_end_of_word(&VIsual);
3138 		}
3139 		else
3140 		{
3141 		    find_start_of_word(&VIsual);
3142 		    if (*p_sel == 'e' && *ml_get_cursor() != NUL)
3143 #ifdef FEAT_MBYTE
3144 			curwin->w_cursor.col +=
3145 					 (*mb_ptr2len)(ml_get_cursor());
3146 #else
3147 			++curwin->w_cursor.col;
3148 #endif
3149 		    find_end_of_word(&curwin->w_cursor);
3150 		}
3151 	    }
3152 	    curwin->w_set_curswant = TRUE;
3153 	}
3154 	if (is_click)
3155 	    redraw_curbuf_later(INVERTED);	/* update the inversion */
3156     }
3157     else if (VIsual_active && !old_active)
3158     {
3159 	if (mod_mask & MOD_MASK_ALT)
3160 	    VIsual_mode = Ctrl_V;
3161 	else
3162 	    VIsual_mode = 'v';
3163     }
3164 
3165     /* If Visual mode changed show it later. */
3166     if ((!VIsual_active && old_active && mode_displayed)
3167 	    || (VIsual_active && p_smd && msg_silent == 0
3168 				 && (!old_active || VIsual_mode != old_mode)))
3169 	redraw_cmdline = TRUE;
3170 
3171     return moved;
3172 }
3173 
3174 /*
3175  * Move "pos" back to the start of the word it's in.
3176  */
3177     static void
3178 find_start_of_word(pos)
3179     pos_T	*pos;
3180 {
3181     char_u	*line;
3182     int		cclass;
3183     int		col;
3184 
3185     line = ml_get(pos->lnum);
3186     cclass = get_mouse_class(line + pos->col);
3187 
3188     while (pos->col > 0)
3189     {
3190 	col = pos->col - 1;
3191 #ifdef FEAT_MBYTE
3192 	col -= (*mb_head_off)(line, line + col);
3193 #endif
3194 	if (get_mouse_class(line + col) != cclass)
3195 	    break;
3196 	pos->col = col;
3197     }
3198 }
3199 
3200 /*
3201  * Move "pos" forward to the end of the word it's in.
3202  * When 'selection' is "exclusive", the position is just after the word.
3203  */
3204     static void
3205 find_end_of_word(pos)
3206     pos_T	*pos;
3207 {
3208     char_u	*line;
3209     int		cclass;
3210     int		col;
3211 
3212     line = ml_get(pos->lnum);
3213     if (*p_sel == 'e' && pos->col > 0)
3214     {
3215 	--pos->col;
3216 #ifdef FEAT_MBYTE
3217 	pos->col -= (*mb_head_off)(line, line + pos->col);
3218 #endif
3219     }
3220     cclass = get_mouse_class(line + pos->col);
3221     while (line[pos->col] != NUL)
3222     {
3223 #ifdef FEAT_MBYTE
3224 	col = pos->col + (*mb_ptr2len)(line + pos->col);
3225 #else
3226 	col = pos->col + 1;
3227 #endif
3228 	if (get_mouse_class(line + col) != cclass)
3229 	{
3230 	    if (*p_sel == 'e')
3231 		pos->col = col;
3232 	    break;
3233 	}
3234 	pos->col = col;
3235     }
3236 }
3237 
3238 /*
3239  * Get class of a character for selection: same class means same word.
3240  * 0: blank
3241  * 1: punctuation groups
3242  * 2: normal word character
3243  * >2: multi-byte word character.
3244  */
3245     static int
3246 get_mouse_class(p)
3247     char_u	*p;
3248 {
3249     int		c;
3250 
3251 #ifdef FEAT_MBYTE
3252     if (has_mbyte && MB_BYTE2LEN(p[0]) > 1)
3253 	return mb_get_class(p);
3254 #endif
3255 
3256     c = *p;
3257     if (c == ' ' || c == '\t')
3258 	return 0;
3259 
3260     if (vim_iswordc(c))
3261 	return 2;
3262 
3263     /*
3264      * There are a few special cases where we want certain combinations of
3265      * characters to be considered as a single word.  These are things like
3266      * "->", "/ *", "*=", "+=", "&=", "<=", ">=", "!=" etc.  Otherwise, each
3267      * character is in its own class.
3268      */
3269     if (c != NUL && vim_strchr((char_u *)"-+*/%<>&|^!=", c) != NULL)
3270 	return 1;
3271     return c;
3272 }
3273 #endif /* FEAT_MOUSE */
3274 
3275 /*
3276  * Check if  highlighting for visual mode is possible, give a warning message
3277  * if not.
3278  */
3279     void
3280 check_visual_highlight()
3281 {
3282     static int	    did_check = FALSE;
3283 
3284     if (full_screen)
3285     {
3286 	if (!did_check && hl_attr(HLF_V) == 0)
3287 	    MSG(_("Warning: terminal cannot highlight"));
3288 	did_check = TRUE;
3289     }
3290 }
3291 
3292 /*
3293  * End Visual mode.
3294  * This function should ALWAYS be called to end Visual mode, except from
3295  * do_pending_operator().
3296  */
3297     void
3298 end_visual_mode()
3299 {
3300 #ifdef FEAT_CLIPBOARD
3301     /*
3302      * If we are using the clipboard, then remember what was selected in case
3303      * we need to paste it somewhere while we still own the selection.
3304      * Only do this when the clipboard is already owned.  Don't want to grab
3305      * the selection when hitting ESC.
3306      */
3307     if (clip_star.available && clip_star.owned)
3308 	clip_auto_select();
3309 #endif
3310 
3311     VIsual_active = FALSE;
3312 #ifdef FEAT_MOUSE
3313     setmouse();
3314     mouse_dragging = 0;
3315 #endif
3316 
3317     /* Save the current VIsual area for '< and '> marks, and "gv" */
3318     curbuf->b_visual.vi_mode = VIsual_mode;
3319     curbuf->b_visual.vi_start = VIsual;
3320     curbuf->b_visual.vi_end = curwin->w_cursor;
3321     curbuf->b_visual.vi_curswant = curwin->w_curswant;
3322 #ifdef FEAT_EVAL
3323     curbuf->b_visual_mode_eval = VIsual_mode;
3324 #endif
3325 #ifdef FEAT_VIRTUALEDIT
3326     if (!virtual_active())
3327 	curwin->w_cursor.coladd = 0;
3328 #endif
3329     may_clear_cmdline();
3330 
3331     adjust_cursor_eol();
3332 }
3333 
3334 /*
3335  * Reset VIsual_active and VIsual_reselect.
3336  */
3337     void
3338 reset_VIsual_and_resel()
3339 {
3340     if (VIsual_active)
3341     {
3342 	end_visual_mode();
3343 	redraw_curbuf_later(INVERTED);	/* delete the inversion later */
3344     }
3345     VIsual_reselect = FALSE;
3346 }
3347 
3348 /*
3349  * Reset VIsual_active and VIsual_reselect if it's set.
3350  */
3351     void
3352 reset_VIsual()
3353 {
3354     if (VIsual_active)
3355     {
3356 	end_visual_mode();
3357 	redraw_curbuf_later(INVERTED);	/* delete the inversion later */
3358 	VIsual_reselect = FALSE;
3359     }
3360 }
3361 
3362 #if defined(FEAT_BEVAL)
3363 static int find_is_eval_item __ARGS((char_u *ptr, int *colp, int *nbp, int dir));
3364 
3365 /*
3366  * Check for a balloon-eval special item to include when searching for an
3367  * identifier.  When "dir" is BACKWARD "ptr[-1]" must be valid!
3368  * Returns TRUE if the character at "*ptr" should be included.
3369  * "dir" is FORWARD or BACKWARD, the direction of searching.
3370  * "*colp" is in/decremented if "ptr[-dir]" should also be included.
3371  * "bnp" points to a counter for square brackets.
3372  */
3373     static int
3374 find_is_eval_item(ptr, colp, bnp, dir)
3375     char_u	*ptr;
3376     int		*colp;
3377     int		*bnp;
3378     int		dir;
3379 {
3380     /* Accept everything inside []. */
3381     if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD))
3382 	++*bnp;
3383     if (*bnp > 0)
3384     {
3385 	if ((*ptr == '[' && dir == BACKWARD) || (*ptr == ']' && dir == FORWARD))
3386 	    --*bnp;
3387 	return TRUE;
3388     }
3389 
3390     /* skip over "s.var" */
3391     if (*ptr == '.')
3392 	return TRUE;
3393 
3394     /* two-character item: s->var */
3395     if (ptr[dir == BACKWARD ? 0 : 1] == '>'
3396 	    && ptr[dir == BACKWARD ? -1 : 0] == '-')
3397     {
3398 	*colp += dir;
3399 	return TRUE;
3400     }
3401     return FALSE;
3402 }
3403 #endif
3404 
3405 /*
3406  * Find the identifier under or to the right of the cursor.
3407  * "find_type" can have one of three values:
3408  * FIND_IDENT:   find an identifier (keyword)
3409  * FIND_STRING:  find any non-white string
3410  * FIND_IDENT + FIND_STRING: find any non-white string, identifier preferred.
3411  * FIND_EVAL:	 find text useful for C program debugging
3412  *
3413  * There are three steps:
3414  * 1. Search forward for the start of an identifier/string.  Doesn't move if
3415  *    already on one.
3416  * 2. Search backward for the start of this identifier/string.
3417  *    This doesn't match the real Vi but I like it a little better and it
3418  *    shouldn't bother anyone.
3419  * 3. Search forward to the end of this identifier/string.
3420  *    When FIND_IDENT isn't defined, we backup until a blank.
3421  *
3422  * Returns the length of the string, or zero if no string is found.
3423  * If a string is found, a pointer to the string is put in "*string".  This
3424  * string is not always NUL terminated.
3425  */
3426     int
3427 find_ident_under_cursor(string, find_type)
3428     char_u	**string;
3429     int		find_type;
3430 {
3431     return find_ident_at_pos(curwin, curwin->w_cursor.lnum,
3432 				     curwin->w_cursor.col, string, find_type);
3433 }
3434 
3435 /*
3436  * Like find_ident_under_cursor(), but for any window and any position.
3437  * However: Uses 'iskeyword' from the current window!.
3438  */
3439     int
3440 find_ident_at_pos(wp, lnum, startcol, string, find_type)
3441     win_T	*wp;
3442     linenr_T	lnum;
3443     colnr_T	startcol;
3444     char_u	**string;
3445     int		find_type;
3446 {
3447     char_u	*ptr;
3448     int		col = 0;	    /* init to shut up GCC */
3449     int		i;
3450 #ifdef FEAT_MBYTE
3451     int		this_class = 0;
3452     int		prev_class;
3453     int		prevcol;
3454 #endif
3455 #if defined(FEAT_BEVAL)
3456     int		bn = 0;	    /* bracket nesting */
3457 #endif
3458 
3459     /*
3460      * if i == 0: try to find an identifier
3461      * if i == 1: try to find any non-white string
3462      */
3463     ptr = ml_get_buf(wp->w_buffer, lnum, FALSE);
3464     for (i = (find_type & FIND_IDENT) ? 0 : 1;	i < 2; ++i)
3465     {
3466 	/*
3467 	 * 1. skip to start of identifier/string
3468 	 */
3469 	col = startcol;
3470 #ifdef FEAT_MBYTE
3471 	if (has_mbyte)
3472 	{
3473 	    while (ptr[col] != NUL)
3474 	    {
3475 # if defined(FEAT_BEVAL)
3476 		/* Stop at a ']' to evaluate "a[x]". */
3477 		if ((find_type & FIND_EVAL) && ptr[col] == ']')
3478 		    break;
3479 # endif
3480 		this_class = mb_get_class(ptr + col);
3481 		if (this_class != 0 && (i == 1 || this_class != 1))
3482 		    break;
3483 		col += (*mb_ptr2len)(ptr + col);
3484 	    }
3485 	}
3486 	else
3487 #endif
3488 	    while (ptr[col] != NUL
3489 		    && (i == 0 ? !vim_iswordc(ptr[col]) : vim_iswhite(ptr[col]))
3490 # if defined(FEAT_BEVAL)
3491 		    && (!(find_type & FIND_EVAL) || ptr[col] != ']')
3492 # endif
3493 		    )
3494 		++col;
3495 
3496 #if defined(FEAT_BEVAL)
3497 	/* When starting on a ']' count it, so that we include the '['. */
3498 	bn = ptr[col] == ']';
3499 #endif
3500 
3501 	/*
3502 	 * 2. Back up to start of identifier/string.
3503 	 */
3504 #ifdef FEAT_MBYTE
3505 	if (has_mbyte)
3506 	{
3507 	    /* Remember class of character under cursor. */
3508 # if defined(FEAT_BEVAL)
3509 	    if ((find_type & FIND_EVAL) && ptr[col] == ']')
3510 		this_class = mb_get_class((char_u *)"a");
3511 	    else
3512 # endif
3513 		this_class = mb_get_class(ptr + col);
3514 	    while (col > 0 && this_class != 0)
3515 	    {
3516 		prevcol = col - 1 - (*mb_head_off)(ptr, ptr + col - 1);
3517 		prev_class = mb_get_class(ptr + prevcol);
3518 		if (this_class != prev_class
3519 			&& (i == 0
3520 			    || prev_class == 0
3521 			    || (find_type & FIND_IDENT))
3522 # if defined(FEAT_BEVAL)
3523 			&& (!(find_type & FIND_EVAL)
3524 			    || prevcol == 0
3525 			    || !find_is_eval_item(ptr + prevcol, &prevcol,
3526 							       &bn, BACKWARD))
3527 # endif
3528 			)
3529 		    break;
3530 		col = prevcol;
3531 	    }
3532 
3533 	    /* If we don't want just any old string, or we've found an
3534 	     * identifier, stop searching. */
3535 	    if (this_class > 2)
3536 		this_class = 2;
3537 	    if (!(find_type & FIND_STRING) || this_class == 2)
3538 		break;
3539 	}
3540 	else
3541 #endif
3542 	{
3543 	    while (col > 0
3544 		    && ((i == 0
3545 			    ? vim_iswordc(ptr[col - 1])
3546 			    : (!vim_iswhite(ptr[col - 1])
3547 				&& (!(find_type & FIND_IDENT)
3548 				    || !vim_iswordc(ptr[col - 1]))))
3549 #if defined(FEAT_BEVAL)
3550 			|| ((find_type & FIND_EVAL)
3551 			    && col > 1
3552 			    && find_is_eval_item(ptr + col - 1, &col,
3553 							       &bn, BACKWARD))
3554 #endif
3555 			))
3556 		--col;
3557 
3558 	    /* If we don't want just any old string, or we've found an
3559 	     * identifier, stop searching. */
3560 	    if (!(find_type & FIND_STRING) || vim_iswordc(ptr[col]))
3561 		break;
3562 	}
3563     }
3564 
3565     if (ptr[col] == NUL || (i == 0 && (
3566 #ifdef FEAT_MBYTE
3567 		has_mbyte ? this_class != 2 :
3568 #endif
3569 		!vim_iswordc(ptr[col]))))
3570     {
3571 	/*
3572 	 * didn't find an identifier or string
3573 	 */
3574 	if (find_type & FIND_STRING)
3575 	    EMSG(_("E348: No string under cursor"));
3576 	else
3577 	    EMSG(_(e_noident));
3578 	return 0;
3579     }
3580     ptr += col;
3581     *string = ptr;
3582 
3583     /*
3584      * 3. Find the end if the identifier/string.
3585      */
3586 #if defined(FEAT_BEVAL)
3587     bn = 0;
3588     startcol -= col;
3589 #endif
3590     col = 0;
3591 #ifdef FEAT_MBYTE
3592     if (has_mbyte)
3593     {
3594 	/* Search for point of changing multibyte character class. */
3595 	this_class = mb_get_class(ptr);
3596 	while (ptr[col] != NUL
3597 		&& ((i == 0 ? mb_get_class(ptr + col) == this_class
3598 			    : mb_get_class(ptr + col) != 0)
3599 # if defined(FEAT_BEVAL)
3600 		    || ((find_type & FIND_EVAL)
3601 			&& col <= (int)startcol
3602 			&& find_is_eval_item(ptr + col, &col, &bn, FORWARD))
3603 # endif
3604 		))
3605 	    col += (*mb_ptr2len)(ptr + col);
3606     }
3607     else
3608 #endif
3609 	while ((i == 0 ? vim_iswordc(ptr[col])
3610 		       : (ptr[col] != NUL && !vim_iswhite(ptr[col])))
3611 # if defined(FEAT_BEVAL)
3612 		    || ((find_type & FIND_EVAL)
3613 			&& col <= (int)startcol
3614 			&& find_is_eval_item(ptr + col, &col, &bn, FORWARD))
3615 # endif
3616 		)
3617 	{
3618 	    ++col;
3619 	}
3620 
3621     return col;
3622 }
3623 
3624 /*
3625  * Prepare for redo of a normal command.
3626  */
3627     static void
3628 prep_redo_cmd(cap)
3629     cmdarg_T  *cap;
3630 {
3631     prep_redo(cap->oap->regname, cap->count0,
3632 				     NUL, cap->cmdchar, NUL, NUL, cap->nchar);
3633 }
3634 
3635 /*
3636  * Prepare for redo of any command.
3637  * Note that only the last argument can be a multi-byte char.
3638  */
3639     static void
3640 prep_redo(regname, num, cmd1, cmd2, cmd3, cmd4, cmd5)
3641     int	    regname;
3642     long    num;
3643     int	    cmd1;
3644     int	    cmd2;
3645     int	    cmd3;
3646     int	    cmd4;
3647     int	    cmd5;
3648 {
3649     ResetRedobuff();
3650     if (regname != 0)	/* yank from specified buffer */
3651     {
3652 	AppendCharToRedobuff('"');
3653 	AppendCharToRedobuff(regname);
3654     }
3655     if (num)
3656 	AppendNumberToRedobuff(num);
3657 
3658     if (cmd1 != NUL)
3659 	AppendCharToRedobuff(cmd1);
3660     if (cmd2 != NUL)
3661 	AppendCharToRedobuff(cmd2);
3662     if (cmd3 != NUL)
3663 	AppendCharToRedobuff(cmd3);
3664     if (cmd4 != NUL)
3665 	AppendCharToRedobuff(cmd4);
3666     if (cmd5 != NUL)
3667 	AppendCharToRedobuff(cmd5);
3668 }
3669 
3670 /*
3671  * check for operator active and clear it
3672  *
3673  * return TRUE if operator was active
3674  */
3675     static int
3676 checkclearop(oap)
3677     oparg_T	*oap;
3678 {
3679     if (oap->op_type == OP_NOP)
3680 	return FALSE;
3681     clearopbeep(oap);
3682     return TRUE;
3683 }
3684 
3685 /*
3686  * Check for operator or Visual active.  Clear active operator.
3687  *
3688  * Return TRUE if operator or Visual was active.
3689  */
3690     static int
3691 checkclearopq(oap)
3692     oparg_T	*oap;
3693 {
3694     if (oap->op_type == OP_NOP && !VIsual_active)
3695 	return FALSE;
3696     clearopbeep(oap);
3697     return TRUE;
3698 }
3699 
3700     static void
3701 clearop(oap)
3702     oparg_T	*oap;
3703 {
3704     oap->op_type = OP_NOP;
3705     oap->regname = 0;
3706     oap->motion_force = NUL;
3707     oap->use_reg_one = FALSE;
3708 }
3709 
3710     static void
3711 clearopbeep(oap)
3712     oparg_T	*oap;
3713 {
3714     clearop(oap);
3715     beep_flush();
3716 }
3717 
3718 /*
3719  * Remove the shift modifier from a special key.
3720  */
3721     static void
3722 unshift_special(cap)
3723     cmdarg_T	*cap;
3724 {
3725     switch (cap->cmdchar)
3726     {
3727 	case K_S_RIGHT:	cap->cmdchar = K_RIGHT; break;
3728 	case K_S_LEFT:	cap->cmdchar = K_LEFT; break;
3729 	case K_S_UP:	cap->cmdchar = K_UP; break;
3730 	case K_S_DOWN:	cap->cmdchar = K_DOWN; break;
3731 	case K_S_HOME:	cap->cmdchar = K_HOME; break;
3732 	case K_S_END:	cap->cmdchar = K_END; break;
3733     }
3734     cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask);
3735 }
3736 
3737 /*
3738  * If the mode is currently displayed clear the command line or update the
3739  * command displayed.
3740  */
3741     static void
3742 may_clear_cmdline()
3743 {
3744     if (mode_displayed)
3745 	clear_cmdline = TRUE;   /* unshow visual mode later */
3746 #ifdef FEAT_CMDL_INFO
3747     else
3748 	clear_showcmd();
3749 #endif
3750 }
3751 
3752 #if defined(FEAT_CMDL_INFO) || defined(PROTO)
3753 /*
3754  * Routines for displaying a partly typed command
3755  */
3756 
3757 #define SHOWCMD_BUFLEN SHOWCMD_COLS + 1 + 30
3758 static char_u	showcmd_buf[SHOWCMD_BUFLEN];
3759 static char_u	old_showcmd_buf[SHOWCMD_BUFLEN];  /* For push_showcmd() */
3760 static int	showcmd_is_clear = TRUE;
3761 static int	showcmd_visual = FALSE;
3762 
3763 static void display_showcmd __ARGS((void));
3764 
3765     void
3766 clear_showcmd()
3767 {
3768     if (!p_sc)
3769 	return;
3770 
3771     if (VIsual_active && !char_avail())
3772     {
3773 	int		cursor_bot = lt(VIsual, curwin->w_cursor);
3774 	long		lines;
3775 	colnr_T		leftcol, rightcol;
3776 	linenr_T	top, bot;
3777 
3778 	/* Show the size of the Visual area. */
3779 	if (cursor_bot)
3780 	{
3781 	    top = VIsual.lnum;
3782 	    bot = curwin->w_cursor.lnum;
3783 	}
3784 	else
3785 	{
3786 	    top = curwin->w_cursor.lnum;
3787 	    bot = VIsual.lnum;
3788 	}
3789 # ifdef FEAT_FOLDING
3790 	/* Include closed folds as a whole. */
3791 	(void)hasFolding(top, &top, NULL);
3792 	(void)hasFolding(bot, NULL, &bot);
3793 # endif
3794 	lines = bot - top + 1;
3795 
3796 	if (VIsual_mode == Ctrl_V)
3797 	{
3798 # ifdef FEAT_LINEBREAK
3799 	    char_u *saved_sbr = p_sbr;
3800 
3801 	    /* Make 'sbr' empty for a moment to get the correct size. */
3802 	    p_sbr = empty_option;
3803 # endif
3804 	    getvcols(curwin, &curwin->w_cursor, &VIsual, &leftcol, &rightcol);
3805 # ifdef FEAT_LINEBREAK
3806 	    p_sbr = saved_sbr;
3807 # endif
3808 	    sprintf((char *)showcmd_buf, "%ldx%ld", lines,
3809 					      (long)(rightcol - leftcol + 1));
3810 	}
3811 	else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum)
3812 	    sprintf((char *)showcmd_buf, "%ld", lines);
3813 	else
3814 	{
3815 	    char_u  *s, *e;
3816 	    int	    l;
3817 	    int	    bytes = 0;
3818 	    int	    chars = 0;
3819 
3820 	    if (cursor_bot)
3821 	    {
3822 		s = ml_get_pos(&VIsual);
3823 		e = ml_get_cursor();
3824 	    }
3825 	    else
3826 	    {
3827 		s = ml_get_cursor();
3828 		e = ml_get_pos(&VIsual);
3829 	    }
3830 	    while ((*p_sel != 'e') ? s <= e : s < e)
3831 	    {
3832 # ifdef FEAT_MBYTE
3833 		l = (*mb_ptr2len)(s);
3834 # else
3835 		l = (*s == NUL) ? 0 : 1;
3836 # endif
3837 		if (l == 0)
3838 		{
3839 		    ++bytes;
3840 		    ++chars;
3841 		    break;  /* end of line */
3842 		}
3843 		bytes += l;
3844 		++chars;
3845 		s += l;
3846 	    }
3847 	    if (bytes == chars)
3848 		sprintf((char *)showcmd_buf, "%d", chars);
3849 	    else
3850 		sprintf((char *)showcmd_buf, "%d-%d", chars, bytes);
3851 	}
3852 	showcmd_buf[SHOWCMD_COLS] = NUL;	/* truncate */
3853 	showcmd_visual = TRUE;
3854     }
3855     else
3856     {
3857 	showcmd_buf[0] = NUL;
3858 	showcmd_visual = FALSE;
3859 
3860 	/* Don't actually display something if there is nothing to clear. */
3861 	if (showcmd_is_clear)
3862 	    return;
3863     }
3864 
3865     display_showcmd();
3866 }
3867 
3868 /*
3869  * Add 'c' to string of shown command chars.
3870  * Return TRUE if output has been written (and setcursor() has been called).
3871  */
3872     int
3873 add_to_showcmd(c)
3874     int		c;
3875 {
3876     char_u	*p;
3877     int		old_len;
3878     int		extra_len;
3879     int		overflow;
3880 #if defined(FEAT_MOUSE)
3881     int		i;
3882     static int	ignore[] =
3883     {
3884 # ifdef FEAT_GUI
3885 	K_VER_SCROLLBAR, K_HOR_SCROLLBAR,
3886 	K_LEFTMOUSE_NM, K_LEFTRELEASE_NM,
3887 # endif
3888 	K_IGNORE,
3889 	K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE,
3890 	K_MIDDLEMOUSE, K_MIDDLEDRAG, K_MIDDLERELEASE,
3891 	K_RIGHTMOUSE, K_RIGHTDRAG, K_RIGHTRELEASE,
3892 	K_MOUSEDOWN, K_MOUSEUP, K_MOUSELEFT, K_MOUSERIGHT,
3893 	K_X1MOUSE, K_X1DRAG, K_X1RELEASE, K_X2MOUSE, K_X2DRAG, K_X2RELEASE,
3894 	K_CURSORHOLD,
3895 	0
3896     };
3897 #endif
3898 
3899     if (!p_sc || msg_silent != 0)
3900 	return FALSE;
3901 
3902     if (showcmd_visual)
3903     {
3904 	showcmd_buf[0] = NUL;
3905 	showcmd_visual = FALSE;
3906     }
3907 
3908 #if defined(FEAT_MOUSE)
3909     /* Ignore keys that are scrollbar updates and mouse clicks */
3910     if (IS_SPECIAL(c))
3911 	for (i = 0; ignore[i] != 0; ++i)
3912 	    if (ignore[i] == c)
3913 		return FALSE;
3914 #endif
3915 
3916     p = transchar(c);
3917     if (*p == ' ')
3918 	STRCPY(p, "<20>");
3919     old_len = (int)STRLEN(showcmd_buf);
3920     extra_len = (int)STRLEN(p);
3921     overflow = old_len + extra_len - SHOWCMD_COLS;
3922     if (overflow > 0)
3923 	mch_memmove(showcmd_buf, showcmd_buf + overflow,
3924 						      old_len - overflow + 1);
3925     STRCAT(showcmd_buf, p);
3926 
3927     if (char_avail())
3928 	return FALSE;
3929 
3930     display_showcmd();
3931 
3932     return TRUE;
3933 }
3934 
3935     void
3936 add_to_showcmd_c(c)
3937     int		c;
3938 {
3939     if (!add_to_showcmd(c))
3940 	setcursor();
3941 }
3942 
3943 /*
3944  * Delete 'len' characters from the end of the shown command.
3945  */
3946     static void
3947 del_from_showcmd(len)
3948     int	    len;
3949 {
3950     int	    old_len;
3951 
3952     if (!p_sc)
3953 	return;
3954 
3955     old_len = (int)STRLEN(showcmd_buf);
3956     if (len > old_len)
3957 	len = old_len;
3958     showcmd_buf[old_len - len] = NUL;
3959 
3960     if (!char_avail())
3961 	display_showcmd();
3962 }
3963 
3964 /*
3965  * push_showcmd() and pop_showcmd() are used when waiting for the user to type
3966  * something and there is a partial mapping.
3967  */
3968     void
3969 push_showcmd()
3970 {
3971     if (p_sc)
3972 	STRCPY(old_showcmd_buf, showcmd_buf);
3973 }
3974 
3975     void
3976 pop_showcmd()
3977 {
3978     if (!p_sc)
3979 	return;
3980 
3981     STRCPY(showcmd_buf, old_showcmd_buf);
3982 
3983     display_showcmd();
3984 }
3985 
3986     static void
3987 display_showcmd()
3988 {
3989     int	    len;
3990 
3991     cursor_off();
3992 
3993     len = (int)STRLEN(showcmd_buf);
3994     if (len == 0)
3995 	showcmd_is_clear = TRUE;
3996     else
3997     {
3998 	screen_puts(showcmd_buf, (int)Rows - 1, sc_col, 0);
3999 	showcmd_is_clear = FALSE;
4000     }
4001 
4002     /*
4003      * clear the rest of an old message by outputting up to SHOWCMD_COLS
4004      * spaces
4005      */
4006     screen_puts((char_u *)"          " + len, (int)Rows - 1, sc_col + len, 0);
4007 
4008     setcursor();	    /* put cursor back where it belongs */
4009 }
4010 #endif
4011 
4012 #ifdef FEAT_SCROLLBIND
4013 /*
4014  * When "check" is FALSE, prepare for commands that scroll the window.
4015  * When "check" is TRUE, take care of scroll-binding after the window has
4016  * scrolled.  Called from normal_cmd() and edit().
4017  */
4018     void
4019 do_check_scrollbind(check)
4020     int		check;
4021 {
4022     static win_T	*old_curwin = NULL;
4023     static linenr_T	old_topline = 0;
4024 #ifdef FEAT_DIFF
4025     static int		old_topfill = 0;
4026 #endif
4027     static buf_T	*old_buf = NULL;
4028     static colnr_T	old_leftcol = 0;
4029 
4030     if (check && curwin->w_p_scb)
4031     {
4032 	/* If a ":syncbind" command was just used, don't scroll, only reset
4033 	 * the values. */
4034 	if (did_syncbind)
4035 	    did_syncbind = FALSE;
4036 	else if (curwin == old_curwin)
4037 	{
4038 	    /*
4039 	     * Synchronize other windows, as necessary according to
4040 	     * 'scrollbind'.  Don't do this after an ":edit" command, except
4041 	     * when 'diff' is set.
4042 	     */
4043 	    if ((curwin->w_buffer == old_buf
4044 #ifdef FEAT_DIFF
4045 			|| curwin->w_p_diff
4046 #endif
4047 		)
4048 		&& (curwin->w_topline != old_topline
4049 #ifdef FEAT_DIFF
4050 			|| curwin->w_topfill != old_topfill
4051 #endif
4052 			|| curwin->w_leftcol != old_leftcol))
4053 	    {
4054 		check_scrollbind(curwin->w_topline - old_topline,
4055 			(long)(curwin->w_leftcol - old_leftcol));
4056 	    }
4057 	}
4058 	else if (vim_strchr(p_sbo, 'j')) /* jump flag set in 'scrollopt' */
4059 	{
4060 	    /*
4061 	     * When switching between windows, make sure that the relative
4062 	     * vertical offset is valid for the new window.  The relative
4063 	     * offset is invalid whenever another 'scrollbind' window has
4064 	     * scrolled to a point that would force the current window to
4065 	     * scroll past the beginning or end of its buffer.  When the
4066 	     * resync is performed, some of the other 'scrollbind' windows may
4067 	     * need to jump so that the current window's relative position is
4068 	     * visible on-screen.
4069 	     */
4070 	    check_scrollbind(curwin->w_topline - curwin->w_scbind_pos, 0L);
4071 	}
4072 	curwin->w_scbind_pos = curwin->w_topline;
4073     }
4074 
4075     old_curwin = curwin;
4076     old_topline = curwin->w_topline;
4077 #ifdef FEAT_DIFF
4078     old_topfill = curwin->w_topfill;
4079 #endif
4080     old_buf = curwin->w_buffer;
4081     old_leftcol = curwin->w_leftcol;
4082 }
4083 
4084 /*
4085  * Synchronize any windows that have "scrollbind" set, based on the
4086  * number of rows by which the current window has changed
4087  * (1998-11-02 16:21:01  R. Edward Ralston <[email protected]>)
4088  */
4089     void
4090 check_scrollbind(topline_diff, leftcol_diff)
4091     linenr_T	topline_diff;
4092     long	leftcol_diff;
4093 {
4094     int		want_ver;
4095     int		want_hor;
4096     win_T	*old_curwin = curwin;
4097     buf_T	*old_curbuf = curbuf;
4098     int		old_VIsual_select = VIsual_select;
4099     int		old_VIsual_active = VIsual_active;
4100     colnr_T	tgt_leftcol = curwin->w_leftcol;
4101     long	topline;
4102     long	y;
4103 
4104     /*
4105      * check 'scrollopt' string for vertical and horizontal scroll options
4106      */
4107     want_ver = (vim_strchr(p_sbo, 'v') && topline_diff != 0);
4108 #ifdef FEAT_DIFF
4109     want_ver |= old_curwin->w_p_diff;
4110 #endif
4111     want_hor = (vim_strchr(p_sbo, 'h') && (leftcol_diff || topline_diff != 0));
4112 
4113     /*
4114      * loop through the scrollbound windows and scroll accordingly
4115      */
4116     VIsual_select = VIsual_active = 0;
4117     for (curwin = firstwin; curwin; curwin = curwin->w_next)
4118     {
4119 	curbuf = curwin->w_buffer;
4120 	/* skip original window  and windows with 'noscrollbind' */
4121 	if (curwin != old_curwin && curwin->w_p_scb)
4122 	{
4123 	    /*
4124 	     * do the vertical scroll
4125 	     */
4126 	    if (want_ver)
4127 	    {
4128 #ifdef FEAT_DIFF
4129 		if (old_curwin->w_p_diff && curwin->w_p_diff)
4130 		{
4131 		    diff_set_topline(old_curwin, curwin);
4132 		}
4133 		else
4134 #endif
4135 		{
4136 		    curwin->w_scbind_pos += topline_diff;
4137 		    topline = curwin->w_scbind_pos;
4138 		    if (topline > curbuf->b_ml.ml_line_count)
4139 			topline = curbuf->b_ml.ml_line_count;
4140 		    if (topline < 1)
4141 			topline = 1;
4142 
4143 		    y = topline - curwin->w_topline;
4144 		    if (y > 0)
4145 			scrollup(y, FALSE);
4146 		    else
4147 			scrolldown(-y, FALSE);
4148 		}
4149 
4150 		redraw_later(VALID);
4151 		cursor_correct();
4152 #ifdef FEAT_WINDOWS
4153 		curwin->w_redr_status = TRUE;
4154 #endif
4155 	    }
4156 
4157 	    /*
4158 	     * do the horizontal scroll
4159 	     */
4160 	    if (want_hor && curwin->w_leftcol != tgt_leftcol)
4161 	    {
4162 		curwin->w_leftcol = tgt_leftcol;
4163 		leftcol_changed();
4164 	    }
4165 	}
4166     }
4167 
4168     /*
4169      * reset current-window
4170      */
4171     VIsual_select = old_VIsual_select;
4172     VIsual_active = old_VIsual_active;
4173     curwin = old_curwin;
4174     curbuf = old_curbuf;
4175 }
4176 #endif /* #ifdef FEAT_SCROLLBIND */
4177 
4178 /*
4179  * Command character that's ignored.
4180  * Used for CTRL-Q and CTRL-S to avoid problems with terminals that use
4181  * xon/xoff.
4182  */
4183     static void
4184 nv_ignore(cap)
4185     cmdarg_T	*cap;
4186 {
4187     cap->retval |= CA_COMMAND_BUSY;	/* don't call edit() now */
4188 }
4189 
4190 /*
4191  * Command character that doesn't do anything, but unlike nv_ignore() does
4192  * start edit().  Used for "startinsert" executed while starting up.
4193  */
4194     static void
4195 nv_nop(cap)
4196     cmdarg_T	*cap UNUSED;
4197 {
4198 }
4199 
4200 /*
4201  * Command character doesn't exist.
4202  */
4203     static void
4204 nv_error(cap)
4205     cmdarg_T	*cap;
4206 {
4207     clearopbeep(cap->oap);
4208 }
4209 
4210 /*
4211  * <Help> and <F1> commands.
4212  */
4213     static void
4214 nv_help(cap)
4215     cmdarg_T	*cap;
4216 {
4217     if (!checkclearopq(cap->oap))
4218 	ex_help(NULL);
4219 }
4220 
4221 /*
4222  * CTRL-A and CTRL-X: Add or subtract from letter or number under cursor.
4223  */
4224     static void
4225 nv_addsub(cap)
4226     cmdarg_T	*cap;
4227 {
4228     if (!VIsual_active && cap->oap->op_type == OP_NOP)
4229     {
4230 	prep_redo_cmd(cap);
4231 	cap->oap->op_type = cap->cmdchar == Ctrl_A ?  OP_NR_ADD : OP_NR_SUB;
4232 	op_addsub(cap->oap, cap->count1, cap->arg);
4233 	cap->oap->op_type = OP_NOP;
4234     }
4235     else if (VIsual_active)
4236 	nv_operator(cap);
4237     else
4238 	clearop(cap->oap);
4239 }
4240 
4241 /*
4242  * CTRL-F, CTRL-B, etc: Scroll page up or down.
4243  */
4244     static void
4245 nv_page(cap)
4246     cmdarg_T	*cap;
4247 {
4248     if (!checkclearop(cap->oap))
4249     {
4250 #ifdef FEAT_WINDOWS
4251 	if (mod_mask & MOD_MASK_CTRL)
4252 	{
4253 	    /* <C-PageUp>: tab page back; <C-PageDown>: tab page forward */
4254 	    if (cap->arg == BACKWARD)
4255 		goto_tabpage(-(int)cap->count1);
4256 	    else
4257 		goto_tabpage((int)cap->count0);
4258 	}
4259 	else
4260 #endif
4261 	(void)onepage(cap->arg, cap->count1);
4262     }
4263 }
4264 
4265 /*
4266  * Implementation of "gd" and "gD" command.
4267  */
4268     static void
4269 nv_gd(oap, nchar, thisblock)
4270     oparg_T	*oap;
4271     int		nchar;
4272     int		thisblock;	/* 1 for "1gd" and "1gD" */
4273 {
4274     int		len;
4275     char_u	*ptr;
4276 
4277     if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0
4278 	    || find_decl(ptr, len, nchar == 'd', thisblock, 0) == FAIL)
4279 	clearopbeep(oap);
4280 #ifdef FEAT_FOLDING
4281     else if ((fdo_flags & FDO_SEARCH) && KeyTyped && oap->op_type == OP_NOP)
4282 	foldOpenCursor();
4283 #endif
4284 }
4285 
4286 /*
4287  * Search for variable declaration of "ptr[len]".
4288  * When "locally" is TRUE in the current function ("gd"), otherwise in the
4289  * current file ("gD").
4290  * When "thisblock" is TRUE check the {} block scope.
4291  * Return FAIL when not found.
4292  */
4293     int
4294 find_decl(ptr, len, locally, thisblock, searchflags)
4295     char_u	*ptr;
4296     int		len;
4297     int		locally;
4298     int		thisblock;
4299     int		searchflags;	/* flags passed to searchit() */
4300 {
4301     char_u	*pat;
4302     pos_T	old_pos;
4303     pos_T	par_pos;
4304     pos_T	found_pos;
4305     int		t;
4306     int		save_p_ws;
4307     int		save_p_scs;
4308     int		retval = OK;
4309     int		incll;
4310 
4311     if ((pat = alloc(len + 7)) == NULL)
4312 	return FAIL;
4313 
4314     /* Put "\V" before the pattern to avoid that the special meaning of "."
4315      * and "~" causes trouble. */
4316     sprintf((char *)pat, vim_iswordp(ptr) ? "\\V\\<%.*s\\>" : "\\V%.*s",
4317 								    len, ptr);
4318     old_pos = curwin->w_cursor;
4319     save_p_ws = p_ws;
4320     save_p_scs = p_scs;
4321     p_ws = FALSE;	/* don't wrap around end of file now */
4322     p_scs = FALSE;	/* don't switch ignorecase off now */
4323 
4324     /*
4325      * With "gD" go to line 1.
4326      * With "gd" Search back for the start of the current function, then go
4327      * back until a blank line.  If this fails go to line 1.
4328      */
4329     if (!locally || !findpar(&incll, BACKWARD, 1L, '{', FALSE))
4330     {
4331 	setpcmark();			/* Set in findpar() otherwise */
4332 	curwin->w_cursor.lnum = 1;
4333 	par_pos = curwin->w_cursor;
4334     }
4335     else
4336     {
4337 	par_pos = curwin->w_cursor;
4338 	while (curwin->w_cursor.lnum > 1 && *skipwhite(ml_get_curline()) != NUL)
4339 	    --curwin->w_cursor.lnum;
4340     }
4341     curwin->w_cursor.col = 0;
4342 
4343     /* Search forward for the identifier, ignore comment lines. */
4344     clearpos(&found_pos);
4345     for (;;)
4346     {
4347 	t = searchit(curwin, curbuf, &curwin->w_cursor, FORWARD,
4348 			    pat, 1L, searchflags, RE_LAST, (linenr_T)0, NULL);
4349 	if (curwin->w_cursor.lnum >= old_pos.lnum)
4350 	    t = FAIL;	/* match after start is failure too */
4351 
4352 	if (thisblock && t != FAIL)
4353 	{
4354 	    pos_T	*pos;
4355 
4356 	    /* Check that the block the match is in doesn't end before the
4357 	     * position where we started the search from. */
4358 	    if ((pos = findmatchlimit(NULL, '}', FM_FORWARD,
4359 		     (int)(old_pos.lnum - curwin->w_cursor.lnum + 1))) != NULL
4360 		    && pos->lnum < old_pos.lnum)
4361 		continue;
4362 	}
4363 
4364 	if (t == FAIL)
4365 	{
4366 	    /* If we previously found a valid position, use it. */
4367 	    if (found_pos.lnum != 0)
4368 	    {
4369 		curwin->w_cursor = found_pos;
4370 		t = OK;
4371 	    }
4372 	    break;
4373 	}
4374 #ifdef FEAT_COMMENTS
4375 	if (get_leader_len(ml_get_curline(), NULL, FALSE, TRUE) > 0)
4376 	{
4377 	    /* Ignore this line, continue at start of next line. */
4378 	    ++curwin->w_cursor.lnum;
4379 	    curwin->w_cursor.col = 0;
4380 	    continue;
4381 	}
4382 #endif
4383 	if (!locally)	/* global search: use first match found */
4384 	    break;
4385 	if (curwin->w_cursor.lnum >= par_pos.lnum)
4386 	{
4387 	    /* If we previously found a valid position, use it. */
4388 	    if (found_pos.lnum != 0)
4389 		curwin->w_cursor = found_pos;
4390 	    break;
4391 	}
4392 
4393 	/* For finding a local variable and the match is before the "{" search
4394 	 * to find a later match.  For K&R style function declarations this
4395 	 * skips the function header without types. */
4396 	found_pos = curwin->w_cursor;
4397     }
4398 
4399     if (t == FAIL)
4400     {
4401 	retval = FAIL;
4402 	curwin->w_cursor = old_pos;
4403     }
4404     else
4405     {
4406 	curwin->w_set_curswant = TRUE;
4407 	/* "n" searches forward now */
4408 	reset_search_dir();
4409     }
4410 
4411     vim_free(pat);
4412     p_ws = save_p_ws;
4413     p_scs = save_p_scs;
4414 
4415     return retval;
4416 }
4417 
4418 /*
4419  * Move 'dist' lines in direction 'dir', counting lines by *screen*
4420  * lines rather than lines in the file.
4421  * 'dist' must be positive.
4422  *
4423  * Return OK if able to move cursor, FAIL otherwise.
4424  */
4425     static int
4426 nv_screengo(oap, dir, dist)
4427     oparg_T	*oap;
4428     int		dir;
4429     long	dist;
4430 {
4431     int		linelen = linetabsize(ml_get_curline());
4432     int		retval = OK;
4433     int		atend = FALSE;
4434     int		n;
4435     int		col_off1;	/* margin offset for first screen line */
4436     int		col_off2;	/* margin offset for wrapped screen line */
4437     int		width1;		/* text width for first screen line */
4438     int		width2;		/* test width for wrapped screen line */
4439 
4440     oap->motion_type = MCHAR;
4441     oap->inclusive = (curwin->w_curswant == MAXCOL);
4442 
4443     col_off1 = curwin_col_off();
4444     col_off2 = col_off1 - curwin_col_off2();
4445     width1 = W_WIDTH(curwin) - col_off1;
4446     width2 = W_WIDTH(curwin) - col_off2;
4447     if (width2 == 0)
4448 	width2 = 1; /* avoid divide by zero */
4449 
4450 #ifdef FEAT_VERTSPLIT
4451     if (curwin->w_width != 0)
4452     {
4453 #endif
4454       /*
4455        * Instead of sticking at the last character of the buffer line we
4456        * try to stick in the last column of the screen.
4457        */
4458       if (curwin->w_curswant == MAXCOL)
4459       {
4460 	atend = TRUE;
4461 	validate_virtcol();
4462 	if (width1 <= 0)
4463 	    curwin->w_curswant = 0;
4464 	else
4465 	{
4466 	    curwin->w_curswant = width1 - 1;
4467 	    if (curwin->w_virtcol > curwin->w_curswant)
4468 		curwin->w_curswant += ((curwin->w_virtcol
4469 			     - curwin->w_curswant - 1) / width2 + 1) * width2;
4470 	}
4471       }
4472       else
4473       {
4474 	if (linelen > width1)
4475 	    n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1;
4476 	else
4477 	    n = width1;
4478 	if (curwin->w_curswant > (colnr_T)n + 1)
4479 	    curwin->w_curswant -= ((curwin->w_curswant - n) / width2 + 1)
4480 								     * width2;
4481       }
4482 
4483       while (dist--)
4484       {
4485 	if (dir == BACKWARD)
4486 	{
4487 	    if ((long)curwin->w_curswant >= width2)
4488 		/* move back within line */
4489 		curwin->w_curswant -= width2;
4490 	    else
4491 	    {
4492 		/* to previous line */
4493 		if (curwin->w_cursor.lnum == 1)
4494 		{
4495 		    retval = FAIL;
4496 		    break;
4497 		}
4498 		--curwin->w_cursor.lnum;
4499 #ifdef FEAT_FOLDING
4500 		/* Move to the start of a closed fold.  Don't do that when
4501 		 * 'foldopen' contains "all": it will open in a moment. */
4502 		if (!(fdo_flags & FDO_ALL))
4503 		    (void)hasFolding(curwin->w_cursor.lnum,
4504 						&curwin->w_cursor.lnum, NULL);
4505 #endif
4506 		linelen = linetabsize(ml_get_curline());
4507 		if (linelen > width1)
4508 		    curwin->w_curswant += (((linelen - width1 - 1) / width2)
4509 								+ 1) * width2;
4510 	    }
4511 	}
4512 	else /* dir == FORWARD */
4513 	{
4514 	    if (linelen > width1)
4515 		n = ((linelen - width1 - 1) / width2 + 1) * width2 + width1;
4516 	    else
4517 		n = width1;
4518 	    if (curwin->w_curswant + width2 < (colnr_T)n)
4519 		/* move forward within line */
4520 		curwin->w_curswant += width2;
4521 	    else
4522 	    {
4523 		/* to next line */
4524 #ifdef FEAT_FOLDING
4525 		/* Move to the end of a closed fold. */
4526 		(void)hasFolding(curwin->w_cursor.lnum, NULL,
4527 						      &curwin->w_cursor.lnum);
4528 #endif
4529 		if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
4530 		{
4531 		    retval = FAIL;
4532 		    break;
4533 		}
4534 		curwin->w_cursor.lnum++;
4535 		curwin->w_curswant %= width2;
4536 		linelen = linetabsize(ml_get_curline());
4537 	    }
4538 	}
4539       }
4540 #ifdef FEAT_VERTSPLIT
4541     }
4542 #endif
4543 
4544     if (virtual_active() && atend)
4545 	coladvance(MAXCOL);
4546     else
4547 	coladvance(curwin->w_curswant);
4548 
4549 #if defined(FEAT_LINEBREAK) || defined(FEAT_MBYTE)
4550     if (curwin->w_cursor.col > 0 && curwin->w_p_wrap)
4551     {
4552 	colnr_T virtcol;
4553 
4554 	/*
4555 	 * Check for landing on a character that got split at the end of the
4556 	 * last line.  We want to advance a screenline, not end up in the same
4557 	 * screenline or move two screenlines.
4558 	 */
4559 	validate_virtcol();
4560 	virtcol = curwin->w_virtcol;
4561 # if defined(FEAT_LINEBREAK)
4562 	if (virtcol > (colnr_T)width1 && *p_sbr != NUL)
4563 	    virtcol -= vim_strsize(p_sbr);
4564 # endif
4565 
4566 	if (virtcol > curwin->w_curswant
4567 		&& (curwin->w_curswant < (colnr_T)width1
4568 		    ? (curwin->w_curswant > (colnr_T)width1 / 2)
4569 		    : ((curwin->w_curswant - width1) % width2
4570 						      > (colnr_T)width2 / 2)))
4571 	    --curwin->w_cursor.col;
4572     }
4573 #endif
4574 
4575     if (atend)
4576 	curwin->w_curswant = MAXCOL;	    /* stick in the last column */
4577 
4578     return retval;
4579 }
4580 
4581 #ifdef FEAT_MOUSE
4582 /*
4583  * Mouse scroll wheel: Default action is to scroll three lines, or one page
4584  * when Shift or Ctrl is used.
4585  * K_MOUSEUP (cap->arg == 1) or K_MOUSEDOWN (cap->arg == 0) or
4586  * K_MOUSELEFT (cap->arg == -1) or K_MOUSERIGHT (cap->arg == -2)
4587  */
4588     static void
4589 nv_mousescroll(cap)
4590     cmdarg_T	*cap;
4591 {
4592 # ifdef FEAT_WINDOWS
4593     win_T *old_curwin = curwin;
4594 
4595     if (mouse_row >= 0 && mouse_col >= 0)
4596     {
4597 	int row, col;
4598 
4599 	row = mouse_row;
4600 	col = mouse_col;
4601 
4602 	/* find the window at the pointer coordinates */
4603 	curwin = mouse_find_win(&row, &col);
4604 	curbuf = curwin->w_buffer;
4605     }
4606 # endif
4607 
4608     if (cap->arg == MSCR_UP || cap->arg == MSCR_DOWN)
4609     {
4610 	if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
4611 	{
4612 	    (void)onepage(cap->arg ? FORWARD : BACKWARD, 1L);
4613 	}
4614 	else
4615 	{
4616 	    cap->count1 = 3;
4617 	    cap->count0 = 3;
4618 	    nv_scroll_line(cap);
4619 	}
4620     }
4621 # ifdef FEAT_GUI
4622     else
4623     {
4624 	/* Horizontal scroll - only allowed when 'wrap' is disabled */
4625 	if (!curwin->w_p_wrap)
4626 	{
4627 	    int val, step = 6;
4628 
4629 	    if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
4630 		step = W_WIDTH(curwin);
4631 	    val = curwin->w_leftcol + (cap->arg == MSCR_RIGHT ? -step : +step);
4632 	    if (val < 0)
4633 		val = 0;
4634 
4635 	    gui_do_horiz_scroll(val, TRUE);
4636 	}
4637     }
4638 # endif
4639 
4640 # ifdef FEAT_WINDOWS
4641     curwin->w_redr_status = TRUE;
4642 
4643     curwin = old_curwin;
4644     curbuf = curwin->w_buffer;
4645 # endif
4646 }
4647 
4648 /*
4649  * Mouse clicks and drags.
4650  */
4651     static void
4652 nv_mouse(cap)
4653     cmdarg_T	*cap;
4654 {
4655     (void)do_mouse(cap->oap, cap->cmdchar, BACKWARD, cap->count1, 0);
4656 }
4657 #endif
4658 
4659 /*
4660  * Handle CTRL-E and CTRL-Y commands: scroll a line up or down.
4661  * cap->arg must be TRUE for CTRL-E.
4662  */
4663     static void
4664 nv_scroll_line(cap)
4665     cmdarg_T	*cap;
4666 {
4667     if (!checkclearop(cap->oap))
4668 	scroll_redraw(cap->arg, cap->count1);
4669 }
4670 
4671 /*
4672  * Scroll "count" lines up or down, and redraw.
4673  */
4674     void
4675 scroll_redraw(up, count)
4676     int		up;
4677     long	count;
4678 {
4679     linenr_T	prev_topline = curwin->w_topline;
4680 #ifdef FEAT_DIFF
4681     int		prev_topfill = curwin->w_topfill;
4682 #endif
4683     linenr_T	prev_lnum = curwin->w_cursor.lnum;
4684 
4685     if (up)
4686 	scrollup(count, TRUE);
4687     else
4688 	scrolldown(count, TRUE);
4689     if (p_so)
4690     {
4691 	/* Adjust the cursor position for 'scrolloff'.  Mark w_topline as
4692 	 * valid, otherwise the screen jumps back at the end of the file. */
4693 	cursor_correct();
4694 	check_cursor_moved(curwin);
4695 	curwin->w_valid |= VALID_TOPLINE;
4696 
4697 	/* If moved back to where we were, at least move the cursor, otherwise
4698 	 * we get stuck at one position.  Don't move the cursor up if the
4699 	 * first line of the buffer is already on the screen */
4700 	while (curwin->w_topline == prev_topline
4701 #ifdef FEAT_DIFF
4702 		&& curwin->w_topfill == prev_topfill
4703 #endif
4704 		)
4705 	{
4706 	    if (up)
4707 	    {
4708 		if (curwin->w_cursor.lnum > prev_lnum
4709 			|| cursor_down(1L, FALSE) == FAIL)
4710 		    break;
4711 	    }
4712 	    else
4713 	    {
4714 		if (curwin->w_cursor.lnum < prev_lnum
4715 			|| prev_topline == 1L
4716 			|| cursor_up(1L, FALSE) == FAIL)
4717 		    break;
4718 	    }
4719 	    /* Mark w_topline as valid, otherwise the screen jumps back at the
4720 	     * end of the file. */
4721 	    check_cursor_moved(curwin);
4722 	    curwin->w_valid |= VALID_TOPLINE;
4723 	}
4724     }
4725     if (curwin->w_cursor.lnum != prev_lnum)
4726 	coladvance(curwin->w_curswant);
4727     redraw_later(VALID);
4728 }
4729 
4730 /*
4731  * Commands that start with "z".
4732  */
4733     static void
4734 nv_zet(cap)
4735     cmdarg_T  *cap;
4736 {
4737     long	n;
4738     colnr_T	col;
4739     int		nchar = cap->nchar;
4740 #ifdef FEAT_FOLDING
4741     long	old_fdl = curwin->w_p_fdl;
4742     int		old_fen = curwin->w_p_fen;
4743 #endif
4744 #ifdef FEAT_SPELL
4745     int		undo = FALSE;
4746 #endif
4747 
4748     if (VIM_ISDIGIT(nchar))
4749     {
4750 	/*
4751 	 * "z123{nchar}": edit the count before obtaining {nchar}
4752 	 */
4753 	if (checkclearop(cap->oap))
4754 	    return;
4755 	n = nchar - '0';
4756 	for (;;)
4757 	{
4758 #ifdef USE_ON_FLY_SCROLL
4759 	    dont_scroll = TRUE;		/* disallow scrolling here */
4760 #endif
4761 	    ++no_mapping;
4762 	    ++allow_keys;   /* no mapping for nchar, but allow key codes */
4763 	    nchar = plain_vgetc();
4764 	    LANGMAP_ADJUST(nchar, TRUE);
4765 	    --no_mapping;
4766 	    --allow_keys;
4767 #ifdef FEAT_CMDL_INFO
4768 	    (void)add_to_showcmd(nchar);
4769 #endif
4770 	    if (nchar == K_DEL || nchar == K_KDEL)
4771 		n /= 10;
4772 	    else if (VIM_ISDIGIT(nchar))
4773 		n = n * 10 + (nchar - '0');
4774 	    else if (nchar == CAR)
4775 	    {
4776 #ifdef FEAT_GUI
4777 		need_mouse_correct = TRUE;
4778 #endif
4779 		win_setheight((int)n);
4780 		break;
4781 	    }
4782 	    else if (nchar == 'l'
4783 		    || nchar == 'h'
4784 		    || nchar == K_LEFT
4785 		    || nchar == K_RIGHT)
4786 	    {
4787 		cap->count1 = n ? n * cap->count1 : cap->count1;
4788 		goto dozet;
4789 	    }
4790 	    else
4791 	    {
4792 		clearopbeep(cap->oap);
4793 		break;
4794 	    }
4795 	}
4796 	cap->oap->op_type = OP_NOP;
4797 	return;
4798     }
4799 
4800 dozet:
4801     if (
4802 #ifdef FEAT_FOLDING
4803 	    /* "zf" and "zF" are always an operator, "zd", "zo", "zO", "zc"
4804 	     * and "zC" only in Visual mode.  "zj" and "zk" are motion
4805 	     * commands. */
4806 	    cap->nchar != 'f' && cap->nchar != 'F'
4807 	    && !(VIsual_active && vim_strchr((char_u *)"dcCoO", cap->nchar))
4808 	    && cap->nchar != 'j' && cap->nchar != 'k'
4809 	    &&
4810 #endif
4811 	    checkclearop(cap->oap))
4812 	return;
4813 
4814     /*
4815      * For "z+", "z<CR>", "zt", "z.", "zz", "z^", "z-", "zb":
4816      * If line number given, set cursor.
4817      */
4818     if ((vim_strchr((char_u *)"+\r\nt.z^-b", nchar) != NULL)
4819 	    && cap->count0
4820 	    && cap->count0 != curwin->w_cursor.lnum)
4821     {
4822 	setpcmark();
4823 	if (cap->count0 > curbuf->b_ml.ml_line_count)
4824 	    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4825 	else
4826 	    curwin->w_cursor.lnum = cap->count0;
4827 	check_cursor_col();
4828     }
4829 
4830     switch (nchar)
4831     {
4832 		/* "z+", "z<CR>" and "zt": put cursor at top of screen */
4833     case '+':
4834 		if (cap->count0 == 0)
4835 		{
4836 		    /* No count given: put cursor at the line below screen */
4837 		    validate_botline();	/* make sure w_botline is valid */
4838 		    if (curwin->w_botline > curbuf->b_ml.ml_line_count)
4839 			curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4840 		    else
4841 			curwin->w_cursor.lnum = curwin->w_botline;
4842 		}
4843 		/* FALLTHROUGH */
4844     case NL:
4845     case CAR:
4846     case K_KENTER:
4847 		beginline(BL_WHITE | BL_FIX);
4848 		/* FALLTHROUGH */
4849 
4850     case 't':	scroll_cursor_top(0, TRUE);
4851 		redraw_later(VALID);
4852 		set_fraction(curwin);
4853 		break;
4854 
4855 		/* "z." and "zz": put cursor in middle of screen */
4856     case '.':	beginline(BL_WHITE | BL_FIX);
4857 		/* FALLTHROUGH */
4858 
4859     case 'z':	scroll_cursor_halfway(TRUE);
4860 		redraw_later(VALID);
4861 		set_fraction(curwin);
4862 		break;
4863 
4864 		/* "z^", "z-" and "zb": put cursor at bottom of screen */
4865     case '^':	/* Strange Vi behavior: <count>z^ finds line at top of window
4866 		 * when <count> is at bottom of window, and puts that one at
4867 		 * bottom of window. */
4868 		if (cap->count0 != 0)
4869 		{
4870 		    scroll_cursor_bot(0, TRUE);
4871 		    curwin->w_cursor.lnum = curwin->w_topline;
4872 		}
4873 		else if (curwin->w_topline == 1)
4874 		    curwin->w_cursor.lnum = 1;
4875 		else
4876 		    curwin->w_cursor.lnum = curwin->w_topline - 1;
4877 		/* FALLTHROUGH */
4878     case '-':
4879 		beginline(BL_WHITE | BL_FIX);
4880 		/* FALLTHROUGH */
4881 
4882     case 'b':	scroll_cursor_bot(0, TRUE);
4883 		redraw_later(VALID);
4884 		set_fraction(curwin);
4885 		break;
4886 
4887 		/* "zH" - scroll screen right half-page */
4888     case 'H':
4889 		cap->count1 *= W_WIDTH(curwin) / 2;
4890 		/* FALLTHROUGH */
4891 
4892 		/* "zh" - scroll screen to the right */
4893     case 'h':
4894     case K_LEFT:
4895 		if (!curwin->w_p_wrap)
4896 		{
4897 		    if ((colnr_T)cap->count1 > curwin->w_leftcol)
4898 			curwin->w_leftcol = 0;
4899 		    else
4900 			curwin->w_leftcol -= (colnr_T)cap->count1;
4901 		    leftcol_changed();
4902 		}
4903 		break;
4904 
4905 		/* "zL" - scroll screen left half-page */
4906     case 'L':	cap->count1 *= W_WIDTH(curwin) / 2;
4907 		/* FALLTHROUGH */
4908 
4909 		/* "zl" - scroll screen to the left */
4910     case 'l':
4911     case K_RIGHT:
4912 		if (!curwin->w_p_wrap)
4913 		{
4914 		    /* scroll the window left */
4915 		    curwin->w_leftcol += (colnr_T)cap->count1;
4916 		    leftcol_changed();
4917 		}
4918 		break;
4919 
4920 		/* "zs" - scroll screen, cursor at the start */
4921     case 's':	if (!curwin->w_p_wrap)
4922 		{
4923 #ifdef FEAT_FOLDING
4924 		    if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
4925 			col = 0;	/* like the cursor is in col 0 */
4926 		    else
4927 #endif
4928 		    getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
4929 		    if ((long)col > p_siso)
4930 			col -= p_siso;
4931 		    else
4932 			col = 0;
4933 		    if (curwin->w_leftcol != col)
4934 		    {
4935 			curwin->w_leftcol = col;
4936 			redraw_later(NOT_VALID);
4937 		    }
4938 		}
4939 		break;
4940 
4941 		/* "ze" - scroll screen, cursor at the end */
4942     case 'e':	if (!curwin->w_p_wrap)
4943 		{
4944 #ifdef FEAT_FOLDING
4945 		    if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
4946 			col = 0;	/* like the cursor is in col 0 */
4947 		    else
4948 #endif
4949 		    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
4950 		    n = W_WIDTH(curwin) - curwin_col_off();
4951 		    if ((long)col + p_siso < n)
4952 			col = 0;
4953 		    else
4954 			col = col + p_siso - n + 1;
4955 		    if (curwin->w_leftcol != col)
4956 		    {
4957 			curwin->w_leftcol = col;
4958 			redraw_later(NOT_VALID);
4959 		    }
4960 		}
4961 		break;
4962 
4963 #ifdef FEAT_FOLDING
4964 		/* "zF": create fold command */
4965 		/* "zf": create fold operator */
4966     case 'F':
4967     case 'f':   if (foldManualAllowed(TRUE))
4968 		{
4969 		    cap->nchar = 'f';
4970 		    nv_operator(cap);
4971 		    curwin->w_p_fen = TRUE;
4972 
4973 		    /* "zF" is like "zfzf" */
4974 		    if (nchar == 'F' && cap->oap->op_type == OP_FOLD)
4975 		    {
4976 			nv_operator(cap);
4977 			finish_op = TRUE;
4978 		    }
4979 		}
4980 		else
4981 		    clearopbeep(cap->oap);
4982 		break;
4983 
4984 		/* "zd": delete fold at cursor */
4985 		/* "zD": delete fold at cursor recursively */
4986     case 'd':
4987     case 'D':	if (foldManualAllowed(FALSE))
4988 		{
4989 		    if (VIsual_active)
4990 			nv_operator(cap);
4991 		    else
4992 			deleteFold(curwin->w_cursor.lnum,
4993 				  curwin->w_cursor.lnum, nchar == 'D', FALSE);
4994 		}
4995 		break;
4996 
4997 		/* "zE": erase all folds */
4998     case 'E':	if (foldmethodIsManual(curwin))
4999 		{
5000 		    clearFolding(curwin);
5001 		    changed_window_setting();
5002 		}
5003 		else if (foldmethodIsMarker(curwin))
5004 		    deleteFold((linenr_T)1, curbuf->b_ml.ml_line_count,
5005 								 TRUE, FALSE);
5006 		else
5007 		    EMSG(_("E352: Cannot erase folds with current 'foldmethod'"));
5008 		break;
5009 
5010 		/* "zn": fold none: reset 'foldenable' */
5011     case 'n':	curwin->w_p_fen = FALSE;
5012 		break;
5013 
5014 		/* "zN": fold Normal: set 'foldenable' */
5015     case 'N':	curwin->w_p_fen = TRUE;
5016 		break;
5017 
5018 		/* "zi": invert folding: toggle 'foldenable' */
5019     case 'i':	curwin->w_p_fen = !curwin->w_p_fen;
5020 		break;
5021 
5022 		/* "za": open closed fold or close open fold at cursor */
5023     case 'a':	if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
5024 		    openFold(curwin->w_cursor.lnum, cap->count1);
5025 		else
5026 		{
5027 		    closeFold(curwin->w_cursor.lnum, cap->count1);
5028 		    curwin->w_p_fen = TRUE;
5029 		}
5030 		break;
5031 
5032 		/* "zA": open fold at cursor recursively */
5033     case 'A':	if (hasFolding(curwin->w_cursor.lnum, NULL, NULL))
5034 		    openFoldRecurse(curwin->w_cursor.lnum);
5035 		else
5036 		{
5037 		    closeFoldRecurse(curwin->w_cursor.lnum);
5038 		    curwin->w_p_fen = TRUE;
5039 		}
5040 		break;
5041 
5042 		/* "zo": open fold at cursor or Visual area */
5043     case 'o':	if (VIsual_active)
5044 		    nv_operator(cap);
5045 		else
5046 		    openFold(curwin->w_cursor.lnum, cap->count1);
5047 		break;
5048 
5049 		/* "zO": open fold recursively */
5050     case 'O':	if (VIsual_active)
5051 		    nv_operator(cap);
5052 		else
5053 		    openFoldRecurse(curwin->w_cursor.lnum);
5054 		break;
5055 
5056 		/* "zc": close fold at cursor or Visual area */
5057     case 'c':	if (VIsual_active)
5058 		    nv_operator(cap);
5059 		else
5060 		    closeFold(curwin->w_cursor.lnum, cap->count1);
5061 		curwin->w_p_fen = TRUE;
5062 		break;
5063 
5064 		/* "zC": close fold recursively */
5065     case 'C':	if (VIsual_active)
5066 		    nv_operator(cap);
5067 		else
5068 		    closeFoldRecurse(curwin->w_cursor.lnum);
5069 		curwin->w_p_fen = TRUE;
5070 		break;
5071 
5072 		/* "zv": open folds at the cursor */
5073     case 'v':	foldOpenCursor();
5074 		break;
5075 
5076 		/* "zx": re-apply 'foldlevel' and open folds at the cursor */
5077     case 'x':	curwin->w_p_fen = TRUE;
5078 		curwin->w_foldinvalid = TRUE;	/* recompute folds */
5079 		newFoldLevel();			/* update right now */
5080 		foldOpenCursor();
5081 		break;
5082 
5083 		/* "zX": undo manual opens/closes, re-apply 'foldlevel' */
5084     case 'X':	curwin->w_p_fen = TRUE;
5085 		curwin->w_foldinvalid = TRUE;	/* recompute folds */
5086 		old_fdl = -1;			/* force an update */
5087 		break;
5088 
5089 		/* "zm": fold more */
5090     case 'm':	if (curwin->w_p_fdl > 0)
5091 		{
5092 		    curwin->w_p_fdl -= cap->count1;
5093 		    if (curwin->w_p_fdl < 0)
5094 			curwin->w_p_fdl = 0;
5095 		}
5096 		old_fdl = -1;		/* force an update */
5097 		curwin->w_p_fen = TRUE;
5098 		break;
5099 
5100 		/* "zM": close all folds */
5101     case 'M':	curwin->w_p_fdl = 0;
5102 		old_fdl = -1;		/* force an update */
5103 		curwin->w_p_fen = TRUE;
5104 		break;
5105 
5106 		/* "zr": reduce folding */
5107     case 'r':	curwin->w_p_fdl += cap->count1;
5108 		{
5109 		    int d = getDeepestNesting();
5110 
5111 		    if (curwin->w_p_fdl >= d)
5112 			curwin->w_p_fdl = d;
5113 		}
5114 		break;
5115 
5116 		/* "zR": open all folds */
5117     case 'R':	curwin->w_p_fdl = getDeepestNesting();
5118 		old_fdl = -1;		/* force an update */
5119 		break;
5120 
5121     case 'j':	/* "zj" move to next fold downwards */
5122     case 'k':	/* "zk" move to next fold upwards */
5123 		if (foldMoveTo(TRUE, nchar == 'j' ? FORWARD : BACKWARD,
5124 							  cap->count1) == FAIL)
5125 		    clearopbeep(cap->oap);
5126 		break;
5127 
5128 #endif /* FEAT_FOLDING */
5129 
5130 #ifdef FEAT_SPELL
5131     case 'u':	/* "zug" and "zuw": undo "zg" and "zw" */
5132 		++no_mapping;
5133 		++allow_keys;   /* no mapping for nchar, but allow key codes */
5134 		nchar = plain_vgetc();
5135 		LANGMAP_ADJUST(nchar, TRUE);
5136 		--no_mapping;
5137 		--allow_keys;
5138 #ifdef FEAT_CMDL_INFO
5139 		(void)add_to_showcmd(nchar);
5140 #endif
5141 		if (vim_strchr((char_u *)"gGwW", nchar) == NULL)
5142 		{
5143 		    clearopbeep(cap->oap);
5144 		    break;
5145 		}
5146 		undo = TRUE;
5147 		/*FALLTHROUGH*/
5148 
5149     case 'g':	/* "zg": add good word to word list */
5150     case 'w':	/* "zw": add wrong word to word list */
5151     case 'G':	/* "zG": add good word to temp word list */
5152     case 'W':	/* "zW": add wrong word to temp word list */
5153 		{
5154 		    char_u  *ptr = NULL;
5155 		    int	    len;
5156 
5157 		    if (checkclearop(cap->oap))
5158 			break;
5159 		    if (VIsual_active && get_visual_text(cap, &ptr, &len)
5160 								      == FAIL)
5161 			return;
5162 		    if (ptr == NULL)
5163 		    {
5164 			pos_T	pos = curwin->w_cursor;
5165 
5166 			/* Find bad word under the cursor.  When 'spell' is
5167 			 * off this fails and find_ident_under_cursor() is
5168 			 * used below. */
5169 			emsg_off++;
5170 			len = spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL);
5171 			emsg_off--;
5172 			if (len != 0 && curwin->w_cursor.col <= pos.col)
5173 			    ptr = ml_get_pos(&curwin->w_cursor);
5174 			curwin->w_cursor = pos;
5175 		    }
5176 
5177 		    if (ptr == NULL && (len = find_ident_under_cursor(&ptr,
5178 							    FIND_IDENT)) == 0)
5179 			return;
5180 		    spell_add_word(ptr, len, nchar == 'w' || nchar == 'W',
5181 					    (nchar == 'G' || nchar == 'W')
5182 						       ? 0 : (int)cap->count1,
5183 					    undo);
5184 		}
5185 		break;
5186 
5187     case '=':	/* "z=": suggestions for a badly spelled word  */
5188 		if (!checkclearop(cap->oap))
5189 		    spell_suggest((int)cap->count0);
5190 		break;
5191 #endif
5192 
5193     default:	clearopbeep(cap->oap);
5194     }
5195 
5196 #ifdef FEAT_FOLDING
5197     /* Redraw when 'foldenable' changed */
5198     if (old_fen != curwin->w_p_fen)
5199     {
5200 # ifdef FEAT_DIFF
5201 	win_T	    *wp;
5202 
5203 	if (foldmethodIsDiff(curwin) && curwin->w_p_scb)
5204 	{
5205 	    /* Adjust 'foldenable' in diff-synced windows. */
5206 	    FOR_ALL_WINDOWS(wp)
5207 	    {
5208 		if (wp != curwin && foldmethodIsDiff(wp) && wp->w_p_scb)
5209 		{
5210 		    wp->w_p_fen = curwin->w_p_fen;
5211 		    changed_window_setting_win(wp);
5212 		}
5213 	    }
5214 	}
5215 # endif
5216 	changed_window_setting();
5217     }
5218 
5219     /* Redraw when 'foldlevel' changed. */
5220     if (old_fdl != curwin->w_p_fdl)
5221 	newFoldLevel();
5222 #endif
5223 }
5224 
5225 #ifdef FEAT_GUI
5226 /*
5227  * Vertical scrollbar movement.
5228  */
5229     static void
5230 nv_ver_scrollbar(cap)
5231     cmdarg_T	*cap;
5232 {
5233     if (cap->oap->op_type != OP_NOP)
5234 	clearopbeep(cap->oap);
5235 
5236     /* Even if an operator was pending, we still want to scroll */
5237     gui_do_scroll();
5238 }
5239 
5240 /*
5241  * Horizontal scrollbar movement.
5242  */
5243     static void
5244 nv_hor_scrollbar(cap)
5245     cmdarg_T	*cap;
5246 {
5247     if (cap->oap->op_type != OP_NOP)
5248 	clearopbeep(cap->oap);
5249 
5250     /* Even if an operator was pending, we still want to scroll */
5251     gui_do_horiz_scroll(scrollbar_value, FALSE);
5252 }
5253 #endif
5254 
5255 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
5256 /*
5257  * Click in GUI tab.
5258  */
5259     static void
5260 nv_tabline(cap)
5261     cmdarg_T	*cap;
5262 {
5263     if (cap->oap->op_type != OP_NOP)
5264 	clearopbeep(cap->oap);
5265 
5266     /* Even if an operator was pending, we still want to jump tabs. */
5267     goto_tabpage(current_tab);
5268 }
5269 
5270 /*
5271  * Selected item in tab line menu.
5272  */
5273     static void
5274 nv_tabmenu(cap)
5275     cmdarg_T	*cap;
5276 {
5277     if (cap->oap->op_type != OP_NOP)
5278 	clearopbeep(cap->oap);
5279 
5280     /* Even if an operator was pending, we still want to jump tabs. */
5281     handle_tabmenu();
5282 }
5283 
5284 /*
5285  * Handle selecting an item of the GUI tab line menu.
5286  * Used in Normal and Insert mode.
5287  */
5288     void
5289 handle_tabmenu()
5290 {
5291     switch (current_tabmenu)
5292     {
5293 	case TABLINE_MENU_CLOSE:
5294 	    if (current_tab == 0)
5295 		do_cmdline_cmd((char_u *)"tabclose");
5296 	    else
5297 	    {
5298 		vim_snprintf((char *)IObuff, IOSIZE, "tabclose %d",
5299 								 current_tab);
5300 		do_cmdline_cmd(IObuff);
5301 	    }
5302 	    break;
5303 
5304 	case TABLINE_MENU_NEW:
5305 	    if (current_tab == 0)
5306 		do_cmdline_cmd((char_u *)"$tabnew");
5307 	    else
5308 	    {
5309 		vim_snprintf((char *)IObuff, IOSIZE, "%dtabnew",
5310 							     current_tab - 1);
5311 		do_cmdline_cmd(IObuff);
5312 	    }
5313 	    break;
5314 
5315 	case TABLINE_MENU_OPEN:
5316 	    if (current_tab == 0)
5317 		do_cmdline_cmd((char_u *)"browse $tabnew");
5318 	    else
5319 	    {
5320 		vim_snprintf((char *)IObuff, IOSIZE, "browse %dtabnew",
5321 							     current_tab - 1);
5322 		do_cmdline_cmd(IObuff);
5323 	    }
5324 	    break;
5325     }
5326 }
5327 #endif
5328 
5329 /*
5330  * "Q" command.
5331  */
5332     static void
5333 nv_exmode(cap)
5334     cmdarg_T	*cap;
5335 {
5336     /*
5337      * Ignore 'Q' in Visual mode, just give a beep.
5338      */
5339     if (VIsual_active)
5340 	vim_beep(BO_EX);
5341     else if (!checkclearop(cap->oap))
5342 	do_exmode(FALSE);
5343 }
5344 
5345 /*
5346  * Handle a ":" command.
5347  */
5348     static void
5349 nv_colon(cap)
5350     cmdarg_T  *cap;
5351 {
5352     int	    old_p_im;
5353     int	    cmd_result;
5354 
5355     if (VIsual_active)
5356 	nv_operator(cap);
5357     else
5358     {
5359 	if (cap->oap->op_type != OP_NOP)
5360 	{
5361 	    /* Using ":" as a movement is characterwise exclusive. */
5362 	    cap->oap->motion_type = MCHAR;
5363 	    cap->oap->inclusive = FALSE;
5364 	}
5365 	else if (cap->count0)
5366 	{
5367 	    /* translate "count:" into ":.,.+(count - 1)" */
5368 	    stuffcharReadbuff('.');
5369 	    if (cap->count0 > 1)
5370 	    {
5371 		stuffReadbuff((char_u *)",.+");
5372 		stuffnumReadbuff((long)cap->count0 - 1L);
5373 	    }
5374 	}
5375 
5376 	/* When typing, don't type below an old message */
5377 	if (KeyTyped)
5378 	    compute_cmdrow();
5379 
5380 	old_p_im = p_im;
5381 
5382 	/* get a command line and execute it */
5383 	cmd_result = do_cmdline(NULL, getexline, NULL,
5384 			    cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0);
5385 
5386 	/* If 'insertmode' changed, enter or exit Insert mode */
5387 	if (p_im != old_p_im)
5388 	{
5389 	    if (p_im)
5390 		restart_edit = 'i';
5391 	    else
5392 		restart_edit = 0;
5393 	}
5394 
5395 	if (cmd_result == FAIL)
5396 	    /* The Ex command failed, do not execute the operator. */
5397 	    clearop(cap->oap);
5398 	else if (cap->oap->op_type != OP_NOP
5399 		&& (cap->oap->start.lnum > curbuf->b_ml.ml_line_count
5400 		    || cap->oap->start.col >
5401 			       (colnr_T)STRLEN(ml_get(cap->oap->start.lnum))
5402 		    || did_emsg
5403 		    ))
5404 	    /* The start of the operator has become invalid by the Ex command.
5405 	     */
5406 	    clearopbeep(cap->oap);
5407     }
5408 }
5409 
5410 /*
5411  * Handle CTRL-G command.
5412  */
5413     static void
5414 nv_ctrlg(cap)
5415     cmdarg_T *cap;
5416 {
5417     if (VIsual_active)	/* toggle Selection/Visual mode */
5418     {
5419 	VIsual_select = !VIsual_select;
5420 	showmode();
5421     }
5422     else if (!checkclearop(cap->oap))
5423 	/* print full name if count given or :cd used */
5424 	fileinfo((int)cap->count0, FALSE, TRUE);
5425 }
5426 
5427 /*
5428  * Handle CTRL-H <Backspace> command.
5429  */
5430     static void
5431 nv_ctrlh(cap)
5432     cmdarg_T *cap;
5433 {
5434     if (VIsual_active && VIsual_select)
5435     {
5436 	cap->cmdchar = 'x';	/* BS key behaves like 'x' in Select mode */
5437 	v_visop(cap);
5438     }
5439     else
5440 	nv_left(cap);
5441 }
5442 
5443 /*
5444  * CTRL-L: clear screen and redraw.
5445  */
5446     static void
5447 nv_clear(cap)
5448     cmdarg_T	*cap;
5449 {
5450     if (!checkclearop(cap->oap))
5451     {
5452 #if defined(__BEOS__) && !USE_THREAD_FOR_INPUT_WITH_TIMEOUT
5453 	/*
5454 	 * Right now, the BeBox doesn't seem to have an easy way to detect
5455 	 * window resizing, so we cheat and make the user detect it
5456 	 * manually with CTRL-L instead
5457 	 */
5458 	ui_get_shellsize();
5459 #endif
5460 #ifdef FEAT_SYN_HL
5461 	/* Clear all syntax states to force resyncing. */
5462 	syn_stack_free_all(curwin->w_s);
5463 #endif
5464 	redraw_later(CLEAR);
5465     }
5466 }
5467 
5468 /*
5469  * CTRL-O: In Select mode: switch to Visual mode for one command.
5470  * Otherwise: Go to older pcmark.
5471  */
5472     static void
5473 nv_ctrlo(cap)
5474     cmdarg_T	*cap;
5475 {
5476     if (VIsual_active && VIsual_select)
5477     {
5478 	VIsual_select = FALSE;
5479 	showmode();
5480 	restart_VIsual_select = 2;	/* restart Select mode later */
5481     }
5482     else
5483     {
5484 	cap->count1 = -cap->count1;
5485 	nv_pcmark(cap);
5486     }
5487 }
5488 
5489 /*
5490  * CTRL-^ command, short for ":e #"
5491  */
5492     static void
5493 nv_hat(cap)
5494     cmdarg_T	*cap;
5495 {
5496     if (!checkclearopq(cap->oap))
5497 	(void)buflist_getfile((int)cap->count0, (linenr_T)0,
5498 						GETF_SETMARK|GETF_ALT, FALSE);
5499 }
5500 
5501 /*
5502  * "Z" commands.
5503  */
5504     static void
5505 nv_Zet(cap)
5506     cmdarg_T *cap;
5507 {
5508     if (!checkclearopq(cap->oap))
5509     {
5510 	switch (cap->nchar)
5511 	{
5512 			/* "ZZ": equivalent to ":x". */
5513 	    case 'Z':	do_cmdline_cmd((char_u *)"x");
5514 			break;
5515 
5516 			/* "ZQ": equivalent to ":q!" (Elvis compatible). */
5517 	    case 'Q':	do_cmdline_cmd((char_u *)"q!");
5518 			break;
5519 
5520 	    default:	clearopbeep(cap->oap);
5521 	}
5522     }
5523 }
5524 
5525 #if defined(FEAT_WINDOWS) || defined(PROTO)
5526 /*
5527  * Call nv_ident() as if "c1" was used, with "c2" as next character.
5528  */
5529     void
5530 do_nv_ident(c1, c2)
5531     int		c1;
5532     int		c2;
5533 {
5534     oparg_T	oa;
5535     cmdarg_T	ca;
5536 
5537     clear_oparg(&oa);
5538     vim_memset(&ca, 0, sizeof(ca));
5539     ca.oap = &oa;
5540     ca.cmdchar = c1;
5541     ca.nchar = c2;
5542     nv_ident(&ca);
5543 }
5544 #endif
5545 
5546 /*
5547  * Handle the commands that use the word under the cursor.
5548  * [g] CTRL-]	:ta to current identifier
5549  * [g] 'K'	run program for current identifier
5550  * [g] '*'	/ to current identifier or string
5551  * [g] '#'	? to current identifier or string
5552  *  g  ']'	:tselect for current identifier
5553  */
5554     static void
5555 nv_ident(cap)
5556     cmdarg_T	*cap;
5557 {
5558     char_u	*ptr = NULL;
5559     char_u	*buf;
5560     char_u	*newbuf;
5561     char_u	*p;
5562     char_u	*kp;		/* value of 'keywordprg' */
5563     int		kp_help;	/* 'keywordprg' is ":help" */
5564     int		n = 0;		/* init for GCC */
5565     int		cmdchar;
5566     int		g_cmd;		/* "g" command */
5567     int		tag_cmd = FALSE;
5568     char_u	*aux_ptr;
5569     int		isman;
5570     int		isman_s;
5571 
5572     if (cap->cmdchar == 'g')	/* "g*", "g#", "g]" and "gCTRL-]" */
5573     {
5574 	cmdchar = cap->nchar;
5575 	g_cmd = TRUE;
5576     }
5577     else
5578     {
5579 	cmdchar = cap->cmdchar;
5580 	g_cmd = FALSE;
5581     }
5582 
5583     if (cmdchar == POUND)	/* the pound sign, '#' for English keyboards */
5584 	cmdchar = '#';
5585 
5586     /*
5587      * The "]", "CTRL-]" and "K" commands accept an argument in Visual mode.
5588      */
5589     if (cmdchar == ']' || cmdchar == Ctrl_RSB || cmdchar == 'K')
5590     {
5591 	if (VIsual_active && get_visual_text(cap, &ptr, &n) == FAIL)
5592 	    return;
5593 	if (checkclearopq(cap->oap))
5594 	    return;
5595     }
5596 
5597     if (ptr == NULL && (n = find_ident_under_cursor(&ptr,
5598 		    (cmdchar == '*' || cmdchar == '#')
5599 				 ? FIND_IDENT|FIND_STRING : FIND_IDENT)) == 0)
5600     {
5601 	clearop(cap->oap);
5602 	return;
5603     }
5604 
5605     /* Allocate buffer to put the command in.  Inserting backslashes can
5606      * double the length of the word.  p_kp / curbuf->b_p_kp could be added
5607      * and some numbers. */
5608     kp = (*curbuf->b_p_kp == NUL ? p_kp : curbuf->b_p_kp);
5609     kp_help = (*kp == NUL || STRCMP(kp, ":he") == 0
5610 						 || STRCMP(kp, ":help") == 0);
5611     buf = alloc((unsigned)(n * 2 + 30 + STRLEN(kp)));
5612     if (buf == NULL)
5613 	return;
5614     buf[0] = NUL;
5615 
5616     switch (cmdchar)
5617     {
5618 	case '*':
5619 	case '#':
5620 	    /*
5621 	     * Put cursor at start of word, makes search skip the word
5622 	     * under the cursor.
5623 	     * Call setpcmark() first, so "*``" puts the cursor back where
5624 	     * it was.
5625 	     */
5626 	    setpcmark();
5627 	    curwin->w_cursor.col = (colnr_T) (ptr - ml_get_curline());
5628 
5629 	    if (!g_cmd && vim_iswordp(ptr))
5630 		STRCPY(buf, "\\<");
5631 	    no_smartcase = TRUE;	/* don't use 'smartcase' now */
5632 	    break;
5633 
5634 	case 'K':
5635 	    if (kp_help)
5636 		STRCPY(buf, "he! ");
5637 	    else
5638 	    {
5639 		/* An external command will probably use an argument starting
5640 		 * with "-" as an option.  To avoid trouble we skip the "-". */
5641 		while (*ptr == '-' && n > 0)
5642 		{
5643 		    ++ptr;
5644 		    --n;
5645 		}
5646 		if (n == 0)
5647 		{
5648 		    EMSG(_(e_noident));	 /* found dashes only */
5649 		    vim_free(buf);
5650 		    return;
5651 		}
5652 
5653 		/* When a count is given, turn it into a range.  Is this
5654 		 * really what we want? */
5655 		isman = (STRCMP(kp, "man") == 0);
5656 		isman_s = (STRCMP(kp, "man -s") == 0);
5657 		if (cap->count0 != 0 && !(isman || isman_s))
5658 		    sprintf((char *)buf, ".,.+%ld", cap->count0 - 1);
5659 
5660 		STRCAT(buf, "! ");
5661 		if (cap->count0 == 0 && isman_s)
5662 		    STRCAT(buf, "man");
5663 		else
5664 		    STRCAT(buf, kp);
5665 		STRCAT(buf, " ");
5666 		if (cap->count0 != 0 && (isman || isman_s))
5667 		{
5668 		    sprintf((char *)buf + STRLEN(buf), "%ld", cap->count0);
5669 		    STRCAT(buf, " ");
5670 		}
5671 	    }
5672 	    break;
5673 
5674 	case ']':
5675 	    tag_cmd = TRUE;
5676 #ifdef FEAT_CSCOPE
5677 	    if (p_cst)
5678 		STRCPY(buf, "cstag ");
5679 	    else
5680 #endif
5681 		STRCPY(buf, "ts ");
5682 	    break;
5683 
5684 	default:
5685 	    tag_cmd = TRUE;
5686 	    if (curbuf->b_help)
5687 		STRCPY(buf, "he! ");
5688 	    else
5689 	    {
5690 		if (g_cmd)
5691 		    STRCPY(buf, "tj ");
5692 		else
5693 		    sprintf((char *)buf, "%ldta ", cap->count0);
5694 	    }
5695     }
5696 
5697     /*
5698      * Now grab the chars in the identifier
5699      */
5700     if (cmdchar == 'K' && !kp_help)
5701     {
5702 	/* Escape the argument properly for a shell command */
5703 	ptr = vim_strnsave(ptr, n);
5704 	p = vim_strsave_shellescape(ptr, TRUE, TRUE);
5705 	vim_free(ptr);
5706 	if (p == NULL)
5707 	{
5708 	    vim_free(buf);
5709 	    return;
5710 	}
5711 	newbuf = (char_u *)vim_realloc(buf, STRLEN(buf) + STRLEN(p) + 1);
5712 	if (newbuf == NULL)
5713 	{
5714 	    vim_free(buf);
5715 	    vim_free(p);
5716 	    return;
5717 	}
5718 	buf = newbuf;
5719 	STRCAT(buf, p);
5720 	vim_free(p);
5721     }
5722     else
5723     {
5724 	if (cmdchar == '*')
5725 	    aux_ptr = (char_u *)(p_magic ? "/.*~[^$\\" : "/^$\\");
5726 	else if (cmdchar == '#')
5727 	    aux_ptr = (char_u *)(p_magic ? "/?.*~[^$\\" : "/?^$\\");
5728 	else if (tag_cmd)
5729 	{
5730 	    if (curbuf->b_help)
5731 		/* ":help" handles unescaped argument */
5732 		aux_ptr = (char_u *)"";
5733 	    else
5734 		aux_ptr = (char_u *)"\\|\"\n[";
5735 	}
5736 	else
5737 	    aux_ptr = (char_u *)"\\|\"\n*?[";
5738 
5739 	p = buf + STRLEN(buf);
5740 	while (n-- > 0)
5741 	{
5742 	    /* put a backslash before \ and some others */
5743 	    if (vim_strchr(aux_ptr, *ptr) != NULL)
5744 		*p++ = '\\';
5745 #ifdef FEAT_MBYTE
5746 	    /* When current byte is a part of multibyte character, copy all
5747 	     * bytes of that character. */
5748 	    if (has_mbyte)
5749 	    {
5750 		int i;
5751 		int len = (*mb_ptr2len)(ptr) - 1;
5752 
5753 		for (i = 0; i < len && n >= 1; ++i, --n)
5754 		    *p++ = *ptr++;
5755 	    }
5756 #endif
5757 	    *p++ = *ptr++;
5758 	}
5759 	*p = NUL;
5760     }
5761 
5762     /*
5763      * Execute the command.
5764      */
5765     if (cmdchar == '*' || cmdchar == '#')
5766     {
5767 	if (!g_cmd && (
5768 #ifdef FEAT_MBYTE
5769 		has_mbyte ? vim_iswordp(mb_prevptr(ml_get_curline(), ptr)) :
5770 #endif
5771 		vim_iswordc(ptr[-1])))
5772 	    STRCAT(buf, "\\>");
5773 #ifdef FEAT_CMDHIST
5774 	/* put pattern in search history */
5775 	init_history();
5776 	add_to_history(HIST_SEARCH, buf, TRUE, NUL);
5777 #endif
5778 	(void)normal_search(cap, cmdchar == '*' ? '/' : '?', buf, 0);
5779     }
5780     else
5781 	do_cmdline_cmd(buf);
5782 
5783     vim_free(buf);
5784 }
5785 
5786 /*
5787  * Get visually selected text, within one line only.
5788  * Returns FAIL if more than one line selected.
5789  */
5790     int
5791 get_visual_text(cap, pp, lenp)
5792     cmdarg_T	*cap;
5793     char_u	**pp;	    /* return: start of selected text */
5794     int		*lenp;	    /* return: length of selected text */
5795 {
5796     if (VIsual_mode != 'V')
5797 	unadjust_for_sel();
5798     if (VIsual.lnum != curwin->w_cursor.lnum)
5799     {
5800 	if (cap != NULL)
5801 	    clearopbeep(cap->oap);
5802 	return FAIL;
5803     }
5804     if (VIsual_mode == 'V')
5805     {
5806 	*pp = ml_get_curline();
5807 	*lenp = (int)STRLEN(*pp);
5808     }
5809     else
5810     {
5811 	if (lt(curwin->w_cursor, VIsual))
5812 	{
5813 	    *pp = ml_get_pos(&curwin->w_cursor);
5814 	    *lenp = VIsual.col - curwin->w_cursor.col + 1;
5815 	}
5816 	else
5817 	{
5818 	    *pp = ml_get_pos(&VIsual);
5819 	    *lenp = curwin->w_cursor.col - VIsual.col + 1;
5820 	}
5821 #ifdef FEAT_MBYTE
5822 	if (has_mbyte)
5823 	    /* Correct the length to include the whole last character. */
5824 	    *lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
5825 #endif
5826     }
5827     reset_VIsual_and_resel();
5828     return OK;
5829 }
5830 
5831 /*
5832  * CTRL-T: backwards in tag stack
5833  */
5834     static void
5835 nv_tagpop(cap)
5836     cmdarg_T	*cap;
5837 {
5838     if (!checkclearopq(cap->oap))
5839 	do_tag((char_u *)"", DT_POP, (int)cap->count1, FALSE, TRUE);
5840 }
5841 
5842 /*
5843  * Handle scrolling command 'H', 'L' and 'M'.
5844  */
5845     static void
5846 nv_scroll(cap)
5847     cmdarg_T  *cap;
5848 {
5849     int		used = 0;
5850     long	n;
5851 #ifdef FEAT_FOLDING
5852     linenr_T	lnum;
5853 #endif
5854     int		half;
5855 
5856     cap->oap->motion_type = MLINE;
5857     setpcmark();
5858 
5859     if (cap->cmdchar == 'L')
5860     {
5861 	validate_botline();	    /* make sure curwin->w_botline is valid */
5862 	curwin->w_cursor.lnum = curwin->w_botline - 1;
5863 	if (cap->count1 - 1 >= curwin->w_cursor.lnum)
5864 	    curwin->w_cursor.lnum = 1;
5865 	else
5866 	{
5867 #ifdef FEAT_FOLDING
5868 	    if (hasAnyFolding(curwin))
5869 	    {
5870 		/* Count a fold for one screen line. */
5871 		for (n = cap->count1 - 1; n > 0
5872 			    && curwin->w_cursor.lnum > curwin->w_topline; --n)
5873 		{
5874 		    (void)hasFolding(curwin->w_cursor.lnum,
5875 						&curwin->w_cursor.lnum, NULL);
5876 		    --curwin->w_cursor.lnum;
5877 		}
5878 	    }
5879 	    else
5880 #endif
5881 		curwin->w_cursor.lnum -= cap->count1 - 1;
5882 	}
5883     }
5884     else
5885     {
5886 	if (cap->cmdchar == 'M')
5887 	{
5888 #ifdef FEAT_DIFF
5889 	    /* Don't count filler lines above the window. */
5890 	    used -= diff_check_fill(curwin, curwin->w_topline)
5891 							  - curwin->w_topfill;
5892 #endif
5893 	    validate_botline();	    /* make sure w_empty_rows is valid */
5894 	    half = (curwin->w_height - curwin->w_empty_rows + 1) / 2;
5895 	    for (n = 0; curwin->w_topline + n < curbuf->b_ml.ml_line_count; ++n)
5896 	    {
5897 #ifdef FEAT_DIFF
5898 		/* Count half he number of filler lines to be "below this
5899 		 * line" and half to be "above the next line". */
5900 		if (n > 0 && used + diff_check_fill(curwin, curwin->w_topline
5901 							     + n) / 2 >= half)
5902 		{
5903 		    --n;
5904 		    break;
5905 		}
5906 #endif
5907 		used += plines(curwin->w_topline + n);
5908 		if (used >= half)
5909 		    break;
5910 #ifdef FEAT_FOLDING
5911 		if (hasFolding(curwin->w_topline + n, NULL, &lnum))
5912 		    n = lnum - curwin->w_topline;
5913 #endif
5914 	    }
5915 	    if (n > 0 && used > curwin->w_height)
5916 		--n;
5917 	}
5918 	else /* (cap->cmdchar == 'H') */
5919 	{
5920 	    n = cap->count1 - 1;
5921 #ifdef FEAT_FOLDING
5922 	    if (hasAnyFolding(curwin))
5923 	    {
5924 		/* Count a fold for one screen line. */
5925 		lnum = curwin->w_topline;
5926 		while (n-- > 0 && lnum < curwin->w_botline - 1)
5927 		{
5928 		    (void)hasFolding(lnum, NULL, &lnum);
5929 		    ++lnum;
5930 		}
5931 		n = lnum - curwin->w_topline;
5932 	    }
5933 #endif
5934 	}
5935 	curwin->w_cursor.lnum = curwin->w_topline + n;
5936 	if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
5937 	    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5938     }
5939 
5940     cursor_correct();	/* correct for 'so' */
5941     beginline(BL_SOL | BL_FIX);
5942 }
5943 
5944 /*
5945  * Cursor right commands.
5946  */
5947     static void
5948 nv_right(cap)
5949     cmdarg_T	*cap;
5950 {
5951     long	n;
5952     int		past_line;
5953 
5954     if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
5955     {
5956 	/* <C-Right> and <S-Right> move a word or WORD right */
5957 	if (mod_mask & MOD_MASK_CTRL)
5958 	    cap->arg = TRUE;
5959 	nv_wordcmd(cap);
5960 	return;
5961     }
5962 
5963     cap->oap->motion_type = MCHAR;
5964     cap->oap->inclusive = FALSE;
5965     past_line = (VIsual_active && *p_sel != 'o');
5966 
5967 #ifdef FEAT_VIRTUALEDIT
5968     /*
5969      * In virtual edit mode, there's no such thing as "past_line", as lines
5970      * are (theoretically) infinitely long.
5971      */
5972     if (virtual_active())
5973 	past_line = 0;
5974 #endif
5975 
5976     for (n = cap->count1; n > 0; --n)
5977     {
5978 	if ((!past_line && oneright() == FAIL)
5979 		|| (past_line && *ml_get_cursor() == NUL)
5980 		)
5981 	{
5982 	    /*
5983 	     *	  <Space> wraps to next line if 'whichwrap' has 's'.
5984 	     *	      'l' wraps to next line if 'whichwrap' has 'l'.
5985 	     * CURS_RIGHT wraps to next line if 'whichwrap' has '>'.
5986 	     */
5987 	    if (       ((cap->cmdchar == ' '
5988 			    && vim_strchr(p_ww, 's') != NULL)
5989 			|| (cap->cmdchar == 'l'
5990 			    && vim_strchr(p_ww, 'l') != NULL)
5991 			|| (cap->cmdchar == K_RIGHT
5992 			    && vim_strchr(p_ww, '>') != NULL))
5993 		    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
5994 	    {
5995 		/* When deleting we also count the NL as a character.
5996 		 * Set cap->oap->inclusive when last char in the line is
5997 		 * included, move to next line after that */
5998 		if (	   cap->oap->op_type != OP_NOP
5999 			&& !cap->oap->inclusive
6000 			&& !lineempty(curwin->w_cursor.lnum))
6001 		    cap->oap->inclusive = TRUE;
6002 		else
6003 		{
6004 		    ++curwin->w_cursor.lnum;
6005 		    curwin->w_cursor.col = 0;
6006 #ifdef FEAT_VIRTUALEDIT
6007 		    curwin->w_cursor.coladd = 0;
6008 #endif
6009 		    curwin->w_set_curswant = TRUE;
6010 		    cap->oap->inclusive = FALSE;
6011 		}
6012 		continue;
6013 	    }
6014 	    if (cap->oap->op_type == OP_NOP)
6015 	    {
6016 		/* Only beep and flush if not moved at all */
6017 		if (n == cap->count1)
6018 		    beep_flush();
6019 	    }
6020 	    else
6021 	    {
6022 		if (!lineempty(curwin->w_cursor.lnum))
6023 		    cap->oap->inclusive = TRUE;
6024 	    }
6025 	    break;
6026 	}
6027 	else if (past_line)
6028 	{
6029 	    curwin->w_set_curswant = TRUE;
6030 #ifdef FEAT_VIRTUALEDIT
6031 	    if (virtual_active())
6032 		oneright();
6033 	    else
6034 #endif
6035 	    {
6036 #ifdef FEAT_MBYTE
6037 		if (has_mbyte)
6038 		    curwin->w_cursor.col +=
6039 					 (*mb_ptr2len)(ml_get_cursor());
6040 		else
6041 #endif
6042 		    ++curwin->w_cursor.col;
6043 	    }
6044 	}
6045     }
6046 #ifdef FEAT_FOLDING
6047     if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped
6048 					       && cap->oap->op_type == OP_NOP)
6049 	foldOpenCursor();
6050 #endif
6051 }
6052 
6053 /*
6054  * Cursor left commands.
6055  *
6056  * Returns TRUE when operator end should not be adjusted.
6057  */
6058     static void
6059 nv_left(cap)
6060     cmdarg_T	*cap;
6061 {
6062     long	n;
6063 
6064     if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
6065     {
6066 	/* <C-Left> and <S-Left> move a word or WORD left */
6067 	if (mod_mask & MOD_MASK_CTRL)
6068 	    cap->arg = 1;
6069 	nv_bck_word(cap);
6070 	return;
6071     }
6072 
6073     cap->oap->motion_type = MCHAR;
6074     cap->oap->inclusive = FALSE;
6075     for (n = cap->count1; n > 0; --n)
6076     {
6077 	if (oneleft() == FAIL)
6078 	{
6079 	    /* <BS> and <Del> wrap to previous line if 'whichwrap' has 'b'.
6080 	     *		 'h' wraps to previous line if 'whichwrap' has 'h'.
6081 	     *	   CURS_LEFT wraps to previous line if 'whichwrap' has '<'.
6082 	     */
6083 	    if (       (((cap->cmdchar == K_BS
6084 				|| cap->cmdchar == Ctrl_H)
6085 			    && vim_strchr(p_ww, 'b') != NULL)
6086 			|| (cap->cmdchar == 'h'
6087 			    && vim_strchr(p_ww, 'h') != NULL)
6088 			|| (cap->cmdchar == K_LEFT
6089 			    && vim_strchr(p_ww, '<') != NULL))
6090 		    && curwin->w_cursor.lnum > 1)
6091 	    {
6092 		--(curwin->w_cursor.lnum);
6093 		coladvance((colnr_T)MAXCOL);
6094 		curwin->w_set_curswant = TRUE;
6095 
6096 		/* When the NL before the first char has to be deleted we
6097 		 * put the cursor on the NUL after the previous line.
6098 		 * This is a very special case, be careful!
6099 		 * Don't adjust op_end now, otherwise it won't work. */
6100 		if (	   (cap->oap->op_type == OP_DELETE
6101 			    || cap->oap->op_type == OP_CHANGE)
6102 			&& !lineempty(curwin->w_cursor.lnum))
6103 		{
6104 		    char_u *cp = ml_get_cursor();
6105 
6106 		    if (*cp != NUL)
6107 		    {
6108 #ifdef FEAT_MBYTE
6109 			if (has_mbyte)
6110 			    curwin->w_cursor.col += (*mb_ptr2len)(cp);
6111 			else
6112 #endif
6113 			    ++curwin->w_cursor.col;
6114 		    }
6115 		    cap->retval |= CA_NO_ADJ_OP_END;
6116 		}
6117 		continue;
6118 	    }
6119 	    /* Only beep and flush if not moved at all */
6120 	    else if (cap->oap->op_type == OP_NOP && n == cap->count1)
6121 		beep_flush();
6122 	    break;
6123 	}
6124     }
6125 #ifdef FEAT_FOLDING
6126     if (n != cap->count1 && (fdo_flags & FDO_HOR) && KeyTyped
6127 					       && cap->oap->op_type == OP_NOP)
6128 	foldOpenCursor();
6129 #endif
6130 }
6131 
6132 /*
6133  * Cursor up commands.
6134  * cap->arg is TRUE for "-": Move cursor to first non-blank.
6135  */
6136     static void
6137 nv_up(cap)
6138     cmdarg_T	*cap;
6139 {
6140     if (mod_mask & MOD_MASK_SHIFT)
6141     {
6142 	/* <S-Up> is page up */
6143 	cap->arg = BACKWARD;
6144 	nv_page(cap);
6145     }
6146     else
6147     {
6148 	cap->oap->motion_type = MLINE;
6149 	if (cursor_up(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
6150 	    clearopbeep(cap->oap);
6151 	else if (cap->arg)
6152 	    beginline(BL_WHITE | BL_FIX);
6153     }
6154 }
6155 
6156 /*
6157  * Cursor down commands.
6158  * cap->arg is TRUE for CR and "+": Move cursor to first non-blank.
6159  */
6160     static void
6161 nv_down(cap)
6162     cmdarg_T	*cap;
6163 {
6164     if (mod_mask & MOD_MASK_SHIFT)
6165     {
6166 	/* <S-Down> is page down */
6167 	cap->arg = FORWARD;
6168 	nv_page(cap);
6169     }
6170     else
6171 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
6172     /* In a quickfix window a <CR> jumps to the error under the cursor. */
6173     if (bt_quickfix(curbuf) && cap->cmdchar == CAR)
6174 	if (curwin->w_llist_ref == NULL)
6175 	    do_cmdline_cmd((char_u *)".cc");	/* quickfix window */
6176 	else
6177 	    do_cmdline_cmd((char_u *)".ll");	/* location list window */
6178     else
6179 #endif
6180     {
6181 #ifdef FEAT_CMDWIN
6182 	/* In the cmdline window a <CR> executes the command. */
6183 	if (cmdwin_type != 0 && cap->cmdchar == CAR)
6184 	    cmdwin_result = CAR;
6185 	else
6186 #endif
6187 	{
6188 	    cap->oap->motion_type = MLINE;
6189 	    if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
6190 		clearopbeep(cap->oap);
6191 	    else if (cap->arg)
6192 		beginline(BL_WHITE | BL_FIX);
6193 	}
6194     }
6195 }
6196 
6197 #ifdef FEAT_SEARCHPATH
6198 /*
6199  * Grab the file name under the cursor and edit it.
6200  */
6201     static void
6202 nv_gotofile(cap)
6203     cmdarg_T	*cap;
6204 {
6205     char_u	*ptr;
6206     linenr_T	lnum = -1;
6207 
6208     if (text_locked())
6209     {
6210 	clearopbeep(cap->oap);
6211 	text_locked_msg();
6212 	return;
6213     }
6214 #ifdef FEAT_AUTOCMD
6215     if (curbuf_locked())
6216     {
6217 	clearop(cap->oap);
6218 	return;
6219     }
6220 #endif
6221 
6222     ptr = grab_file_name(cap->count1, &lnum);
6223 
6224     if (ptr != NULL)
6225     {
6226 	/* do autowrite if necessary */
6227 	if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !P_HID(curbuf))
6228 	    (void)autowrite(curbuf, FALSE);
6229 	setpcmark();
6230 	(void)do_ecmd(0, ptr, NULL, NULL, ECMD_LAST,
6231 				       P_HID(curbuf) ? ECMD_HIDE : 0, curwin);
6232 	if (cap->nchar == 'F' && lnum >= 0)
6233 	{
6234 	    curwin->w_cursor.lnum = lnum;
6235 	    check_cursor_lnum();
6236 	    beginline(BL_SOL | BL_FIX);
6237 	}
6238 	vim_free(ptr);
6239     }
6240     else
6241 	clearop(cap->oap);
6242 }
6243 #endif
6244 
6245 /*
6246  * <End> command: to end of current line or last line.
6247  */
6248     static void
6249 nv_end(cap)
6250     cmdarg_T	*cap;
6251 {
6252     if (cap->arg || (mod_mask & MOD_MASK_CTRL))	/* CTRL-END = goto last line */
6253     {
6254 	cap->arg = TRUE;
6255 	nv_goto(cap);
6256 	cap->count1 = 1;		/* to end of current line */
6257     }
6258     nv_dollar(cap);
6259 }
6260 
6261 /*
6262  * Handle the "$" command.
6263  */
6264     static void
6265 nv_dollar(cap)
6266     cmdarg_T	*cap;
6267 {
6268     cap->oap->motion_type = MCHAR;
6269     cap->oap->inclusive = TRUE;
6270 #ifdef FEAT_VIRTUALEDIT
6271     /* In virtual mode when off the edge of a line and an operator
6272      * is pending (whew!) keep the cursor where it is.
6273      * Otherwise, send it to the end of the line. */
6274     if (!virtual_active() || gchar_cursor() != NUL
6275 					       || cap->oap->op_type == OP_NOP)
6276 #endif
6277 	curwin->w_curswant = MAXCOL;	/* so we stay at the end */
6278     if (cursor_down((long)(cap->count1 - 1),
6279 					 cap->oap->op_type == OP_NOP) == FAIL)
6280 	clearopbeep(cap->oap);
6281 #ifdef FEAT_FOLDING
6282     else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6283 	foldOpenCursor();
6284 #endif
6285 }
6286 
6287 /*
6288  * Implementation of '?' and '/' commands.
6289  * If cap->arg is TRUE don't set PC mark.
6290  */
6291     static void
6292 nv_search(cap)
6293     cmdarg_T	    *cap;
6294 {
6295     oparg_T	*oap = cap->oap;
6296 
6297     if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13)
6298     {
6299 	/* Translate "g??" to "g?g?" */
6300 	cap->cmdchar = 'g';
6301 	cap->nchar = '?';
6302 	nv_operator(cap);
6303 	return;
6304     }
6305 
6306     cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0);
6307 
6308     if (cap->searchbuf == NULL)
6309     {
6310 	clearop(oap);
6311 	return;
6312     }
6313 
6314     (void)normal_search(cap, cap->cmdchar, cap->searchbuf,
6315 						(cap->arg ? 0 : SEARCH_MARK));
6316 }
6317 
6318 /*
6319  * Handle "N" and "n" commands.
6320  * cap->arg is SEARCH_REV for "N", 0 for "n".
6321  */
6322     static void
6323 nv_next(cap)
6324     cmdarg_T	*cap;
6325 {
6326     pos_T old = curwin->w_cursor;
6327     int   i = normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg);
6328 
6329     if (i == 1 && equalpos(old, curwin->w_cursor))
6330     {
6331 	/* Avoid getting stuck on the current cursor position, which can
6332 	 * happen when an offset is given and the cursor is on the last char
6333 	 * in the buffer: Repeat with count + 1. */
6334 	cap->count1 += 1;
6335 	(void)normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg);
6336 	cap->count1 -= 1;
6337     }
6338 }
6339 
6340 /*
6341  * Search for "pat" in direction "dir" ('/' or '?', 0 for repeat).
6342  * Uses only cap->count1 and cap->oap from "cap".
6343  * Return 0 for failure, 1 for found, 2 for found and line offset added.
6344  */
6345     static int
6346 normal_search(cap, dir, pat, opt)
6347     cmdarg_T	*cap;
6348     int		dir;
6349     char_u	*pat;
6350     int		opt;		/* extra flags for do_search() */
6351 {
6352     int		i;
6353 
6354     cap->oap->motion_type = MCHAR;
6355     cap->oap->inclusive = FALSE;
6356     cap->oap->use_reg_one = TRUE;
6357     curwin->w_set_curswant = TRUE;
6358 
6359     i = do_search(cap->oap, dir, pat, cap->count1,
6360 			   opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, NULL);
6361     if (i == 0)
6362 	clearop(cap->oap);
6363     else
6364     {
6365 	if (i == 2)
6366 	    cap->oap->motion_type = MLINE;
6367 #ifdef FEAT_VIRTUALEDIT
6368 	curwin->w_cursor.coladd = 0;
6369 #endif
6370 #ifdef FEAT_FOLDING
6371 	if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
6372 	    foldOpenCursor();
6373 #endif
6374     }
6375 
6376     /* "/$" will put the cursor after the end of the line, may need to
6377      * correct that here */
6378     check_cursor();
6379     return i;
6380 }
6381 
6382 /*
6383  * Character search commands.
6384  * cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', TRUE for
6385  * ',' and FALSE for ';'.
6386  * cap->nchar is NUL for ',' and ';' (repeat the search)
6387  */
6388     static void
6389 nv_csearch(cap)
6390     cmdarg_T	*cap;
6391 {
6392     int		t_cmd;
6393 
6394     if (cap->cmdchar == 't' || cap->cmdchar == 'T')
6395 	t_cmd = TRUE;
6396     else
6397 	t_cmd = FALSE;
6398 
6399     cap->oap->motion_type = MCHAR;
6400     if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == FAIL)
6401 	clearopbeep(cap->oap);
6402     else
6403     {
6404 	curwin->w_set_curswant = TRUE;
6405 #ifdef FEAT_VIRTUALEDIT
6406 	/* Include a Tab for "tx" and for "dfx". */
6407 	if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD
6408 		&& (t_cmd || cap->oap->op_type != OP_NOP))
6409 	{
6410 	    colnr_T	scol, ecol;
6411 
6412 	    getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
6413 	    curwin->w_cursor.coladd = ecol - scol;
6414 	}
6415 	else
6416 	    curwin->w_cursor.coladd = 0;
6417 #endif
6418 	adjust_for_sel(cap);
6419 #ifdef FEAT_FOLDING
6420 	if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6421 	    foldOpenCursor();
6422 #endif
6423     }
6424 }
6425 
6426 /*
6427  * "[" and "]" commands.
6428  * cap->arg is BACKWARD for "[" and FORWARD for "]".
6429  */
6430     static void
6431 nv_brackets(cap)
6432     cmdarg_T	*cap;
6433 {
6434     pos_T	new_pos = INIT_POS_T(0, 0, 0);
6435     pos_T	prev_pos;
6436     pos_T	*pos = NULL;	    /* init for GCC */
6437     pos_T	old_pos;	    /* cursor position before command */
6438     int		flag;
6439     long	n;
6440     int		findc;
6441     int		c;
6442 
6443     cap->oap->motion_type = MCHAR;
6444     cap->oap->inclusive = FALSE;
6445     old_pos = curwin->w_cursor;
6446 #ifdef FEAT_VIRTUALEDIT
6447     curwin->w_cursor.coladd = 0;	    /* TODO: don't do this for an error. */
6448 #endif
6449 
6450 #ifdef FEAT_SEARCHPATH
6451     /*
6452      * "[f" or "]f" : Edit file under the cursor (same as "gf")
6453      */
6454     if (cap->nchar == 'f')
6455 	nv_gotofile(cap);
6456     else
6457 #endif
6458 
6459 #ifdef FEAT_FIND_ID
6460     /*
6461      * Find the occurrence(s) of the identifier or define under cursor
6462      * in current and included files or jump to the first occurrence.
6463      *
6464      *			search	     list	    jump
6465      *		      fwd   bwd    fwd	 bwd	 fwd	bwd
6466      * identifier     "]i"  "[i"   "]I"  "[I"	"]^I"  "[^I"
6467      * define	      "]d"  "[d"   "]D"  "[D"	"]^D"  "[^D"
6468      */
6469     if (vim_strchr((char_u *)
6470 #ifdef EBCDIC
6471 		"iI\005dD\067",
6472 #else
6473 		"iI\011dD\004",
6474 #endif
6475 		cap->nchar) != NULL)
6476     {
6477 	char_u	*ptr;
6478 	int	len;
6479 
6480 	if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
6481 	    clearop(cap->oap);
6482 	else
6483 	{
6484 	    find_pattern_in_path(ptr, 0, len, TRUE,
6485 		cap->count0 == 0 ? !isupper(cap->nchar) : FALSE,
6486 		((cap->nchar & 0xf) == ('d' & 0xf)) ?  FIND_DEFINE : FIND_ANY,
6487 		cap->count1,
6488 		isupper(cap->nchar) ? ACTION_SHOW_ALL :
6489 			    islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO,
6490 		cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1,
6491 		(linenr_T)MAXLNUM);
6492 	    curwin->w_set_curswant = TRUE;
6493 	}
6494     }
6495     else
6496 #endif
6497 
6498     /*
6499      * "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')'
6500      * "[#", "]#": go to start/end of Nth innermost #if..#endif construct.
6501      * "[/", "[*", "]/", "]*": go to Nth comment start/end.
6502      * "[m" or "]m" search for prev/next start of (Java) method.
6503      * "[M" or "]M" search for prev/next end of (Java) method.
6504      */
6505     if (  (cap->cmdchar == '['
6506 		&& vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL)
6507 	    || (cap->cmdchar == ']'
6508 		&& vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL))
6509     {
6510 	if (cap->nchar == '*')
6511 	    cap->nchar = '/';
6512 	prev_pos.lnum = 0;
6513 	if (cap->nchar == 'm' || cap->nchar == 'M')
6514 	{
6515 	    if (cap->cmdchar == '[')
6516 		findc = '{';
6517 	    else
6518 		findc = '}';
6519 	    n = 9999;
6520 	}
6521 	else
6522 	{
6523 	    findc = cap->nchar;
6524 	    n = cap->count1;
6525 	}
6526 	for ( ; n > 0; --n)
6527 	{
6528 	    if ((pos = findmatchlimit(cap->oap, findc,
6529 		(cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL)
6530 	    {
6531 		if (new_pos.lnum == 0)	/* nothing found */
6532 		{
6533 		    if (cap->nchar != 'm' && cap->nchar != 'M')
6534 			clearopbeep(cap->oap);
6535 		}
6536 		else
6537 		    pos = &new_pos;	/* use last one found */
6538 		break;
6539 	    }
6540 	    prev_pos = new_pos;
6541 	    curwin->w_cursor = *pos;
6542 	    new_pos = *pos;
6543 	}
6544 	curwin->w_cursor = old_pos;
6545 
6546 	/*
6547 	 * Handle "[m", "]m", "[M" and "[M".  The findmatchlimit() only
6548 	 * brought us to the match for "[m" and "]M" when inside a method.
6549 	 * Try finding the '{' or '}' we want to be at.
6550 	 * Also repeat for the given count.
6551 	 */
6552 	if (cap->nchar == 'm' || cap->nchar == 'M')
6553 	{
6554 	    /* norm is TRUE for "]M" and "[m" */
6555 	    int	    norm = ((findc == '{') == (cap->nchar == 'm'));
6556 
6557 	    n = cap->count1;
6558 	    /* found a match: we were inside a method */
6559 	    if (prev_pos.lnum != 0)
6560 	    {
6561 		pos = &prev_pos;
6562 		curwin->w_cursor = prev_pos;
6563 		if (norm)
6564 		    --n;
6565 	    }
6566 	    else
6567 		pos = NULL;
6568 	    while (n > 0)
6569 	    {
6570 		for (;;)
6571 		{
6572 		    if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0)
6573 		    {
6574 			/* if not found anything, that's an error */
6575 			if (pos == NULL)
6576 			    clearopbeep(cap->oap);
6577 			n = 0;
6578 			break;
6579 		    }
6580 		    c = gchar_cursor();
6581 		    if (c == '{' || c == '}')
6582 		    {
6583 			/* Must have found end/start of class: use it.
6584 			 * Or found the place to be at. */
6585 			if ((c == findc && norm) || (n == 1 && !norm))
6586 			{
6587 			    new_pos = curwin->w_cursor;
6588 			    pos = &new_pos;
6589 			    n = 0;
6590 			}
6591 			/* if no match found at all, we started outside of the
6592 			 * class and we're inside now.  Just go on. */
6593 			else if (new_pos.lnum == 0)
6594 			{
6595 			    new_pos = curwin->w_cursor;
6596 			    pos = &new_pos;
6597 			}
6598 			/* found start/end of other method: go to match */
6599 			else if ((pos = findmatchlimit(cap->oap, findc,
6600 			    (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD,
6601 								  0)) == NULL)
6602 			    n = 0;
6603 			else
6604 			    curwin->w_cursor = *pos;
6605 			break;
6606 		    }
6607 		}
6608 		--n;
6609 	    }
6610 	    curwin->w_cursor = old_pos;
6611 	    if (pos == NULL && new_pos.lnum != 0)
6612 		clearopbeep(cap->oap);
6613 	}
6614 	if (pos != NULL)
6615 	{
6616 	    setpcmark();
6617 	    curwin->w_cursor = *pos;
6618 	    curwin->w_set_curswant = TRUE;
6619 #ifdef FEAT_FOLDING
6620 	    if ((fdo_flags & FDO_BLOCK) && KeyTyped
6621 					       && cap->oap->op_type == OP_NOP)
6622 		foldOpenCursor();
6623 #endif
6624 	}
6625     }
6626 
6627     /*
6628      * "[[", "[]", "]]" and "][": move to start or end of function
6629      */
6630     else if (cap->nchar == '[' || cap->nchar == ']')
6631     {
6632 	if (cap->nchar == cap->cmdchar)		    /* "]]" or "[[" */
6633 	    flag = '{';
6634 	else
6635 	    flag = '}';		    /* "][" or "[]" */
6636 
6637 	curwin->w_set_curswant = TRUE;
6638 	/*
6639 	 * Imitate strange Vi behaviour: When using "]]" with an operator
6640 	 * we also stop at '}'.
6641 	 */
6642 	if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag,
6643 	      (cap->oap->op_type != OP_NOP
6644 				      && cap->arg == FORWARD && flag == '{')))
6645 	    clearopbeep(cap->oap);
6646 	else
6647 	{
6648 	    if (cap->oap->op_type == OP_NOP)
6649 		beginline(BL_WHITE | BL_FIX);
6650 #ifdef FEAT_FOLDING
6651 	    if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
6652 		foldOpenCursor();
6653 #endif
6654 	}
6655     }
6656 
6657     /*
6658      * "[p", "[P", "]P" and "]p": put with indent adjustment
6659      */
6660     else if (cap->nchar == 'p' || cap->nchar == 'P')
6661     {
6662 	if (!checkclearop(cap->oap))
6663 	{
6664 	    int	    dir = (cap->cmdchar == ']' && cap->nchar == 'p')
6665 							 ? FORWARD : BACKWARD;
6666 	    int	    regname = cap->oap->regname;
6667 	    int	    was_visual = VIsual_active;
6668 	    int	    line_count = curbuf->b_ml.ml_line_count;
6669 	    pos_T   start, end;
6670 
6671 	    if (VIsual_active)
6672 	    {
6673 		start = ltoreq(VIsual, curwin->w_cursor)
6674 						  ? VIsual : curwin->w_cursor;
6675 		end =  equalpos(start,VIsual) ? curwin->w_cursor : VIsual;
6676 		curwin->w_cursor = (dir == BACKWARD ? start : end);
6677 	    }
6678 # ifdef FEAT_CLIPBOARD
6679 	    adjust_clip_reg(&regname);
6680 # endif
6681 	    prep_redo_cmd(cap);
6682 
6683 	    do_put(regname, dir, cap->count1, PUT_FIXINDENT);
6684 	    if (was_visual)
6685 	    {
6686 		VIsual = start;
6687 		curwin->w_cursor = end;
6688 		if (dir == BACKWARD)
6689 		{
6690 		    /* adjust lines */
6691 		    VIsual.lnum += curbuf->b_ml.ml_line_count - line_count;
6692 		    curwin->w_cursor.lnum +=
6693 				      curbuf->b_ml.ml_line_count - line_count;
6694 		}
6695 
6696 		VIsual_active = TRUE;
6697 		if (VIsual_mode == 'V')
6698 		{
6699 		    /* delete visually selected lines */
6700 		    cap->cmdchar = 'd';
6701 		    cap->nchar = NUL;
6702 		    cap->oap->regname = regname;
6703 		    nv_operator(cap);
6704 		    do_pending_operator(cap, 0, FALSE);
6705 		}
6706 		if (VIsual_active)
6707 		{
6708 		    end_visual_mode();
6709 		    redraw_later(SOME_VALID);
6710 		}
6711 	    }
6712 	}
6713     }
6714 
6715     /*
6716      * "['", "[`", "]'" and "]`": jump to next mark
6717      */
6718     else if (cap->nchar == '\'' || cap->nchar == '`')
6719     {
6720 	pos = &curwin->w_cursor;
6721 	for (n = cap->count1; n > 0; --n)
6722 	{
6723 	    prev_pos = *pos;
6724 	    pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD,
6725 							  cap->nchar == '\'');
6726 	    if (pos == NULL)
6727 		break;
6728 	}
6729 	if (pos == NULL)
6730 	    pos = &prev_pos;
6731 	nv_cursormark(cap, cap->nchar == '\'', pos);
6732     }
6733 
6734 #ifdef FEAT_MOUSE
6735     /*
6736      * [ or ] followed by a middle mouse click: put selected text with
6737      * indent adjustment.  Any other button just does as usual.
6738      */
6739     else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE)
6740     {
6741 	(void)do_mouse(cap->oap, cap->nchar,
6742 		       (cap->cmdchar == ']') ? FORWARD : BACKWARD,
6743 		       cap->count1, PUT_FIXINDENT);
6744     }
6745 #endif /* FEAT_MOUSE */
6746 
6747 #ifdef FEAT_FOLDING
6748     /*
6749      * "[z" and "]z": move to start or end of open fold.
6750      */
6751     else if (cap->nchar == 'z')
6752     {
6753 	if (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD,
6754 							 cap->count1) == FAIL)
6755 	    clearopbeep(cap->oap);
6756     }
6757 #endif
6758 
6759 #ifdef FEAT_DIFF
6760     /*
6761      * "[c" and "]c": move to next or previous diff-change.
6762      */
6763     else if (cap->nchar == 'c')
6764     {
6765 	if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD,
6766 							 cap->count1) == FAIL)
6767 	    clearopbeep(cap->oap);
6768     }
6769 #endif
6770 
6771 #ifdef FEAT_SPELL
6772     /*
6773      * "[s", "[S", "]s" and "]S": move to next spell error.
6774      */
6775     else if (cap->nchar == 's' || cap->nchar == 'S')
6776     {
6777 	setpcmark();
6778 	for (n = 0; n < cap->count1; ++n)
6779 	    if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD,
6780 			  cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0)
6781 	    {
6782 		clearopbeep(cap->oap);
6783 		break;
6784 	    }
6785 # ifdef FEAT_FOLDING
6786 	if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
6787 	    foldOpenCursor();
6788 # endif
6789     }
6790 #endif
6791 
6792     /* Not a valid cap->nchar. */
6793     else
6794 	clearopbeep(cap->oap);
6795 }
6796 
6797 /*
6798  * Handle Normal mode "%" command.
6799  */
6800     static void
6801 nv_percent(cap)
6802     cmdarg_T	*cap;
6803 {
6804     pos_T	*pos;
6805 #if defined(FEAT_FOLDING)
6806     linenr_T	lnum = curwin->w_cursor.lnum;
6807 #endif
6808 
6809     cap->oap->inclusive = TRUE;
6810     if (cap->count0)	    /* {cnt}% : goto {cnt} percentage in file */
6811     {
6812 	if (cap->count0 > 100)
6813 	    clearopbeep(cap->oap);
6814 	else
6815 	{
6816 	    cap->oap->motion_type = MLINE;
6817 	    setpcmark();
6818 	    /* Round up, so CTRL-G will give same value.  Watch out for a
6819 	     * large line count, the line number must not go negative! */
6820 	    if (curbuf->b_ml.ml_line_count > 1000000)
6821 		curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99L)
6822 							 / 100L * cap->count0;
6823 	    else
6824 		curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count *
6825 						    cap->count0 + 99L) / 100L;
6826 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6827 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6828 	    beginline(BL_SOL | BL_FIX);
6829 	}
6830     }
6831     else		    /* "%" : go to matching paren */
6832     {
6833 	cap->oap->motion_type = MCHAR;
6834 	cap->oap->use_reg_one = TRUE;
6835 	if ((pos = findmatch(cap->oap, NUL)) == NULL)
6836 	    clearopbeep(cap->oap);
6837 	else
6838 	{
6839 	    setpcmark();
6840 	    curwin->w_cursor = *pos;
6841 	    curwin->w_set_curswant = TRUE;
6842 #ifdef FEAT_VIRTUALEDIT
6843 	    curwin->w_cursor.coladd = 0;
6844 #endif
6845 	    adjust_for_sel(cap);
6846 	}
6847     }
6848 #ifdef FEAT_FOLDING
6849     if (cap->oap->op_type == OP_NOP
6850 	    && lnum != curwin->w_cursor.lnum
6851 	    && (fdo_flags & FDO_PERCENT)
6852 	    && KeyTyped)
6853 	foldOpenCursor();
6854 #endif
6855 }
6856 
6857 /*
6858  * Handle "(" and ")" commands.
6859  * cap->arg is BACKWARD for "(" and FORWARD for ")".
6860  */
6861     static void
6862 nv_brace(cap)
6863     cmdarg_T	*cap;
6864 {
6865     cap->oap->motion_type = MCHAR;
6866     cap->oap->use_reg_one = TRUE;
6867     /* The motion used to be inclusive for "(", but that is not what Vi does. */
6868     cap->oap->inclusive = FALSE;
6869     curwin->w_set_curswant = TRUE;
6870 
6871     if (findsent(cap->arg, cap->count1) == FAIL)
6872 	clearopbeep(cap->oap);
6873     else
6874     {
6875 	/* Don't leave the cursor on the NUL past end of line. */
6876 	adjust_cursor(cap->oap);
6877 #ifdef FEAT_VIRTUALEDIT
6878 	curwin->w_cursor.coladd = 0;
6879 #endif
6880 #ifdef FEAT_FOLDING
6881 	if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
6882 	    foldOpenCursor();
6883 #endif
6884     }
6885 }
6886 
6887 /*
6888  * "m" command: Mark a position.
6889  */
6890     static void
6891 nv_mark(cap)
6892     cmdarg_T	*cap;
6893 {
6894     if (!checkclearop(cap->oap))
6895     {
6896 	if (setmark(cap->nchar) == FAIL)
6897 	    clearopbeep(cap->oap);
6898     }
6899 }
6900 
6901 /*
6902  * "{" and "}" commands.
6903  * cmd->arg is BACKWARD for "{" and FORWARD for "}".
6904  */
6905     static void
6906 nv_findpar(cap)
6907     cmdarg_T	*cap;
6908 {
6909     cap->oap->motion_type = MCHAR;
6910     cap->oap->inclusive = FALSE;
6911     cap->oap->use_reg_one = TRUE;
6912     curwin->w_set_curswant = TRUE;
6913     if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, FALSE))
6914 	clearopbeep(cap->oap);
6915     else
6916     {
6917 #ifdef FEAT_VIRTUALEDIT
6918 	curwin->w_cursor.coladd = 0;
6919 #endif
6920 #ifdef FEAT_FOLDING
6921 	if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
6922 	    foldOpenCursor();
6923 #endif
6924     }
6925 }
6926 
6927 /*
6928  * "u" command: Undo or make lower case.
6929  */
6930     static void
6931 nv_undo(cap)
6932     cmdarg_T	*cap;
6933 {
6934     if (cap->oap->op_type == OP_LOWER || VIsual_active)
6935     {
6936 	/* translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" */
6937 	cap->cmdchar = 'g';
6938 	cap->nchar = 'u';
6939 	nv_operator(cap);
6940     }
6941     else
6942 	nv_kundo(cap);
6943 }
6944 
6945 /*
6946  * <Undo> command.
6947  */
6948     static void
6949 nv_kundo(cap)
6950     cmdarg_T	*cap;
6951 {
6952     if (!checkclearopq(cap->oap))
6953     {
6954 	u_undo((int)cap->count1);
6955 	curwin->w_set_curswant = TRUE;
6956     }
6957 }
6958 
6959 /*
6960  * Handle the "r" command.
6961  */
6962     static void
6963 nv_replace(cap)
6964     cmdarg_T	*cap;
6965 {
6966     char_u	*ptr;
6967     int		had_ctrl_v;
6968     long	n;
6969 
6970     if (checkclearop(cap->oap))
6971 	return;
6972 
6973     /* get another character */
6974     if (cap->nchar == Ctrl_V)
6975     {
6976 	had_ctrl_v = Ctrl_V;
6977 	cap->nchar = get_literal();
6978 	/* Don't redo a multibyte character with CTRL-V. */
6979 	if (cap->nchar > DEL)
6980 	    had_ctrl_v = NUL;
6981     }
6982     else
6983 	had_ctrl_v = NUL;
6984 
6985     /* Abort if the character is a special key. */
6986     if (IS_SPECIAL(cap->nchar))
6987     {
6988 	clearopbeep(cap->oap);
6989 	return;
6990     }
6991 
6992     /* Visual mode "r" */
6993     if (VIsual_active)
6994     {
6995 	if (got_int)
6996 	    reset_VIsual();
6997 	if (had_ctrl_v)
6998 	{
6999 	    if (cap->nchar == '\r')
7000 		cap->nchar = -1;
7001 	    else if (cap->nchar == '\n')
7002 		cap->nchar = -2;
7003 	}
7004 	nv_operator(cap);
7005 	return;
7006     }
7007 
7008 #ifdef FEAT_VIRTUALEDIT
7009     /* Break tabs, etc. */
7010     if (virtual_active())
7011     {
7012 	if (u_save_cursor() == FAIL)
7013 	    return;
7014 	if (gchar_cursor() == NUL)
7015 	{
7016 	    /* Add extra space and put the cursor on the first one. */
7017 	    coladvance_force((colnr_T)(getviscol() + cap->count1));
7018 	    curwin->w_cursor.col -= cap->count1;
7019 	}
7020 	else if (gchar_cursor() == TAB)
7021 	    coladvance_force(getviscol());
7022     }
7023 #endif
7024 
7025     /* Abort if not enough characters to replace. */
7026     ptr = ml_get_cursor();
7027     if (STRLEN(ptr) < (unsigned)cap->count1
7028 #ifdef FEAT_MBYTE
7029 	    || (has_mbyte && mb_charlen(ptr) < cap->count1)
7030 #endif
7031 	    )
7032     {
7033 	clearopbeep(cap->oap);
7034 	return;
7035     }
7036 
7037     /*
7038      * Replacing with a TAB is done by edit() when it is complicated because
7039      * 'expandtab' or 'smarttab' is set.  CTRL-V TAB inserts a literal TAB.
7040      * Other characters are done below to avoid problems with things like
7041      * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC).
7042      */
7043     if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta))
7044     {
7045 	stuffnumReadbuff(cap->count1);
7046 	stuffcharReadbuff('R');
7047 	stuffcharReadbuff('\t');
7048 	stuffcharReadbuff(ESC);
7049 	return;
7050     }
7051 
7052     /* save line for undo */
7053     if (u_save_cursor() == FAIL)
7054 	return;
7055 
7056     if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n'))
7057     {
7058 	/*
7059 	 * Replace character(s) by a single newline.
7060 	 * Strange vi behaviour: Only one newline is inserted.
7061 	 * Delete the characters here.
7062 	 * Insert the newline with an insert command, takes care of
7063 	 * autoindent.	The insert command depends on being on the last
7064 	 * character of a line or not.
7065 	 */
7066 #ifdef FEAT_MBYTE
7067 	(void)del_chars(cap->count1, FALSE);	/* delete the characters */
7068 #else
7069 	(void)del_bytes(cap->count1, FALSE, FALSE); /* delete the characters */
7070 #endif
7071 	stuffcharReadbuff('\r');
7072 	stuffcharReadbuff(ESC);
7073 
7074 	/* Give 'r' to edit(), to get the redo command right. */
7075 	invoke_edit(cap, TRUE, 'r', FALSE);
7076     }
7077     else
7078     {
7079 	prep_redo(cap->oap->regname, cap->count1,
7080 				       NUL, 'r', NUL, had_ctrl_v, cap->nchar);
7081 
7082 	curbuf->b_op_start = curwin->w_cursor;
7083 #ifdef FEAT_MBYTE
7084 	if (has_mbyte)
7085 	{
7086 	    int		old_State = State;
7087 
7088 	    if (cap->ncharC1 != 0)
7089 		AppendCharToRedobuff(cap->ncharC1);
7090 	    if (cap->ncharC2 != 0)
7091 		AppendCharToRedobuff(cap->ncharC2);
7092 
7093 	    /* This is slow, but it handles replacing a single-byte with a
7094 	     * multi-byte and the other way around.  Also handles adding
7095 	     * composing characters for utf-8. */
7096 	    for (n = cap->count1; n > 0; --n)
7097 	    {
7098 		State = REPLACE;
7099 		if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
7100 		{
7101 		    int c = ins_copychar(curwin->w_cursor.lnum
7102 					   + (cap->nchar == Ctrl_Y ? -1 : 1));
7103 		    if (c != NUL)
7104 			ins_char(c);
7105 		    else
7106 			/* will be decremented further down */
7107 			++curwin->w_cursor.col;
7108 		}
7109 		else
7110 		    ins_char(cap->nchar);
7111 		State = old_State;
7112 		if (cap->ncharC1 != 0)
7113 		    ins_char(cap->ncharC1);
7114 		if (cap->ncharC2 != 0)
7115 		    ins_char(cap->ncharC2);
7116 	    }
7117 	}
7118 	else
7119 #endif
7120 	{
7121 	    /*
7122 	     * Replace the characters within one line.
7123 	     */
7124 	    for (n = cap->count1; n > 0; --n)
7125 	    {
7126 		/*
7127 		 * Get ptr again, because u_save and/or showmatch() will have
7128 		 * released the line.  At the same time we let know that the
7129 		 * line will be changed.
7130 		 */
7131 		ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);
7132 		if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
7133 		{
7134 		  int c = ins_copychar(curwin->w_cursor.lnum
7135 					   + (cap->nchar == Ctrl_Y ? -1 : 1));
7136 		  if (c != NUL)
7137 		    ptr[curwin->w_cursor.col] = c;
7138 		}
7139 		else
7140 		    ptr[curwin->w_cursor.col] = cap->nchar;
7141 		if (p_sm && msg_silent == 0)
7142 		    showmatch(cap->nchar);
7143 		++curwin->w_cursor.col;
7144 	    }
7145 #ifdef FEAT_NETBEANS_INTG
7146 	    if (netbeans_active())
7147 	    {
7148 		colnr_T  start = (colnr_T)(curwin->w_cursor.col - cap->count1);
7149 
7150 		netbeans_removed(curbuf, curwin->w_cursor.lnum, start,
7151 							   (long)cap->count1);
7152 		netbeans_inserted(curbuf, curwin->w_cursor.lnum, start,
7153 					       &ptr[start], (int)cap->count1);
7154 	    }
7155 #endif
7156 
7157 	    /* mark the buffer as changed and prepare for displaying */
7158 	    changed_bytes(curwin->w_cursor.lnum,
7159 			       (colnr_T)(curwin->w_cursor.col - cap->count1));
7160 	}
7161 	--curwin->w_cursor.col;	    /* cursor on the last replaced char */
7162 #ifdef FEAT_MBYTE
7163 	/* if the character on the left of the current cursor is a multi-byte
7164 	 * character, move two characters left */
7165 	if (has_mbyte)
7166 	    mb_adjust_cursor();
7167 #endif
7168 	curbuf->b_op_end = curwin->w_cursor;
7169 	curwin->w_set_curswant = TRUE;
7170 	set_last_insert(cap->nchar);
7171     }
7172 }
7173 
7174 /*
7175  * 'o': Exchange start and end of Visual area.
7176  * 'O': same, but in block mode exchange left and right corners.
7177  */
7178     static void
7179 v_swap_corners(cmdchar)
7180     int		cmdchar;
7181 {
7182     pos_T	old_cursor;
7183     colnr_T	left, right;
7184 
7185     if (cmdchar == 'O' && VIsual_mode == Ctrl_V)
7186     {
7187 	old_cursor = curwin->w_cursor;
7188 	getvcols(curwin, &old_cursor, &VIsual, &left, &right);
7189 	curwin->w_cursor.lnum = VIsual.lnum;
7190 	coladvance(left);
7191 	VIsual = curwin->w_cursor;
7192 
7193 	curwin->w_cursor.lnum = old_cursor.lnum;
7194 	curwin->w_curswant = right;
7195 	/* 'selection "exclusive" and cursor at right-bottom corner: move it
7196 	 * right one column */
7197 	if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e')
7198 	    ++curwin->w_curswant;
7199 	coladvance(curwin->w_curswant);
7200 	if (curwin->w_cursor.col == old_cursor.col
7201 #ifdef FEAT_VIRTUALEDIT
7202 		&& (!virtual_active()
7203 		    || curwin->w_cursor.coladd == old_cursor.coladd)
7204 #endif
7205 		)
7206 	{
7207 	    curwin->w_cursor.lnum = VIsual.lnum;
7208 	    if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e')
7209 		++right;
7210 	    coladvance(right);
7211 	    VIsual = curwin->w_cursor;
7212 
7213 	    curwin->w_cursor.lnum = old_cursor.lnum;
7214 	    coladvance(left);
7215 	    curwin->w_curswant = left;
7216 	}
7217     }
7218     else
7219     {
7220 	old_cursor = curwin->w_cursor;
7221 	curwin->w_cursor = VIsual;
7222 	VIsual = old_cursor;
7223 	curwin->w_set_curswant = TRUE;
7224     }
7225 }
7226 
7227 /*
7228  * "R" (cap->arg is FALSE) and "gR" (cap->arg is TRUE).
7229  */
7230     static void
7231 nv_Replace(cap)
7232     cmdarg_T	    *cap;
7233 {
7234     if (VIsual_active)		/* "R" is replace lines */
7235     {
7236 	cap->cmdchar = 'c';
7237 	cap->nchar = NUL;
7238 	VIsual_mode_orig = VIsual_mode; /* remember original area for gv */
7239 	VIsual_mode = 'V';
7240 	nv_operator(cap);
7241     }
7242     else if (!checkclearopq(cap->oap))
7243     {
7244 	if (!curbuf->b_p_ma)
7245 	    EMSG(_(e_modifiable));
7246 	else
7247 	{
7248 #ifdef FEAT_VIRTUALEDIT
7249 	    if (virtual_active())
7250 		coladvance(getviscol());
7251 #endif
7252 	    invoke_edit(cap, FALSE, cap->arg ? 'V' : 'R', FALSE);
7253 	}
7254     }
7255 }
7256 
7257 #ifdef FEAT_VREPLACE
7258 /*
7259  * "gr".
7260  */
7261     static void
7262 nv_vreplace(cap)
7263     cmdarg_T	*cap;
7264 {
7265     if (VIsual_active)
7266     {
7267 	cap->cmdchar = 'r';
7268 	cap->nchar = cap->extra_char;
7269 	nv_replace(cap);	/* Do same as "r" in Visual mode for now */
7270     }
7271     else if (!checkclearopq(cap->oap))
7272     {
7273 	if (!curbuf->b_p_ma)
7274 	    EMSG(_(e_modifiable));
7275 	else
7276 	{
7277 	    if (cap->extra_char == Ctrl_V)	/* get another character */
7278 		cap->extra_char = get_literal();
7279 	    stuffcharReadbuff(cap->extra_char);
7280 	    stuffcharReadbuff(ESC);
7281 # ifdef FEAT_VIRTUALEDIT
7282 	    if (virtual_active())
7283 		coladvance(getviscol());
7284 # endif
7285 	    invoke_edit(cap, TRUE, 'v', FALSE);
7286 	}
7287     }
7288 }
7289 #endif
7290 
7291 /*
7292  * Swap case for "~" command, when it does not work like an operator.
7293  */
7294     static void
7295 n_swapchar(cap)
7296     cmdarg_T	*cap;
7297 {
7298     long	n;
7299     pos_T	startpos;
7300     int		did_change = 0;
7301 #ifdef FEAT_NETBEANS_INTG
7302     pos_T	pos;
7303     char_u	*ptr;
7304     int		count;
7305 #endif
7306 
7307     if (checkclearopq(cap->oap))
7308 	return;
7309 
7310     if (lineempty(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL)
7311     {
7312 	clearopbeep(cap->oap);
7313 	return;
7314     }
7315 
7316     prep_redo_cmd(cap);
7317 
7318     if (u_save_cursor() == FAIL)
7319 	return;
7320 
7321     startpos = curwin->w_cursor;
7322 #ifdef FEAT_NETBEANS_INTG
7323     pos = startpos;
7324 #endif
7325     for (n = cap->count1; n > 0; --n)
7326     {
7327 	did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor);
7328 	inc_cursor();
7329 	if (gchar_cursor() == NUL)
7330 	{
7331 	    if (vim_strchr(p_ww, '~') != NULL
7332 		    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
7333 	    {
7334 #ifdef FEAT_NETBEANS_INTG
7335 		if (netbeans_active())
7336 		{
7337 		    if (did_change)
7338 		    {
7339 			ptr = ml_get(pos.lnum);
7340 			count = (int)STRLEN(ptr) - pos.col;
7341 			netbeans_removed(curbuf, pos.lnum, pos.col,
7342 								 (long)count);
7343 			netbeans_inserted(curbuf, pos.lnum, pos.col,
7344 							&ptr[pos.col], count);
7345 		    }
7346 		    pos.col = 0;
7347 		    pos.lnum++;
7348 		}
7349 #endif
7350 		++curwin->w_cursor.lnum;
7351 		curwin->w_cursor.col = 0;
7352 		if (n > 1)
7353 		{
7354 		    if (u_savesub(curwin->w_cursor.lnum) == FAIL)
7355 			break;
7356 		    u_clearline();
7357 		}
7358 	    }
7359 	    else
7360 		break;
7361 	}
7362     }
7363 #ifdef FEAT_NETBEANS_INTG
7364     if (did_change && netbeans_active())
7365     {
7366 	ptr = ml_get(pos.lnum);
7367 	count = curwin->w_cursor.col - pos.col;
7368 	netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
7369 	netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count);
7370     }
7371 #endif
7372 
7373 
7374     check_cursor();
7375     curwin->w_set_curswant = TRUE;
7376     if (did_change)
7377     {
7378 	changed_lines(startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1,
7379 									  0L);
7380 	curbuf->b_op_start = startpos;
7381 	curbuf->b_op_end = curwin->w_cursor;
7382 	if (curbuf->b_op_end.col > 0)
7383 	    --curbuf->b_op_end.col;
7384     }
7385 }
7386 
7387 /*
7388  * Move cursor to mark.
7389  */
7390     static void
7391 nv_cursormark(cap, flag, pos)
7392     cmdarg_T	*cap;
7393     int		flag;
7394     pos_T	*pos;
7395 {
7396     if (check_mark(pos) == FAIL)
7397 	clearop(cap->oap);
7398     else
7399     {
7400 	if (cap->cmdchar == '\''
7401 		|| cap->cmdchar == '`'
7402 		|| cap->cmdchar == '['
7403 		|| cap->cmdchar == ']')
7404 	    setpcmark();
7405 	curwin->w_cursor = *pos;
7406 	if (flag)
7407 	    beginline(BL_WHITE | BL_FIX);
7408 	else
7409 	    check_cursor();
7410     }
7411     cap->oap->motion_type = flag ? MLINE : MCHAR;
7412     if (cap->cmdchar == '`')
7413 	cap->oap->use_reg_one = TRUE;
7414     cap->oap->inclusive = FALSE;		/* ignored if not MCHAR */
7415     curwin->w_set_curswant = TRUE;
7416 }
7417 
7418 /*
7419  * Handle commands that are operators in Visual mode.
7420  */
7421     static void
7422 v_visop(cap)
7423     cmdarg_T	*cap;
7424 {
7425     static char_u trans[] = "YyDdCcxdXdAAIIrr";
7426 
7427     /* Uppercase means linewise, except in block mode, then "D" deletes till
7428      * the end of the line, and "C" replaces till EOL */
7429     if (isupper(cap->cmdchar))
7430     {
7431 	if (VIsual_mode != Ctrl_V)
7432 	{
7433 	    VIsual_mode_orig = VIsual_mode;
7434 	    VIsual_mode = 'V';
7435 	}
7436 	else if (cap->cmdchar == 'C' || cap->cmdchar == 'D')
7437 	    curwin->w_curswant = MAXCOL;
7438     }
7439     cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1);
7440     nv_operator(cap);
7441 }
7442 
7443 /*
7444  * "s" and "S" commands.
7445  */
7446     static void
7447 nv_subst(cap)
7448     cmdarg_T	*cap;
7449 {
7450     if (VIsual_active)	/* "vs" and "vS" are the same as "vc" */
7451     {
7452 	if (cap->cmdchar == 'S')
7453 	{
7454 	    VIsual_mode_orig = VIsual_mode;
7455 	    VIsual_mode = 'V';
7456 	}
7457 	cap->cmdchar = 'c';
7458 	nv_operator(cap);
7459     }
7460     else
7461 	nv_optrans(cap);
7462 }
7463 
7464 /*
7465  * Abbreviated commands.
7466  */
7467     static void
7468 nv_abbrev(cap)
7469     cmdarg_T	*cap;
7470 {
7471     if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL)
7472 	cap->cmdchar = 'x';		/* DEL key behaves like 'x' */
7473 
7474     /* in Visual mode these commands are operators */
7475     if (VIsual_active)
7476 	v_visop(cap);
7477     else
7478 	nv_optrans(cap);
7479 }
7480 
7481 /*
7482  * Translate a command into another command.
7483  */
7484     static void
7485 nv_optrans(cap)
7486     cmdarg_T	*cap;
7487 {
7488     static char_u *(ar[8]) = {(char_u *)"dl", (char_u *)"dh",
7489 			      (char_u *)"d$", (char_u *)"c$",
7490 			      (char_u *)"cl", (char_u *)"cc",
7491 			      (char_u *)"yy", (char_u *)":s\r"};
7492     static char_u *str = (char_u *)"xXDCsSY&";
7493 
7494     if (!checkclearopq(cap->oap))
7495     {
7496 	/* In Vi "2D" doesn't delete the next line.  Can't translate it
7497 	 * either, because "2." should also not use the count. */
7498 	if (cap->cmdchar == 'D' && vim_strchr(p_cpo, CPO_HASH) != NULL)
7499 	{
7500 	    cap->oap->start = curwin->w_cursor;
7501 	    cap->oap->op_type = OP_DELETE;
7502 #ifdef FEAT_EVAL
7503 	    set_op_var(OP_DELETE);
7504 #endif
7505 	    cap->count1 = 1;
7506 	    nv_dollar(cap);
7507 	    finish_op = TRUE;
7508 	    ResetRedobuff();
7509 	    AppendCharToRedobuff('D');
7510 	}
7511 	else
7512 	{
7513 	    if (cap->count0)
7514 		stuffnumReadbuff(cap->count0);
7515 	    stuffReadbuff(ar[(int)(vim_strchr(str, cap->cmdchar) - str)]);
7516 	}
7517     }
7518     cap->opcount = 0;
7519 }
7520 
7521 /*
7522  * "'" and "`" commands.  Also for "g'" and "g`".
7523  * cap->arg is TRUE for "'" and "g'".
7524  */
7525     static void
7526 nv_gomark(cap)
7527     cmdarg_T	*cap;
7528 {
7529     pos_T	*pos;
7530     int		c;
7531 #ifdef FEAT_FOLDING
7532     pos_T	old_cursor = curwin->w_cursor;
7533     int		old_KeyTyped = KeyTyped;    /* getting file may reset it */
7534 #endif
7535 
7536     if (cap->cmdchar == 'g')
7537 	c = cap->extra_char;
7538     else
7539 	c = cap->nchar;
7540     pos = getmark(c, (cap->oap->op_type == OP_NOP));
7541     if (pos == (pos_T *)-1)	    /* jumped to other file */
7542     {
7543 	if (cap->arg)
7544 	{
7545 	    check_cursor_lnum();
7546 	    beginline(BL_WHITE | BL_FIX);
7547 	}
7548 	else
7549 	    check_cursor();
7550     }
7551     else
7552 	nv_cursormark(cap, cap->arg, pos);
7553 
7554 #ifdef FEAT_VIRTUALEDIT
7555     /* May need to clear the coladd that a mark includes. */
7556     if (!virtual_active())
7557 	curwin->w_cursor.coladd = 0;
7558 #endif
7559 #ifdef FEAT_FOLDING
7560     if (cap->oap->op_type == OP_NOP
7561 	    && pos != NULL
7562 	    && (pos == (pos_T *)-1 || !equalpos(old_cursor, *pos))
7563 	    && (fdo_flags & FDO_MARK)
7564 	    && old_KeyTyped)
7565 	foldOpenCursor();
7566 #endif
7567 }
7568 
7569 /*
7570  * Handle CTRL-O, CTRL-I, "g;" and "g," commands.
7571  */
7572     static void
7573 nv_pcmark(cap)
7574     cmdarg_T	*cap;
7575 {
7576 #ifdef FEAT_JUMPLIST
7577     pos_T	*pos;
7578 # ifdef FEAT_FOLDING
7579     linenr_T	lnum = curwin->w_cursor.lnum;
7580     int		old_KeyTyped = KeyTyped;    /* getting file may reset it */
7581 # endif
7582 
7583     if (!checkclearopq(cap->oap))
7584     {
7585 	if (cap->cmdchar == 'g')
7586 	    pos = movechangelist((int)cap->count1);
7587 	else
7588 	    pos = movemark((int)cap->count1);
7589 	if (pos == (pos_T *)-1)		/* jump to other file */
7590 	{
7591 	    curwin->w_set_curswant = TRUE;
7592 	    check_cursor();
7593 	}
7594 	else if (pos != NULL)		    /* can jump */
7595 	    nv_cursormark(cap, FALSE, pos);
7596 	else if (cap->cmdchar == 'g')
7597 	{
7598 	    if (curbuf->b_changelistlen == 0)
7599 		EMSG(_("E664: changelist is empty"));
7600 	    else if (cap->count1 < 0)
7601 		EMSG(_("E662: At start of changelist"));
7602 	    else
7603 		EMSG(_("E663: At end of changelist"));
7604 	}
7605 	else
7606 	    clearopbeep(cap->oap);
7607 # ifdef FEAT_FOLDING
7608 	if (cap->oap->op_type == OP_NOP
7609 		&& (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum)
7610 		&& (fdo_flags & FDO_MARK)
7611 		&& old_KeyTyped)
7612 	    foldOpenCursor();
7613 # endif
7614     }
7615 #else
7616     clearopbeep(cap->oap);
7617 #endif
7618 }
7619 
7620 /*
7621  * Handle '"' command.
7622  */
7623     static void
7624 nv_regname(cap)
7625     cmdarg_T	*cap;
7626 {
7627     if (checkclearop(cap->oap))
7628 	return;
7629 #ifdef FEAT_EVAL
7630     if (cap->nchar == '=')
7631 	cap->nchar = get_expr_register();
7632 #endif
7633     if (cap->nchar != NUL && valid_yank_reg(cap->nchar, FALSE))
7634     {
7635 	cap->oap->regname = cap->nchar;
7636 	cap->opcount = cap->count0;	/* remember count before '"' */
7637 #ifdef FEAT_EVAL
7638 	set_reg_var(cap->oap->regname);
7639 #endif
7640     }
7641     else
7642 	clearopbeep(cap->oap);
7643 }
7644 
7645 /*
7646  * Handle "v", "V" and "CTRL-V" commands.
7647  * Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg
7648  * is TRUE.
7649  * Handle CTRL-Q just like CTRL-V.
7650  */
7651     static void
7652 nv_visual(cap)
7653     cmdarg_T	*cap;
7654 {
7655     if (cap->cmdchar == Ctrl_Q)
7656 	cap->cmdchar = Ctrl_V;
7657 
7658     /* 'v', 'V' and CTRL-V can be used while an operator is pending to make it
7659      * characterwise, linewise, or blockwise. */
7660     if (cap->oap->op_type != OP_NOP)
7661     {
7662 	cap->oap->motion_force = cap->cmdchar;
7663 	finish_op = FALSE;	/* operator doesn't finish now but later */
7664 	return;
7665     }
7666 
7667     VIsual_select = cap->arg;
7668     if (VIsual_active)	    /* change Visual mode */
7669     {
7670 	if (VIsual_mode == cap->cmdchar)    /* stop visual mode */
7671 	    end_visual_mode();
7672 	else				    /* toggle char/block mode */
7673 	{				    /*	   or char/line mode */
7674 	    VIsual_mode = cap->cmdchar;
7675 	    showmode();
7676 	}
7677 	redraw_curbuf_later(INVERTED);	    /* update the inversion */
7678     }
7679     else		    /* start Visual mode */
7680     {
7681 	check_visual_highlight();
7682 	if (cap->count0 > 0 && resel_VIsual_mode != NUL)
7683 	{
7684 	    /* use previously selected part */
7685 	    VIsual = curwin->w_cursor;
7686 
7687 	    VIsual_active = TRUE;
7688 	    VIsual_reselect = TRUE;
7689 	    if (!cap->arg)
7690 		/* start Select mode when 'selectmode' contains "cmd" */
7691 		may_start_select('c');
7692 #ifdef FEAT_MOUSE
7693 	    setmouse();
7694 #endif
7695 	    if (p_smd && msg_silent == 0)
7696 		redraw_cmdline = TRUE;	    /* show visual mode later */
7697 	    /*
7698 	     * For V and ^V, we multiply the number of lines even if there
7699 	     * was only one -- webb
7700 	     */
7701 	    if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1)
7702 	    {
7703 		curwin->w_cursor.lnum +=
7704 				    resel_VIsual_line_count * cap->count0 - 1;
7705 		if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
7706 		    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7707 	    }
7708 	    VIsual_mode = resel_VIsual_mode;
7709 	    if (VIsual_mode == 'v')
7710 	    {
7711 		if (resel_VIsual_line_count <= 1)
7712 		{
7713 		    validate_virtcol();
7714 		    curwin->w_curswant = curwin->w_virtcol
7715 					+ resel_VIsual_vcol * cap->count0 - 1;
7716 		}
7717 		else
7718 		    curwin->w_curswant = resel_VIsual_vcol;
7719 		coladvance(curwin->w_curswant);
7720 	    }
7721 	    if (resel_VIsual_vcol == MAXCOL)
7722 	    {
7723 		curwin->w_curswant = MAXCOL;
7724 		coladvance((colnr_T)MAXCOL);
7725 	    }
7726 	    else if (VIsual_mode == Ctrl_V)
7727 	    {
7728 		validate_virtcol();
7729 		curwin->w_curswant = curwin->w_virtcol
7730 					+ resel_VIsual_vcol * cap->count0 - 1;
7731 		coladvance(curwin->w_curswant);
7732 	    }
7733 	    else
7734 		curwin->w_set_curswant = TRUE;
7735 	    redraw_curbuf_later(INVERTED);	/* show the inversion */
7736 	}
7737 	else
7738 	{
7739 	    if (!cap->arg)
7740 		/* start Select mode when 'selectmode' contains "cmd" */
7741 		may_start_select('c');
7742 	    n_start_visual_mode(cap->cmdchar);
7743 	    if (VIsual_mode != 'V' && *p_sel == 'e')
7744 		++cap->count1;  /* include one more char */
7745 	    if (cap->count0 > 0 && --cap->count1 > 0)
7746 	    {
7747 		/* With a count select that many characters or lines. */
7748 		if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V)
7749 		    nv_right(cap);
7750 		else if (VIsual_mode == 'V')
7751 		    nv_down(cap);
7752 	    }
7753 	}
7754     }
7755 }
7756 
7757 /*
7758  * Start selection for Shift-movement keys.
7759  */
7760     void
7761 start_selection()
7762 {
7763     /* if 'selectmode' contains "key", start Select mode */
7764     may_start_select('k');
7765     n_start_visual_mode('v');
7766 }
7767 
7768 /*
7769  * Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu.
7770  */
7771     void
7772 may_start_select(c)
7773     int		c;
7774 {
7775     VIsual_select = (stuff_empty() && typebuf_typed()
7776 		    && (vim_strchr(p_slm, c) != NULL));
7777 }
7778 
7779 /*
7780  * Start Visual mode "c".
7781  * Should set VIsual_select before calling this.
7782  */
7783     static void
7784 n_start_visual_mode(c)
7785     int		c;
7786 {
7787 #ifdef FEAT_CONCEAL
7788     /* Check for redraw before changing the state. */
7789     conceal_check_cursur_line();
7790 #endif
7791 
7792     VIsual_mode = c;
7793     VIsual_active = TRUE;
7794     VIsual_reselect = TRUE;
7795 #ifdef FEAT_VIRTUALEDIT
7796     /* Corner case: the 0 position in a tab may change when going into
7797      * virtualedit.  Recalculate curwin->w_cursor to avoid bad hilighting.
7798      */
7799     if (c == Ctrl_V && (ve_flags & VE_BLOCK) && gchar_cursor() == TAB)
7800     {
7801 	validate_virtcol();
7802 	coladvance(curwin->w_virtcol);
7803     }
7804 #endif
7805     VIsual = curwin->w_cursor;
7806 
7807 #ifdef FEAT_FOLDING
7808     foldAdjustVisual();
7809 #endif
7810 
7811 #ifdef FEAT_MOUSE
7812     setmouse();
7813 #endif
7814 #ifdef FEAT_CONCEAL
7815     /* Check for redraw after changing the state. */
7816     conceal_check_cursur_line();
7817 #endif
7818 
7819     if (p_smd && msg_silent == 0)
7820 	redraw_cmdline = TRUE;	/* show visual mode later */
7821 #ifdef FEAT_CLIPBOARD
7822     /* Make sure the clipboard gets updated.  Needed because start and
7823      * end may still be the same, and the selection needs to be owned */
7824     clip_star.vmode = NUL;
7825 #endif
7826 
7827     /* Only need to redraw this line, unless still need to redraw an old
7828      * Visual area (when 'lazyredraw' is set). */
7829     if (curwin->w_redr_type < INVERTED)
7830     {
7831 	curwin->w_old_cursor_lnum = curwin->w_cursor.lnum;
7832 	curwin->w_old_visual_lnum = curwin->w_cursor.lnum;
7833     }
7834 }
7835 
7836 
7837 /*
7838  * CTRL-W: Window commands
7839  */
7840     static void
7841 nv_window(cap)
7842     cmdarg_T	*cap;
7843 {
7844 #ifdef FEAT_WINDOWS
7845     if (!checkclearop(cap->oap))
7846 	do_window(cap->nchar, cap->count0, NUL); /* everything is in window.c */
7847 #else
7848     (void)checkclearop(cap->oap);
7849 #endif
7850 }
7851 
7852 /*
7853  * CTRL-Z: Suspend
7854  */
7855     static void
7856 nv_suspend(cap)
7857     cmdarg_T	*cap;
7858 {
7859     clearop(cap->oap);
7860     if (VIsual_active)
7861 	end_visual_mode();		/* stop Visual mode */
7862     do_cmdline_cmd((char_u *)"st");
7863 }
7864 
7865 /*
7866  * Commands starting with "g".
7867  */
7868     static void
7869 nv_g_cmd(cap)
7870     cmdarg_T	*cap;
7871 {
7872     oparg_T	*oap = cap->oap;
7873     pos_T	tpos;
7874     int		i;
7875     int		flag = FALSE;
7876 
7877     switch (cap->nchar)
7878     {
7879     case Ctrl_A:
7880     case Ctrl_X:
7881 #ifdef MEM_PROFILE
7882     /*
7883      * "g^A": dump log of used memory.
7884      */
7885 	if (!VIsual_active && cap->nchar == Ctrl_A)
7886 	    vim_mem_profile_dump();
7887 	else
7888 #endif
7889     /*
7890      * "g^A/g^X": sequentially increment visually selected region
7891      */
7892 	     if (VIsual_active)
7893 	{
7894 	    cap->arg = TRUE;
7895 	    cap->cmdchar = cap->nchar;
7896 	    cap->nchar = NUL;
7897 	    nv_addsub(cap);
7898 	}
7899 	else
7900 	    clearopbeep(oap);
7901 	break;
7902 
7903 #ifdef FEAT_VREPLACE
7904     /*
7905      * "gR": Enter virtual replace mode.
7906      */
7907     case 'R':
7908 	cap->arg = TRUE;
7909 	nv_Replace(cap);
7910 	break;
7911 
7912     case 'r':
7913 	nv_vreplace(cap);
7914 	break;
7915 #endif
7916 
7917     case '&':
7918 	do_cmdline_cmd((char_u *)"%s//~/&");
7919 	break;
7920 
7921     /*
7922      * "gv": Reselect the previous Visual area.  If Visual already active,
7923      *	     exchange previous and current Visual area.
7924      */
7925     case 'v':
7926 	if (checkclearop(oap))
7927 	    break;
7928 
7929 	if (	   curbuf->b_visual.vi_start.lnum == 0
7930 		|| curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count
7931 		|| curbuf->b_visual.vi_end.lnum == 0)
7932 	    beep_flush();
7933 	else
7934 	{
7935 	    /* set w_cursor to the start of the Visual area, tpos to the end */
7936 	    if (VIsual_active)
7937 	    {
7938 		i = VIsual_mode;
7939 		VIsual_mode = curbuf->b_visual.vi_mode;
7940 		curbuf->b_visual.vi_mode = i;
7941 # ifdef FEAT_EVAL
7942 		curbuf->b_visual_mode_eval = i;
7943 # endif
7944 		i = curwin->w_curswant;
7945 		curwin->w_curswant = curbuf->b_visual.vi_curswant;
7946 		curbuf->b_visual.vi_curswant = i;
7947 
7948 		tpos = curbuf->b_visual.vi_end;
7949 		curbuf->b_visual.vi_end = curwin->w_cursor;
7950 		curwin->w_cursor = curbuf->b_visual.vi_start;
7951 		curbuf->b_visual.vi_start = VIsual;
7952 	    }
7953 	    else
7954 	    {
7955 		VIsual_mode = curbuf->b_visual.vi_mode;
7956 		curwin->w_curswant = curbuf->b_visual.vi_curswant;
7957 		tpos = curbuf->b_visual.vi_end;
7958 		curwin->w_cursor = curbuf->b_visual.vi_start;
7959 	    }
7960 
7961 	    VIsual_active = TRUE;
7962 	    VIsual_reselect = TRUE;
7963 
7964 	    /* Set Visual to the start and w_cursor to the end of the Visual
7965 	     * area.  Make sure they are on an existing character. */
7966 	    check_cursor();
7967 	    VIsual = curwin->w_cursor;
7968 	    curwin->w_cursor = tpos;
7969 	    check_cursor();
7970 	    update_topline();
7971 	    /*
7972 	     * When called from normal "g" command: start Select mode when
7973 	     * 'selectmode' contains "cmd".  When called for K_SELECT, always
7974 	     * start Select mode.
7975 	     */
7976 	    if (cap->arg)
7977 		VIsual_select = TRUE;
7978 	    else
7979 		may_start_select('c');
7980 #ifdef FEAT_MOUSE
7981 	    setmouse();
7982 #endif
7983 #ifdef FEAT_CLIPBOARD
7984 	    /* Make sure the clipboard gets updated.  Needed because start and
7985 	     * end are still the same, and the selection needs to be owned */
7986 	    clip_star.vmode = NUL;
7987 #endif
7988 	    redraw_curbuf_later(INVERTED);
7989 	    showmode();
7990 	}
7991 	break;
7992     /*
7993      * "gV": Don't reselect the previous Visual area after a Select mode
7994      *	     mapping of menu.
7995      */
7996     case 'V':
7997 	VIsual_reselect = FALSE;
7998 	break;
7999 
8000     /*
8001      * "gh":  start Select mode.
8002      * "gH":  start Select line mode.
8003      * "g^H": start Select block mode.
8004      */
8005     case K_BS:
8006 	cap->nchar = Ctrl_H;
8007 	/* FALLTHROUGH */
8008     case 'h':
8009     case 'H':
8010     case Ctrl_H:
8011 # ifdef EBCDIC
8012 	/* EBCDIC: 'v'-'h' != '^v'-'^h' */
8013 	if (cap->nchar == Ctrl_H)
8014 	    cap->cmdchar = Ctrl_V;
8015 	else
8016 # endif
8017 	cap->cmdchar = cap->nchar + ('v' - 'h');
8018 	cap->arg = TRUE;
8019 	nv_visual(cap);
8020 	break;
8021 
8022     /* "gn", "gN" visually select next/previous search match
8023      * "gn" selects next match
8024      * "gN" selects previous match
8025      */
8026     case 'N':
8027     case 'n':
8028 	if (!current_search(cap->count1, cap->nchar == 'n'))
8029 	    clearopbeep(oap);
8030 	break;
8031 
8032     /*
8033      * "gj" and "gk" two new funny movement keys -- up and down
8034      * movement based on *screen* line rather than *file* line.
8035      */
8036     case 'j':
8037     case K_DOWN:
8038 	/* with 'nowrap' it works just like the normal "j" command; also when
8039 	 * in a closed fold */
8040 	if (!curwin->w_p_wrap
8041 #ifdef FEAT_FOLDING
8042 		|| hasFolding(curwin->w_cursor.lnum, NULL, NULL)
8043 #endif
8044 		)
8045 	{
8046 	    oap->motion_type = MLINE;
8047 	    i = cursor_down(cap->count1, oap->op_type == OP_NOP);
8048 	}
8049 	else
8050 	    i = nv_screengo(oap, FORWARD, cap->count1);
8051 	if (i == FAIL)
8052 	    clearopbeep(oap);
8053 	break;
8054 
8055     case 'k':
8056     case K_UP:
8057 	/* with 'nowrap' it works just like the normal "k" command; also when
8058 	 * in a closed fold */
8059 	if (!curwin->w_p_wrap
8060 #ifdef FEAT_FOLDING
8061 		|| hasFolding(curwin->w_cursor.lnum, NULL, NULL)
8062 #endif
8063 	   )
8064 	{
8065 	    oap->motion_type = MLINE;
8066 	    i = cursor_up(cap->count1, oap->op_type == OP_NOP);
8067 	}
8068 	else
8069 	    i = nv_screengo(oap, BACKWARD, cap->count1);
8070 	if (i == FAIL)
8071 	    clearopbeep(oap);
8072 	break;
8073 
8074     /*
8075      * "gJ": join two lines without inserting a space.
8076      */
8077     case 'J':
8078 	nv_join(cap);
8079 	break;
8080 
8081     /*
8082      * "g0", "g^" and "g$": Like "0", "^" and "$" but for screen lines.
8083      * "gm": middle of "g0" and "g$".
8084      */
8085     case '^':
8086 	flag = TRUE;
8087 	/* FALLTHROUGH */
8088 
8089     case '0':
8090     case 'm':
8091     case K_HOME:
8092     case K_KHOME:
8093 	oap->motion_type = MCHAR;
8094 	oap->inclusive = FALSE;
8095 	if (curwin->w_p_wrap
8096 #ifdef FEAT_VERTSPLIT
8097 		&& curwin->w_width != 0
8098 #endif
8099 		)
8100 	{
8101 	    int		width1 = W_WIDTH(curwin) - curwin_col_off();
8102 	    int		width2 = width1 + curwin_col_off2();
8103 
8104 	    validate_virtcol();
8105 	    i = 0;
8106 	    if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0)
8107 		i = (curwin->w_virtcol - width1) / width2 * width2 + width1;
8108 	}
8109 	else
8110 	    i = curwin->w_leftcol;
8111 	/* Go to the middle of the screen line.  When 'number' or
8112 	 * 'relativenumber' is on and lines are wrapping the middle can be more
8113 	 * to the left. */
8114 	if (cap->nchar == 'm')
8115 	    i += (W_WIDTH(curwin) - curwin_col_off()
8116 		    + ((curwin->w_p_wrap && i > 0)
8117 			? curwin_col_off2() : 0)) / 2;
8118 	coladvance((colnr_T)i);
8119 	if (flag)
8120 	{
8121 	    do
8122 		i = gchar_cursor();
8123 	    while (vim_iswhite(i) && oneright() == OK);
8124 	}
8125 	curwin->w_set_curswant = TRUE;
8126 	break;
8127 
8128     case '_':
8129 	/* "g_": to the last non-blank character in the line or <count> lines
8130 	 * downward. */
8131 	cap->oap->motion_type = MCHAR;
8132 	cap->oap->inclusive = TRUE;
8133 	curwin->w_curswant = MAXCOL;
8134 	if (cursor_down((long)(cap->count1 - 1),
8135 					 cap->oap->op_type == OP_NOP) == FAIL)
8136 	    clearopbeep(cap->oap);
8137 	else
8138 	{
8139 	    char_u  *ptr = ml_get_curline();
8140 
8141 	    /* In Visual mode we may end up after the line. */
8142 	    if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL)
8143 		--curwin->w_cursor.col;
8144 
8145 	    /* Decrease the cursor column until it's on a non-blank. */
8146 	    while (curwin->w_cursor.col > 0
8147 				    && vim_iswhite(ptr[curwin->w_cursor.col]))
8148 		--curwin->w_cursor.col;
8149 	    curwin->w_set_curswant = TRUE;
8150 	    adjust_for_sel(cap);
8151 	}
8152 	break;
8153 
8154     case '$':
8155     case K_END:
8156     case K_KEND:
8157 	{
8158 	    int col_off = curwin_col_off();
8159 
8160 	    oap->motion_type = MCHAR;
8161 	    oap->inclusive = TRUE;
8162 	    if (curwin->w_p_wrap
8163 #ifdef FEAT_VERTSPLIT
8164 		    && curwin->w_width != 0
8165 #endif
8166 	       )
8167 	    {
8168 		curwin->w_curswant = MAXCOL;    /* so we stay at the end */
8169 		if (cap->count1 == 1)
8170 		{
8171 		    int		width1 = W_WIDTH(curwin) - col_off;
8172 		    int		width2 = width1 + curwin_col_off2();
8173 
8174 		    validate_virtcol();
8175 		    i = width1 - 1;
8176 		    if (curwin->w_virtcol >= (colnr_T)width1)
8177 			i += ((curwin->w_virtcol - width1) / width2 + 1)
8178 								     * width2;
8179 		    coladvance((colnr_T)i);
8180 
8181 		    /* Make sure we stick in this column. */
8182 		    validate_virtcol();
8183 		    curwin->w_curswant = curwin->w_virtcol;
8184 		    curwin->w_set_curswant = FALSE;
8185 #if defined(FEAT_LINEBREAK) || defined(FEAT_MBYTE)
8186 		    if (curwin->w_cursor.col > 0 && curwin->w_p_wrap)
8187 		    {
8188 			/*
8189 			 * Check for landing on a character that got split at
8190 			 * the end of the line.  We do not want to advance to
8191 			 * the next screen line.
8192 			 */
8193 			if (curwin->w_virtcol > (colnr_T)i)
8194 			    --curwin->w_cursor.col;
8195 		    }
8196 #endif
8197 		}
8198 		else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == FAIL)
8199 		    clearopbeep(oap);
8200 	    }
8201 	    else
8202 	    {
8203 		i = curwin->w_leftcol + W_WIDTH(curwin) - col_off - 1;
8204 		coladvance((colnr_T)i);
8205 
8206 		/* Make sure we stick in this column. */
8207 		validate_virtcol();
8208 		curwin->w_curswant = curwin->w_virtcol;
8209 		curwin->w_set_curswant = FALSE;
8210 	    }
8211 	}
8212 	break;
8213 
8214     /*
8215      * "g*" and "g#", like "*" and "#" but without using "\<" and "\>"
8216      */
8217     case '*':
8218     case '#':
8219 #if POUND != '#'
8220     case POUND:		/* pound sign (sometimes equal to '#') */
8221 #endif
8222     case Ctrl_RSB:		/* :tag or :tselect for current identifier */
8223     case ']':			/* :tselect for current identifier */
8224 	nv_ident(cap);
8225 	break;
8226 
8227     /*
8228      * ge and gE: go back to end of word
8229      */
8230     case 'e':
8231     case 'E':
8232 	oap->motion_type = MCHAR;
8233 	curwin->w_set_curswant = TRUE;
8234 	oap->inclusive = TRUE;
8235 	if (bckend_word(cap->count1, cap->nchar == 'E', FALSE) == FAIL)
8236 	    clearopbeep(oap);
8237 	break;
8238 
8239     /*
8240      * "g CTRL-G": display info about cursor position
8241      */
8242     case Ctrl_G:
8243 	cursor_pos_info(NULL);
8244 	break;
8245 
8246     /*
8247      * "gi": start Insert at the last position.
8248      */
8249     case 'i':
8250 	if (curbuf->b_last_insert.lnum != 0)
8251 	{
8252 	    curwin->w_cursor = curbuf->b_last_insert;
8253 	    check_cursor_lnum();
8254 	    i = (int)STRLEN(ml_get_curline());
8255 	    if (curwin->w_cursor.col > (colnr_T)i)
8256 	    {
8257 #ifdef FEAT_VIRTUALEDIT
8258 		if (virtual_active())
8259 		    curwin->w_cursor.coladd += curwin->w_cursor.col - i;
8260 #endif
8261 		curwin->w_cursor.col = i;
8262 	    }
8263 	}
8264 	cap->cmdchar = 'i';
8265 	nv_edit(cap);
8266 	break;
8267 
8268     /*
8269      * "gI": Start insert in column 1.
8270      */
8271     case 'I':
8272 	beginline(0);
8273 	if (!checkclearopq(oap))
8274 	    invoke_edit(cap, FALSE, 'g', FALSE);
8275 	break;
8276 
8277 #ifdef FEAT_SEARCHPATH
8278     /*
8279      * "gf": goto file, edit file under cursor
8280      * "]f" and "[f": can also be used.
8281      */
8282     case 'f':
8283     case 'F':
8284 	nv_gotofile(cap);
8285 	break;
8286 #endif
8287 
8288 	/* "g'm" and "g`m": jump to mark without setting pcmark */
8289     case '\'':
8290 	cap->arg = TRUE;
8291 	/*FALLTHROUGH*/
8292     case '`':
8293 	nv_gomark(cap);
8294 	break;
8295 
8296     /*
8297      * "gs": Goto sleep.
8298      */
8299     case 's':
8300 	do_sleep(cap->count1 * 1000L);
8301 	break;
8302 
8303     /*
8304      * "ga": Display the ascii value of the character under the
8305      * cursor.	It is displayed in decimal, hex, and octal. -- webb
8306      */
8307     case 'a':
8308 	do_ascii(NULL);
8309 	break;
8310 
8311 #ifdef FEAT_MBYTE
8312     /*
8313      * "g8": Display the bytes used for the UTF-8 character under the
8314      * cursor.	It is displayed in hex.
8315      * "8g8" finds illegal byte sequence.
8316      */
8317     case '8':
8318 	if (cap->count0 == 8)
8319 	    utf_find_illegal();
8320 	else
8321 	    show_utf8();
8322 	break;
8323 #endif
8324 
8325     case '<':
8326 	show_sb_text();
8327 	break;
8328 
8329     /*
8330      * "gg": Goto the first line in file.  With a count it goes to
8331      * that line number like for "G". -- webb
8332      */
8333     case 'g':
8334 	cap->arg = FALSE;
8335 	nv_goto(cap);
8336 	break;
8337 
8338     /*
8339      *	 Two-character operators:
8340      *	 "gq"	    Format text
8341      *	 "gw"	    Format text and keep cursor position
8342      *	 "g~"	    Toggle the case of the text.
8343      *	 "gu"	    Change text to lower case.
8344      *	 "gU"	    Change text to upper case.
8345      *   "g?"	    rot13 encoding
8346      *   "g@"	    call 'operatorfunc'
8347      */
8348     case 'q':
8349     case 'w':
8350 	oap->cursor_start = curwin->w_cursor;
8351 	/*FALLTHROUGH*/
8352     case '~':
8353     case 'u':
8354     case 'U':
8355     case '?':
8356     case '@':
8357 	nv_operator(cap);
8358 	break;
8359 
8360     /*
8361      * "gd": Find first occurrence of pattern under the cursor in the
8362      *	 current function
8363      * "gD": idem, but in the current file.
8364      */
8365     case 'd':
8366     case 'D':
8367 	nv_gd(oap, cap->nchar, (int)cap->count0);
8368 	break;
8369 
8370 #ifdef FEAT_MOUSE
8371     /*
8372      * g<*Mouse> : <C-*mouse>
8373      */
8374     case K_MIDDLEMOUSE:
8375     case K_MIDDLEDRAG:
8376     case K_MIDDLERELEASE:
8377     case K_LEFTMOUSE:
8378     case K_LEFTDRAG:
8379     case K_LEFTRELEASE:
8380     case K_RIGHTMOUSE:
8381     case K_RIGHTDRAG:
8382     case K_RIGHTRELEASE:
8383     case K_X1MOUSE:
8384     case K_X1DRAG:
8385     case K_X1RELEASE:
8386     case K_X2MOUSE:
8387     case K_X2DRAG:
8388     case K_X2RELEASE:
8389 	mod_mask = MOD_MASK_CTRL;
8390 	(void)do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0);
8391 	break;
8392 #endif
8393 
8394     case K_IGNORE:
8395 	break;
8396 
8397     /*
8398      * "gP" and "gp": same as "P" and "p" but leave cursor just after new text
8399      */
8400     case 'p':
8401     case 'P':
8402 	nv_put(cap);
8403 	break;
8404 
8405 #ifdef FEAT_BYTEOFF
8406     /* "go": goto byte count from start of buffer */
8407     case 'o':
8408 	goto_byte(cap->count0);
8409 	break;
8410 #endif
8411 
8412     /* "gQ": improved Ex mode */
8413     case 'Q':
8414 	if (text_locked())
8415 	{
8416 	    clearopbeep(cap->oap);
8417 	    text_locked_msg();
8418 	    break;
8419 	}
8420 
8421 	if (!checkclearopq(oap))
8422 	    do_exmode(TRUE);
8423 	break;
8424 
8425 #ifdef FEAT_JUMPLIST
8426     case ',':
8427 	nv_pcmark(cap);
8428 	break;
8429 
8430     case ';':
8431 	cap->count1 = -cap->count1;
8432 	nv_pcmark(cap);
8433 	break;
8434 #endif
8435 
8436 #ifdef FEAT_WINDOWS
8437     case 't':
8438 	if (!checkclearop(oap))
8439 	    goto_tabpage((int)cap->count0);
8440 	break;
8441     case 'T':
8442 	if (!checkclearop(oap))
8443 	    goto_tabpage(-(int)cap->count1);
8444 	break;
8445 #endif
8446 
8447     case '+':
8448     case '-': /* "g+" and "g-": undo or redo along the timeline */
8449 	if (!checkclearopq(oap))
8450 	    undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1,
8451 							 FALSE, FALSE, FALSE);
8452 	break;
8453 
8454     default:
8455 	clearopbeep(oap);
8456 	break;
8457     }
8458 }
8459 
8460 /*
8461  * Handle "o" and "O" commands.
8462  */
8463     static void
8464 n_opencmd(cap)
8465     cmdarg_T	*cap;
8466 {
8467 #ifdef FEAT_CONCEAL
8468     linenr_T	oldline = curwin->w_cursor.lnum;
8469 #endif
8470 
8471     if (!checkclearopq(cap->oap))
8472     {
8473 #ifdef FEAT_FOLDING
8474 	if (cap->cmdchar == 'O')
8475 	    /* Open above the first line of a folded sequence of lines */
8476 	    (void)hasFolding(curwin->w_cursor.lnum,
8477 						&curwin->w_cursor.lnum, NULL);
8478 	else
8479 	    /* Open below the last line of a folded sequence of lines */
8480 	    (void)hasFolding(curwin->w_cursor.lnum,
8481 						NULL, &curwin->w_cursor.lnum);
8482 #endif
8483 	if (u_save((linenr_T)(curwin->w_cursor.lnum -
8484 					       (cap->cmdchar == 'O' ? 1 : 0)),
8485 		   (linenr_T)(curwin->w_cursor.lnum +
8486 					       (cap->cmdchar == 'o' ? 1 : 0))
8487 		       ) == OK
8488 		&& open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD,
8489 #ifdef FEAT_COMMENTS
8490 		    has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM :
8491 #endif
8492 		    0, 0))
8493 	{
8494 #ifdef FEAT_CONCEAL
8495 	    if (curwin->w_p_cole > 0 && oldline != curwin->w_cursor.lnum)
8496 		update_single_line(curwin, oldline);
8497 #endif
8498 	    /* When '#' is in 'cpoptions' ignore the count. */
8499 	    if (vim_strchr(p_cpo, CPO_HASH) != NULL)
8500 		cap->count1 = 1;
8501 #ifdef FEAT_SYN_HL
8502 	    if (curwin->w_p_cul)
8503 		/* force redraw of cursorline */
8504 		curwin->w_valid &= ~VALID_CROW;
8505 #endif
8506 	    invoke_edit(cap, FALSE, cap->cmdchar, TRUE);
8507 	}
8508     }
8509 }
8510 
8511 /*
8512  * "." command: redo last change.
8513  */
8514     static void
8515 nv_dot(cap)
8516     cmdarg_T	*cap;
8517 {
8518     if (!checkclearopq(cap->oap))
8519     {
8520 	/*
8521 	 * If "restart_edit" is TRUE, the last but one command is repeated
8522 	 * instead of the last command (inserting text). This is used for
8523 	 * CTRL-O <.> in insert mode.
8524 	 */
8525 	if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == FAIL)
8526 	    clearopbeep(cap->oap);
8527     }
8528 }
8529 
8530 /*
8531  * CTRL-R: undo undo
8532  */
8533     static void
8534 nv_redo(cap)
8535     cmdarg_T	*cap;
8536 {
8537     if (!checkclearopq(cap->oap))
8538     {
8539 	u_redo((int)cap->count1);
8540 	curwin->w_set_curswant = TRUE;
8541     }
8542 }
8543 
8544 /*
8545  * Handle "U" command.
8546  */
8547     static void
8548 nv_Undo(cap)
8549     cmdarg_T	*cap;
8550 {
8551     /* In Visual mode and typing "gUU" triggers an operator */
8552     if (cap->oap->op_type == OP_UPPER || VIsual_active)
8553     {
8554 	/* translate "gUU" to "gUgU" */
8555 	cap->cmdchar = 'g';
8556 	cap->nchar = 'U';
8557 	nv_operator(cap);
8558     }
8559     else if (!checkclearopq(cap->oap))
8560     {
8561 	u_undoline();
8562 	curwin->w_set_curswant = TRUE;
8563     }
8564 }
8565 
8566 /*
8567  * '~' command: If tilde is not an operator and Visual is off: swap case of a
8568  * single character.
8569  */
8570     static void
8571 nv_tilde(cap)
8572     cmdarg_T	*cap;
8573 {
8574     if (!p_to && !VIsual_active && cap->oap->op_type != OP_TILDE)
8575 	n_swapchar(cap);
8576     else
8577 	nv_operator(cap);
8578 }
8579 
8580 /*
8581  * Handle an operator command.
8582  * The actual work is done by do_pending_operator().
8583  */
8584     static void
8585 nv_operator(cap)
8586     cmdarg_T	*cap;
8587 {
8588     int	    op_type;
8589 
8590     op_type = get_op_type(cap->cmdchar, cap->nchar);
8591 
8592     if (op_type == cap->oap->op_type)	    /* double operator works on lines */
8593 	nv_lineop(cap);
8594     else if (!checkclearop(cap->oap))
8595     {
8596 	cap->oap->start = curwin->w_cursor;
8597 	cap->oap->op_type = op_type;
8598 #ifdef FEAT_EVAL
8599 	set_op_var(op_type);
8600 #endif
8601     }
8602 }
8603 
8604 #ifdef FEAT_EVAL
8605 /*
8606  * Set v:operator to the characters for "optype".
8607  */
8608     static void
8609 set_op_var(optype)
8610     int optype;
8611 {
8612     char_u	opchars[3];
8613 
8614     if (optype == OP_NOP)
8615 	set_vim_var_string(VV_OP, NULL, 0);
8616     else
8617     {
8618 	opchars[0] = get_op_char(optype);
8619 	opchars[1] = get_extra_op_char(optype);
8620 	opchars[2] = NUL;
8621 	set_vim_var_string(VV_OP, opchars, -1);
8622     }
8623 }
8624 #endif
8625 
8626 /*
8627  * Handle linewise operator "dd", "yy", etc.
8628  *
8629  * "_" is is a strange motion command that helps make operators more logical.
8630  * It is actually implemented, but not documented in the real Vi.  This motion
8631  * command actually refers to "the current line".  Commands like "dd" and "yy"
8632  * are really an alternate form of "d_" and "y_".  It does accept a count, so
8633  * "d3_" works to delete 3 lines.
8634  */
8635     static void
8636 nv_lineop(cap)
8637     cmdarg_T	*cap;
8638 {
8639     cap->oap->motion_type = MLINE;
8640     if (cursor_down(cap->count1 - 1L, cap->oap->op_type == OP_NOP) == FAIL)
8641 	clearopbeep(cap->oap);
8642     else if (  (cap->oap->op_type == OP_DELETE /* only with linewise motions */
8643 		&& cap->oap->motion_force != 'v'
8644 		&& cap->oap->motion_force != Ctrl_V)
8645 	    || cap->oap->op_type == OP_LSHIFT
8646 	    || cap->oap->op_type == OP_RSHIFT)
8647 	beginline(BL_SOL | BL_FIX);
8648     else if (cap->oap->op_type != OP_YANK)	/* 'Y' does not move cursor */
8649 	beginline(BL_WHITE | BL_FIX);
8650 }
8651 
8652 /*
8653  * <Home> command.
8654  */
8655     static void
8656 nv_home(cap)
8657     cmdarg_T	*cap;
8658 {
8659     /* CTRL-HOME is like "gg" */
8660     if (mod_mask & MOD_MASK_CTRL)
8661 	nv_goto(cap);
8662     else
8663     {
8664 	cap->count0 = 1;
8665 	nv_pipe(cap);
8666     }
8667     ins_at_eol = FALSE;	    /* Don't move cursor past eol (only necessary in a
8668 			       one-character line). */
8669 }
8670 
8671 /*
8672  * "|" command.
8673  */
8674     static void
8675 nv_pipe(cap)
8676     cmdarg_T *cap;
8677 {
8678     cap->oap->motion_type = MCHAR;
8679     cap->oap->inclusive = FALSE;
8680     beginline(0);
8681     if (cap->count0 > 0)
8682     {
8683 	coladvance((colnr_T)(cap->count0 - 1));
8684 	curwin->w_curswant = (colnr_T)(cap->count0 - 1);
8685     }
8686     else
8687 	curwin->w_curswant = 0;
8688     /* keep curswant at the column where we wanted to go, not where
8689      * we ended; differs if line is too short */
8690     curwin->w_set_curswant = FALSE;
8691 }
8692 
8693 /*
8694  * Handle back-word command "b" and "B".
8695  * cap->arg is 1 for "B"
8696  */
8697     static void
8698 nv_bck_word(cap)
8699     cmdarg_T	*cap;
8700 {
8701     cap->oap->motion_type = MCHAR;
8702     cap->oap->inclusive = FALSE;
8703     curwin->w_set_curswant = TRUE;
8704     if (bck_word(cap->count1, cap->arg, FALSE) == FAIL)
8705 	clearopbeep(cap->oap);
8706 #ifdef FEAT_FOLDING
8707     else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
8708 	foldOpenCursor();
8709 #endif
8710 }
8711 
8712 /*
8713  * Handle word motion commands "e", "E", "w" and "W".
8714  * cap->arg is TRUE for "E" and "W".
8715  */
8716     static void
8717 nv_wordcmd(cap)
8718     cmdarg_T	*cap;
8719 {
8720     int		n;
8721     int		word_end;
8722     int		flag = FALSE;
8723     pos_T	startpos = curwin->w_cursor;
8724 
8725     /*
8726      * Set inclusive for the "E" and "e" command.
8727      */
8728     if (cap->cmdchar == 'e' || cap->cmdchar == 'E')
8729 	word_end = TRUE;
8730     else
8731 	word_end = FALSE;
8732     cap->oap->inclusive = word_end;
8733 
8734     /*
8735      * "cw" and "cW" are a special case.
8736      */
8737     if (!word_end && cap->oap->op_type == OP_CHANGE)
8738     {
8739 	n = gchar_cursor();
8740 	if (n != NUL)			/* not an empty line */
8741 	{
8742 	    if (vim_iswhite(n))
8743 	    {
8744 		/*
8745 		 * Reproduce a funny Vi behaviour: "cw" on a blank only
8746 		 * changes one character, not all blanks until the start of
8747 		 * the next word.  Only do this when the 'w' flag is included
8748 		 * in 'cpoptions'.
8749 		 */
8750 		if (cap->count1 == 1 && vim_strchr(p_cpo, CPO_CW) != NULL)
8751 		{
8752 		    cap->oap->inclusive = TRUE;
8753 		    cap->oap->motion_type = MCHAR;
8754 		    return;
8755 		}
8756 	    }
8757 	    else
8758 	    {
8759 		/*
8760 		 * This is a little strange. To match what the real Vi does,
8761 		 * we effectively map 'cw' to 'ce', and 'cW' to 'cE', provided
8762 		 * that we are not on a space or a TAB.  This seems impolite
8763 		 * at first, but it's really more what we mean when we say
8764 		 * 'cw'.
8765 		 * Another strangeness: When standing on the end of a word
8766 		 * "ce" will change until the end of the next word, but "cw"
8767 		 * will change only one character! This is done by setting
8768 		 * flag.
8769 		 */
8770 		cap->oap->inclusive = TRUE;
8771 		word_end = TRUE;
8772 		flag = TRUE;
8773 	    }
8774 	}
8775     }
8776 
8777     cap->oap->motion_type = MCHAR;
8778     curwin->w_set_curswant = TRUE;
8779     if (word_end)
8780 	n = end_word(cap->count1, cap->arg, flag, FALSE);
8781     else
8782 	n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP);
8783 
8784     /* Don't leave the cursor on the NUL past the end of line. Unless we
8785      * didn't move it forward. */
8786     if (lt(startpos, curwin->w_cursor))
8787 	adjust_cursor(cap->oap);
8788 
8789     if (n == FAIL && cap->oap->op_type == OP_NOP)
8790 	clearopbeep(cap->oap);
8791     else
8792     {
8793 	adjust_for_sel(cap);
8794 #ifdef FEAT_FOLDING
8795 	if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
8796 	    foldOpenCursor();
8797 #endif
8798     }
8799 }
8800 
8801 /*
8802  * Used after a movement command: If the cursor ends up on the NUL after the
8803  * end of the line, may move it back to the last character and make the motion
8804  * inclusive.
8805  */
8806     static void
8807 adjust_cursor(oap)
8808     oparg_T *oap;
8809 {
8810     /* The cursor cannot remain on the NUL when:
8811      * - the column is > 0
8812      * - not in Visual mode or 'selection' is "o"
8813      * - 'virtualedit' is not "all" and not "onemore".
8814      */
8815     if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL
8816 		&& (!VIsual_active || *p_sel == 'o')
8817 #ifdef FEAT_VIRTUALEDIT
8818 		&& !virtual_active() && (ve_flags & VE_ONEMORE) == 0
8819 #endif
8820 		)
8821     {
8822 	--curwin->w_cursor.col;
8823 #ifdef FEAT_MBYTE
8824 	/* prevent cursor from moving on the trail byte */
8825 	if (has_mbyte)
8826 	    mb_adjust_cursor();
8827 #endif
8828 	oap->inclusive = TRUE;
8829     }
8830 }
8831 
8832 /*
8833  * "0" and "^" commands.
8834  * cap->arg is the argument for beginline().
8835  */
8836     static void
8837 nv_beginline(cap)
8838     cmdarg_T	*cap;
8839 {
8840     cap->oap->motion_type = MCHAR;
8841     cap->oap->inclusive = FALSE;
8842     beginline(cap->arg);
8843 #ifdef FEAT_FOLDING
8844     if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
8845 	foldOpenCursor();
8846 #endif
8847     ins_at_eol = FALSE;	    /* Don't move cursor past eol (only necessary in a
8848 			       one-character line). */
8849 }
8850 
8851 /*
8852  * In exclusive Visual mode, may include the last character.
8853  */
8854     static void
8855 adjust_for_sel(cap)
8856     cmdarg_T	*cap;
8857 {
8858     if (VIsual_active && cap->oap->inclusive && *p_sel == 'e'
8859 	    && gchar_cursor() != NUL && lt(VIsual, curwin->w_cursor))
8860     {
8861 #ifdef FEAT_MBYTE
8862 	if (has_mbyte)
8863 	    inc_cursor();
8864 	else
8865 #endif
8866 	    ++curwin->w_cursor.col;
8867 	cap->oap->inclusive = FALSE;
8868     }
8869 }
8870 
8871 /*
8872  * Exclude last character at end of Visual area for 'selection' == "exclusive".
8873  * Should check VIsual_mode before calling this.
8874  * Returns TRUE when backed up to the previous line.
8875  */
8876     static int
8877 unadjust_for_sel()
8878 {
8879     pos_T	*pp;
8880 
8881     if (*p_sel == 'e' && !equalpos(VIsual, curwin->w_cursor))
8882     {
8883 	if (lt(VIsual, curwin->w_cursor))
8884 	    pp = &curwin->w_cursor;
8885 	else
8886 	    pp = &VIsual;
8887 #ifdef FEAT_VIRTUALEDIT
8888 	if (pp->coladd > 0)
8889 	    --pp->coladd;
8890 	else
8891 #endif
8892 	if (pp->col > 0)
8893 	{
8894 	    --pp->col;
8895 #ifdef FEAT_MBYTE
8896 	    mb_adjustpos(curbuf, pp);
8897 #endif
8898 	}
8899 	else if (pp->lnum > 1)
8900 	{
8901 	    --pp->lnum;
8902 	    pp->col = (colnr_T)STRLEN(ml_get(pp->lnum));
8903 	    return TRUE;
8904 	}
8905     }
8906     return FALSE;
8907 }
8908 
8909 /*
8910  * SELECT key in Normal or Visual mode: end of Select mode mapping.
8911  */
8912     static void
8913 nv_select(cap)
8914     cmdarg_T	*cap;
8915 {
8916     if (VIsual_active)
8917 	VIsual_select = TRUE;
8918     else if (VIsual_reselect)
8919     {
8920 	cap->nchar = 'v';	    /* fake "gv" command */
8921 	cap->arg = TRUE;
8922 	nv_g_cmd(cap);
8923     }
8924 }
8925 
8926 
8927 /*
8928  * "G", "gg", CTRL-END, CTRL-HOME.
8929  * cap->arg is TRUE for "G".
8930  */
8931     static void
8932 nv_goto(cap)
8933     cmdarg_T	*cap;
8934 {
8935     linenr_T	lnum;
8936 
8937     if (cap->arg)
8938 	lnum = curbuf->b_ml.ml_line_count;
8939     else
8940 	lnum = 1L;
8941     cap->oap->motion_type = MLINE;
8942     setpcmark();
8943 
8944     /* When a count is given, use it instead of the default lnum */
8945     if (cap->count0 != 0)
8946 	lnum = cap->count0;
8947     if (lnum < 1L)
8948 	lnum = 1L;
8949     else if (lnum > curbuf->b_ml.ml_line_count)
8950 	lnum = curbuf->b_ml.ml_line_count;
8951     curwin->w_cursor.lnum = lnum;
8952     beginline(BL_SOL | BL_FIX);
8953 #ifdef FEAT_FOLDING
8954     if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP)
8955 	foldOpenCursor();
8956 #endif
8957 }
8958 
8959 /*
8960  * CTRL-\ in Normal mode.
8961  */
8962     static void
8963 nv_normal(cap)
8964     cmdarg_T	*cap;
8965 {
8966     if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G)
8967     {
8968 	clearop(cap->oap);
8969 	if (restart_edit != 0 && mode_displayed)
8970 	    clear_cmdline = TRUE;		/* unshow mode later */
8971 	restart_edit = 0;
8972 #ifdef FEAT_CMDWIN
8973 	if (cmdwin_type != 0)
8974 	    cmdwin_result = Ctrl_C;
8975 #endif
8976 	if (VIsual_active)
8977 	{
8978 	    end_visual_mode();		/* stop Visual */
8979 	    redraw_curbuf_later(INVERTED);
8980 	}
8981 	/* CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. */
8982 	if (cap->nchar == Ctrl_G && p_im)
8983 	    restart_edit = 'a';
8984     }
8985     else
8986 	clearopbeep(cap->oap);
8987 }
8988 
8989 /*
8990  * ESC in Normal mode: beep, but don't flush buffers.
8991  * Don't even beep if we are canceling a command.
8992  */
8993     static void
8994 nv_esc(cap)
8995     cmdarg_T	*cap;
8996 {
8997     int		no_reason;
8998 
8999     no_reason = (cap->oap->op_type == OP_NOP
9000 		&& cap->opcount == 0
9001 		&& cap->count0 == 0
9002 		&& cap->oap->regname == 0
9003 		&& !p_im);
9004 
9005     if (cap->arg)		/* TRUE for CTRL-C */
9006     {
9007 	if (restart_edit == 0
9008 #ifdef FEAT_CMDWIN
9009 		&& cmdwin_type == 0
9010 #endif
9011 		&& !VIsual_active
9012 		&& no_reason)
9013 	    MSG(_("Type  :quit<Enter>  to exit Vim"));
9014 
9015 	/* Don't reset "restart_edit" when 'insertmode' is set, it won't be
9016 	 * set again below when halfway a mapping. */
9017 	if (!p_im)
9018 	    restart_edit = 0;
9019 #ifdef FEAT_CMDWIN
9020 	if (cmdwin_type != 0)
9021 	{
9022 	    cmdwin_result = K_IGNORE;
9023 	    got_int = FALSE;	/* don't stop executing autocommands et al. */
9024 	    return;
9025 	}
9026 #endif
9027     }
9028 
9029     if (VIsual_active)
9030     {
9031 	end_visual_mode();	/* stop Visual */
9032 	check_cursor_col();	/* make sure cursor is not beyond EOL */
9033 	curwin->w_set_curswant = TRUE;
9034 	redraw_curbuf_later(INVERTED);
9035     }
9036     else if (no_reason)
9037 	vim_beep(BO_ESC);
9038     clearop(cap->oap);
9039 
9040     /* A CTRL-C is often used at the start of a menu.  When 'insertmode' is
9041      * set return to Insert mode afterwards. */
9042     if (restart_edit == 0 && goto_im()
9043 #ifdef FEAT_EX_EXTRA
9044 	    && ex_normal_busy == 0
9045 #endif
9046 	    )
9047 	restart_edit = 'a';
9048 }
9049 
9050 /*
9051  * Handle "A", "a", "I", "i" and <Insert> commands.
9052  */
9053     static void
9054 nv_edit(cap)
9055     cmdarg_T *cap;
9056 {
9057     /* <Insert> is equal to "i" */
9058     if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS)
9059 	cap->cmdchar = 'i';
9060 
9061     /* in Visual mode "A" and "I" are an operator */
9062     if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I'))
9063 	v_visop(cap);
9064 
9065     /* in Visual mode and after an operator "a" and "i" are for text objects */
9066     else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i')
9067 	    && (cap->oap->op_type != OP_NOP || VIsual_active))
9068     {
9069 #ifdef FEAT_TEXTOBJ
9070 	nv_object(cap);
9071 #else
9072 	clearopbeep(cap->oap);
9073 #endif
9074     }
9075     else if (!curbuf->b_p_ma && !p_im)
9076     {
9077 	/* Only give this error when 'insertmode' is off. */
9078 	EMSG(_(e_modifiable));
9079 	clearop(cap->oap);
9080     }
9081     else if (!checkclearopq(cap->oap))
9082     {
9083 	switch (cap->cmdchar)
9084 	{
9085 	    case 'A':	/* "A"ppend after the line */
9086 		curwin->w_set_curswant = TRUE;
9087 #ifdef FEAT_VIRTUALEDIT
9088 		if (ve_flags == VE_ALL)
9089 		{
9090 		    int save_State = State;
9091 
9092 		    /* Pretend Insert mode here to allow the cursor on the
9093 		     * character past the end of the line */
9094 		    State = INSERT;
9095 		    coladvance((colnr_T)MAXCOL);
9096 		    State = save_State;
9097 		}
9098 		else
9099 #endif
9100 		    curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9101 		break;
9102 
9103 	    case 'I':	/* "I"nsert before the first non-blank */
9104 		if (vim_strchr(p_cpo, CPO_INSEND) == NULL)
9105 		    beginline(BL_WHITE);
9106 		else
9107 		    beginline(BL_WHITE|BL_FIX);
9108 		break;
9109 
9110 	    case 'a':	/* "a"ppend is like "i"nsert on the next character. */
9111 #ifdef FEAT_VIRTUALEDIT
9112 		/* increment coladd when in virtual space, increment the
9113 		 * column otherwise, also to append after an unprintable char */
9114 		if (virtual_active()
9115 			&& (curwin->w_cursor.coladd > 0
9116 			    || *ml_get_cursor() == NUL
9117 			    || *ml_get_cursor() == TAB))
9118 		    curwin->w_cursor.coladd++;
9119 		else
9120 #endif
9121 		if (*ml_get_cursor() != NUL)
9122 		    inc_cursor();
9123 		break;
9124 	}
9125 
9126 #ifdef FEAT_VIRTUALEDIT
9127 	if (curwin->w_cursor.coladd && cap->cmdchar != 'A')
9128 	{
9129 	    int save_State = State;
9130 
9131 	    /* Pretend Insert mode here to allow the cursor on the
9132 	     * character past the end of the line */
9133 	    State = INSERT;
9134 	    coladvance(getviscol());
9135 	    State = save_State;
9136 	}
9137 #endif
9138 
9139 	invoke_edit(cap, FALSE, cap->cmdchar, FALSE);
9140     }
9141 }
9142 
9143 /*
9144  * Invoke edit() and take care of "restart_edit" and the return value.
9145  */
9146     static void
9147 invoke_edit(cap, repl, cmd, startln)
9148     cmdarg_T	*cap;
9149     int		repl;		/* "r" or "gr" command */
9150     int		cmd;
9151     int		startln;
9152 {
9153     int		restart_edit_save = 0;
9154 
9155     /* Complicated: When the user types "a<C-O>a" we don't want to do Insert
9156      * mode recursively.  But when doing "a<C-O>." or "a<C-O>rx" we do allow
9157      * it. */
9158     if (repl || !stuff_empty())
9159 	restart_edit_save = restart_edit;
9160     else
9161 	restart_edit_save = 0;
9162 
9163     /* Always reset "restart_edit", this is not a restarted edit. */
9164     restart_edit = 0;
9165 
9166     if (edit(cmd, startln, cap->count1))
9167 	cap->retval |= CA_COMMAND_BUSY;
9168 
9169     if (restart_edit == 0)
9170 	restart_edit = restart_edit_save;
9171 }
9172 
9173 #ifdef FEAT_TEXTOBJ
9174 /*
9175  * "a" or "i" while an operator is pending or in Visual mode: object motion.
9176  */
9177     static void
9178 nv_object(cap)
9179     cmdarg_T	*cap;
9180 {
9181     int		flag;
9182     int		include;
9183     char_u	*mps_save;
9184 
9185     if (cap->cmdchar == 'i')
9186 	include = FALSE;    /* "ix" = inner object: exclude white space */
9187     else
9188 	include = TRUE;	    /* "ax" = an object: include white space */
9189 
9190     /* Make sure (), [], {} and <> are in 'matchpairs' */
9191     mps_save = curbuf->b_p_mps;
9192     curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>";
9193 
9194     switch (cap->nchar)
9195     {
9196 	case 'w': /* "aw" = a word */
9197 		flag = current_word(cap->oap, cap->count1, include, FALSE);
9198 		break;
9199 	case 'W': /* "aW" = a WORD */
9200 		flag = current_word(cap->oap, cap->count1, include, TRUE);
9201 		break;
9202 	case 'b': /* "ab" = a braces block */
9203 	case '(':
9204 	case ')':
9205 		flag = current_block(cap->oap, cap->count1, include, '(', ')');
9206 		break;
9207 	case 'B': /* "aB" = a Brackets block */
9208 	case '{':
9209 	case '}':
9210 		flag = current_block(cap->oap, cap->count1, include, '{', '}');
9211 		break;
9212 	case '[': /* "a[" = a [] block */
9213 	case ']':
9214 		flag = current_block(cap->oap, cap->count1, include, '[', ']');
9215 		break;
9216 	case '<': /* "a<" = a <> block */
9217 	case '>':
9218 		flag = current_block(cap->oap, cap->count1, include, '<', '>');
9219 		break;
9220 	case 't': /* "at" = a tag block (xml and html) */
9221 		/* Do not adjust oap->end in do_pending_operator()
9222 		 * otherwise there are different results for 'dit'
9223 		 * (note leading whitespace in last line):
9224 		 * 1) <b>      2) <b>
9225 		 *    foobar      foobar
9226 		 *    </b>            </b>
9227 		 */
9228 		cap->retval |= CA_NO_ADJ_OP_END;
9229 		flag = current_tagblock(cap->oap, cap->count1, include);
9230 		break;
9231 	case 'p': /* "ap" = a paragraph */
9232 		flag = current_par(cap->oap, cap->count1, include, 'p');
9233 		break;
9234 	case 's': /* "as" = a sentence */
9235 		flag = current_sent(cap->oap, cap->count1, include);
9236 		break;
9237 	case '"': /* "a"" = a double quoted string */
9238 	case '\'': /* "a'" = a single quoted string */
9239 	case '`': /* "a`" = a backtick quoted string */
9240 		flag = current_quote(cap->oap, cap->count1, include,
9241 								  cap->nchar);
9242 		break;
9243 #if 0	/* TODO */
9244 	case 'S': /* "aS" = a section */
9245 	case 'f': /* "af" = a filename */
9246 	case 'u': /* "au" = a URL */
9247 #endif
9248 	default:
9249 		flag = FAIL;
9250 		break;
9251     }
9252 
9253     curbuf->b_p_mps = mps_save;
9254     if (flag == FAIL)
9255 	clearopbeep(cap->oap);
9256     adjust_cursor_col();
9257     curwin->w_set_curswant = TRUE;
9258 }
9259 #endif
9260 
9261 /*
9262  * "q" command: Start/stop recording.
9263  * "q:", "q/", "q?": edit command-line in command-line window.
9264  */
9265     static void
9266 nv_record(cap)
9267     cmdarg_T	*cap;
9268 {
9269     if (cap->oap->op_type == OP_FORMAT)
9270     {
9271 	/* "gqq" is the same as "gqgq": format line */
9272 	cap->cmdchar = 'g';
9273 	cap->nchar = 'q';
9274 	nv_operator(cap);
9275     }
9276     else if (!checkclearop(cap->oap))
9277     {
9278 #ifdef FEAT_CMDWIN
9279 	if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?')
9280 	{
9281 	    stuffcharReadbuff(cap->nchar);
9282 	    stuffcharReadbuff(K_CMDWIN);
9283 	}
9284 	else
9285 #endif
9286 	    /* (stop) recording into a named register, unless executing a
9287 	     * register */
9288 	    if (!Exec_reg && do_record(cap->nchar) == FAIL)
9289 		clearopbeep(cap->oap);
9290     }
9291 }
9292 
9293 /*
9294  * Handle the "@r" command.
9295  */
9296     static void
9297 nv_at(cap)
9298     cmdarg_T	*cap;
9299 {
9300     if (checkclearop(cap->oap))
9301 	return;
9302 #ifdef FEAT_EVAL
9303     if (cap->nchar == '=')
9304     {
9305 	if (get_expr_register() == NUL)
9306 	    return;
9307     }
9308 #endif
9309     while (cap->count1-- && !got_int)
9310     {
9311 	if (do_execreg(cap->nchar, FALSE, FALSE, FALSE) == FAIL)
9312 	{
9313 	    clearopbeep(cap->oap);
9314 	    break;
9315 	}
9316 	line_breakcheck();
9317     }
9318 }
9319 
9320 /*
9321  * Handle the CTRL-U and CTRL-D commands.
9322  */
9323     static void
9324 nv_halfpage(cap)
9325     cmdarg_T	*cap;
9326 {
9327     if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1)
9328 	    || (cap->cmdchar == Ctrl_D
9329 		&& curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count))
9330 	clearopbeep(cap->oap);
9331     else if (!checkclearop(cap->oap))
9332 	halfpage(cap->cmdchar == Ctrl_D, cap->count0);
9333 }
9334 
9335 /*
9336  * Handle "J" or "gJ" command.
9337  */
9338     static void
9339 nv_join(cap)
9340     cmdarg_T *cap;
9341 {
9342     if (VIsual_active)	/* join the visual lines */
9343 	nv_operator(cap);
9344     else if (!checkclearop(cap->oap))
9345     {
9346 	if (cap->count0 <= 1)
9347 	    cap->count0 = 2;	    /* default for join is two lines! */
9348 	if (curwin->w_cursor.lnum + cap->count0 - 1 >
9349 						   curbuf->b_ml.ml_line_count)
9350 	    clearopbeep(cap->oap);  /* beyond last line */
9351 	else
9352 	{
9353 	    prep_redo(cap->oap->regname, cap->count0,
9354 			 NUL, cap->cmdchar, NUL, NUL, cap->nchar);
9355 	    (void)do_join(cap->count0, cap->nchar == NUL, TRUE, TRUE, TRUE);
9356 	}
9357     }
9358 }
9359 
9360 /*
9361  * "P", "gP", "p" and "gp" commands.
9362  */
9363     static void
9364 nv_put(cap)
9365     cmdarg_T  *cap;
9366 {
9367     int		regname = 0;
9368     void	*reg1 = NULL, *reg2 = NULL;
9369     int		empty = FALSE;
9370     int		was_visual = FALSE;
9371     int		dir;
9372     int		flags = 0;
9373 
9374     if (cap->oap->op_type != OP_NOP)
9375     {
9376 #ifdef FEAT_DIFF
9377 	/* "dp" is ":diffput" */
9378 	if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p')
9379 	{
9380 	    clearop(cap->oap);
9381 	    nv_diffgetput(TRUE, cap->opcount);
9382 	}
9383 	else
9384 #endif
9385 	clearopbeep(cap->oap);
9386     }
9387     else
9388     {
9389 	dir = (cap->cmdchar == 'P'
9390 		|| (cap->cmdchar == 'g' && cap->nchar == 'P'))
9391 							 ? BACKWARD : FORWARD;
9392 	prep_redo_cmd(cap);
9393 	if (cap->cmdchar == 'g')
9394 	    flags |= PUT_CURSEND;
9395 
9396 	if (VIsual_active)
9397 	{
9398 	    /* Putting in Visual mode: The put text replaces the selected
9399 	     * text.  First delete the selected text, then put the new text.
9400 	     * Need to save and restore the registers that the delete
9401 	     * overwrites if the old contents is being put.
9402 	     */
9403 	    was_visual = TRUE;
9404 	    regname = cap->oap->regname;
9405 #ifdef FEAT_CLIPBOARD
9406 	    adjust_clip_reg(&regname);
9407 #endif
9408 	   if (regname == 0 || regname == '"'
9409 				     || VIM_ISDIGIT(regname) || regname == '-'
9410 #ifdef FEAT_CLIPBOARD
9411 		    || (clip_unnamed && (regname == '*' || regname == '+'))
9412 #endif
9413 
9414 		    )
9415 	    {
9416 		/* The delete is going to overwrite the register we want to
9417 		 * put, save it first. */
9418 		reg1 = get_register(regname, TRUE);
9419 	    }
9420 
9421 	    /* Now delete the selected text. */
9422 	    cap->cmdchar = 'd';
9423 	    cap->nchar = NUL;
9424 	    cap->oap->regname = NUL;
9425 	    nv_operator(cap);
9426 	    do_pending_operator(cap, 0, FALSE);
9427 	    empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
9428 
9429 	    /* delete PUT_LINE_BACKWARD; */
9430 	    cap->oap->regname = regname;
9431 
9432 	    if (reg1 != NULL)
9433 	    {
9434 		/* Delete probably changed the register we want to put, save
9435 		 * it first. Then put back what was there before the delete. */
9436 		reg2 = get_register(regname, FALSE);
9437 		put_register(regname, reg1);
9438 	    }
9439 
9440 	    /* When deleted a linewise Visual area, put the register as
9441 	     * lines to avoid it joined with the next line.  When deletion was
9442 	     * characterwise, split a line when putting lines. */
9443 	    if (VIsual_mode == 'V')
9444 		flags |= PUT_LINE;
9445 	    else if (VIsual_mode == 'v')
9446 		flags |= PUT_LINE_SPLIT;
9447 	    if (VIsual_mode == Ctrl_V && dir == FORWARD)
9448 		flags |= PUT_LINE_FORWARD;
9449 	    dir = BACKWARD;
9450 	    if ((VIsual_mode != 'V'
9451 			&& curwin->w_cursor.col < curbuf->b_op_start.col)
9452 		    || (VIsual_mode == 'V'
9453 			&& curwin->w_cursor.lnum < curbuf->b_op_start.lnum))
9454 		/* cursor is at the end of the line or end of file, put
9455 		 * forward. */
9456 		dir = FORWARD;
9457 	    /* May have been reset in do_put(). */
9458 	    VIsual_active = TRUE;
9459 	}
9460 	do_put(cap->oap->regname, dir, cap->count1, flags);
9461 
9462 	/* If a register was saved, put it back now. */
9463 	if (reg2 != NULL)
9464 	    put_register(regname, reg2);
9465 
9466 	/* What to reselect with "gv"?  Selecting the just put text seems to
9467 	 * be the most useful, since the original text was removed. */
9468 	if (was_visual)
9469 	{
9470 	    curbuf->b_visual.vi_start = curbuf->b_op_start;
9471 	    curbuf->b_visual.vi_end = curbuf->b_op_end;
9472 	    /* need to adjust cursor position */
9473 	    if (*p_sel == 'e')
9474 		inc(&curbuf->b_visual.vi_end);
9475 	}
9476 
9477 	/* When all lines were selected and deleted do_put() leaves an empty
9478 	 * line that needs to be deleted now. */
9479 	if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL)
9480 	{
9481 	    ml_delete(curbuf->b_ml.ml_line_count, TRUE);
9482 
9483 	    /* If the cursor was in that line, move it to the end of the last
9484 	     * line. */
9485 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
9486 	    {
9487 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9488 		coladvance((colnr_T)MAXCOL);
9489 	    }
9490 	}
9491 	auto_format(FALSE, TRUE);
9492     }
9493 }
9494 
9495 /*
9496  * "o" and "O" commands.
9497  */
9498     static void
9499 nv_open(cap)
9500     cmdarg_T	*cap;
9501 {
9502 #ifdef FEAT_DIFF
9503     /* "do" is ":diffget" */
9504     if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o')
9505     {
9506 	clearop(cap->oap);
9507 	nv_diffgetput(FALSE, cap->opcount);
9508     }
9509     else
9510 #endif
9511     if (VIsual_active)  /* switch start and end of visual */
9512 	v_swap_corners(cap->cmdchar);
9513     else
9514 	n_opencmd(cap);
9515 }
9516 
9517 #ifdef FEAT_SNIFF
9518     static void
9519 nv_sniff(cap)
9520     cmdarg_T	*cap UNUSED;
9521 {
9522     ProcessSniffRequests();
9523 }
9524 #endif
9525 
9526 #ifdef FEAT_NETBEANS_INTG
9527     static void
9528 nv_nbcmd(cap)
9529     cmdarg_T	*cap;
9530 {
9531     netbeans_keycommand(cap->nchar);
9532 }
9533 #endif
9534 
9535 #ifdef FEAT_DND
9536     static void
9537 nv_drop(cap)
9538     cmdarg_T	*cap UNUSED;
9539 {
9540     do_put('~', BACKWARD, 1L, PUT_CURSEND);
9541 }
9542 #endif
9543 
9544 #ifdef FEAT_AUTOCMD
9545 /*
9546  * Trigger CursorHold event.
9547  * When waiting for a character for 'updatetime' K_CURSORHOLD is put in the
9548  * input buffer.  "did_cursorhold" is set to avoid retriggering.
9549  */
9550     static void
9551 nv_cursorhold(cap)
9552     cmdarg_T	*cap;
9553 {
9554     apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf);
9555     did_cursorhold = TRUE;
9556     cap->retval |= CA_COMMAND_BUSY;	/* don't call edit() now */
9557 }
9558 #endif
9559 
9560 /*
9561  * Calculate start/end virtual columns for operating in block mode.
9562  */
9563     static void
9564 get_op_vcol(oap, redo_VIsual_vcol, initial)
9565     oparg_T	*oap;
9566     colnr_T	redo_VIsual_vcol;
9567     int		initial;    /* when TRUE adjust position for 'selectmode' */
9568 {
9569     colnr_T	    start, end;
9570 
9571     if (VIsual_mode != Ctrl_V
9572 	    || (!initial && oap->end.col < W_WIDTH(curwin)))
9573 	return;
9574 
9575     oap->block_mode = TRUE;
9576 
9577 #ifdef FEAT_MBYTE
9578     /* prevent from moving onto a trail byte */
9579     if (has_mbyte)
9580 	mb_adjustpos(curwin->w_buffer, &oap->end);
9581 #endif
9582 
9583     getvvcol(curwin, &(oap->start), &oap->start_vcol, NULL, &oap->end_vcol);
9584 
9585     if (!redo_VIsual_busy)
9586     {
9587 	getvvcol(curwin, &(oap->end), &start, NULL, &end);
9588 
9589 	if (start < oap->start_vcol)
9590 	    oap->start_vcol = start;
9591 	if (end > oap->end_vcol)
9592 	{
9593 	    if (initial && *p_sel == 'e' && start >= 1
9594 				    && start - 1 >= oap->end_vcol)
9595 		oap->end_vcol = start - 1;
9596 	    else
9597 		oap->end_vcol = end;
9598 	}
9599     }
9600 
9601     /* if '$' was used, get oap->end_vcol from longest line */
9602     if (curwin->w_curswant == MAXCOL)
9603     {
9604 	curwin->w_cursor.col = MAXCOL;
9605 	oap->end_vcol = 0;
9606 	for (curwin->w_cursor.lnum = oap->start.lnum;
9607 		curwin->w_cursor.lnum <= oap->end.lnum;
9608 					++curwin->w_cursor.lnum)
9609 	{
9610 	    getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &end);
9611 	    if (end > oap->end_vcol)
9612 		oap->end_vcol = end;
9613 	}
9614     }
9615     else if (redo_VIsual_busy)
9616 	oap->end_vcol = oap->start_vcol + redo_VIsual_vcol - 1;
9617     /*
9618     * Correct oap->end.col and oap->start.col to be the
9619     * upper-left and lower-right corner of the block area.
9620     *
9621     * (Actually, this does convert column positions into character
9622     * positions)
9623     */
9624     curwin->w_cursor.lnum = oap->end.lnum;
9625     coladvance(oap->end_vcol);
9626     oap->end = curwin->w_cursor;
9627 
9628     curwin->w_cursor = oap->start;
9629     coladvance(oap->start_vcol);
9630     oap->start = curwin->w_cursor;
9631 }
9632