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