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