xref: /vim-8.2.3635/src/normal.c (revision fc65cabb)
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 static void	nv_vreplace(cmdarg_T *cap);
115 static void	v_swap_corners(int cmdchar);
116 static void	nv_replace(cmdarg_T *cap);
117 static void	n_swapchar(cmdarg_T *cap);
118 static void	nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos);
119 static void	v_visop(cmdarg_T *cap);
120 static void	nv_subst(cmdarg_T *cap);
121 static void	nv_abbrev(cmdarg_T *cap);
122 static void	nv_optrans(cmdarg_T *cap);
123 static void	nv_gomark(cmdarg_T *cap);
124 static void	nv_pcmark(cmdarg_T *cap);
125 static void	nv_regname(cmdarg_T *cap);
126 static void	nv_visual(cmdarg_T *cap);
127 static void	n_start_visual_mode(int c);
128 static void	nv_window(cmdarg_T *cap);
129 static void	nv_suspend(cmdarg_T *cap);
130 static void	nv_g_cmd(cmdarg_T *cap);
131 static void	n_opencmd(cmdarg_T *cap);
132 static void	nv_dot(cmdarg_T *cap);
133 static void	nv_redo(cmdarg_T *cap);
134 static void	nv_Undo(cmdarg_T *cap);
135 static void	nv_tilde(cmdarg_T *cap);
136 static void	nv_operator(cmdarg_T *cap);
137 #ifdef FEAT_EVAL
138 static void	set_op_var(int optype);
139 #endif
140 static void	nv_lineop(cmdarg_T *cap);
141 static void	nv_home(cmdarg_T *cap);
142 static void	nv_pipe(cmdarg_T *cap);
143 static void	nv_bck_word(cmdarg_T *cap);
144 static void	nv_wordcmd(cmdarg_T *cap);
145 static void	nv_beginline(cmdarg_T *cap);
146 static void	adjust_cursor(oparg_T *oap);
147 static void	adjust_for_sel(cmdarg_T *cap);
148 static int	unadjust_for_sel(void);
149 static void	nv_select(cmdarg_T *cap);
150 static void	nv_goto(cmdarg_T *cap);
151 static void	nv_normal(cmdarg_T *cap);
152 static void	nv_esc(cmdarg_T *oap);
153 static void	nv_edit(cmdarg_T *cap);
154 static void	invoke_edit(cmdarg_T *cap, int repl, int cmd, int startln);
155 #ifdef FEAT_TEXTOBJ
156 static void	nv_object(cmdarg_T *cap);
157 #endif
158 static void	nv_record(cmdarg_T *cap);
159 static void	nv_at(cmdarg_T *cap);
160 static void	nv_halfpage(cmdarg_T *cap);
161 static void	nv_join(cmdarg_T *cap);
162 static void	nv_put(cmdarg_T *cap);
163 static void	nv_open(cmdarg_T *cap);
164 #ifdef FEAT_NETBEANS_INTG
165 static void	nv_nbcmd(cmdarg_T *cap);
166 #endif
167 #ifdef FEAT_DND
168 static void	nv_drop(cmdarg_T *cap);
169 #endif
170 static void	nv_cursorhold(cmdarg_T *cap);
171 static void	get_op_vcol(oparg_T *oap, colnr_T col, int initial);
172 
173 static char *e_noident = N_("E349: No identifier under cursor");
174 
175 /*
176  * Function to be called for a Normal or Visual mode command.
177  * The argument is a cmdarg_T.
178  */
179 typedef void (*nv_func_T)(cmdarg_T *cap);
180 
181 /* Values for cmd_flags. */
182 #define NV_NCH	    0x01	  /* may need to get a second char */
183 #define NV_NCH_NOP  (0x02|NV_NCH) /* get second char when no operator pending */
184 #define NV_NCH_ALW  (0x04|NV_NCH) /* always get a second char */
185 #define NV_LANG	    0x08	/* second char needs language adjustment */
186 
187 #define NV_SS	    0x10	/* may start selection */
188 #define NV_SSS	    0x20	/* may start selection with shift modifier */
189 #define NV_STS	    0x40	/* may stop selection without shift modif. */
190 #define NV_RL	    0x80	/* 'rightleft' modifies command */
191 #define NV_KEEPREG  0x100	/* don't clear regname */
192 #define NV_NCW	    0x200	/* not allowed in command-line window */
193 
194 /*
195  * Generally speaking, every Normal mode command should either clear any
196  * pending operator (with *clearop*()), or set the motion type variable
197  * oap->motion_type.
198  *
199  * When a cursor motion command is made, it is marked as being a character or
200  * line oriented motion.  Then, if an operator is in effect, the operation
201  * becomes character or line oriented accordingly.
202  */
203 
204 /*
205  * This table contains one entry for every Normal or Visual mode command.
206  * The order doesn't matter, init_normal_cmds() will create a sorted index.
207  * It is faster when all keys from zero to '~' are present.
208  */
209 static const struct nv_cmd
210 {
211     int		cmd_char;	/* (first) command character */
212     nv_func_T   cmd_func;	/* function for this command */
213     short_u	cmd_flags;	/* NV_ flags */
214     short	cmd_arg;	/* value for ca.arg */
215 } nv_cmds[] =
216 {
217     {NUL,	nv_error,	0,			0},
218     {Ctrl_A,	nv_addsub,	0,			0},
219     {Ctrl_B,	nv_page,	NV_STS,			BACKWARD},
220     {Ctrl_C,	nv_esc,		0,			TRUE},
221     {Ctrl_D,	nv_halfpage,	0,			0},
222     {Ctrl_E,	nv_scroll_line,	0,			TRUE},
223     {Ctrl_F,	nv_page,	NV_STS,			FORWARD},
224     {Ctrl_G,	nv_ctrlg,	0,			0},
225     {Ctrl_H,	nv_ctrlh,	0,			0},
226     {Ctrl_I,	nv_pcmark,	0,			0},
227     {NL,	nv_down,	0,			FALSE},
228     {Ctrl_K,	nv_error,	0,			0},
229     {Ctrl_L,	nv_clear,	0,			0},
230     {Ctrl_M,	nv_down,	0,			TRUE},
231     {Ctrl_N,	nv_down,	NV_STS,			FALSE},
232     {Ctrl_O,	nv_ctrlo,	0,			0},
233     {Ctrl_P,	nv_up,		NV_STS,			FALSE},
234     {Ctrl_Q,	nv_visual,	0,			FALSE},
235     {Ctrl_R,	nv_redo,	0,			0},
236     {Ctrl_S,	nv_ignore,	0,			0},
237     {Ctrl_T,	nv_tagpop,	NV_NCW,			0},
238     {Ctrl_U,	nv_halfpage,	0,			0},
239     {Ctrl_V,	nv_visual,	0,			FALSE},
240     {'V',	nv_visual,	0,			FALSE},
241     {'v',	nv_visual,	0,			FALSE},
242     {Ctrl_W,	nv_window,	0,			0},
243     {Ctrl_X,	nv_addsub,	0,			0},
244     {Ctrl_Y,	nv_scroll_line,	0,			FALSE},
245     {Ctrl_Z,	nv_suspend,	0,			0},
246     {ESC,	nv_esc,		0,			FALSE},
247     {Ctrl_BSL,	nv_normal,	NV_NCH_ALW,		0},
248     {Ctrl_RSB,	nv_ident,	NV_NCW,			0},
249     {Ctrl_HAT,	nv_hat,		NV_NCW,			0},
250     {Ctrl__,	nv_error,	0,			0},
251     {' ',	nv_right,	0,			0},
252     {'!',	nv_operator,	0,			0},
253     {'"',	nv_regname,	NV_NCH_NOP|NV_KEEPREG,	0},
254     {'#',	nv_ident,	0,			0},
255     {'$',	nv_dollar,	0,			0},
256     {'%',	nv_percent,	0,			0},
257     {'&',	nv_optrans,	0,			0},
258     {'\'',	nv_gomark,	NV_NCH_ALW,		TRUE},
259     {'(',	nv_brace,	0,			BACKWARD},
260     {')',	nv_brace,	0,			FORWARD},
261     {'*',	nv_ident,	0,			0},
262     {'+',	nv_down,	0,			TRUE},
263     {',',	nv_csearch,	0,			TRUE},
264     {'-',	nv_up,		0,			TRUE},
265     {'.',	nv_dot,		NV_KEEPREG,		0},
266     {'/',	nv_search,	0,			FALSE},
267     {'0',	nv_beginline,	0,			0},
268     {'1',	nv_ignore,	0,			0},
269     {'2',	nv_ignore,	0,			0},
270     {'3',	nv_ignore,	0,			0},
271     {'4',	nv_ignore,	0,			0},
272     {'5',	nv_ignore,	0,			0},
273     {'6',	nv_ignore,	0,			0},
274     {'7',	nv_ignore,	0,			0},
275     {'8',	nv_ignore,	0,			0},
276     {'9',	nv_ignore,	0,			0},
277     {':',	nv_colon,	0,			0},
278     {';',	nv_csearch,	0,			FALSE},
279     {'<',	nv_operator,	NV_RL,			0},
280     {'=',	nv_operator,	0,			0},
281     {'>',	nv_operator,	NV_RL,			0},
282     {'?',	nv_search,	0,			FALSE},
283     {'@',	nv_at,		NV_NCH_NOP,		FALSE},
284     {'A',	nv_edit,	0,			0},
285     {'B',	nv_bck_word,	0,			1},
286     {'C',	nv_abbrev,	NV_KEEPREG,		0},
287     {'D',	nv_abbrev,	NV_KEEPREG,		0},
288     {'E',	nv_wordcmd,	0,			TRUE},
289     {'F',	nv_csearch,	NV_NCH_ALW|NV_LANG,	BACKWARD},
290     {'G',	nv_goto,	0,			TRUE},
291     {'H',	nv_scroll,	0,			0},
292     {'I',	nv_edit,	0,			0},
293     {'J',	nv_join,	0,			0},
294     {'K',	nv_ident,	0,			0},
295     {'L',	nv_scroll,	0,			0},
296     {'M',	nv_scroll,	0,			0},
297     {'N',	nv_next,	0,			SEARCH_REV},
298     {'O',	nv_open,	0,			0},
299     {'P',	nv_put,		0,			0},
300     {'Q',	nv_exmode,	NV_NCW,			0},
301     {'R',	nv_Replace,	0,			FALSE},
302     {'S',	nv_subst,	NV_KEEPREG,		0},
303     {'T',	nv_csearch,	NV_NCH_ALW|NV_LANG,	BACKWARD},
304     {'U',	nv_Undo,	0,			0},
305     {'W',	nv_wordcmd,	0,			TRUE},
306     {'X',	nv_abbrev,	NV_KEEPREG,		0},
307     {'Y',	nv_abbrev,	NV_KEEPREG,		0},
308     {'Z',	nv_Zet,		NV_NCH_NOP|NV_NCW,	0},
309     {'[',	nv_brackets,	NV_NCH_ALW,		BACKWARD},
310     {'\\',	nv_error,	0,			0},
311     {']',	nv_brackets,	NV_NCH_ALW,		FORWARD},
312     {'^',	nv_beginline,	0,			BL_WHITE | BL_FIX},
313     {'_',	nv_lineop,	0,			0},
314     {'`',	nv_gomark,	NV_NCH_ALW,		FALSE},
315     {'a',	nv_edit,	NV_NCH,			0},
316     {'b',	nv_bck_word,	0,			0},
317     {'c',	nv_operator,	0,			0},
318     {'d',	nv_operator,	0,			0},
319     {'e',	nv_wordcmd,	0,			FALSE},
320     {'f',	nv_csearch,	NV_NCH_ALW|NV_LANG,	FORWARD},
321     {'g',	nv_g_cmd,	NV_NCH_ALW,		FALSE},
322     {'h',	nv_left,	NV_RL,			0},
323     {'i',	nv_edit,	NV_NCH,			0},
324     {'j',	nv_down,	0,			FALSE},
325     {'k',	nv_up,		0,			FALSE},
326     {'l',	nv_right,	NV_RL,			0},
327     {'m',	nv_mark,	NV_NCH_NOP,		0},
328     {'n',	nv_next,	0,			0},
329     {'o',	nv_open,	0,			0},
330     {'p',	nv_put,		0,			0},
331     {'q',	nv_record,	NV_NCH,			0},
332     {'r',	nv_replace,	NV_NCH_NOP|NV_LANG,	0},
333     {'s',	nv_subst,	NV_KEEPREG,		0},
334     {'t',	nv_csearch,	NV_NCH_ALW|NV_LANG,	FORWARD},
335     {'u',	nv_undo,	0,			0},
336     {'w',	nv_wordcmd,	0,			FALSE},
337     {'x',	nv_abbrev,	NV_KEEPREG,		0},
338     {'y',	nv_operator,	0,			0},
339     {'z',	nv_zet,		NV_NCH_ALW,		0},
340     {'{',	nv_findpar,	0,			BACKWARD},
341     {'|',	nv_pipe,	0,			0},
342     {'}',	nv_findpar,	0,			FORWARD},
343     {'~',	nv_tilde,	0,			0},
344 
345     /* pound sign */
346     {POUND,	nv_ident,	0,			0},
347 #ifdef FEAT_MOUSE
348     {K_MOUSEUP, nv_mousescroll,	0,			MSCR_UP},
349     {K_MOUSEDOWN, nv_mousescroll, 0,			MSCR_DOWN},
350     {K_MOUSELEFT, nv_mousescroll, 0,			MSCR_LEFT},
351     {K_MOUSERIGHT, nv_mousescroll, 0,			MSCR_RIGHT},
352     {K_LEFTMOUSE, nv_mouse,	0,			0},
353     {K_LEFTMOUSE_NM, nv_mouse,	0,			0},
354     {K_LEFTDRAG, nv_mouse,	0,			0},
355     {K_LEFTRELEASE, nv_mouse,	0,			0},
356     {K_LEFTRELEASE_NM, nv_mouse, 0,			0},
357     {K_MOUSEMOVE, nv_mouse,	0,			0},
358     {K_MIDDLEMOUSE, nv_mouse,	0,			0},
359     {K_MIDDLEDRAG, nv_mouse,	0,			0},
360     {K_MIDDLERELEASE, nv_mouse,	0,			0},
361     {K_RIGHTMOUSE, nv_mouse,	0,			0},
362     {K_RIGHTDRAG, nv_mouse,	0,			0},
363     {K_RIGHTRELEASE, nv_mouse,	0,			0},
364     {K_X1MOUSE, nv_mouse,	0,			0},
365     {K_X1DRAG, nv_mouse,	0,			0},
366     {K_X1RELEASE, nv_mouse,	0,			0},
367     {K_X2MOUSE, nv_mouse,	0,			0},
368     {K_X2DRAG, nv_mouse,	0,			0},
369     {K_X2RELEASE, nv_mouse,	0,			0},
370 #endif
371     {K_IGNORE,	nv_ignore,	NV_KEEPREG,		0},
372     {K_NOP,	nv_nop,		0,			0},
373     {K_INS,	nv_edit,	0,			0},
374     {K_KINS,	nv_edit,	0,			0},
375     {K_BS,	nv_ctrlh,	0,			0},
376     {K_UP,	nv_up,		NV_SSS|NV_STS,		FALSE},
377     {K_S_UP,	nv_page,	NV_SS,			BACKWARD},
378     {K_DOWN,	nv_down,	NV_SSS|NV_STS,		FALSE},
379     {K_S_DOWN,	nv_page,	NV_SS,			FORWARD},
380     {K_LEFT,	nv_left,	NV_SSS|NV_STS|NV_RL,	0},
381     {K_S_LEFT,	nv_bck_word,	NV_SS|NV_RL,		0},
382     {K_C_LEFT,	nv_bck_word,	NV_SSS|NV_RL|NV_STS,	1},
383     {K_RIGHT,	nv_right,	NV_SSS|NV_STS|NV_RL,	0},
384     {K_S_RIGHT,	nv_wordcmd,	NV_SS|NV_RL,		FALSE},
385     {K_C_RIGHT,	nv_wordcmd,	NV_SSS|NV_RL|NV_STS,	TRUE},
386     {K_PAGEUP,	nv_page,	NV_SSS|NV_STS,		BACKWARD},
387     {K_KPAGEUP,	nv_page,	NV_SSS|NV_STS,		BACKWARD},
388     {K_PAGEDOWN, nv_page,	NV_SSS|NV_STS,		FORWARD},
389     {K_KPAGEDOWN, nv_page,	NV_SSS|NV_STS,		FORWARD},
390     {K_END,	nv_end,		NV_SSS|NV_STS,		FALSE},
391     {K_KEND,	nv_end,		NV_SSS|NV_STS,		FALSE},
392     {K_S_END,	nv_end,		NV_SS,			FALSE},
393     {K_C_END,	nv_end,		NV_SSS|NV_STS,		TRUE},
394     {K_HOME,	nv_home,	NV_SSS|NV_STS,		0},
395     {K_KHOME,	nv_home,	NV_SSS|NV_STS,		0},
396     {K_S_HOME,	nv_home,	NV_SS,			0},
397     {K_C_HOME,	nv_goto,	NV_SSS|NV_STS,		FALSE},
398     {K_DEL,	nv_abbrev,	0,			0},
399     {K_KDEL,	nv_abbrev,	0,			0},
400     {K_UNDO,	nv_kundo,	0,			0},
401     {K_HELP,	nv_help,	NV_NCW,			0},
402     {K_F1,	nv_help,	NV_NCW,			0},
403     {K_XF1,	nv_help,	NV_NCW,			0},
404     {K_SELECT,	nv_select,	0,			0},
405 #ifdef FEAT_GUI
406     {K_VER_SCROLLBAR, nv_ver_scrollbar, 0,		0},
407     {K_HOR_SCROLLBAR, nv_hor_scrollbar, 0,		0},
408 #endif
409 #ifdef FEAT_GUI_TABLINE
410     {K_TABLINE, nv_tabline,	0,			0},
411     {K_TABMENU, nv_tabmenu,	0,			0},
412 #endif
413 #ifdef FEAT_FKMAP
414     {K_F8,	farsi_f8,	0,			0},
415     {K_F9,	farsi_f9,	0,			0},
416 #endif
417 #ifdef FEAT_NETBEANS_INTG
418     {K_F21,	nv_nbcmd,	NV_NCH_ALW,		0},
419 #endif
420 #ifdef FEAT_DND
421     {K_DROP,	nv_drop,	NV_STS,			0},
422 #endif
423     {K_CURSORHOLD, nv_cursorhold, NV_KEEPREG,		0},
424     {K_PS,	nv_edit,	0,			0},
425 };
426 
427 /* Number of commands in nv_cmds[]. */
428 #define NV_CMDS_SIZE (sizeof(nv_cmds) / sizeof(struct nv_cmd))
429 
430 /* Sorted index of commands in nv_cmds[]. */
431 static short nv_cmd_idx[NV_CMDS_SIZE];
432 
433 /* The highest index for which
434  * nv_cmds[idx].cmd_char == nv_cmd_idx[nv_cmds[idx].cmd_char] */
435 static int nv_max_linear;
436 
437 /*
438  * Compare functions for qsort() below, that checks the command character
439  * through the index in nv_cmd_idx[].
440  */
441     static int
442 #ifdef __BORLANDC__
443 _RTLENTRYF
444 #endif
445 nv_compare(const void *s1, const void *s2)
446 {
447     int		c1, c2;
448 
449     /* The commands are sorted on absolute value. */
450     c1 = nv_cmds[*(const short *)s1].cmd_char;
451     c2 = nv_cmds[*(const short *)s2].cmd_char;
452     if (c1 < 0)
453 	c1 = -c1;
454     if (c2 < 0)
455 	c2 = -c2;
456     return c1 - c2;
457 }
458 
459 /*
460  * Initialize the nv_cmd_idx[] table.
461  */
462     void
463 init_normal_cmds(void)
464 {
465     int		i;
466 
467     /* Fill the index table with a one to one relation. */
468     for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
469 	nv_cmd_idx[i] = i;
470 
471     /* Sort the commands by the command character.  */
472     qsort((void *)&nv_cmd_idx, (size_t)NV_CMDS_SIZE, sizeof(short), nv_compare);
473 
474     /* Find the first entry that can't be indexed by the command character. */
475     for (i = 0; i < (int)NV_CMDS_SIZE; ++i)
476 	if (i != nv_cmds[nv_cmd_idx[i]].cmd_char)
477 	    break;
478     nv_max_linear = i - 1;
479 }
480 
481 /*
482  * Search for a command in the commands table.
483  * Returns -1 for invalid command.
484  */
485     static int
486 find_command(int cmdchar)
487 {
488     int		i;
489     int		idx;
490     int		top, bot;
491     int		c;
492 
493 #ifdef FEAT_MBYTE
494     /* A multi-byte character is never a command. */
495     if (cmdchar >= 0x100)
496 	return -1;
497 #endif
498 
499     /* We use the absolute value of the character.  Special keys have a
500      * negative value, but are sorted on their absolute value. */
501     if (cmdchar < 0)
502 	cmdchar = -cmdchar;
503 
504     /* If the character is in the first part: The character is the index into
505      * nv_cmd_idx[]. */
506     if (cmdchar <= nv_max_linear)
507 	return nv_cmd_idx[cmdchar];
508 
509     /* Perform a binary search. */
510     bot = nv_max_linear + 1;
511     top = NV_CMDS_SIZE - 1;
512     idx = -1;
513     while (bot <= top)
514     {
515 	i = (top + bot) / 2;
516 	c = nv_cmds[nv_cmd_idx[i]].cmd_char;
517 	if (c < 0)
518 	    c = -c;
519 	if (cmdchar == c)
520 	{
521 	    idx = nv_cmd_idx[i];
522 	    break;
523 	}
524 	if (cmdchar > c)
525 	    bot = i + 1;
526 	else
527 	    top = i - 1;
528     }
529     return idx;
530 }
531 
532 /*
533  * Execute a command in Normal mode.
534  */
535     void
536 normal_cmd(
537     oparg_T	*oap,
538     int		toplevel UNUSED)	/* TRUE when called from main() */
539 {
540     cmdarg_T	ca;			/* command arguments */
541     int		c;
542     int		ctrl_w = FALSE;		/* got CTRL-W command */
543     int		old_col = curwin->w_curswant;
544 #ifdef FEAT_CMDL_INFO
545     int		need_flushbuf;		/* need to call out_flush() */
546 #endif
547     pos_T	old_pos;		/* cursor position before command */
548     int		mapped_len;
549     static int	old_mapped_len = 0;
550     int		idx;
551 #ifdef FEAT_EVAL
552     int		set_prevcount = FALSE;
553 #endif
554 
555     vim_memset(&ca, 0, sizeof(ca));	/* also resets ca.retval */
556     ca.oap = oap;
557 
558     /* Use a count remembered from before entering an operator.  After typing
559      * "3d" we return from normal_cmd() and come back here, the "3" is
560      * remembered in "opcount". */
561     ca.opcount = opcount;
562 
563     /*
564      * If there is an operator pending, then the command we take this time
565      * will terminate it. Finish_op tells us to finish the operation before
566      * returning this time (unless the operation was cancelled).
567      */
568 #ifdef CURSOR_SHAPE
569     c = finish_op;
570 #endif
571     finish_op = (oap->op_type != OP_NOP);
572 #ifdef CURSOR_SHAPE
573     if (finish_op != c)
574     {
575 	ui_cursor_shape();		/* may show different cursor shape */
576 # ifdef FEAT_MOUSESHAPE
577 	update_mouseshape(-1);
578 # endif
579     }
580 #endif
581 
582     /* When not finishing an operator and no register name typed, reset the
583      * count. */
584     if (!finish_op && !oap->regname)
585     {
586 	ca.opcount = 0;
587 #ifdef FEAT_EVAL
588 	set_prevcount = TRUE;
589 #endif
590     }
591 
592     /* Restore counts from before receiving K_CURSORHOLD.  This means after
593      * typing "3", handling K_CURSORHOLD and then typing "2" we get "32", not
594      * "3 * 2". */
595     if (oap->prev_opcount > 0 || oap->prev_count0 > 0)
596     {
597 	ca.opcount = oap->prev_opcount;
598 	ca.count0 = oap->prev_count0;
599 	oap->prev_opcount = 0;
600 	oap->prev_count0 = 0;
601     }
602 
603     mapped_len = typebuf_maplen();
604 
605     State = NORMAL_BUSY;
606 #ifdef USE_ON_FLY_SCROLL
607     dont_scroll = FALSE;	/* allow scrolling here */
608 #endif
609 
610 #ifdef FEAT_EVAL
611     /* Set v:count here, when called from main() and not a stuffed
612      * command, so that v:count can be used in an expression mapping
613      * when there is no count. Do set it for redo. */
614     if (toplevel && readbuf1_empty())
615 	set_vcount_ca(&ca, &set_prevcount);
616 #endif
617 
618     /*
619      * Get the command character from the user.
620      */
621     c = safe_vgetc();
622     LANGMAP_ADJUST(c, get_real_state() != SELECTMODE);
623 
624     /*
625      * If a mapping was started in Visual or Select mode, remember the length
626      * of the mapping.  This is used below to not return to Insert mode for as
627      * long as the mapping is being executed.
628      */
629     if (restart_edit == 0)
630 	old_mapped_len = 0;
631     else if (old_mapped_len
632 		|| (VIsual_active && mapped_len == 0 && typebuf_maplen() > 0))
633 	old_mapped_len = typebuf_maplen();
634 
635     if (c == NUL)
636 	c = K_ZERO;
637 
638     /*
639      * In Select mode, typed text replaces the selection.
640      */
641     if (VIsual_active
642 	    && VIsual_select
643 	    && (vim_isprintc(c) || c == NL || c == CAR || c == K_KENTER))
644     {
645 	/* Fake a "c"hange command.  When "restart_edit" is set (e.g., because
646 	 * 'insertmode' is set) fake a "d"elete command, Insert mode will
647 	 * restart automatically.
648 	 * Insert the typed character in the typeahead buffer, so that it can
649 	 * be mapped in Insert mode.  Required for ":lmap" to work. */
650 	ins_char_typebuf(c);
651 	if (restart_edit != 0)
652 	    c = 'd';
653 	else
654 	    c = 'c';
655 	msg_nowait = TRUE;	/* don't delay going to insert mode */
656 	old_mapped_len = 0;	/* do go to Insert mode */
657     }
658 
659 #ifdef FEAT_CMDL_INFO
660     need_flushbuf = add_to_showcmd(c);
661 #endif
662 
663 getcount:
664     if (!(VIsual_active && VIsual_select))
665     {
666 	/*
667 	 * Handle a count before a command and compute ca.count0.
668 	 * Note that '0' is a command and not the start of a count, but it's
669 	 * part of a count after other digits.
670 	 */
671 	while (    (c >= '1' && c <= '9')
672 		|| (ca.count0 != 0 && (c == K_DEL || c == K_KDEL || c == '0')))
673 	{
674 	    if (c == K_DEL || c == K_KDEL)
675 	    {
676 		ca.count0 /= 10;
677 #ifdef FEAT_CMDL_INFO
678 		del_from_showcmd(4);	/* delete the digit and ~@% */
679 #endif
680 	    }
681 	    else
682 		ca.count0 = ca.count0 * 10 + (c - '0');
683 	    if (ca.count0 < 0)	    /* got too large! */
684 		ca.count0 = 999999999L;
685 #ifdef FEAT_EVAL
686 	    /* Set v:count here, when called from main() and not a stuffed
687 	     * command, so that v:count can be used in an expression mapping
688 	     * right after the count. Do set it for redo. */
689 	    if (toplevel && readbuf1_empty())
690 		set_vcount_ca(&ca, &set_prevcount);
691 #endif
692 	    if (ctrl_w)
693 	    {
694 		++no_mapping;
695 		++allow_keys;		/* no mapping for nchar, but keys */
696 	    }
697 	    ++no_zero_mapping;		/* don't map zero here */
698 	    c = plain_vgetc();
699 	    LANGMAP_ADJUST(c, TRUE);
700 	    --no_zero_mapping;
701 	    if (ctrl_w)
702 	    {
703 		--no_mapping;
704 		--allow_keys;
705 	    }
706 #ifdef FEAT_CMDL_INFO
707 	    need_flushbuf |= add_to_showcmd(c);
708 #endif
709 	}
710 
711 	/*
712 	 * If we got CTRL-W there may be a/another count
713 	 */
714 	if (c == Ctrl_W && !ctrl_w && oap->op_type == OP_NOP)
715 	{
716 	    ctrl_w = TRUE;
717 	    ca.opcount = ca.count0;	/* remember first count */
718 	    ca.count0 = 0;
719 	    ++no_mapping;
720 	    ++allow_keys;		/* no mapping for nchar, but keys */
721 	    c = plain_vgetc();		/* get next character */
722 	    LANGMAP_ADJUST(c, TRUE);
723 	    --no_mapping;
724 	    --allow_keys;
725 #ifdef FEAT_CMDL_INFO
726 	    need_flushbuf |= add_to_showcmd(c);
727 #endif
728 	    goto getcount;		/* jump back */
729 	}
730     }
731 
732     if (c == K_CURSORHOLD)
733     {
734 	/* Save the count values so that ca.opcount and ca.count0 are exactly
735 	 * the same when coming back here after handling K_CURSORHOLD. */
736 	oap->prev_opcount = ca.opcount;
737 	oap->prev_count0 = ca.count0;
738     }
739     else if (ca.opcount != 0)
740     {
741 	/*
742 	 * If we're in the middle of an operator (including after entering a
743 	 * yank buffer with '"') AND we had a count before the operator, then
744 	 * that count overrides the current value of ca.count0.
745 	 * What this means effectively, is that commands like "3dw" get turned
746 	 * into "d3w" which makes things fall into place pretty neatly.
747 	 * If you give a count before AND after the operator, they are
748 	 * multiplied.
749 	 */
750 	if (ca.count0)
751 	    ca.count0 *= ca.opcount;
752 	else
753 	    ca.count0 = ca.opcount;
754     }
755 
756     /*
757      * Always remember the count.  It will be set to zero (on the next call,
758      * above) when there is no pending operator.
759      * When called from main(), save the count for use by the "count" built-in
760      * variable.
761      */
762     ca.opcount = ca.count0;
763     ca.count1 = (ca.count0 == 0 ? 1 : ca.count0);
764 
765 #ifdef FEAT_EVAL
766     /*
767      * Only set v:count when called from main() and not a stuffed command.
768      * Do set it for redo.
769      */
770     if (toplevel && readbuf1_empty())
771 	set_vcount(ca.count0, ca.count1, set_prevcount);
772 #endif
773 
774     /*
775      * Find the command character in the table of commands.
776      * For CTRL-W we already got nchar when looking for a count.
777      */
778     if (ctrl_w)
779     {
780 	ca.nchar = c;
781 	ca.cmdchar = Ctrl_W;
782     }
783     else
784 	ca.cmdchar = c;
785     idx = find_command(ca.cmdchar);
786     if (idx < 0)
787     {
788 	/* Not a known command: beep. */
789 	clearopbeep(oap);
790 	goto normal_end;
791     }
792 
793     if (text_locked() && (nv_cmds[idx].cmd_flags & NV_NCW))
794     {
795 	/* This command is not allowed while editing a cmdline: beep. */
796 	clearopbeep(oap);
797 	text_locked_msg();
798 	goto normal_end;
799     }
800     if ((nv_cmds[idx].cmd_flags & NV_NCW) && curbuf_locked())
801 	goto normal_end;
802 
803     /*
804      * In Visual/Select mode, a few keys are handled in a special way.
805      */
806     if (VIsual_active)
807     {
808 	/* when 'keymodel' contains "stopsel" may stop Select/Visual mode */
809 	if (km_stopsel
810 		&& (nv_cmds[idx].cmd_flags & NV_STS)
811 		&& !(mod_mask & MOD_MASK_SHIFT))
812 	{
813 	    end_visual_mode();
814 	    redraw_curbuf_later(INVERTED);
815 	}
816 
817 	/* Keys that work different when 'keymodel' contains "startsel" */
818 	if (km_startsel)
819 	{
820 	    if (nv_cmds[idx].cmd_flags & NV_SS)
821 	    {
822 		unshift_special(&ca);
823 		idx = find_command(ca.cmdchar);
824 		if (idx < 0)
825 		{
826 		    /* Just in case */
827 		    clearopbeep(oap);
828 		    goto normal_end;
829 		}
830 	    }
831 	    else if ((nv_cmds[idx].cmd_flags & NV_SSS)
832 					       && (mod_mask & MOD_MASK_SHIFT))
833 	    {
834 		mod_mask &= ~MOD_MASK_SHIFT;
835 	    }
836 	}
837     }
838 
839 #ifdef FEAT_RIGHTLEFT
840     if (curwin->w_p_rl && KeyTyped && !KeyStuffed
841 					  && (nv_cmds[idx].cmd_flags & NV_RL))
842     {
843 	/* Invert horizontal movements and operations.  Only when typed by the
844 	 * user directly, not when the result of a mapping or "x" translated
845 	 * to "dl". */
846 	switch (ca.cmdchar)
847 	{
848 	    case 'l':	    ca.cmdchar = 'h'; break;
849 	    case K_RIGHT:   ca.cmdchar = K_LEFT; break;
850 	    case K_S_RIGHT: ca.cmdchar = K_S_LEFT; break;
851 	    case K_C_RIGHT: ca.cmdchar = K_C_LEFT; break;
852 	    case 'h':	    ca.cmdchar = 'l'; break;
853 	    case K_LEFT:    ca.cmdchar = K_RIGHT; break;
854 	    case K_S_LEFT:  ca.cmdchar = K_S_RIGHT; break;
855 	    case K_C_LEFT:  ca.cmdchar = K_C_RIGHT; break;
856 	    case '>':	    ca.cmdchar = '<'; break;
857 	    case '<':	    ca.cmdchar = '>'; break;
858 	}
859 	idx = find_command(ca.cmdchar);
860     }
861 #endif
862 
863     /*
864      * Get an additional character if we need one.
865      */
866     if ((nv_cmds[idx].cmd_flags & NV_NCH)
867 	    && (((nv_cmds[idx].cmd_flags & NV_NCH_NOP) == NV_NCH_NOP
868 		    && oap->op_type == OP_NOP)
869 		|| (nv_cmds[idx].cmd_flags & NV_NCH_ALW) == NV_NCH_ALW
870 		|| (ca.cmdchar == 'q'
871 		    && oap->op_type == OP_NOP
872 		    && reg_recording == 0
873 		    && reg_executing == 0)
874 		|| ((ca.cmdchar == 'a' || ca.cmdchar == 'i')
875 		    && (oap->op_type != OP_NOP || VIsual_active))))
876     {
877 	int	*cp;
878 	int	repl = FALSE;	/* get character for replace mode */
879 	int	lit = FALSE;	/* get extra character literally */
880 	int	langmap_active = FALSE;    /* using :lmap mappings */
881 	int	lang;		/* getting a text character */
882 #ifdef HAVE_INPUT_METHOD
883 	int	save_smd;	/* saved value of p_smd */
884 #endif
885 
886 	++no_mapping;
887 	++allow_keys;		/* no mapping for nchar, but allow key codes */
888 	/* Don't generate a CursorHold event here, most commands can't handle
889 	 * it, e.g., nv_replace(), nv_csearch(). */
890 	did_cursorhold = TRUE;
891 	if (ca.cmdchar == 'g')
892 	{
893 	    /*
894 	     * For 'g' get the next character now, so that we can check for
895 	     * "gr", "g'" and "g`".
896 	     */
897 	    ca.nchar = plain_vgetc();
898 	    LANGMAP_ADJUST(ca.nchar, TRUE);
899 #ifdef FEAT_CMDL_INFO
900 	    need_flushbuf |= add_to_showcmd(ca.nchar);
901 #endif
902 	    if (ca.nchar == 'r' || ca.nchar == '\'' || ca.nchar == '`'
903 						       || ca.nchar == Ctrl_BSL)
904 	    {
905 		cp = &ca.extra_char;	/* need to get a third character */
906 		if (ca.nchar != 'r')
907 		    lit = TRUE;			/* get it literally */
908 		else
909 		    repl = TRUE;		/* get it in replace mode */
910 	    }
911 	    else
912 		cp = NULL;		/* no third character needed */
913 	}
914 	else
915 	{
916 	    if (ca.cmdchar == 'r')		/* get it in replace mode */
917 		repl = TRUE;
918 	    cp = &ca.nchar;
919 	}
920 	lang = (repl || (nv_cmds[idx].cmd_flags & NV_LANG));
921 
922 	/*
923 	 * Get a second or third character.
924 	 */
925 	if (cp != NULL)
926 	{
927 #ifdef CURSOR_SHAPE
928 	    if (repl)
929 	    {
930 		State = REPLACE;	/* pretend Replace mode */
931 		ui_cursor_shape();	/* show different cursor shape */
932 	    }
933 #endif
934 	    if (lang && curbuf->b_p_iminsert == B_IMODE_LMAP)
935 	    {
936 		/* Allow mappings defined with ":lmap". */
937 		--no_mapping;
938 		--allow_keys;
939 		if (repl)
940 		    State = LREPLACE;
941 		else
942 		    State = LANGMAP;
943 		langmap_active = TRUE;
944 	    }
945 #ifdef HAVE_INPUT_METHOD
946 	    save_smd = p_smd;
947 	    p_smd = FALSE;	/* Don't let the IM code show the mode here */
948 	    if (lang && curbuf->b_p_iminsert == B_IMODE_IM)
949 		im_set_active(TRUE);
950 #endif
951 
952 	    *cp = plain_vgetc();
953 
954 	    if (langmap_active)
955 	    {
956 		/* Undo the decrement done above */
957 		++no_mapping;
958 		++allow_keys;
959 		State = NORMAL_BUSY;
960 	    }
961 #ifdef HAVE_INPUT_METHOD
962 	    if (lang)
963 	    {
964 		if (curbuf->b_p_iminsert != B_IMODE_LMAP)
965 		    im_save_status(&curbuf->b_p_iminsert);
966 		im_set_active(FALSE);
967 	    }
968 	    p_smd = save_smd;
969 #endif
970 #ifdef CURSOR_SHAPE
971 	    State = NORMAL_BUSY;
972 #endif
973 #ifdef FEAT_CMDL_INFO
974 	    need_flushbuf |= add_to_showcmd(*cp);
975 #endif
976 
977 	    if (!lit)
978 	    {
979 #ifdef FEAT_DIGRAPHS
980 		/* Typing CTRL-K gets a digraph. */
981 		if (*cp == Ctrl_K
982 			&& ((nv_cmds[idx].cmd_flags & NV_LANG)
983 			    || cp == &ca.extra_char)
984 			&& vim_strchr(p_cpo, CPO_DIGRAPH) == NULL)
985 		{
986 		    c = get_digraph(FALSE);
987 		    if (c > 0)
988 		    {
989 			*cp = c;
990 # ifdef FEAT_CMDL_INFO
991 			/* Guessing how to update showcmd here... */
992 			del_from_showcmd(3);
993 			need_flushbuf |= add_to_showcmd(*cp);
994 # endif
995 		    }
996 		}
997 #endif
998 
999 		/* adjust chars > 127, except after "tTfFr" commands */
1000 		LANGMAP_ADJUST(*cp, !lang);
1001 #ifdef FEAT_RIGHTLEFT
1002 		/* adjust Hebrew mapped char */
1003 		if (p_hkmap && lang && KeyTyped)
1004 		    *cp = hkmap(*cp);
1005 # ifdef FEAT_FKMAP
1006 		/* adjust Farsi mapped char */
1007 		if (p_fkmap && lang && KeyTyped)
1008 		    *cp = fkmap(*cp);
1009 # endif
1010 #endif
1011 	    }
1012 
1013 	    /*
1014 	     * When the next character is CTRL-\ a following CTRL-N means the
1015 	     * command is aborted and we go to Normal mode.
1016 	     */
1017 	    if (cp == &ca.extra_char
1018 		    && ca.nchar == Ctrl_BSL
1019 		    && (ca.extra_char == Ctrl_N || ca.extra_char == Ctrl_G))
1020 	    {
1021 		ca.cmdchar = Ctrl_BSL;
1022 		ca.nchar = ca.extra_char;
1023 		idx = find_command(ca.cmdchar);
1024 	    }
1025 	    else if ((ca.nchar == 'n' || ca.nchar == 'N') && ca.cmdchar == 'g')
1026 		ca.oap->op_type = get_op_type(*cp, NUL);
1027 	    else if (*cp == Ctrl_BSL)
1028 	    {
1029 		long towait = (p_ttm >= 0 ? p_ttm : p_tm);
1030 
1031 		/* There is a busy wait here when typing "f<C-\>" and then
1032 		 * something different from CTRL-N.  Can't be avoided. */
1033 		while ((c = vpeekc()) <= 0 && towait > 0L)
1034 		{
1035 		    do_sleep(towait > 50L ? 50L : towait);
1036 		    towait -= 50L;
1037 		}
1038 		if (c > 0)
1039 		{
1040 		    c = plain_vgetc();
1041 		    if (c != Ctrl_N && c != Ctrl_G)
1042 			vungetc(c);
1043 		    else
1044 		    {
1045 			ca.cmdchar = Ctrl_BSL;
1046 			ca.nchar = c;
1047 			idx = find_command(ca.cmdchar);
1048 		    }
1049 		}
1050 	    }
1051 
1052 #ifdef FEAT_MBYTE
1053 	    /* When getting a text character and the next character is a
1054 	     * multi-byte character, it could be a composing character.
1055 	     * However, don't wait for it to arrive. Also, do enable mapping,
1056 	     * because if it's put back with vungetc() it's too late to apply
1057 	     * mapping. */
1058 	    --no_mapping;
1059 	    while (enc_utf8 && lang && (c = vpeekc()) > 0
1060 				 && (c >= 0x100 || MB_BYTE2LEN(vpeekc()) > 1))
1061 	    {
1062 		c = plain_vgetc();
1063 		if (!utf_iscomposing(c))
1064 		{
1065 		    vungetc(c);		/* it wasn't, put it back */
1066 		    break;
1067 		}
1068 		else if (ca.ncharC1 == 0)
1069 		    ca.ncharC1 = c;
1070 		else
1071 		    ca.ncharC2 = c;
1072 	    }
1073 	    ++no_mapping;
1074 #endif
1075 	}
1076 	--no_mapping;
1077 	--allow_keys;
1078     }
1079 
1080 #ifdef FEAT_CMDL_INFO
1081     /*
1082      * Flush the showcmd characters onto the screen so we can see them while
1083      * the command is being executed.  Only do this when the shown command was
1084      * actually displayed, otherwise this will slow down a lot when executing
1085      * mappings.
1086      */
1087     if (need_flushbuf)
1088 	out_flush();
1089 #endif
1090     if (ca.cmdchar != K_IGNORE)
1091 	did_cursorhold = FALSE;
1092 
1093     State = NORMAL;
1094 
1095     if (ca.nchar == ESC)
1096     {
1097 	clearop(oap);
1098 	if (restart_edit == 0 && goto_im())
1099 	    restart_edit = 'a';
1100 	goto normal_end;
1101     }
1102 
1103     if (ca.cmdchar != K_IGNORE)
1104     {
1105 	msg_didout = FALSE;    /* don't scroll screen up for normal command */
1106 	msg_col = 0;
1107     }
1108 
1109     old_pos = curwin->w_cursor;		/* remember where cursor was */
1110 
1111     /* When 'keymodel' contains "startsel" some keys start Select/Visual
1112      * mode. */
1113     if (!VIsual_active && km_startsel)
1114     {
1115 	if (nv_cmds[idx].cmd_flags & NV_SS)
1116 	{
1117 	    start_selection();
1118 	    unshift_special(&ca);
1119 	    idx = find_command(ca.cmdchar);
1120 	}
1121 	else if ((nv_cmds[idx].cmd_flags & NV_SSS)
1122 					   && (mod_mask & MOD_MASK_SHIFT))
1123 	{
1124 	    start_selection();
1125 	    mod_mask &= ~MOD_MASK_SHIFT;
1126 	}
1127     }
1128 
1129     /*
1130      * Execute the command!
1131      * Call the command function found in the commands table.
1132      */
1133     ca.arg = nv_cmds[idx].cmd_arg;
1134     (nv_cmds[idx].cmd_func)(&ca);
1135 
1136     /*
1137      * If we didn't start or finish an operator, reset oap->regname, unless we
1138      * need it later.
1139      */
1140     if (!finish_op
1141 	    && !oap->op_type
1142 	    && (idx < 0 || !(nv_cmds[idx].cmd_flags & NV_KEEPREG)))
1143     {
1144 	clearop(oap);
1145 #ifdef FEAT_EVAL
1146 	{
1147 	    int regname = 0;
1148 
1149 	    /* Adjust the register according to 'clipboard', so that when
1150 	     * "unnamed" is present it becomes '*' or '+' instead of '"'. */
1151 # ifdef FEAT_CLIPBOARD
1152 	    adjust_clip_reg(&regname);
1153 # endif
1154 	    set_reg_var(regname);
1155 	}
1156 #endif
1157     }
1158 
1159     /* Get the length of mapped chars again after typing a count, second
1160      * character or "z333<cr>". */
1161     if (old_mapped_len > 0)
1162 	old_mapped_len = typebuf_maplen();
1163 
1164     /*
1165      * If an operation is pending, handle it...
1166      */
1167     do_pending_operator(&ca, old_col, FALSE);
1168 
1169     /*
1170      * Wait for a moment when a message is displayed that will be overwritten
1171      * by the mode message.
1172      * In Visual mode and with "^O" in Insert mode, a short message will be
1173      * overwritten by the mode message.  Wait a bit, until a key is hit.
1174      * In Visual mode, it's more important to keep the Visual area updated
1175      * than keeping a message (e.g. from a /pat search).
1176      * Only do this if the command was typed, not from a mapping.
1177      * Don't wait when emsg_silent is non-zero.
1178      * Also wait a bit after an error message, e.g. for "^O:".
1179      * Don't redraw the screen, it would remove the message.
1180      */
1181     if (       ((p_smd
1182 		    && msg_silent == 0
1183 		    && (restart_edit != 0
1184 			|| (VIsual_active
1185 			    && old_pos.lnum == curwin->w_cursor.lnum
1186 			    && old_pos.col == curwin->w_cursor.col)
1187 		       )
1188 		    && (clear_cmdline
1189 			|| redraw_cmdline)
1190 		    && (msg_didout || (msg_didany && msg_scroll))
1191 		    && !msg_nowait
1192 		    && KeyTyped)
1193 		|| (restart_edit != 0
1194 		    && !VIsual_active
1195 		    && (msg_scroll
1196 			|| emsg_on_display)))
1197 	    && oap->regname == 0
1198 	    && !(ca.retval & CA_COMMAND_BUSY)
1199 	    && stuff_empty()
1200 	    && typebuf_typed()
1201 	    && emsg_silent == 0
1202 	    && !did_wait_return
1203 	    && oap->op_type == OP_NOP)
1204     {
1205 	int	save_State = State;
1206 
1207 	/* Draw the cursor with the right shape here */
1208 	if (restart_edit != 0)
1209 	    State = INSERT;
1210 
1211 	/* If need to redraw, and there is a "keep_msg", redraw before the
1212 	 * delay */
1213 	if (must_redraw && keep_msg != NULL && !emsg_on_display)
1214 	{
1215 	    char_u	*kmsg;
1216 
1217 	    kmsg = keep_msg;
1218 	    keep_msg = NULL;
1219 	    /* showmode() will clear keep_msg, but we want to use it anyway */
1220 	    update_screen(0);
1221 	    /* now reset it, otherwise it's put in the history again */
1222 	    keep_msg = kmsg;
1223 	    msg_attr(kmsg, keep_msg_attr);
1224 	    vim_free(kmsg);
1225 	}
1226 	setcursor();
1227 	cursor_on();
1228 	out_flush();
1229 	if (msg_scroll || emsg_on_display)
1230 	    ui_delay(1000L, TRUE);	/* wait at least one second */
1231 	ui_delay(3000L, FALSE);		/* wait up to three seconds */
1232 	State = save_State;
1233 
1234 	msg_scroll = FALSE;
1235 	emsg_on_display = FALSE;
1236     }
1237 
1238     /*
1239      * Finish up after executing a Normal mode command.
1240      */
1241 normal_end:
1242 
1243     msg_nowait = FALSE;
1244 
1245     /* Reset finish_op, in case it was set */
1246 #ifdef CURSOR_SHAPE
1247     c = finish_op;
1248 #endif
1249     finish_op = FALSE;
1250 #ifdef CURSOR_SHAPE
1251     /* Redraw the cursor with another shape, if we were in Operator-pending
1252      * mode or did a replace command. */
1253     if (c || ca.cmdchar == 'r')
1254     {
1255 	ui_cursor_shape();		/* may show different cursor shape */
1256 # ifdef FEAT_MOUSESHAPE
1257 	update_mouseshape(-1);
1258 # endif
1259     }
1260 #endif
1261 
1262 #ifdef FEAT_CMDL_INFO
1263     if (oap->op_type == OP_NOP && oap->regname == 0
1264 	    && ca.cmdchar != K_CURSORHOLD)
1265 	clear_showcmd();
1266 #endif
1267 
1268     checkpcmark();		/* check if we moved since setting pcmark */
1269     vim_free(ca.searchbuf);
1270 
1271 #ifdef FEAT_MBYTE
1272     if (has_mbyte)
1273 	mb_adjust_cursor();
1274 #endif
1275 
1276     if (curwin->w_p_scb && toplevel)
1277     {
1278 	validate_cursor();	/* may need to update w_leftcol */
1279 	do_check_scrollbind(TRUE);
1280     }
1281 
1282     if (curwin->w_p_crb && toplevel)
1283     {
1284 	validate_cursor();	/* may need to update w_leftcol */
1285 	do_check_cursorbind();
1286     }
1287 
1288 #ifdef FEAT_TERMINAL
1289     /* don't go to Insert mode if a terminal has a running job */
1290     if (term_job_running(curbuf->b_term))
1291 	restart_edit = 0;
1292 #endif
1293 
1294     /*
1295      * May restart edit(), if we got here with CTRL-O in Insert mode (but not
1296      * if still inside a mapping that started in Visual mode).
1297      * May switch from Visual to Select mode after CTRL-O command.
1298      */
1299     if (       oap->op_type == OP_NOP
1300 	    && ((restart_edit != 0 && !VIsual_active && old_mapped_len == 0)
1301 		|| restart_VIsual_select == 1)
1302 	    && !(ca.retval & CA_COMMAND_BUSY)
1303 	    && stuff_empty()
1304 	    && oap->regname == 0)
1305     {
1306 	if (restart_VIsual_select == 1)
1307 	{
1308 	    VIsual_select = TRUE;
1309 	    showmode();
1310 	    restart_VIsual_select = 0;
1311 	}
1312 	if (restart_edit != 0 && !VIsual_active && old_mapped_len == 0)
1313 	    (void)edit(restart_edit, FALSE, 1L);
1314     }
1315 
1316     if (restart_VIsual_select == 2)
1317 	restart_VIsual_select = 1;
1318 
1319     /* Save count before an operator for next time. */
1320     opcount = ca.opcount;
1321 }
1322 
1323 #ifdef FEAT_EVAL
1324 /*
1325  * Set v:count and v:count1 according to "cap".
1326  * Set v:prevcount only when "set_prevcount" is TRUE.
1327  */
1328     static void
1329 set_vcount_ca(cmdarg_T *cap, int *set_prevcount)
1330 {
1331     long count = cap->count0;
1332 
1333     /* multiply with cap->opcount the same way as above */
1334     if (cap->opcount != 0)
1335 	count = cap->opcount * (count == 0 ? 1 : count);
1336     set_vcount(count, count == 0 ? 1 : count, *set_prevcount);
1337     *set_prevcount = FALSE;  /* only set v:prevcount once */
1338 }
1339 #endif
1340 
1341 /*
1342  * Handle an operator after visual mode or when the movement is finished
1343  */
1344     void
1345 do_pending_operator(cmdarg_T *cap, int old_col, int gui_yank)
1346 {
1347     oparg_T	*oap = cap->oap;
1348     pos_T	old_cursor;
1349     int		empty_region_error;
1350     int		restart_edit_save;
1351 #ifdef FEAT_LINEBREAK
1352     int		lbr_saved = curwin->w_p_lbr;
1353 #endif
1354 
1355     /* The visual area is remembered for redo */
1356     static int	    redo_VIsual_mode = NUL; /* 'v', 'V', or Ctrl-V */
1357     static linenr_T redo_VIsual_line_count; /* number of lines */
1358     static colnr_T  redo_VIsual_vcol;	    /* number of cols or end column */
1359     static long	    redo_VIsual_count;	    /* count for Visual operator */
1360     static int	    redo_VIsual_arg;	    /* extra argument */
1361 #ifdef FEAT_VIRTUALEDIT
1362     int		    include_line_break = FALSE;
1363 #endif
1364 
1365 #if defined(FEAT_CLIPBOARD)
1366     /*
1367      * Yank the visual area into the GUI selection register before we operate
1368      * on it and lose it forever.
1369      * Don't do it if a specific register was specified, so that ""x"*P works.
1370      * This could call do_pending_operator() recursively, but that's OK
1371      * because gui_yank will be TRUE for the nested call.
1372      */
1373     if ((clip_star.available || clip_plus.available)
1374 	    && oap->op_type != OP_NOP
1375 	    && !gui_yank
1376 	    && VIsual_active
1377 	    && !redo_VIsual_busy
1378 	    && oap->regname == 0)
1379 	clip_auto_select();
1380 #endif
1381     old_cursor = curwin->w_cursor;
1382 
1383     /*
1384      * If an operation is pending, handle it...
1385      */
1386     if ((finish_op || VIsual_active) && oap->op_type != OP_NOP)
1387     {
1388 #ifdef FEAT_LINEBREAK
1389 	/* Avoid a problem with unwanted linebreaks in block mode. */
1390 	if (curwin->w_p_lbr)
1391 	    curwin->w_valid &= ~VALID_VIRTCOL;
1392 	curwin->w_p_lbr = FALSE;
1393 #endif
1394 	oap->is_VIsual = VIsual_active;
1395 	if (oap->motion_force == 'V')
1396 	    oap->motion_type = MLINE;
1397 	else if (oap->motion_force == 'v')
1398 	{
1399 	    /* If the motion was linewise, "inclusive" will not have been set.
1400 	     * Use "exclusive" to be consistent.  Makes "dvj" work nice. */
1401 	    if (oap->motion_type == MLINE)
1402 		oap->inclusive = FALSE;
1403 	    /* If the motion already was characterwise, toggle "inclusive" */
1404 	    else if (oap->motion_type == MCHAR)
1405 		oap->inclusive = !oap->inclusive;
1406 	    oap->motion_type = MCHAR;
1407 	}
1408 	else if (oap->motion_force == Ctrl_V)
1409 	{
1410 	    /* Change line- or characterwise motion into Visual block mode. */
1411 	    VIsual_active = TRUE;
1412 	    VIsual = oap->start;
1413 	    VIsual_mode = Ctrl_V;
1414 	    VIsual_select = FALSE;
1415 	    VIsual_reselect = FALSE;
1416 	}
1417 
1418 	/* Only redo yank when 'y' flag is in 'cpoptions'. */
1419 	/* Never redo "zf" (define fold). */
1420 	if ((vim_strchr(p_cpo, CPO_YANK) != NULL || oap->op_type != OP_YANK)
1421 		&& ((!VIsual_active || oap->motion_force)
1422 		    /* Also redo Operator-pending Visual mode mappings */
1423 		    || (VIsual_active && cap->cmdchar == ':'
1424 						 && oap->op_type != OP_COLON))
1425 		&& cap->cmdchar != 'D'
1426 #ifdef FEAT_FOLDING
1427 		&& oap->op_type != OP_FOLD
1428 		&& oap->op_type != OP_FOLDOPEN
1429 		&& oap->op_type != OP_FOLDOPENREC
1430 		&& oap->op_type != OP_FOLDCLOSE
1431 		&& oap->op_type != OP_FOLDCLOSEREC
1432 		&& oap->op_type != OP_FOLDDEL
1433 		&& oap->op_type != OP_FOLDDELREC
1434 #endif
1435 		)
1436 	{
1437 	    prep_redo(oap->regname, cap->count0,
1438 		    get_op_char(oap->op_type), get_extra_op_char(oap->op_type),
1439 		    oap->motion_force, cap->cmdchar, cap->nchar);
1440 	    if (cap->cmdchar == '/' || cap->cmdchar == '?') /* was a search */
1441 	    {
1442 		/*
1443 		 * If 'cpoptions' does not contain 'r', insert the search
1444 		 * pattern to really repeat the same command.
1445 		 */
1446 		if (vim_strchr(p_cpo, CPO_REDO) == NULL)
1447 		    AppendToRedobuffLit(cap->searchbuf, -1);
1448 		AppendToRedobuff(NL_STR);
1449 	    }
1450 	    else if (cap->cmdchar == ':')
1451 	    {
1452 		/* do_cmdline() has stored the first typed line in
1453 		 * "repeat_cmdline".  When several lines are typed repeating
1454 		 * won't be possible. */
1455 		if (repeat_cmdline == NULL)
1456 		    ResetRedobuff();
1457 		else
1458 		{
1459 		    AppendToRedobuffLit(repeat_cmdline, -1);
1460 		    AppendToRedobuff(NL_STR);
1461 		    VIM_CLEAR(repeat_cmdline);
1462 		}
1463 	    }
1464 	}
1465 
1466 	if (redo_VIsual_busy)
1467 	{
1468 	    /* Redo of an operation on a Visual area. Use the same size from
1469 	     * redo_VIsual_line_count and redo_VIsual_vcol. */
1470 	    oap->start = curwin->w_cursor;
1471 	    curwin->w_cursor.lnum += redo_VIsual_line_count - 1;
1472 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
1473 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
1474 	    VIsual_mode = redo_VIsual_mode;
1475 	    if (redo_VIsual_vcol == MAXCOL || VIsual_mode == 'v')
1476 	    {
1477 		if (VIsual_mode == 'v')
1478 		{
1479 		    if (redo_VIsual_line_count <= 1)
1480 		    {
1481 			validate_virtcol();
1482 			curwin->w_curswant =
1483 				     curwin->w_virtcol + redo_VIsual_vcol - 1;
1484 		    }
1485 		    else
1486 			curwin->w_curswant = redo_VIsual_vcol;
1487 		}
1488 		else
1489 		{
1490 		    curwin->w_curswant = MAXCOL;
1491 		}
1492 		coladvance(curwin->w_curswant);
1493 	    }
1494 	    cap->count0 = redo_VIsual_count;
1495 	    if (redo_VIsual_count != 0)
1496 		cap->count1 = redo_VIsual_count;
1497 	    else
1498 		cap->count1 = 1;
1499 	}
1500 	else if (VIsual_active)
1501 	{
1502 	    if (!gui_yank)
1503 	    {
1504 		/* Save the current VIsual area for '< and '> marks, and "gv" */
1505 		curbuf->b_visual.vi_start = VIsual;
1506 		curbuf->b_visual.vi_end = curwin->w_cursor;
1507 		curbuf->b_visual.vi_mode = VIsual_mode;
1508 		if (VIsual_mode_orig != NUL)
1509 		{
1510 		    curbuf->b_visual.vi_mode = VIsual_mode_orig;
1511 		    VIsual_mode_orig = NUL;
1512 		}
1513 		curbuf->b_visual.vi_curswant = curwin->w_curswant;
1514 # ifdef FEAT_EVAL
1515 		curbuf->b_visual_mode_eval = VIsual_mode;
1516 # endif
1517 	    }
1518 
1519 	    /* In Select mode, a linewise selection is operated upon like a
1520 	     * characterwise selection.
1521 	     * Special case: gH<Del> deletes the last line. */
1522 	    if (VIsual_select && VIsual_mode == 'V'
1523 					    && cap->oap->op_type != OP_DELETE)
1524 	    {
1525 		if (LT_POS(VIsual, curwin->w_cursor))
1526 		{
1527 		    VIsual.col = 0;
1528 		    curwin->w_cursor.col =
1529 			       (colnr_T)STRLEN(ml_get(curwin->w_cursor.lnum));
1530 		}
1531 		else
1532 		{
1533 		    curwin->w_cursor.col = 0;
1534 		    VIsual.col = (colnr_T)STRLEN(ml_get(VIsual.lnum));
1535 		}
1536 		VIsual_mode = 'v';
1537 	    }
1538 	    /* If 'selection' is "exclusive", backup one character for
1539 	     * charwise selections. */
1540 	    else if (VIsual_mode == 'v')
1541 	    {
1542 # ifdef FEAT_VIRTUALEDIT
1543 		include_line_break =
1544 # endif
1545 		    unadjust_for_sel();
1546 	    }
1547 
1548 	    oap->start = VIsual;
1549 	    if (VIsual_mode == 'V')
1550 	    {
1551 		oap->start.col = 0;
1552 # ifdef FEAT_VIRTUALEDIT
1553 		oap->start.coladd = 0;
1554 # endif
1555 	    }
1556 	}
1557 
1558 	/*
1559 	 * Set oap->start to the first position of the operated text, oap->end
1560 	 * to the end of the operated text.  w_cursor is equal to oap->start.
1561 	 */
1562 	if (LT_POS(oap->start, curwin->w_cursor))
1563 	{
1564 #ifdef FEAT_FOLDING
1565 	    /* Include folded lines completely. */
1566 	    if (!VIsual_active)
1567 	    {
1568 		if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL))
1569 		    oap->start.col = 0;
1570 		if (hasFolding(curwin->w_cursor.lnum, NULL,
1571 						      &curwin->w_cursor.lnum))
1572 		    curwin->w_cursor.col = (colnr_T)STRLEN(ml_get_curline());
1573 	    }
1574 #endif
1575 	    oap->end = curwin->w_cursor;
1576 	    curwin->w_cursor = oap->start;
1577 
1578 	    /* w_virtcol may have been updated; if the cursor goes back to its
1579 	     * previous position w_virtcol becomes invalid and isn't updated
1580 	     * automatically. */
1581 	    curwin->w_valid &= ~VALID_VIRTCOL;
1582 	}
1583 	else
1584 	{
1585 #ifdef FEAT_FOLDING
1586 	    /* Include folded lines completely. */
1587 	    if (!VIsual_active && oap->motion_type == MLINE)
1588 	    {
1589 		if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum,
1590 									NULL))
1591 		    curwin->w_cursor.col = 0;
1592 		if (hasFolding(oap->start.lnum, NULL, &oap->start.lnum))
1593 		    oap->start.col = (colnr_T)STRLEN(ml_get(oap->start.lnum));
1594 	    }
1595 #endif
1596 	    oap->end = oap->start;
1597 	    oap->start = curwin->w_cursor;
1598 	}
1599 
1600 	/* Just in case lines were deleted that make the position invalid. */
1601 	check_pos(curwin->w_buffer, &oap->end);
1602 	oap->line_count = oap->end.lnum - oap->start.lnum + 1;
1603 
1604 #ifdef FEAT_VIRTUALEDIT
1605 	/* Set "virtual_op" before resetting VIsual_active. */
1606 	virtual_op = virtual_active();
1607 #endif
1608 
1609 	if (VIsual_active || redo_VIsual_busy)
1610 	{
1611 	    get_op_vcol(oap, redo_VIsual_vcol, TRUE);
1612 
1613 	    if (!redo_VIsual_busy && !gui_yank)
1614 	    {
1615 		/*
1616 		 * Prepare to reselect and redo Visual: this is based on the
1617 		 * size of the Visual text
1618 		 */
1619 		resel_VIsual_mode = VIsual_mode;
1620 		if (curwin->w_curswant == MAXCOL)
1621 		    resel_VIsual_vcol = MAXCOL;
1622 		else
1623 		{
1624 		    if (VIsual_mode != Ctrl_V)
1625 			getvvcol(curwin, &(oap->end),
1626 						  NULL, NULL, &oap->end_vcol);
1627 		    if (VIsual_mode == Ctrl_V || oap->line_count <= 1)
1628 		    {
1629 			if (VIsual_mode != Ctrl_V)
1630 			    getvvcol(curwin, &(oap->start),
1631 						&oap->start_vcol, NULL, NULL);
1632 			resel_VIsual_vcol = oap->end_vcol - oap->start_vcol + 1;
1633 		    }
1634 		    else
1635 			resel_VIsual_vcol = oap->end_vcol;
1636 		}
1637 		resel_VIsual_line_count = oap->line_count;
1638 	    }
1639 
1640 	    /* can't redo yank (unless 'y' is in 'cpoptions') and ":" */
1641 	    if ((vim_strchr(p_cpo, CPO_YANK) != NULL || oap->op_type != OP_YANK)
1642 		    && oap->op_type != OP_COLON
1643 #ifdef FEAT_FOLDING
1644 		    && oap->op_type != OP_FOLD
1645 		    && oap->op_type != OP_FOLDOPEN
1646 		    && oap->op_type != OP_FOLDOPENREC
1647 		    && oap->op_type != OP_FOLDCLOSE
1648 		    && oap->op_type != OP_FOLDCLOSEREC
1649 		    && oap->op_type != OP_FOLDDEL
1650 		    && oap->op_type != OP_FOLDDELREC
1651 #endif
1652 		    && oap->motion_force == NUL
1653 		    )
1654 	    {
1655 		/* Prepare for redoing.  Only use the nchar field for "r",
1656 		 * otherwise it might be the second char of the operator. */
1657 		if (cap->cmdchar == 'g' && (cap->nchar == 'n'
1658 							|| cap->nchar == 'N'))
1659 		    prep_redo(oap->regname, cap->count0,
1660 			    get_op_char(oap->op_type), get_extra_op_char(oap->op_type),
1661 			    oap->motion_force, cap->cmdchar, cap->nchar);
1662 		else if (cap->cmdchar != ':')
1663 		{
1664 		    int nchar = oap->op_type == OP_REPLACE ? cap->nchar : NUL;
1665 
1666 		    /* reverse what nv_replace() did */
1667 		    if (nchar == REPLACE_CR_NCHAR)
1668 			nchar = CAR;
1669 		    else if (nchar == REPLACE_NL_NCHAR)
1670 			nchar = NL;
1671 		    prep_redo(oap->regname, 0L, NUL, 'v',
1672 					get_op_char(oap->op_type),
1673 					get_extra_op_char(oap->op_type),
1674 					nchar);
1675 		}
1676 		if (!redo_VIsual_busy)
1677 		{
1678 		    redo_VIsual_mode = resel_VIsual_mode;
1679 		    redo_VIsual_vcol = resel_VIsual_vcol;
1680 		    redo_VIsual_line_count = resel_VIsual_line_count;
1681 		    redo_VIsual_count = cap->count0;
1682 		    redo_VIsual_arg = cap->arg;
1683 		}
1684 	    }
1685 
1686 	    /*
1687 	     * oap->inclusive defaults to TRUE.
1688 	     * If oap->end is on a NUL (empty line) oap->inclusive becomes
1689 	     * FALSE.  This makes "d}P" and "v}dP" work the same.
1690 	     */
1691 	    if (oap->motion_force == NUL || oap->motion_type == MLINE)
1692 		oap->inclusive = TRUE;
1693 	    if (VIsual_mode == 'V')
1694 		oap->motion_type = MLINE;
1695 	    else
1696 	    {
1697 		oap->motion_type = MCHAR;
1698 		if (VIsual_mode != Ctrl_V && *ml_get_pos(&(oap->end)) == NUL
1699 #ifdef FEAT_VIRTUALEDIT
1700 			&& (include_line_break || !virtual_op)
1701 #endif
1702 			)
1703 		{
1704 		    oap->inclusive = FALSE;
1705 		    /* Try to include the newline, unless it's an operator
1706 		     * that works on lines only. */
1707 		    if (*p_sel != 'o'
1708 			    && !op_on_lines(oap->op_type)
1709 			    && oap->end.lnum < curbuf->b_ml.ml_line_count)
1710 		    {
1711 			++oap->end.lnum;
1712 			oap->end.col = 0;
1713 #ifdef FEAT_VIRTUALEDIT
1714 			oap->end.coladd = 0;
1715 #endif
1716 			++oap->line_count;
1717 		    }
1718 		}
1719 	    }
1720 
1721 	    redo_VIsual_busy = FALSE;
1722 
1723 	    /*
1724 	     * Switch Visual off now, so screen updating does
1725 	     * not show inverted text when the screen is redrawn.
1726 	     * With OP_YANK and sometimes with OP_COLON and OP_FILTER there is
1727 	     * no screen redraw, so it is done here to remove the inverted
1728 	     * part.
1729 	     */
1730 	    if (!gui_yank)
1731 	    {
1732 		VIsual_active = FALSE;
1733 #ifdef FEAT_MOUSE
1734 		setmouse();
1735 		mouse_dragging = 0;
1736 #endif
1737 		may_clear_cmdline();
1738 		if ((oap->op_type == OP_YANK
1739 			    || oap->op_type == OP_COLON
1740 			    || oap->op_type == OP_FUNCTION
1741 			    || oap->op_type == OP_FILTER)
1742 			&& oap->motion_force == NUL)
1743 		{
1744 #ifdef FEAT_LINEBREAK
1745 		    /* make sure redrawing is correct */
1746 		    curwin->w_p_lbr = lbr_saved;
1747 #endif
1748 		    redraw_curbuf_later(INVERTED);
1749 		}
1750 	    }
1751 	}
1752 
1753 #ifdef FEAT_MBYTE
1754 	/* Include the trailing byte of a multi-byte char. */
1755 	if (has_mbyte && oap->inclusive)
1756 	{
1757 	    int		l;
1758 
1759 	    l = (*mb_ptr2len)(ml_get_pos(&oap->end));
1760 	    if (l > 1)
1761 		oap->end.col += l - 1;
1762 	}
1763 #endif
1764 	curwin->w_set_curswant = TRUE;
1765 
1766 	/*
1767 	 * oap->empty is set when start and end are the same.  The inclusive
1768 	 * flag affects this too, unless yanking and the end is on a NUL.
1769 	 */
1770 	oap->empty = (oap->motion_type == MCHAR
1771 		    && (!oap->inclusive
1772 			|| (oap->op_type == OP_YANK
1773 			    && gchar_pos(&oap->end) == NUL))
1774 		    && EQUAL_POS(oap->start, oap->end)
1775 #ifdef FEAT_VIRTUALEDIT
1776 		    && !(virtual_op && oap->start.coladd != oap->end.coladd)
1777 #endif
1778 		    );
1779 	/*
1780 	 * For delete, change and yank, it's an error to operate on an
1781 	 * empty region, when 'E' included in 'cpoptions' (Vi compatible).
1782 	 */
1783 	empty_region_error = (oap->empty
1784 				&& vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL);
1785 
1786 	/* Force a redraw when operating on an empty Visual region, when
1787 	 * 'modifiable is off or creating a fold. */
1788 	if (oap->is_VIsual && (oap->empty || !curbuf->b_p_ma
1789 #ifdef FEAT_FOLDING
1790 		    || oap->op_type == OP_FOLD
1791 #endif
1792 		    ))
1793 	{
1794 #ifdef FEAT_LINEBREAK
1795 	    curwin->w_p_lbr = lbr_saved;
1796 #endif
1797 	    redraw_curbuf_later(INVERTED);
1798 	}
1799 
1800 	/*
1801 	 * If the end of an operator is in column one while oap->motion_type
1802 	 * is MCHAR and oap->inclusive is FALSE, we put op_end after the last
1803 	 * character in the previous line. If op_start is on or before the
1804 	 * first non-blank in the line, the operator becomes linewise
1805 	 * (strange, but that's the way vi does it).
1806 	 */
1807 	if (	   oap->motion_type == MCHAR
1808 		&& oap->inclusive == FALSE
1809 		&& !(cap->retval & CA_NO_ADJ_OP_END)
1810 		&& oap->end.col == 0
1811 		&& (!oap->is_VIsual || *p_sel == 'o')
1812 		&& !oap->block_mode
1813 		&& oap->line_count > 1)
1814 	{
1815 	    oap->end_adjusted = TRUE;	    /* remember that we did this */
1816 	    --oap->line_count;
1817 	    --oap->end.lnum;
1818 	    if (inindent(0))
1819 		oap->motion_type = MLINE;
1820 	    else
1821 	    {
1822 		oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum));
1823 		if (oap->end.col)
1824 		{
1825 		    --oap->end.col;
1826 		    oap->inclusive = TRUE;
1827 		}
1828 	    }
1829 	}
1830 	else
1831 	    oap->end_adjusted = FALSE;
1832 
1833 	switch (oap->op_type)
1834 	{
1835 	case OP_LSHIFT:
1836 	case OP_RSHIFT:
1837 	    op_shift(oap, TRUE, oap->is_VIsual ? (int)cap->count1 : 1);
1838 	    auto_format(FALSE, TRUE);
1839 	    break;
1840 
1841 	case OP_JOIN_NS:
1842 	case OP_JOIN:
1843 	    if (oap->line_count < 2)
1844 		oap->line_count = 2;
1845 	    if (curwin->w_cursor.lnum + oap->line_count - 1 >
1846 						   curbuf->b_ml.ml_line_count)
1847 		beep_flush();
1848 	    else
1849 	    {
1850 		(void)do_join(oap->line_count, oap->op_type == OP_JOIN,
1851 							    TRUE, TRUE, TRUE);
1852 		auto_format(FALSE, TRUE);
1853 	    }
1854 	    break;
1855 
1856 	case OP_DELETE:
1857 	    VIsual_reselect = FALSE;	    /* don't reselect now */
1858 	    if (empty_region_error)
1859 	    {
1860 		vim_beep(BO_OPER);
1861 		CancelRedo();
1862 	    }
1863 	    else
1864 	    {
1865 		(void)op_delete(oap);
1866 		if (oap->motion_type == MLINE && has_format_option(FO_AUTO))
1867 		    u_save_cursor();	    /* cursor line wasn't saved yet */
1868 		auto_format(FALSE, TRUE);
1869 	    }
1870 	    break;
1871 
1872 	case OP_YANK:
1873 	    if (empty_region_error)
1874 	    {
1875 		if (!gui_yank)
1876 		{
1877 		    vim_beep(BO_OPER);
1878 		    CancelRedo();
1879 		}
1880 	    }
1881 	    else
1882 	    {
1883 #ifdef FEAT_LINEBREAK
1884 		curwin->w_p_lbr = lbr_saved;
1885 #endif
1886 		(void)op_yank(oap, FALSE, !gui_yank);
1887 	    }
1888 	    check_cursor_col();
1889 	    break;
1890 
1891 	case OP_CHANGE:
1892 	    VIsual_reselect = FALSE;	    /* don't reselect now */
1893 	    if (empty_region_error)
1894 	    {
1895 		vim_beep(BO_OPER);
1896 		CancelRedo();
1897 	    }
1898 	    else
1899 	    {
1900 		/* This is a new edit command, not a restart.  Need to
1901 		 * remember it to make 'insertmode' work with mappings for
1902 		 * Visual mode.  But do this only once and not when typed and
1903 		 * 'insertmode' isn't set. */
1904 		if (p_im || !KeyTyped)
1905 		    restart_edit_save = restart_edit;
1906 		else
1907 		    restart_edit_save = 0;
1908 		restart_edit = 0;
1909 #ifdef FEAT_LINEBREAK
1910 		/* Restore linebreak, so that when the user edits it looks as
1911 		 * before. */
1912 		if (curwin->w_p_lbr != lbr_saved)
1913 		{
1914 		    curwin->w_p_lbr = lbr_saved;
1915 		    get_op_vcol(oap, redo_VIsual_mode, FALSE);
1916 		}
1917 #endif
1918 		/* Reset finish_op now, don't want it set inside edit(). */
1919 		finish_op = FALSE;
1920 		if (op_change(oap))	/* will call edit() */
1921 		    cap->retval |= CA_COMMAND_BUSY;
1922 		if (restart_edit == 0)
1923 		    restart_edit = restart_edit_save;
1924 	    }
1925 	    break;
1926 
1927 	case OP_FILTER:
1928 	    if (vim_strchr(p_cpo, CPO_FILTER) != NULL)
1929 		AppendToRedobuff((char_u *)"!\r");  /* use any last used !cmd */
1930 	    else
1931 		bangredo = TRUE;    /* do_bang() will put cmd in redo buffer */
1932 	    /* FALLTHROUGH */
1933 
1934 	case OP_INDENT:
1935 	case OP_COLON:
1936 
1937 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
1938 	    /*
1939 	     * If 'equalprg' is empty, do the indenting internally.
1940 	     */
1941 	    if (oap->op_type == OP_INDENT && *get_equalprg() == NUL)
1942 	    {
1943 # ifdef FEAT_LISP
1944 		if (curbuf->b_p_lisp)
1945 		{
1946 		    op_reindent(oap, get_lisp_indent);
1947 		    break;
1948 		}
1949 # endif
1950 # ifdef FEAT_CINDENT
1951 		op_reindent(oap,
1952 #  ifdef FEAT_EVAL
1953 			*curbuf->b_p_inde != NUL ? get_expr_indent :
1954 #  endif
1955 			    get_c_indent);
1956 		break;
1957 # endif
1958 	    }
1959 #endif
1960 
1961 	    op_colon(oap);
1962 	    break;
1963 
1964 	case OP_TILDE:
1965 	case OP_UPPER:
1966 	case OP_LOWER:
1967 	case OP_ROT13:
1968 	    if (empty_region_error)
1969 	    {
1970 		vim_beep(BO_OPER);
1971 		CancelRedo();
1972 	    }
1973 	    else
1974 		op_tilde(oap);
1975 	    check_cursor_col();
1976 	    break;
1977 
1978 	case OP_FORMAT:
1979 #if defined(FEAT_EVAL)
1980 	    if (*curbuf->b_p_fex != NUL)
1981 		op_formatexpr(oap);	/* use expression */
1982 	    else
1983 #endif
1984 		if (*p_fp != NUL || *curbuf->b_p_fp != NUL)
1985 		op_colon(oap);		/* use external command */
1986 	    else
1987 		op_format(oap, FALSE);	/* use internal function */
1988 	    break;
1989 
1990 	case OP_FORMAT2:
1991 	    op_format(oap, TRUE);	/* use internal function */
1992 	    break;
1993 
1994 	case OP_FUNCTION:
1995 #ifdef FEAT_LINEBREAK
1996 	    /* Restore linebreak, so that when the user edits it looks as
1997 	     * before. */
1998 	    curwin->w_p_lbr = lbr_saved;
1999 #endif
2000 	    op_function(oap);		/* call 'operatorfunc' */
2001 	    break;
2002 
2003 	case OP_INSERT:
2004 	case OP_APPEND:
2005 	    VIsual_reselect = FALSE;	/* don't reselect now */
2006 #ifdef FEAT_VISUALEXTRA
2007 	    if (empty_region_error)
2008 	    {
2009 		vim_beep(BO_OPER);
2010 		CancelRedo();
2011 	    }
2012 	    else
2013 	    {
2014 		/* This is a new edit command, not a restart.  Need to
2015 		 * remember it to make 'insertmode' work with mappings for
2016 		 * Visual mode.  But do this only once. */
2017 		restart_edit_save = restart_edit;
2018 		restart_edit = 0;
2019 #ifdef FEAT_LINEBREAK
2020 		/* Restore linebreak, so that when the user edits it looks as
2021 		 * before. */
2022 		if (curwin->w_p_lbr != lbr_saved)
2023 		{
2024 		    curwin->w_p_lbr = lbr_saved;
2025 		    get_op_vcol(oap, redo_VIsual_mode, FALSE);
2026 		}
2027 #endif
2028 		op_insert(oap, cap->count1);
2029 #ifdef FEAT_LINEBREAK
2030 		/* Reset linebreak, so that formatting works correctly. */
2031 		curwin->w_p_lbr = FALSE;
2032 #endif
2033 
2034 		/* TODO: when inserting in several lines, should format all
2035 		 * the lines. */
2036 		auto_format(FALSE, TRUE);
2037 
2038 		if (restart_edit == 0)
2039 		    restart_edit = restart_edit_save;
2040 		else
2041 		    cap->retval |= CA_COMMAND_BUSY;
2042 	    }
2043 #else
2044 	    vim_beep(BO_OPER);
2045 #endif
2046 	    break;
2047 
2048 	case OP_REPLACE:
2049 	    VIsual_reselect = FALSE;	/* don't reselect now */
2050 #ifdef FEAT_VISUALEXTRA
2051 	    if (empty_region_error)
2052 #endif
2053 	    {
2054 		vim_beep(BO_OPER);
2055 		CancelRedo();
2056 	    }
2057 #ifdef FEAT_VISUALEXTRA
2058 	    else
2059 	    {
2060 # ifdef FEAT_LINEBREAK
2061 		/* Restore linebreak, so that when the user edits it looks as
2062 		 * before. */
2063 		if (curwin->w_p_lbr != lbr_saved)
2064 		{
2065 		    curwin->w_p_lbr = lbr_saved;
2066 		    get_op_vcol(oap, redo_VIsual_mode, FALSE);
2067 		}
2068 # endif
2069 		op_replace(oap, cap->nchar);
2070 	    }
2071 #endif
2072 	    break;
2073 
2074 #ifdef FEAT_FOLDING
2075 	case OP_FOLD:
2076 	    VIsual_reselect = FALSE;	/* don't reselect now */
2077 	    foldCreate(oap->start.lnum, oap->end.lnum);
2078 	    break;
2079 
2080 	case OP_FOLDOPEN:
2081 	case OP_FOLDOPENREC:
2082 	case OP_FOLDCLOSE:
2083 	case OP_FOLDCLOSEREC:
2084 	    VIsual_reselect = FALSE;	/* don't reselect now */
2085 	    opFoldRange(oap->start.lnum, oap->end.lnum,
2086 		    oap->op_type == OP_FOLDOPEN
2087 					    || oap->op_type == OP_FOLDOPENREC,
2088 		    oap->op_type == OP_FOLDOPENREC
2089 					  || oap->op_type == OP_FOLDCLOSEREC,
2090 					  oap->is_VIsual);
2091 	    break;
2092 
2093 	case OP_FOLDDEL:
2094 	case OP_FOLDDELREC:
2095 	    VIsual_reselect = FALSE;	/* don't reselect now */
2096 	    deleteFold(oap->start.lnum, oap->end.lnum,
2097 			       oap->op_type == OP_FOLDDELREC, oap->is_VIsual);
2098 	    break;
2099 #endif
2100 	case OP_NR_ADD:
2101 	case OP_NR_SUB:
2102 	    if (empty_region_error)
2103 	    {
2104 		vim_beep(BO_OPER);
2105 		CancelRedo();
2106 	    }
2107 	    else
2108 	    {
2109 		VIsual_active = TRUE;
2110 #ifdef FEAT_LINEBREAK
2111 		curwin->w_p_lbr = lbr_saved;
2112 #endif
2113 		op_addsub(oap, cap->count1, redo_VIsual_arg);
2114 		VIsual_active = FALSE;
2115 	    }
2116 	    check_cursor_col();
2117 	    break;
2118 	default:
2119 	    clearopbeep(oap);
2120 	}
2121 #ifdef FEAT_VIRTUALEDIT
2122 	virtual_op = MAYBE;
2123 #endif
2124 	if (!gui_yank)
2125 	{
2126 	    /*
2127 	     * if 'sol' not set, go back to old column for some commands
2128 	     */
2129 	    if (!p_sol && oap->motion_type == MLINE && !oap->end_adjusted
2130 		    && (oap->op_type == OP_LSHIFT || oap->op_type == OP_RSHIFT
2131 						|| oap->op_type == OP_DELETE))
2132 	    {
2133 #ifdef FEAT_LINEBREAK
2134 		curwin->w_p_lbr = FALSE;
2135 #endif
2136 		coladvance(curwin->w_curswant = old_col);
2137 	    }
2138 	}
2139 	else
2140 	{
2141 	    curwin->w_cursor = old_cursor;
2142 	}
2143 	oap->block_mode = FALSE;
2144 	clearop(oap);
2145     }
2146 #ifdef FEAT_LINEBREAK
2147     curwin->w_p_lbr = lbr_saved;
2148 #endif
2149 }
2150 
2151 /*
2152  * Handle indent and format operators and visual mode ":".
2153  */
2154     static void
2155 op_colon(oparg_T *oap)
2156 {
2157     stuffcharReadbuff(':');
2158     if (oap->is_VIsual)
2159 	stuffReadbuff((char_u *)"'<,'>");
2160     else
2161     {
2162 	/*
2163 	 * Make the range look nice, so it can be repeated.
2164 	 */
2165 	if (oap->start.lnum == curwin->w_cursor.lnum)
2166 	    stuffcharReadbuff('.');
2167 	else
2168 	    stuffnumReadbuff((long)oap->start.lnum);
2169 	if (oap->end.lnum != oap->start.lnum)
2170 	{
2171 	    stuffcharReadbuff(',');
2172 	    if (oap->end.lnum == curwin->w_cursor.lnum)
2173 		stuffcharReadbuff('.');
2174 	    else if (oap->end.lnum == curbuf->b_ml.ml_line_count)
2175 		stuffcharReadbuff('$');
2176 	    else if (oap->start.lnum == curwin->w_cursor.lnum)
2177 	    {
2178 		stuffReadbuff((char_u *)".+");
2179 		stuffnumReadbuff((long)oap->line_count - 1);
2180 	    }
2181 	    else
2182 		stuffnumReadbuff((long)oap->end.lnum);
2183 	}
2184     }
2185     if (oap->op_type != OP_COLON)
2186 	stuffReadbuff((char_u *)"!");
2187     if (oap->op_type == OP_INDENT)
2188     {
2189 #ifndef FEAT_CINDENT
2190 	if (*get_equalprg() == NUL)
2191 	    stuffReadbuff((char_u *)"indent");
2192 	else
2193 #endif
2194 	    stuffReadbuff(get_equalprg());
2195 	stuffReadbuff((char_u *)"\n");
2196     }
2197     else if (oap->op_type == OP_FORMAT)
2198     {
2199 	if (*curbuf->b_p_fp != NUL)
2200 	    stuffReadbuff(curbuf->b_p_fp);
2201 	else if (*p_fp != NUL)
2202 	    stuffReadbuff(p_fp);
2203 	else
2204 	    stuffReadbuff((char_u *)"fmt");
2205 	stuffReadbuff((char_u *)"\n']");
2206     }
2207 
2208     /*
2209      * do_cmdline() does the rest
2210      */
2211 }
2212 
2213 /*
2214  * Handle the "g@" operator: call 'operatorfunc'.
2215  */
2216     static void
2217 op_function(oparg_T *oap UNUSED)
2218 {
2219 #ifdef FEAT_EVAL
2220     typval_T	argv[2];
2221 # ifdef FEAT_VIRTUALEDIT
2222     int		save_virtual_op = virtual_op;
2223 # endif
2224 
2225     if (*p_opfunc == NUL)
2226 	EMSG(_("E774: 'operatorfunc' is empty"));
2227     else
2228     {
2229 	/* Set '[ and '] marks to text to be operated on. */
2230 	curbuf->b_op_start = oap->start;
2231 	curbuf->b_op_end = oap->end;
2232 	if (oap->motion_type != MLINE && !oap->inclusive)
2233 	    /* Exclude the end position. */
2234 	    decl(&curbuf->b_op_end);
2235 
2236 	argv[0].v_type = VAR_STRING;
2237 	if (oap->block_mode)
2238 	    argv[0].vval.v_string = (char_u *)"block";
2239 	else if (oap->motion_type == MLINE)
2240 	    argv[0].vval.v_string = (char_u *)"line";
2241 	else
2242 	    argv[0].vval.v_string = (char_u *)"char";
2243 	argv[1].v_type = VAR_UNKNOWN;
2244 
2245 # ifdef FEAT_VIRTUALEDIT
2246 	/* Reset virtual_op so that 'virtualedit' can be changed in the
2247 	 * function. */
2248 	virtual_op = MAYBE;
2249 # endif
2250 
2251 	(void)call_func_retnr(p_opfunc, 1, argv);
2252 
2253 # ifdef FEAT_VIRTUALEDIT
2254 	virtual_op = save_virtual_op;
2255 # endif
2256     }
2257 #else
2258     EMSG(_("E775: Eval feature not available"));
2259 #endif
2260 }
2261 
2262 #if defined(FEAT_MOUSE) || defined(PROTO)
2263 /*
2264  * Do the appropriate action for the current mouse click in the current mode.
2265  * Not used for Command-line mode.
2266  *
2267  * Normal and Visual Mode:
2268  * event	 modi-	position      visual	   change   action
2269  *		 fier	cursor			   window
2270  * left press	  -	yes	    end		    yes
2271  * left press	  C	yes	    end		    yes	    "^]" (2)
2272  * left press	  S	yes	end (popup: extend) yes	    "*" (2)
2273  * left drag	  -	yes	start if moved	    no
2274  * left relse	  -	yes	start if moved	    no
2275  * middle press	  -	yes	 if not active	    no	    put register
2276  * middle press	  -	yes	 if active	    no	    yank and put
2277  * right press	  -	yes	start or extend	    yes
2278  * right press	  S	yes	no change	    yes	    "#" (2)
2279  * right drag	  -	yes	extend		    no
2280  * right relse	  -	yes	extend		    no
2281  *
2282  * Insert or Replace Mode:
2283  * event	 modi-	position      visual	   change   action
2284  *		 fier	cursor			   window
2285  * left press	  -	yes	(cannot be active)  yes
2286  * left press	  C	yes	(cannot be active)  yes	    "CTRL-O^]" (2)
2287  * left press	  S	yes	(cannot be active)  yes	    "CTRL-O*" (2)
2288  * left drag	  -	yes	start or extend (1) no	    CTRL-O (1)
2289  * left relse	  -	yes	start or extend (1) no	    CTRL-O (1)
2290  * middle press	  -	no	(cannot be active)  no	    put register
2291  * right press	  -	yes	start or extend	    yes	    CTRL-O
2292  * right press	  S	yes	(cannot be active)  yes	    "CTRL-O#" (2)
2293  *
2294  * (1) only if mouse pointer moved since press
2295  * (2) only if click is in same buffer
2296  *
2297  * Return TRUE if start_arrow() should be called for edit mode.
2298  */
2299     int
2300 do_mouse(
2301     oparg_T	*oap,		/* operator argument, can be NULL */
2302     int		c,		/* K_LEFTMOUSE, etc */
2303     int		dir,		/* Direction to 'put' if necessary */
2304     long	count,
2305     int		fixindent)	/* PUT_FIXINDENT if fixing indent necessary */
2306 {
2307     static int	do_always = FALSE;	/* ignore 'mouse' setting next time */
2308     static int	got_click = FALSE;	/* got a click some time back */
2309 
2310     int		which_button;	/* MOUSE_LEFT, _MIDDLE or _RIGHT */
2311     int		is_click;	/* If FALSE it's a drag or release event */
2312     int		is_drag;	/* If TRUE it's a drag event */
2313     int		jump_flags = 0;	/* flags for jump_to_mouse() */
2314     pos_T	start_visual;
2315     int		moved;		/* Has cursor moved? */
2316     int		in_status_line;	/* mouse in status line */
2317     static int	in_tab_line = FALSE; /* mouse clicked in tab line */
2318     int		in_sep_line;	/* mouse in vertical separator line */
2319     int		c1, c2;
2320 #if defined(FEAT_FOLDING)
2321     pos_T	save_cursor;
2322 #endif
2323     win_T	*old_curwin = curwin;
2324     static pos_T orig_cursor;
2325     colnr_T	leftcol, rightcol;
2326     pos_T	end_visual;
2327     int		diff;
2328     int		old_active = VIsual_active;
2329     int		old_mode = VIsual_mode;
2330     int		regname;
2331 
2332 #if defined(FEAT_FOLDING)
2333     save_cursor = curwin->w_cursor;
2334 #endif
2335 
2336     /*
2337      * When GUI is active, always recognize mouse events, otherwise:
2338      * - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.
2339      * - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.
2340      * - For command line and insert mode 'mouse' is checked before calling
2341      *	 do_mouse().
2342      */
2343     if (do_always)
2344 	do_always = FALSE;
2345     else
2346 #ifdef FEAT_GUI
2347 	if (!gui.in_use)
2348 #endif
2349 	{
2350 	    if (VIsual_active)
2351 	    {
2352 		if (!mouse_has(MOUSE_VISUAL))
2353 		    return FALSE;
2354 	    }
2355 	    else if (State == NORMAL && !mouse_has(MOUSE_NORMAL))
2356 		return FALSE;
2357 	}
2358 
2359     for (;;)
2360     {
2361 	which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
2362 	if (is_drag)
2363 	{
2364 	    /* If the next character is the same mouse event then use that
2365 	     * one. Speeds up dragging the status line. */
2366 	    if (vpeekc() != NUL)
2367 	    {
2368 		int nc;
2369 		int save_mouse_row = mouse_row;
2370 		int save_mouse_col = mouse_col;
2371 
2372 		/* Need to get the character, peeking doesn't get the actual
2373 		 * one. */
2374 		nc = safe_vgetc();
2375 		if (c == nc)
2376 		    continue;
2377 		vungetc(nc);
2378 		mouse_row = save_mouse_row;
2379 		mouse_col = save_mouse_col;
2380 	    }
2381 	}
2382 	break;
2383     }
2384 
2385     if (c == K_MOUSEMOVE)
2386     {
2387 	/* Mouse moved without a button pressed. */
2388 #ifdef FEAT_BEVAL_TERM
2389 	ui_may_remove_balloon();
2390 	if (p_bevalterm && !VIsual_active)
2391 	{
2392 	    profile_setlimit(p_bdlay, &bevalexpr_due);
2393 	    bevalexpr_due_set = TRUE;
2394 	}
2395 #endif
2396 	return FALSE;
2397     }
2398 
2399 #ifdef FEAT_MOUSESHAPE
2400     /* May have stopped dragging the status or separator line.  The pointer is
2401      * most likely still on the status or separator line. */
2402     if (!is_drag && drag_status_line)
2403     {
2404 	drag_status_line = FALSE;
2405 	update_mouseshape(SHAPE_IDX_STATUS);
2406     }
2407     if (!is_drag && drag_sep_line)
2408     {
2409 	drag_sep_line = FALSE;
2410 	update_mouseshape(SHAPE_IDX_VSEP);
2411     }
2412 #endif
2413 
2414     /*
2415      * Ignore drag and release events if we didn't get a click.
2416      */
2417     if (is_click)
2418 	got_click = TRUE;
2419     else
2420     {
2421 	if (!got_click)			/* didn't get click, ignore */
2422 	    return FALSE;
2423 	if (!is_drag)			/* release, reset got_click */
2424 	{
2425 	    got_click = FALSE;
2426 	    if (in_tab_line)
2427 	    {
2428 		in_tab_line = FALSE;
2429 		return FALSE;
2430 	    }
2431 	}
2432     }
2433 
2434     /*
2435      * CTRL right mouse button does CTRL-T
2436      */
2437     if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)
2438     {
2439 	if (State & INSERT)
2440 	    stuffcharReadbuff(Ctrl_O);
2441 	if (count > 1)
2442 	    stuffnumReadbuff(count);
2443 	stuffcharReadbuff(Ctrl_T);
2444 	got_click = FALSE;		/* ignore drag&release now */
2445 	return FALSE;
2446     }
2447 
2448     /*
2449      * CTRL only works with left mouse button
2450      */
2451     if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)
2452 	return FALSE;
2453 
2454     /*
2455      * When a modifier is down, ignore drag and release events, as well as
2456      * multiple clicks and the middle mouse button.
2457      * Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
2458      */
2459     if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
2460 							     | MOD_MASK_META))
2461 	    && (!is_click
2462 		|| (mod_mask & MOD_MASK_MULTI_CLICK)
2463 		|| which_button == MOUSE_MIDDLE)
2464 	    && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
2465 		&& mouse_model_popup()
2466 		&& which_button == MOUSE_LEFT)
2467 	    && !((mod_mask & MOD_MASK_ALT)
2468 		&& !mouse_model_popup()
2469 		&& which_button == MOUSE_RIGHT)
2470 	    )
2471 	return FALSE;
2472 
2473     /*
2474      * If the button press was used as the movement command for an operator
2475      * (eg "d<MOUSE>"), or it is the middle button that is held down, ignore
2476      * drag/release events.
2477      */
2478     if (!is_click && which_button == MOUSE_MIDDLE)
2479 	return FALSE;
2480 
2481     if (oap != NULL)
2482 	regname = oap->regname;
2483     else
2484 	regname = 0;
2485 
2486     /*
2487      * Middle mouse button does a 'put' of the selected text
2488      */
2489     if (which_button == MOUSE_MIDDLE)
2490     {
2491 	if (State == NORMAL)
2492 	{
2493 	    /*
2494 	     * If an operator was pending, we don't know what the user wanted
2495 	     * to do. Go back to normal mode: Clear the operator and beep().
2496 	     */
2497 	    if (oap != NULL && oap->op_type != OP_NOP)
2498 	    {
2499 		clearopbeep(oap);
2500 		return FALSE;
2501 	    }
2502 
2503 	    /*
2504 	     * If visual was active, yank the highlighted text and put it
2505 	     * before the mouse pointer position.
2506 	     * In Select mode replace the highlighted text with the clipboard.
2507 	     */
2508 	    if (VIsual_active)
2509 	    {
2510 		if (VIsual_select)
2511 		{
2512 		    stuffcharReadbuff(Ctrl_G);
2513 		    stuffReadbuff((char_u *)"\"+p");
2514 		}
2515 		else
2516 		{
2517 		    stuffcharReadbuff('y');
2518 		    stuffcharReadbuff(K_MIDDLEMOUSE);
2519 		}
2520 		do_always = TRUE;	/* ignore 'mouse' setting next time */
2521 		return FALSE;
2522 	    }
2523 	    /*
2524 	     * The rest is below jump_to_mouse()
2525 	     */
2526 	}
2527 
2528 	else if ((State & INSERT) == 0)
2529 	    return FALSE;
2530 
2531 	/*
2532 	 * Middle click in insert mode doesn't move the mouse, just insert the
2533 	 * contents of a register.  '.' register is special, can't insert that
2534 	 * with do_put().
2535 	 * Also paste at the cursor if the current mode isn't in 'mouse' (only
2536 	 * happens for the GUI).
2537 	 */
2538 	if ((State & INSERT) || !mouse_has(MOUSE_NORMAL))
2539 	{
2540 	    if (regname == '.')
2541 		insert_reg(regname, TRUE);
2542 	    else
2543 	    {
2544 #ifdef FEAT_CLIPBOARD
2545 		if (clip_star.available && regname == 0)
2546 		    regname = '*';
2547 #endif
2548 		if ((State & REPLACE_FLAG) && !yank_register_mline(regname))
2549 		    insert_reg(regname, TRUE);
2550 		else
2551 		{
2552 		    do_put(regname, BACKWARD, 1L, fixindent | PUT_CURSEND);
2553 
2554 		    /* Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r */
2555 		    AppendCharToRedobuff(Ctrl_R);
2556 		    AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);
2557 		    AppendCharToRedobuff(regname == 0 ? '"' : regname);
2558 		}
2559 	    }
2560 	    return FALSE;
2561 	}
2562     }
2563 
2564     /* When dragging or button-up stay in the same window. */
2565     if (!is_click)
2566 	jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;
2567 
2568     start_visual.lnum = 0;
2569 
2570     /* Check for clicking in the tab page line. */
2571     if (mouse_row == 0 && firstwin->w_winrow > 0)
2572     {
2573 	if (is_drag)
2574 	{
2575 	    if (in_tab_line)
2576 	    {
2577 		c1 = TabPageIdxs[mouse_col];
2578 		tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)
2579 								? c1 - 1 : c1);
2580 	    }
2581 	    return FALSE;
2582 	}
2583 
2584 	/* click in a tab selects that tab page */
2585 	if (is_click
2586 # ifdef FEAT_CMDWIN
2587 		&& cmdwin_type == 0
2588 # endif
2589 		&& mouse_col < Columns)
2590 	{
2591 	    in_tab_line = TRUE;
2592 	    c1 = TabPageIdxs[mouse_col];
2593 	    if (c1 >= 0)
2594 	    {
2595 		if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
2596 		{
2597 		    /* double click opens new page */
2598 		    end_visual_mode();
2599 		    tabpage_new();
2600 		    tabpage_move(c1 == 0 ? 9999 : c1 - 1);
2601 		}
2602 		else
2603 		{
2604 		    /* Go to specified tab page, or next one if not clicking
2605 		     * on a label. */
2606 		    goto_tabpage(c1);
2607 
2608 		    /* It's like clicking on the status line of a window. */
2609 		    if (curwin != old_curwin)
2610 			end_visual_mode();
2611 		}
2612 	    }
2613 	    else
2614 	    {
2615 		tabpage_T	*tp;
2616 
2617 		/* Close the current or specified tab page. */
2618 		if (c1 == -999)
2619 		    tp = curtab;
2620 		else
2621 		    tp = find_tabpage(-c1);
2622 		if (tp == curtab)
2623 		{
2624 		    if (first_tabpage->tp_next != NULL)
2625 			tabpage_close(FALSE);
2626 		}
2627 		else if (tp != NULL)
2628 		    tabpage_close_other(tp, FALSE);
2629 	    }
2630 	}
2631 	return TRUE;
2632     }
2633     else if (is_drag && in_tab_line)
2634     {
2635 	c1 = TabPageIdxs[mouse_col];
2636 	tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
2637 	return FALSE;
2638     }
2639 
2640     /*
2641      * When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
2642      * right button up   -> pop-up menu
2643      * shift-left button -> right button
2644      * alt-left button   -> alt-right button
2645      */
2646     if (mouse_model_popup())
2647     {
2648 	if (which_button == MOUSE_RIGHT
2649 			    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
2650 	{
2651 #if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
2652 	    || defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN) \
2653 	    || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_PHOTON) \
2654 	    || defined(FEAT_TERM_POPUP_MENU)
2655 # ifdef FEAT_GUI
2656 	    if (gui.in_use)
2657 	    {
2658 #  if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
2659 			  || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2660 		if (!is_click)
2661 		    /* Ignore right button release events, only shows the popup
2662 		     * menu on the button down event. */
2663 		    return FALSE;
2664 #  endif
2665 #  if defined(FEAT_GUI_ATHENA) || defined(FEAT_GUI_MSWIN)
2666 		if (is_click || is_drag)
2667 		    /* Ignore right button down and drag mouse events.  Windows
2668 		     * only shows the popup menu on the button up event. */
2669 		    return FALSE;
2670 #  endif
2671 	    }
2672 # endif
2673 # if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)
2674 	    else
2675 # endif
2676 # if defined(FEAT_TERM_POPUP_MENU)
2677 	    if (!is_click)
2678 		/* Ignore right button release events, only shows the popup
2679 		 * menu on the button down event. */
2680 		return FALSE;
2681 #endif
2682 
2683 	    jump_flags = 0;
2684 	    if (STRCMP(p_mousem, "popup_setpos") == 0)
2685 	    {
2686 		/* First set the cursor position before showing the popup
2687 		 * menu. */
2688 		if (VIsual_active)
2689 		{
2690 		    pos_T    m_pos;
2691 
2692 		    /*
2693 		     * set MOUSE_MAY_STOP_VIS if we are outside the
2694 		     * selection or the current window (might have false
2695 		     * negative here)
2696 		     */
2697 		    if (mouse_row < curwin->w_winrow
2698 			 || mouse_row
2699 				  > (curwin->w_winrow + curwin->w_height))
2700 			jump_flags = MOUSE_MAY_STOP_VIS;
2701 		    else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)
2702 			jump_flags = MOUSE_MAY_STOP_VIS;
2703 		    else
2704 		    {
2705 			if ((LT_POS(curwin->w_cursor, VIsual)
2706 				    && (LT_POS(m_pos, curwin->w_cursor)
2707 					|| LT_POS(VIsual, m_pos)))
2708 				|| (LT_POS(VIsual, curwin->w_cursor)
2709 				    && (LT_POS(m_pos, VIsual)
2710 				      || LT_POS(curwin->w_cursor, m_pos))))
2711 			{
2712 			    jump_flags = MOUSE_MAY_STOP_VIS;
2713 			}
2714 			else if (VIsual_mode == Ctrl_V)
2715 			{
2716 			    getvcols(curwin, &curwin->w_cursor, &VIsual,
2717 						     &leftcol, &rightcol);
2718 			    getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);
2719 			    if (m_pos.col < leftcol || m_pos.col > rightcol)
2720 				jump_flags = MOUSE_MAY_STOP_VIS;
2721 			}
2722 		    }
2723 		}
2724 		else
2725 		    jump_flags = MOUSE_MAY_STOP_VIS;
2726 	    }
2727 	    if (jump_flags)
2728 	    {
2729 		jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
2730 		update_curbuf(VIsual_active ? INVERTED : VALID);
2731 		setcursor();
2732 		out_flush();    /* Update before showing popup menu */
2733 	    }
2734 # ifdef FEAT_MENU
2735 	    show_popupmenu();
2736 	    got_click = FALSE;	/* ignore release events */
2737 # endif
2738 	    return (jump_flags & CURSOR_MOVED) != 0;
2739 #else
2740 	    return FALSE;
2741 #endif
2742 	}
2743 	if (which_button == MOUSE_LEFT
2744 				&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))
2745 	{
2746 	    which_button = MOUSE_RIGHT;
2747 	    mod_mask &= ~MOD_MASK_SHIFT;
2748 	}
2749     }
2750 
2751     if ((State & (NORMAL | INSERT))
2752 			    && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
2753     {
2754 	if (which_button == MOUSE_LEFT)
2755 	{
2756 	    if (is_click)
2757 	    {
2758 		/* stop Visual mode for a left click in a window, but not when
2759 		 * on a status line */
2760 		if (VIsual_active)
2761 		    jump_flags |= MOUSE_MAY_STOP_VIS;
2762 	    }
2763 	    else if (mouse_has(MOUSE_VISUAL))
2764 		jump_flags |= MOUSE_MAY_VIS;
2765 	}
2766 	else if (which_button == MOUSE_RIGHT)
2767 	{
2768 	    if (is_click && VIsual_active)
2769 	    {
2770 		/*
2771 		 * Remember the start and end of visual before moving the
2772 		 * cursor.
2773 		 */
2774 		if (LT_POS(curwin->w_cursor, VIsual))
2775 		{
2776 		    start_visual = curwin->w_cursor;
2777 		    end_visual = VIsual;
2778 		}
2779 		else
2780 		{
2781 		    start_visual = VIsual;
2782 		    end_visual = curwin->w_cursor;
2783 		}
2784 	    }
2785 	    jump_flags |= MOUSE_FOCUS;
2786 	    if (mouse_has(MOUSE_VISUAL))
2787 		jump_flags |= MOUSE_MAY_VIS;
2788 	}
2789     }
2790 
2791     /*
2792      * If an operator is pending, ignore all drags and releases until the
2793      * next mouse click.
2794      */
2795     if (!is_drag && oap != NULL && oap->op_type != OP_NOP)
2796     {
2797 	got_click = FALSE;
2798 	oap->motion_type = MCHAR;
2799     }
2800 
2801     /* When releasing the button let jump_to_mouse() know. */
2802     if (!is_click && !is_drag)
2803 	jump_flags |= MOUSE_RELEASED;
2804 
2805     /*
2806      * JUMP!
2807      */
2808     jump_flags = jump_to_mouse(jump_flags,
2809 			oap == NULL ? NULL : &(oap->inclusive), which_button);
2810 
2811 #ifdef FEAT_MENU
2812     /* A click in the window toolbar has no side effects. */
2813     if (jump_flags & MOUSE_WINBAR)
2814 	return FALSE;
2815 #endif
2816     moved = (jump_flags & CURSOR_MOVED);
2817     in_status_line = (jump_flags & IN_STATUS_LINE);
2818     in_sep_line = (jump_flags & IN_SEP_LINE);
2819 
2820 #ifdef FEAT_NETBEANS_INTG
2821     if (isNetbeansBuffer(curbuf)
2822 			    && !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))
2823     {
2824 	int key = KEY2TERMCAP1(c);
2825 
2826 	if (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE
2827 					       || key == (int)KE_RIGHTRELEASE)
2828 	    netbeans_button_release(which_button);
2829     }
2830 #endif
2831 
2832     /* When jumping to another window, clear a pending operator.  That's a bit
2833      * friendlier than beeping and not jumping to that window. */
2834     if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)
2835 	clearop(oap);
2836 
2837 #ifdef FEAT_FOLDING
2838     if (mod_mask == 0
2839 	    && !is_drag
2840 	    && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
2841 	    && which_button == MOUSE_LEFT)
2842     {
2843 	/* open or close a fold at this line */
2844 	if (jump_flags & MOUSE_FOLD_OPEN)
2845 	    openFold(curwin->w_cursor.lnum, 1L);
2846 	else
2847 	    closeFold(curwin->w_cursor.lnum, 1L);
2848 	/* don't move the cursor if still in the same window */
2849 	if (curwin == old_curwin)
2850 	    curwin->w_cursor = save_cursor;
2851     }
2852 #endif
2853 
2854 #if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)
2855     if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)
2856     {
2857 	clip_modeless(which_button, is_click, is_drag);
2858 	return FALSE;
2859     }
2860 #endif
2861 
2862     /* Set global flag that we are extending the Visual area with mouse
2863      * dragging; temporarily minimize 'scrolloff'. */
2864     if (VIsual_active && is_drag && p_so)
2865     {
2866 	/* In the very first line, allow scrolling one line */
2867 	if (mouse_row == 0)
2868 	    mouse_dragging = 2;
2869 	else
2870 	    mouse_dragging = 1;
2871     }
2872 
2873     /* When dragging the mouse above the window, scroll down. */
2874     if (is_drag && mouse_row < 0 && !in_status_line)
2875     {
2876 	scroll_redraw(FALSE, 1L);
2877 	mouse_row = 0;
2878     }
2879 
2880     if (start_visual.lnum)		/* right click in visual mode */
2881     {
2882        /* When ALT is pressed make Visual mode blockwise. */
2883        if (mod_mask & MOD_MASK_ALT)
2884 	   VIsual_mode = Ctrl_V;
2885 
2886 	/*
2887 	 * In Visual-block mode, divide the area in four, pick up the corner
2888 	 * that is in the quarter that the cursor is in.
2889 	 */
2890 	if (VIsual_mode == Ctrl_V)
2891 	{
2892 	    getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);
2893 	    if (curwin->w_curswant > (leftcol + rightcol) / 2)
2894 		end_visual.col = leftcol;
2895 	    else
2896 		end_visual.col = rightcol;
2897 	    if (curwin->w_cursor.lnum >=
2898 				    (start_visual.lnum + end_visual.lnum) / 2)
2899 		end_visual.lnum = start_visual.lnum;
2900 
2901 	    /* move VIsual to the right column */
2902 	    start_visual = curwin->w_cursor;	    /* save the cursor pos */
2903 	    curwin->w_cursor = end_visual;
2904 	    coladvance(end_visual.col);
2905 	    VIsual = curwin->w_cursor;
2906 	    curwin->w_cursor = start_visual;	    /* restore the cursor */
2907 	}
2908 	else
2909 	{
2910 	    /*
2911 	     * If the click is before the start of visual, change the start.
2912 	     * If the click is after the end of visual, change the end.  If
2913 	     * the click is inside the visual, change the closest side.
2914 	     */
2915 	    if (LT_POS(curwin->w_cursor, start_visual))
2916 		VIsual = end_visual;
2917 	    else if (LT_POS(end_visual, curwin->w_cursor))
2918 		VIsual = start_visual;
2919 	    else
2920 	    {
2921 		/* In the same line, compare column number */
2922 		if (end_visual.lnum == start_visual.lnum)
2923 		{
2924 		    if (curwin->w_cursor.col - start_visual.col >
2925 				    end_visual.col - curwin->w_cursor.col)
2926 			VIsual = start_visual;
2927 		    else
2928 			VIsual = end_visual;
2929 		}
2930 
2931 		/* In different lines, compare line number */
2932 		else
2933 		{
2934 		    diff = (curwin->w_cursor.lnum - start_visual.lnum) -
2935 				(end_visual.lnum - curwin->w_cursor.lnum);
2936 
2937 		    if (diff > 0)		/* closest to end */
2938 			VIsual = start_visual;
2939 		    else if (diff < 0)	/* closest to start */
2940 			VIsual = end_visual;
2941 		    else			/* in the middle line */
2942 		    {
2943 			if (curwin->w_cursor.col <
2944 					(start_visual.col + end_visual.col) / 2)
2945 			    VIsual = end_visual;
2946 			else
2947 			    VIsual = start_visual;
2948 		    }
2949 		}
2950 	    }
2951 	}
2952     }
2953     /*
2954      * If Visual mode started in insert mode, execute "CTRL-O"
2955      */
2956     else if ((State & INSERT) && VIsual_active)
2957 	stuffcharReadbuff(Ctrl_O);
2958 
2959     /*
2960      * Middle mouse click: Put text before cursor.
2961      */
2962     if (which_button == MOUSE_MIDDLE)
2963     {
2964 #ifdef FEAT_CLIPBOARD
2965 	if (clip_star.available && regname == 0)
2966 	    regname = '*';
2967 #endif
2968 	if (yank_register_mline(regname))
2969 	{
2970 	    if (mouse_past_bottom)
2971 		dir = FORWARD;
2972 	}
2973 	else if (mouse_past_eol)
2974 	    dir = FORWARD;
2975 
2976 	if (fixindent)
2977 	{
2978 	    c1 = (dir == BACKWARD) ? '[' : ']';
2979 	    c2 = 'p';
2980 	}
2981 	else
2982 	{
2983 	    c1 = (dir == FORWARD) ? 'p' : 'P';
2984 	    c2 = NUL;
2985 	}
2986 	prep_redo(regname, count, NUL, c1, NUL, c2, NUL);
2987 
2988 	/*
2989 	 * Remember where the paste started, so in edit() Insstart can be set
2990 	 * to this position
2991 	 */
2992 	if (restart_edit != 0)
2993 	    where_paste_started = curwin->w_cursor;
2994 	do_put(regname, dir, count, fixindent | PUT_CURSEND);
2995     }
2996 
2997 #if defined(FEAT_QUICKFIX)
2998     /*
2999      * Ctrl-Mouse click or double click in a quickfix window jumps to the
3000      * error under the mouse pointer.
3001      */
3002     else if (((mod_mask & MOD_MASK_CTRL)
3003 		|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
3004 	    && bt_quickfix(curbuf))
3005     {
3006 	if (curwin->w_llist_ref == NULL)	/* quickfix window */
3007 	    do_cmdline_cmd((char_u *)".cc");
3008 	else					/* location list window */
3009 	    do_cmdline_cmd((char_u *)".ll");
3010 	got_click = FALSE;		/* ignore drag&release now */
3011     }
3012 #endif
3013 
3014     /*
3015      * Ctrl-Mouse click (or double click in a help window) jumps to the tag
3016      * under the mouse pointer.
3017      */
3018     else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help
3019 		     && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))
3020     {
3021 	if (State & INSERT)
3022 	    stuffcharReadbuff(Ctrl_O);
3023 	stuffcharReadbuff(Ctrl_RSB);
3024 	got_click = FALSE;		/* ignore drag&release now */
3025     }
3026 
3027     /*
3028      * Shift-Mouse click searches for the next occurrence of the word under
3029      * the mouse pointer
3030      */
3031     else if ((mod_mask & MOD_MASK_SHIFT))
3032     {
3033 	if ((State & INSERT) || (VIsual_active && VIsual_select))
3034 	    stuffcharReadbuff(Ctrl_O);
3035 	if (which_button == MOUSE_LEFT)
3036 	    stuffcharReadbuff('*');
3037 	else	/* MOUSE_RIGHT */
3038 	    stuffcharReadbuff('#');
3039     }
3040 
3041     /* Handle double clicks, unless on status line */
3042     else if (in_status_line)
3043     {
3044 #ifdef FEAT_MOUSESHAPE
3045 	if ((is_drag || is_click) && !drag_status_line)
3046 	{
3047 	    drag_status_line = TRUE;
3048 	    update_mouseshape(-1);
3049 	}
3050 #endif
3051     }
3052     else if (in_sep_line)
3053     {
3054 #ifdef FEAT_MOUSESHAPE
3055 	if ((is_drag || is_click) && !drag_sep_line)
3056 	{
3057 	    drag_sep_line = TRUE;
3058 	    update_mouseshape(-1);
3059 	}
3060 #endif
3061     }
3062     else if ((mod_mask & MOD_MASK_MULTI_CLICK) && (State & (NORMAL | INSERT))
3063 	     && mouse_has(MOUSE_VISUAL))
3064     {
3065 	if (is_click || !VIsual_active)
3066 	{
3067 	    if (VIsual_active)
3068 		orig_cursor = VIsual;
3069 	    else
3070 	    {
3071 		check_visual_highlight();
3072 		VIsual = curwin->w_cursor;
3073 		orig_cursor = VIsual;
3074 		VIsual_active = TRUE;
3075 		VIsual_reselect = TRUE;
3076 		/* start Select mode if 'selectmode' contains "mouse" */
3077 		may_start_select('o');
3078 		setmouse();
3079 	    }
3080 	    if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
3081 	    {
3082 		/* Double click with ALT pressed makes it blockwise. */
3083 		if (mod_mask & MOD_MASK_ALT)
3084 		    VIsual_mode = Ctrl_V;
3085 		else
3086 		    VIsual_mode = 'v';
3087 	    }
3088 	    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)
3089 		VIsual_mode = 'V';
3090 	    else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)
3091 		VIsual_mode = Ctrl_V;
3092 #ifdef FEAT_CLIPBOARD
3093 	    /* Make sure the clipboard gets updated.  Needed because start and
3094 	     * end may still be the same, and the selection needs to be owned */
3095 	    clip_star.vmode = NUL;
3096 #endif
3097 	}
3098 	/*
3099 	 * A double click selects a word or a block.
3100 	 */
3101 	if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
3102 	{
3103 	    pos_T	*pos = NULL;
3104 	    int		gc;
3105 
3106 	    if (is_click)
3107 	    {
3108 		/* If the character under the cursor (skipping white space) is
3109 		 * not a word character, try finding a match and select a (),
3110 		 * {}, [], #if/#endif, etc. block. */
3111 		end_visual = curwin->w_cursor;
3112 		while (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))
3113 		    inc(&end_visual);
3114 		if (oap != NULL)
3115 		    oap->motion_type = MCHAR;
3116 		if (oap != NULL
3117 			&& VIsual_mode == 'v'
3118 			&& !vim_iswordc(gchar_pos(&end_visual))
3119 			&& EQUAL_POS(curwin->w_cursor, VIsual)
3120 			&& (pos = findmatch(oap, NUL)) != NULL)
3121 		{
3122 		    curwin->w_cursor = *pos;
3123 		    if (oap->motion_type == MLINE)
3124 			VIsual_mode = 'V';
3125 		    else if (*p_sel == 'e')
3126 		    {
3127 			if (LT_POS(curwin->w_cursor, VIsual))
3128 			    ++VIsual.col;
3129 			else
3130 			    ++curwin->w_cursor.col;
3131 		    }
3132 		}
3133 	    }
3134 
3135 	    if (pos == NULL && (is_click || is_drag))
3136 	    {
3137 		/* When not found a match or when dragging: extend to include
3138 		 * a word. */
3139 		if (LT_POS(curwin->w_cursor, orig_cursor))
3140 		{
3141 		    find_start_of_word(&curwin->w_cursor);
3142 		    find_end_of_word(&VIsual);
3143 		}
3144 		else
3145 		{
3146 		    find_start_of_word(&VIsual);
3147 		    if (*p_sel == 'e' && *ml_get_cursor() != NUL)
3148 #ifdef FEAT_MBYTE
3149 			curwin->w_cursor.col +=
3150 					 (*mb_ptr2len)(ml_get_cursor());
3151 #else
3152 			++curwin->w_cursor.col;
3153 #endif
3154 		    find_end_of_word(&curwin->w_cursor);
3155 		}
3156 	    }
3157 	    curwin->w_set_curswant = TRUE;
3158 	}
3159 	if (is_click)
3160 	    redraw_curbuf_later(INVERTED);	/* update the inversion */
3161     }
3162     else if (VIsual_active && !old_active)
3163     {
3164 	if (mod_mask & MOD_MASK_ALT)
3165 	    VIsual_mode = Ctrl_V;
3166 	else
3167 	    VIsual_mode = 'v';
3168     }
3169 
3170     /* If Visual mode changed show it later. */
3171     if ((!VIsual_active && old_active && mode_displayed)
3172 	    || (VIsual_active && p_smd && msg_silent == 0
3173 				 && (!old_active || VIsual_mode != old_mode)))
3174 	redraw_cmdline = TRUE;
3175 
3176     return moved;
3177 }
3178 
3179 /*
3180  * Move "pos" back to the start of the word it's in.
3181  */
3182     static void
3183 find_start_of_word(pos_T *pos)
3184 {
3185     char_u	*line;
3186     int		cclass;
3187     int		col;
3188 
3189     line = ml_get(pos->lnum);
3190     cclass = get_mouse_class(line + pos->col);
3191 
3192     while (pos->col > 0)
3193     {
3194 	col = pos->col - 1;
3195 #ifdef FEAT_MBYTE
3196 	col -= (*mb_head_off)(line, line + col);
3197 #endif
3198 	if (get_mouse_class(line + col) != cclass)
3199 	    break;
3200 	pos->col = col;
3201     }
3202 }
3203 
3204 /*
3205  * Move "pos" forward to the end of the word it's in.
3206  * When 'selection' is "exclusive", the position is just after the word.
3207  */
3208     static void
3209 find_end_of_word(pos_T *pos)
3210 {
3211     char_u	*line;
3212     int		cclass;
3213     int		col;
3214 
3215     line = ml_get(pos->lnum);
3216     if (*p_sel == 'e' && pos->col > 0)
3217     {
3218 	--pos->col;
3219 #ifdef FEAT_MBYTE
3220 	pos->col -= (*mb_head_off)(line, line + pos->col);
3221 #endif
3222     }
3223     cclass = get_mouse_class(line + pos->col);
3224     while (line[pos->col] != NUL)
3225     {
3226 #ifdef FEAT_MBYTE
3227 	col = pos->col + (*mb_ptr2len)(line + pos->col);
3228 #else
3229 	col = pos->col + 1;
3230 #endif
3231 	if (get_mouse_class(line + col) != cclass)
3232 	{
3233 	    if (*p_sel == 'e')
3234 		pos->col = col;
3235 	    break;
3236 	}
3237 	pos->col = col;
3238     }
3239 }
3240 
3241 /*
3242  * Get class of a character for selection: same class means same word.
3243  * 0: blank
3244  * 1: punctuation groups
3245  * 2: normal word character
3246  * >2: multi-byte word character.
3247  */
3248     static int
3249 get_mouse_class(char_u *p)
3250 {
3251     int		c;
3252 
3253 #ifdef FEAT_MBYTE
3254     if (has_mbyte && MB_BYTE2LEN(p[0]) > 1)
3255 	return mb_get_class(p);
3256 #endif
3257 
3258     c = *p;
3259     if (c == ' ' || c == '\t')
3260 	return 0;
3261 
3262     if (vim_iswordc(c))
3263 	return 2;
3264 
3265     /*
3266      * There are a few special cases where we want certain combinations of
3267      * characters to be considered as a single word.  These are things like
3268      * "->", "/ *", "*=", "+=", "&=", "<=", ">=", "!=" etc.  Otherwise, each
3269      * character is in its own class.
3270      */
3271     if (c != NUL && vim_strchr((char_u *)"-+*/%<>&|^!=", c) != NULL)
3272 	return 1;
3273     return c;
3274 }
3275 #endif /* FEAT_MOUSE */
3276 
3277 /*
3278  * Check if  highlighting for visual mode is possible, give a warning message
3279  * if not.
3280  */
3281     void
3282 check_visual_highlight(void)
3283 {
3284     static int	    did_check = FALSE;
3285 
3286     if (full_screen)
3287     {
3288 	if (!did_check && HL_ATTR(HLF_V) == 0)
3289 	    MSG(_("Warning: terminal cannot highlight"));
3290 	did_check = TRUE;
3291     }
3292 }
3293 
3294 /*
3295  * End Visual mode.
3296  * This function should ALWAYS be called to end Visual mode, except from
3297  * do_pending_operator().
3298  */
3299     void
3300 end_visual_mode(void)
3301 {
3302 #ifdef FEAT_CLIPBOARD
3303     /*
3304      * If we are using the clipboard, then remember what was selected in case
3305      * we need to paste it somewhere while we still own the selection.
3306      * Only do this when the clipboard is already owned.  Don't want to grab
3307      * the selection when hitting ESC.
3308      */
3309     if (clip_star.available && clip_star.owned)
3310 	clip_auto_select();
3311 #endif
3312 
3313     VIsual_active = FALSE;
3314 #ifdef FEAT_MOUSE
3315     setmouse();
3316     mouse_dragging = 0;
3317 #endif
3318 
3319     /* Save the current VIsual area for '< and '> marks, and "gv" */
3320     curbuf->b_visual.vi_mode = VIsual_mode;
3321     curbuf->b_visual.vi_start = VIsual;
3322     curbuf->b_visual.vi_end = curwin->w_cursor;
3323     curbuf->b_visual.vi_curswant = curwin->w_curswant;
3324 #ifdef FEAT_EVAL
3325     curbuf->b_visual_mode_eval = VIsual_mode;
3326 #endif
3327 #ifdef FEAT_VIRTUALEDIT
3328     if (!virtual_active())
3329 	curwin->w_cursor.coladd = 0;
3330 #endif
3331     may_clear_cmdline();
3332 
3333     adjust_cursor_eol();
3334 }
3335 
3336 /*
3337  * Reset VIsual_active and VIsual_reselect.
3338  */
3339     void
3340 reset_VIsual_and_resel(void)
3341 {
3342     if (VIsual_active)
3343     {
3344 	end_visual_mode();
3345 	redraw_curbuf_later(INVERTED);	/* delete the inversion later */
3346     }
3347     VIsual_reselect = FALSE;
3348 }
3349 
3350 /*
3351  * Reset VIsual_active and VIsual_reselect if it's set.
3352  */
3353     void
3354 reset_VIsual(void)
3355 {
3356     if (VIsual_active)
3357     {
3358 	end_visual_mode();
3359 	redraw_curbuf_later(INVERTED);	/* delete the inversion later */
3360 	VIsual_reselect = FALSE;
3361     }
3362 }
3363 
3364 /*
3365  * Check for a balloon-eval special item to include when searching for an
3366  * identifier.  When "dir" is BACKWARD "ptr[-1]" must be valid!
3367  * Returns TRUE if the character at "*ptr" should be included.
3368  * "dir" is FORWARD or BACKWARD, the direction of searching.
3369  * "*colp" is in/decremented if "ptr[-dir]" should also be included.
3370  * "bnp" points to a counter for square brackets.
3371  */
3372     static int
3373 find_is_eval_item(
3374     char_u	*ptr,
3375     int		*colp,
3376     int		*bnp,
3377     int		dir)
3378 {
3379     /* Accept everything inside []. */
3380     if ((*ptr == ']' && dir == BACKWARD) || (*ptr == '[' && dir == FORWARD))
3381 	++*bnp;
3382     if (*bnp > 0)
3383     {
3384 	if ((*ptr == '[' && dir == BACKWARD) || (*ptr == ']' && dir == FORWARD))
3385 	    --*bnp;
3386 	return TRUE;
3387     }
3388 
3389     /* skip over "s.var" */
3390     if (*ptr == '.')
3391 	return TRUE;
3392 
3393     /* two-character item: s->var */
3394     if (ptr[dir == BACKWARD ? 0 : 1] == '>'
3395 	    && ptr[dir == BACKWARD ? -1 : 0] == '-')
3396     {
3397 	*colp += dir;
3398 	return TRUE;
3399     }
3400     return FALSE;
3401 }
3402 
3403 /*
3404  * Find the identifier under or to the right of the cursor.
3405  * "find_type" can have one of three values:
3406  * FIND_IDENT:   find an identifier (keyword)
3407  * FIND_STRING:  find any non-white string
3408  * FIND_IDENT + FIND_STRING: find any non-white string, identifier preferred.
3409  * FIND_EVAL:	 find text useful for C program debugging
3410  *
3411  * There are three steps:
3412  * 1. Search forward for the start of an identifier/string.  Doesn't move if
3413  *    already on one.
3414  * 2. Search backward for the start of this identifier/string.
3415  *    This doesn't match the real Vi but I like it a little better and it
3416  *    shouldn't bother anyone.
3417  * 3. Search forward to the end of this identifier/string.
3418  *    When FIND_IDENT isn't defined, we backup until a blank.
3419  *
3420  * Returns the length of the string, or zero if no string is found.
3421  * If a string is found, a pointer to the string is put in "*string".  This
3422  * string is not always NUL terminated.
3423  */
3424     int
3425 find_ident_under_cursor(char_u **string, int find_type)
3426 {
3427     return find_ident_at_pos(curwin, curwin->w_cursor.lnum,
3428 				     curwin->w_cursor.col, string, find_type);
3429 }
3430 
3431 /*
3432  * Like find_ident_under_cursor(), but for any window and any position.
3433  * However: Uses 'iskeyword' from the current window!.
3434  */
3435     int
3436 find_ident_at_pos(
3437     win_T	*wp,
3438     linenr_T	lnum,
3439     colnr_T	startcol,
3440     char_u	**string,
3441     int		find_type)
3442 {
3443     char_u	*ptr;
3444     int		col = 0;	    /* init to shut up GCC */
3445     int		i;
3446 #ifdef FEAT_MBYTE
3447     int		this_class = 0;
3448     int		prev_class;
3449     int		prevcol;
3450 #endif
3451     int		bn = 0;	    /* bracket nesting */
3452 
3453     /*
3454      * if i == 0: try to find an identifier
3455      * if i == 1: try to find any non-white string
3456      */
3457     ptr = ml_get_buf(wp->w_buffer, lnum, FALSE);
3458     for (i = (find_type & FIND_IDENT) ? 0 : 1;	i < 2; ++i)
3459     {
3460 	/*
3461 	 * 1. skip to start of identifier/string
3462 	 */
3463 	col = startcol;
3464 #ifdef FEAT_MBYTE
3465 	if (has_mbyte)
3466 	{
3467 	    while (ptr[col] != NUL)
3468 	    {
3469 		/* Stop at a ']' to evaluate "a[x]". */
3470 		if ((find_type & FIND_EVAL) && ptr[col] == ']')
3471 		    break;
3472 		this_class = mb_get_class(ptr + col);
3473 		if (this_class != 0 && (i == 1 || this_class != 1))
3474 		    break;
3475 		col += (*mb_ptr2len)(ptr + col);
3476 	    }
3477 	}
3478 	else
3479 #endif
3480 	    while (ptr[col] != NUL
3481 		    && (i == 0 ? !vim_iswordc(ptr[col]) : VIM_ISWHITE(ptr[col]))
3482 		    && (!(find_type & FIND_EVAL) || ptr[col] != ']')
3483 		    )
3484 		++col;
3485 
3486 	/* When starting on a ']' count it, so that we include the '['. */
3487 	bn = ptr[col] == ']';
3488 
3489 	/*
3490 	 * 2. Back up to start of identifier/string.
3491 	 */
3492 #ifdef FEAT_MBYTE
3493 	if (has_mbyte)
3494 	{
3495 	    /* Remember class of character under cursor. */
3496 	    if ((find_type & FIND_EVAL) && ptr[col] == ']')
3497 		this_class = mb_get_class((char_u *)"a");
3498 	    else
3499 		this_class = mb_get_class(ptr + col);
3500 	    while (col > 0 && this_class != 0)
3501 	    {
3502 		prevcol = col - 1 - (*mb_head_off)(ptr, ptr + col - 1);
3503 		prev_class = mb_get_class(ptr + prevcol);
3504 		if (this_class != prev_class
3505 			&& (i == 0
3506 			    || prev_class == 0
3507 			    || (find_type & FIND_IDENT))
3508 			&& (!(find_type & FIND_EVAL)
3509 			    || prevcol == 0
3510 			    || !find_is_eval_item(ptr + prevcol, &prevcol,
3511 							       &bn, BACKWARD))
3512 			)
3513 		    break;
3514 		col = prevcol;
3515 	    }
3516 
3517 	    /* If we don't want just any old string, or we've found an
3518 	     * identifier, stop searching. */
3519 	    if (this_class > 2)
3520 		this_class = 2;
3521 	    if (!(find_type & FIND_STRING) || this_class == 2)
3522 		break;
3523 	}
3524 	else
3525 #endif
3526 	{
3527 	    while (col > 0
3528 		    && ((i == 0
3529 			    ? vim_iswordc(ptr[col - 1])
3530 			    : (!VIM_ISWHITE(ptr[col - 1])
3531 				&& (!(find_type & FIND_IDENT)
3532 				    || !vim_iswordc(ptr[col - 1]))))
3533 			|| ((find_type & FIND_EVAL)
3534 			    && col > 1
3535 			    && find_is_eval_item(ptr + col - 1, &col,
3536 							       &bn, BACKWARD))
3537 			))
3538 		--col;
3539 
3540 	    /* If we don't want just any old string, or we've found an
3541 	     * identifier, stop searching. */
3542 	    if (!(find_type & FIND_STRING) || vim_iswordc(ptr[col]))
3543 		break;
3544 	}
3545     }
3546 
3547     if (ptr[col] == NUL || (i == 0 && (
3548 #ifdef FEAT_MBYTE
3549 		has_mbyte ? this_class != 2 :
3550 #endif
3551 		!vim_iswordc(ptr[col]))))
3552     {
3553 	/*
3554 	 * didn't find an identifier or string
3555 	 */
3556 	if (find_type & FIND_STRING)
3557 	    EMSG(_("E348: No string under cursor"));
3558 	else
3559 	    EMSG(_(e_noident));
3560 	return 0;
3561     }
3562     ptr += col;
3563     *string = ptr;
3564 
3565     /*
3566      * 3. Find the end if the identifier/string.
3567      */
3568     bn = 0;
3569     startcol -= col;
3570     col = 0;
3571 #ifdef FEAT_MBYTE
3572     if (has_mbyte)
3573     {
3574 	/* Search for point of changing multibyte character class. */
3575 	this_class = mb_get_class(ptr);
3576 	while (ptr[col] != NUL
3577 		&& ((i == 0 ? mb_get_class(ptr + col) == this_class
3578 			    : mb_get_class(ptr + col) != 0)
3579 		    || ((find_type & FIND_EVAL)
3580 			&& col <= (int)startcol
3581 			&& find_is_eval_item(ptr + col, &col, &bn, FORWARD))
3582 		))
3583 	    col += (*mb_ptr2len)(ptr + col);
3584     }
3585     else
3586 #endif
3587 	while ((i == 0 ? vim_iswordc(ptr[col])
3588 		       : (ptr[col] != NUL && !VIM_ISWHITE(ptr[col])))
3589 		    || ((find_type & FIND_EVAL)
3590 			&& col <= (int)startcol
3591 			&& find_is_eval_item(ptr + col, &col, &bn, FORWARD))
3592 		)
3593 	{
3594 	    ++col;
3595 	}
3596 
3597     return col;
3598 }
3599 
3600 /*
3601  * Prepare for redo of a normal command.
3602  */
3603     static void
3604 prep_redo_cmd(cmdarg_T *cap)
3605 {
3606     prep_redo(cap->oap->regname, cap->count0,
3607 				     NUL, cap->cmdchar, NUL, NUL, cap->nchar);
3608 }
3609 
3610 /*
3611  * Prepare for redo of any command.
3612  * Note that only the last argument can be a multi-byte char.
3613  */
3614     static void
3615 prep_redo(
3616     int	    regname,
3617     long    num,
3618     int	    cmd1,
3619     int	    cmd2,
3620     int	    cmd3,
3621     int	    cmd4,
3622     int	    cmd5)
3623 {
3624     ResetRedobuff();
3625     if (regname != 0)	/* yank from specified buffer */
3626     {
3627 	AppendCharToRedobuff('"');
3628 	AppendCharToRedobuff(regname);
3629     }
3630     if (num)
3631 	AppendNumberToRedobuff(num);
3632 
3633     if (cmd1 != NUL)
3634 	AppendCharToRedobuff(cmd1);
3635     if (cmd2 != NUL)
3636 	AppendCharToRedobuff(cmd2);
3637     if (cmd3 != NUL)
3638 	AppendCharToRedobuff(cmd3);
3639     if (cmd4 != NUL)
3640 	AppendCharToRedobuff(cmd4);
3641     if (cmd5 != NUL)
3642 	AppendCharToRedobuff(cmd5);
3643 }
3644 
3645 /*
3646  * check for operator active and clear it
3647  *
3648  * return TRUE if operator was active
3649  */
3650     static int
3651 checkclearop(oparg_T *oap)
3652 {
3653     if (oap->op_type == OP_NOP)
3654 	return FALSE;
3655     clearopbeep(oap);
3656     return TRUE;
3657 }
3658 
3659 /*
3660  * Check for operator or Visual active.  Clear active operator.
3661  *
3662  * Return TRUE if operator or Visual was active.
3663  */
3664     static int
3665 checkclearopq(oparg_T *oap)
3666 {
3667     if (oap->op_type == OP_NOP && !VIsual_active)
3668 	return FALSE;
3669     clearopbeep(oap);
3670     return TRUE;
3671 }
3672 
3673     static void
3674 clearop(oparg_T *oap)
3675 {
3676     oap->op_type = OP_NOP;
3677     oap->regname = 0;
3678     oap->motion_force = NUL;
3679     oap->use_reg_one = FALSE;
3680 }
3681 
3682     static void
3683 clearopbeep(oparg_T *oap)
3684 {
3685     clearop(oap);
3686     beep_flush();
3687 }
3688 
3689 /*
3690  * Remove the shift modifier from a special key.
3691  */
3692     static void
3693 unshift_special(cmdarg_T *cap)
3694 {
3695     switch (cap->cmdchar)
3696     {
3697 	case K_S_RIGHT:	cap->cmdchar = K_RIGHT; break;
3698 	case K_S_LEFT:	cap->cmdchar = K_LEFT; break;
3699 	case K_S_UP:	cap->cmdchar = K_UP; break;
3700 	case K_S_DOWN:	cap->cmdchar = K_DOWN; break;
3701 	case K_S_HOME:	cap->cmdchar = K_HOME; break;
3702 	case K_S_END:	cap->cmdchar = K_END; break;
3703     }
3704     cap->cmdchar = simplify_key(cap->cmdchar, &mod_mask);
3705 }
3706 
3707 /*
3708  * If the mode is currently displayed clear the command line or update the
3709  * command displayed.
3710  */
3711     static void
3712 may_clear_cmdline(void)
3713 {
3714     if (mode_displayed)
3715 	clear_cmdline = TRUE;   /* unshow visual mode later */
3716 #ifdef FEAT_CMDL_INFO
3717     else
3718 	clear_showcmd();
3719 #endif
3720 }
3721 
3722 #if defined(FEAT_CMDL_INFO) || defined(PROTO)
3723 /*
3724  * Routines for displaying a partly typed command
3725  */
3726 
3727 #define SHOWCMD_BUFLEN SHOWCMD_COLS + 1 + 30
3728 static char_u	showcmd_buf[SHOWCMD_BUFLEN];
3729 static char_u	old_showcmd_buf[SHOWCMD_BUFLEN];  /* For push_showcmd() */
3730 static int	showcmd_is_clear = TRUE;
3731 static int	showcmd_visual = FALSE;
3732 
3733 static void display_showcmd(void);
3734 
3735     void
3736 clear_showcmd(void)
3737 {
3738     if (!p_sc)
3739 	return;
3740 
3741     if (VIsual_active && !char_avail())
3742     {
3743 	int		cursor_bot = LT_POS(VIsual, curwin->w_cursor);
3744 	long		lines;
3745 	colnr_T		leftcol, rightcol;
3746 	linenr_T	top, bot;
3747 
3748 	/* Show the size of the Visual area. */
3749 	if (cursor_bot)
3750 	{
3751 	    top = VIsual.lnum;
3752 	    bot = curwin->w_cursor.lnum;
3753 	}
3754 	else
3755 	{
3756 	    top = curwin->w_cursor.lnum;
3757 	    bot = VIsual.lnum;
3758 	}
3759 # ifdef FEAT_FOLDING
3760 	/* Include closed folds as a whole. */
3761 	(void)hasFolding(top, &top, NULL);
3762 	(void)hasFolding(bot, NULL, &bot);
3763 # endif
3764 	lines = bot - top + 1;
3765 
3766 	if (VIsual_mode == Ctrl_V)
3767 	{
3768 # ifdef FEAT_LINEBREAK
3769 	    char_u *saved_sbr = p_sbr;
3770 
3771 	    /* Make 'sbr' empty for a moment to get the correct size. */
3772 	    p_sbr = empty_option;
3773 # endif
3774 	    getvcols(curwin, &curwin->w_cursor, &VIsual, &leftcol, &rightcol);
3775 # ifdef FEAT_LINEBREAK
3776 	    p_sbr = saved_sbr;
3777 # endif
3778 	    sprintf((char *)showcmd_buf, "%ldx%ld", lines,
3779 					      (long)(rightcol - leftcol + 1));
3780 	}
3781 	else if (VIsual_mode == 'V' || VIsual.lnum != curwin->w_cursor.lnum)
3782 	    sprintf((char *)showcmd_buf, "%ld", lines);
3783 	else
3784 	{
3785 	    char_u  *s, *e;
3786 	    int	    l;
3787 	    int	    bytes = 0;
3788 	    int	    chars = 0;
3789 
3790 	    if (cursor_bot)
3791 	    {
3792 		s = ml_get_pos(&VIsual);
3793 		e = ml_get_cursor();
3794 	    }
3795 	    else
3796 	    {
3797 		s = ml_get_cursor();
3798 		e = ml_get_pos(&VIsual);
3799 	    }
3800 	    while ((*p_sel != 'e') ? s <= e : s < e)
3801 	    {
3802 # ifdef FEAT_MBYTE
3803 		l = (*mb_ptr2len)(s);
3804 # else
3805 		l = (*s == NUL) ? 0 : 1;
3806 # endif
3807 		if (l == 0)
3808 		{
3809 		    ++bytes;
3810 		    ++chars;
3811 		    break;  /* end of line */
3812 		}
3813 		bytes += l;
3814 		++chars;
3815 		s += l;
3816 	    }
3817 	    if (bytes == chars)
3818 		sprintf((char *)showcmd_buf, "%d", chars);
3819 	    else
3820 		sprintf((char *)showcmd_buf, "%d-%d", chars, bytes);
3821 	}
3822 	showcmd_buf[SHOWCMD_COLS] = NUL;	/* truncate */
3823 	showcmd_visual = TRUE;
3824     }
3825     else
3826     {
3827 	showcmd_buf[0] = NUL;
3828 	showcmd_visual = FALSE;
3829 
3830 	/* Don't actually display something if there is nothing to clear. */
3831 	if (showcmd_is_clear)
3832 	    return;
3833     }
3834 
3835     display_showcmd();
3836 }
3837 
3838 /*
3839  * Add 'c' to string of shown command chars.
3840  * Return TRUE if output has been written (and setcursor() has been called).
3841  */
3842     int
3843 add_to_showcmd(int c)
3844 {
3845     char_u	*p;
3846     int		old_len;
3847     int		extra_len;
3848     int		overflow;
3849 #if defined(FEAT_MOUSE)
3850     int		i;
3851     static int	ignore[] =
3852     {
3853 # ifdef FEAT_GUI
3854 	K_VER_SCROLLBAR, K_HOR_SCROLLBAR,
3855 	K_LEFTMOUSE_NM, K_LEFTRELEASE_NM,
3856 # endif
3857 	K_IGNORE, K_PS,
3858 	K_LEFTMOUSE, K_LEFTDRAG, K_LEFTRELEASE, K_MOUSEMOVE,
3859 	K_MIDDLEMOUSE, K_MIDDLEDRAG, K_MIDDLERELEASE,
3860 	K_RIGHTMOUSE, K_RIGHTDRAG, K_RIGHTRELEASE,
3861 	K_MOUSEDOWN, K_MOUSEUP, K_MOUSELEFT, K_MOUSERIGHT,
3862 	K_X1MOUSE, K_X1DRAG, K_X1RELEASE, K_X2MOUSE, K_X2DRAG, K_X2RELEASE,
3863 	K_CURSORHOLD,
3864 	0
3865     };
3866 #endif
3867 
3868     if (!p_sc || msg_silent != 0)
3869 	return FALSE;
3870 
3871     if (showcmd_visual)
3872     {
3873 	showcmd_buf[0] = NUL;
3874 	showcmd_visual = FALSE;
3875     }
3876 
3877 #if defined(FEAT_MOUSE)
3878     /* Ignore keys that are scrollbar updates and mouse clicks */
3879     if (IS_SPECIAL(c))
3880 	for (i = 0; ignore[i] != 0; ++i)
3881 	    if (ignore[i] == c)
3882 		return FALSE;
3883 #endif
3884 
3885     p = transchar(c);
3886     if (*p == ' ')
3887 	STRCPY(p, "<20>");
3888     old_len = (int)STRLEN(showcmd_buf);
3889     extra_len = (int)STRLEN(p);
3890     overflow = old_len + extra_len - SHOWCMD_COLS;
3891     if (overflow > 0)
3892 	mch_memmove(showcmd_buf, showcmd_buf + overflow,
3893 						      old_len - overflow + 1);
3894     STRCAT(showcmd_buf, p);
3895 
3896     if (char_avail())
3897 	return FALSE;
3898 
3899     display_showcmd();
3900 
3901     return TRUE;
3902 }
3903 
3904     void
3905 add_to_showcmd_c(int c)
3906 {
3907     if (!add_to_showcmd(c))
3908 	setcursor();
3909 }
3910 
3911 /*
3912  * Delete 'len' characters from the end of the shown command.
3913  */
3914     static void
3915 del_from_showcmd(int len)
3916 {
3917     int	    old_len;
3918 
3919     if (!p_sc)
3920 	return;
3921 
3922     old_len = (int)STRLEN(showcmd_buf);
3923     if (len > old_len)
3924 	len = old_len;
3925     showcmd_buf[old_len - len] = NUL;
3926 
3927     if (!char_avail())
3928 	display_showcmd();
3929 }
3930 
3931 /*
3932  * push_showcmd() and pop_showcmd() are used when waiting for the user to type
3933  * something and there is a partial mapping.
3934  */
3935     void
3936 push_showcmd(void)
3937 {
3938     if (p_sc)
3939 	STRCPY(old_showcmd_buf, showcmd_buf);
3940 }
3941 
3942     void
3943 pop_showcmd(void)
3944 {
3945     if (!p_sc)
3946 	return;
3947 
3948     STRCPY(showcmd_buf, old_showcmd_buf);
3949 
3950     display_showcmd();
3951 }
3952 
3953     static void
3954 display_showcmd(void)
3955 {
3956     int	    len;
3957 
3958     cursor_off();
3959 
3960     len = (int)STRLEN(showcmd_buf);
3961     if (len == 0)
3962 	showcmd_is_clear = TRUE;
3963     else
3964     {
3965 	screen_puts(showcmd_buf, (int)Rows - 1, sc_col, 0);
3966 	showcmd_is_clear = FALSE;
3967     }
3968 
3969     /*
3970      * clear the rest of an old message by outputting up to SHOWCMD_COLS
3971      * spaces
3972      */
3973     screen_puts((char_u *)"          " + len, (int)Rows - 1, sc_col + len, 0);
3974 
3975     setcursor();	    /* put cursor back where it belongs */
3976 }
3977 #endif
3978 
3979 /*
3980  * When "check" is FALSE, prepare for commands that scroll the window.
3981  * When "check" is TRUE, take care of scroll-binding after the window has
3982  * scrolled.  Called from normal_cmd() and edit().
3983  */
3984     void
3985 do_check_scrollbind(int check)
3986 {
3987     static win_T	*old_curwin = NULL;
3988     static linenr_T	old_topline = 0;
3989 #ifdef FEAT_DIFF
3990     static int		old_topfill = 0;
3991 #endif
3992     static buf_T	*old_buf = NULL;
3993     static colnr_T	old_leftcol = 0;
3994 
3995     if (check && curwin->w_p_scb)
3996     {
3997 	/* If a ":syncbind" command was just used, don't scroll, only reset
3998 	 * the values. */
3999 	if (did_syncbind)
4000 	    did_syncbind = FALSE;
4001 	else if (curwin == old_curwin)
4002 	{
4003 	    /*
4004 	     * Synchronize other windows, as necessary according to
4005 	     * 'scrollbind'.  Don't do this after an ":edit" command, except
4006 	     * when 'diff' is set.
4007 	     */
4008 	    if ((curwin->w_buffer == old_buf
4009 #ifdef FEAT_DIFF
4010 			|| curwin->w_p_diff
4011 #endif
4012 		)
4013 		&& (curwin->w_topline != old_topline
4014 #ifdef FEAT_DIFF
4015 			|| curwin->w_topfill != old_topfill
4016 #endif
4017 			|| curwin->w_leftcol != old_leftcol))
4018 	    {
4019 		check_scrollbind(curwin->w_topline - old_topline,
4020 			(long)(curwin->w_leftcol - old_leftcol));
4021 	    }
4022 	}
4023 	else if (vim_strchr(p_sbo, 'j')) /* jump flag set in 'scrollopt' */
4024 	{
4025 	    /*
4026 	     * When switching between windows, make sure that the relative
4027 	     * vertical offset is valid for the new window.  The relative
4028 	     * offset is invalid whenever another 'scrollbind' window has
4029 	     * scrolled to a point that would force the current window to
4030 	     * scroll past the beginning or end of its buffer.  When the
4031 	     * resync is performed, some of the other 'scrollbind' windows may
4032 	     * need to jump so that the current window's relative position is
4033 	     * visible on-screen.
4034 	     */
4035 	    check_scrollbind(curwin->w_topline - curwin->w_scbind_pos, 0L);
4036 	}
4037 	curwin->w_scbind_pos = curwin->w_topline;
4038     }
4039 
4040     old_curwin = curwin;
4041     old_topline = curwin->w_topline;
4042 #ifdef FEAT_DIFF
4043     old_topfill = curwin->w_topfill;
4044 #endif
4045     old_buf = curwin->w_buffer;
4046     old_leftcol = curwin->w_leftcol;
4047 }
4048 
4049 /*
4050  * Synchronize any windows that have "scrollbind" set, based on the
4051  * number of rows by which the current window has changed
4052  * (1998-11-02 16:21:01  R. Edward Ralston <[email protected]>)
4053  */
4054     void
4055 check_scrollbind(linenr_T topline_diff, long leftcol_diff)
4056 {
4057     int		want_ver;
4058     int		want_hor;
4059     win_T	*old_curwin = curwin;
4060     buf_T	*old_curbuf = curbuf;
4061     int		old_VIsual_select = VIsual_select;
4062     int		old_VIsual_active = VIsual_active;
4063     colnr_T	tgt_leftcol = curwin->w_leftcol;
4064     long	topline;
4065     long	y;
4066 
4067     /*
4068      * check 'scrollopt' string for vertical and horizontal scroll options
4069      */
4070     want_ver = (vim_strchr(p_sbo, 'v') && topline_diff != 0);
4071 #ifdef FEAT_DIFF
4072     want_ver |= old_curwin->w_p_diff;
4073 #endif
4074     want_hor = (vim_strchr(p_sbo, 'h') && (leftcol_diff || topline_diff != 0));
4075 
4076     /*
4077      * loop through the scrollbound windows and scroll accordingly
4078      */
4079     VIsual_select = VIsual_active = 0;
4080     FOR_ALL_WINDOWS(curwin)
4081     {
4082 	curbuf = curwin->w_buffer;
4083 	/* skip original window  and windows with 'noscrollbind' */
4084 	if (curwin != old_curwin && curwin->w_p_scb)
4085 	{
4086 	    /*
4087 	     * do the vertical scroll
4088 	     */
4089 	    if (want_ver)
4090 	    {
4091 #ifdef FEAT_DIFF
4092 		if (old_curwin->w_p_diff && curwin->w_p_diff)
4093 		{
4094 		    diff_set_topline(old_curwin, curwin);
4095 		}
4096 		else
4097 #endif
4098 		{
4099 		    curwin->w_scbind_pos += topline_diff;
4100 		    topline = curwin->w_scbind_pos;
4101 		    if (topline > curbuf->b_ml.ml_line_count)
4102 			topline = curbuf->b_ml.ml_line_count;
4103 		    if (topline < 1)
4104 			topline = 1;
4105 
4106 		    y = topline - curwin->w_topline;
4107 		    if (y > 0)
4108 			scrollup(y, FALSE);
4109 		    else
4110 			scrolldown(-y, FALSE);
4111 		}
4112 
4113 		redraw_later(VALID);
4114 		cursor_correct();
4115 		curwin->w_redr_status = TRUE;
4116 	    }
4117 
4118 	    /*
4119 	     * do the horizontal scroll
4120 	     */
4121 	    if (want_hor && curwin->w_leftcol != tgt_leftcol)
4122 	    {
4123 		curwin->w_leftcol = tgt_leftcol;
4124 		leftcol_changed();
4125 	    }
4126 	}
4127     }
4128 
4129     /*
4130      * reset current-window
4131      */
4132     VIsual_select = old_VIsual_select;
4133     VIsual_active = old_VIsual_active;
4134     curwin = old_curwin;
4135     curbuf = old_curbuf;
4136 }
4137 
4138 /*
4139  * Command character that's ignored.
4140  * Used for CTRL-Q and CTRL-S to avoid problems with terminals that use
4141  * xon/xoff.
4142  */
4143     static void
4144 nv_ignore(cmdarg_T *cap)
4145 {
4146     cap->retval |= CA_COMMAND_BUSY;	/* don't call edit() now */
4147 }
4148 
4149 /*
4150  * Command character that doesn't do anything, but unlike nv_ignore() does
4151  * start edit().  Used for "startinsert" executed while starting up.
4152  */
4153     static void
4154 nv_nop(cmdarg_T *cap UNUSED)
4155 {
4156 }
4157 
4158 /*
4159  * Command character doesn't exist.
4160  */
4161     static void
4162 nv_error(cmdarg_T *cap)
4163 {
4164     clearopbeep(cap->oap);
4165 }
4166 
4167 /*
4168  * <Help> and <F1> commands.
4169  */
4170     static void
4171 nv_help(cmdarg_T *cap)
4172 {
4173     if (!checkclearopq(cap->oap))
4174 	ex_help(NULL);
4175 }
4176 
4177 /*
4178  * CTRL-A and CTRL-X: Add or subtract from letter or number under cursor.
4179  */
4180     static void
4181 nv_addsub(cmdarg_T *cap)
4182 {
4183 #ifdef FEAT_JOB_CHANNEL
4184     if (bt_prompt(curbuf) && !prompt_curpos_editable())
4185 	clearopbeep(cap->oap);
4186     else
4187 #endif
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 #if defined(FEAT_QUICKFIX)
6204     /* Quickfix window only: view the result under the cursor. */
6205     else if (bt_quickfix(curbuf) && cap->cmdchar == CAR)
6206 	qf_view_result(FALSE);
6207 #endif
6208     else
6209     {
6210 #ifdef FEAT_CMDWIN
6211 	/* In the cmdline window a <CR> executes the command. */
6212 	if (cmdwin_type != 0 && cap->cmdchar == CAR)
6213 	    cmdwin_result = CAR;
6214 	else
6215 #endif
6216 #ifdef FEAT_JOB_CHANNEL
6217 	/* In a prompt buffer a <CR> in the last line invokes the callback. */
6218 	if (bt_prompt(curbuf) && cap->cmdchar == CAR
6219 		       && curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
6220 	{
6221 	    invoke_prompt_callback();
6222 	    if (restart_edit == 0)
6223 		restart_edit = 'a';
6224 	}
6225 	else
6226 #endif
6227 	{
6228 	    cap->oap->motion_type = MLINE;
6229 	    if (cursor_down(cap->count1, cap->oap->op_type == OP_NOP) == FAIL)
6230 		clearopbeep(cap->oap);
6231 	    else if (cap->arg)
6232 		beginline(BL_WHITE | BL_FIX);
6233 	}
6234     }
6235 }
6236 
6237 #ifdef FEAT_SEARCHPATH
6238 /*
6239  * Grab the file name under the cursor and edit it.
6240  */
6241     static void
6242 nv_gotofile(cmdarg_T *cap)
6243 {
6244     char_u	*ptr;
6245     linenr_T	lnum = -1;
6246 
6247     if (text_locked())
6248     {
6249 	clearopbeep(cap->oap);
6250 	text_locked_msg();
6251 	return;
6252     }
6253     if (curbuf_locked())
6254     {
6255 	clearop(cap->oap);
6256 	return;
6257     }
6258 
6259     ptr = grab_file_name(cap->count1, &lnum);
6260 
6261     if (ptr != NULL)
6262     {
6263 	/* do autowrite if necessary */
6264 	if (curbufIsChanged() && curbuf->b_nwindows <= 1 && !buf_hide(curbuf))
6265 	    (void)autowrite(curbuf, FALSE);
6266 	setpcmark();
6267 	if (do_ecmd(0, ptr, NULL, NULL, ECMD_LAST,
6268 				buf_hide(curbuf) ? ECMD_HIDE : 0, curwin) == OK
6269 		&& cap->nchar == 'F' && lnum >= 0)
6270 	{
6271 	    curwin->w_cursor.lnum = lnum;
6272 	    check_cursor_lnum();
6273 	    beginline(BL_SOL | BL_FIX);
6274 	}
6275 	vim_free(ptr);
6276     }
6277     else
6278 	clearop(cap->oap);
6279 }
6280 #endif
6281 
6282 /*
6283  * <End> command: to end of current line or last line.
6284  */
6285     static void
6286 nv_end(cmdarg_T *cap)
6287 {
6288     if (cap->arg || (mod_mask & MOD_MASK_CTRL))	/* CTRL-END = goto last line */
6289     {
6290 	cap->arg = TRUE;
6291 	nv_goto(cap);
6292 	cap->count1 = 1;		/* to end of current line */
6293     }
6294     nv_dollar(cap);
6295 }
6296 
6297 /*
6298  * Handle the "$" command.
6299  */
6300     static void
6301 nv_dollar(cmdarg_T *cap)
6302 {
6303     cap->oap->motion_type = MCHAR;
6304     cap->oap->inclusive = TRUE;
6305 #ifdef FEAT_VIRTUALEDIT
6306     /* In virtual mode when off the edge of a line and an operator
6307      * is pending (whew!) keep the cursor where it is.
6308      * Otherwise, send it to the end of the line. */
6309     if (!virtual_active() || gchar_cursor() != NUL
6310 					       || cap->oap->op_type == OP_NOP)
6311 #endif
6312 	curwin->w_curswant = MAXCOL;	/* so we stay at the end */
6313     if (cursor_down((long)(cap->count1 - 1),
6314 					 cap->oap->op_type == OP_NOP) == FAIL)
6315 	clearopbeep(cap->oap);
6316 #ifdef FEAT_FOLDING
6317     else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6318 	foldOpenCursor();
6319 #endif
6320 }
6321 
6322 /*
6323  * Implementation of '?' and '/' commands.
6324  * If cap->arg is TRUE don't set PC mark.
6325  */
6326     static void
6327 nv_search(cmdarg_T *cap)
6328 {
6329     oparg_T	*oap = cap->oap;
6330     pos_T	save_cursor = curwin->w_cursor;
6331 
6332     if (cap->cmdchar == '?' && cap->oap->op_type == OP_ROT13)
6333     {
6334 	/* Translate "g??" to "g?g?" */
6335 	cap->cmdchar = 'g';
6336 	cap->nchar = '?';
6337 	nv_operator(cap);
6338 	return;
6339     }
6340 
6341     /* When using 'incsearch' the cursor may be moved to set a different search
6342      * start position. */
6343     cap->searchbuf = getcmdline(cap->cmdchar, cap->count1, 0);
6344 
6345     if (cap->searchbuf == NULL)
6346     {
6347 	clearop(oap);
6348 	return;
6349     }
6350 
6351     (void)normal_search(cap, cap->cmdchar, cap->searchbuf,
6352 			(cap->arg || !EQUAL_POS(save_cursor, curwin->w_cursor))
6353 							   ? 0 : SEARCH_MARK);
6354 }
6355 
6356 /*
6357  * Handle "N" and "n" commands.
6358  * cap->arg is SEARCH_REV for "N", 0 for "n".
6359  */
6360     static void
6361 nv_next(cmdarg_T *cap)
6362 {
6363     pos_T old = curwin->w_cursor;
6364     int   i = normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg);
6365 
6366     if (i == 1 && EQUAL_POS(old, curwin->w_cursor))
6367     {
6368 	/* Avoid getting stuck on the current cursor position, which can
6369 	 * happen when an offset is given and the cursor is on the last char
6370 	 * in the buffer: Repeat with count + 1. */
6371 	cap->count1 += 1;
6372 	(void)normal_search(cap, 0, NULL, SEARCH_MARK | cap->arg);
6373 	cap->count1 -= 1;
6374     }
6375 }
6376 
6377 /*
6378  * Search for "pat" in direction "dir" ('/' or '?', 0 for repeat).
6379  * Uses only cap->count1 and cap->oap from "cap".
6380  * Return 0 for failure, 1 for found, 2 for found and line offset added.
6381  */
6382     static int
6383 normal_search(
6384     cmdarg_T	*cap,
6385     int		dir,
6386     char_u	*pat,
6387     int		opt)		/* extra flags for do_search() */
6388 {
6389     int		i;
6390 
6391     cap->oap->motion_type = MCHAR;
6392     cap->oap->inclusive = FALSE;
6393     cap->oap->use_reg_one = TRUE;
6394     curwin->w_set_curswant = TRUE;
6395 
6396     i = do_search(cap->oap, dir, pat, cap->count1,
6397 		      opt | SEARCH_OPT | SEARCH_ECHO | SEARCH_MSG, NULL, NULL);
6398     if (i == 0)
6399 	clearop(cap->oap);
6400     else
6401     {
6402 	if (i == 2)
6403 	    cap->oap->motion_type = MLINE;
6404 #ifdef FEAT_VIRTUALEDIT
6405 	curwin->w_cursor.coladd = 0;
6406 #endif
6407 #ifdef FEAT_FOLDING
6408 	if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
6409 	    foldOpenCursor();
6410 #endif
6411     }
6412 
6413     /* "/$" will put the cursor after the end of the line, may need to
6414      * correct that here */
6415     check_cursor();
6416     return i;
6417 }
6418 
6419 /*
6420  * Character search commands.
6421  * cap->arg is BACKWARD for 'F' and 'T', FORWARD for 'f' and 't', TRUE for
6422  * ',' and FALSE for ';'.
6423  * cap->nchar is NUL for ',' and ';' (repeat the search)
6424  */
6425     static void
6426 nv_csearch(cmdarg_T *cap)
6427 {
6428     int		t_cmd;
6429 
6430     if (cap->cmdchar == 't' || cap->cmdchar == 'T')
6431 	t_cmd = TRUE;
6432     else
6433 	t_cmd = FALSE;
6434 
6435     cap->oap->motion_type = MCHAR;
6436     if (IS_SPECIAL(cap->nchar) || searchc(cap, t_cmd) == FAIL)
6437 	clearopbeep(cap->oap);
6438     else
6439     {
6440 	curwin->w_set_curswant = TRUE;
6441 #ifdef FEAT_VIRTUALEDIT
6442 	/* Include a Tab for "tx" and for "dfx". */
6443 	if (gchar_cursor() == TAB && virtual_active() && cap->arg == FORWARD
6444 		&& (t_cmd || cap->oap->op_type != OP_NOP))
6445 	{
6446 	    colnr_T	scol, ecol;
6447 
6448 	    getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol);
6449 	    curwin->w_cursor.coladd = ecol - scol;
6450 	}
6451 	else
6452 	    curwin->w_cursor.coladd = 0;
6453 #endif
6454 	adjust_for_sel(cap);
6455 #ifdef FEAT_FOLDING
6456 	if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
6457 	    foldOpenCursor();
6458 #endif
6459     }
6460 }
6461 
6462 /*
6463  * "[" and "]" commands.
6464  * cap->arg is BACKWARD for "[" and FORWARD for "]".
6465  */
6466     static void
6467 nv_brackets(cmdarg_T *cap)
6468 {
6469     pos_T	new_pos = INIT_POS_T(0, 0, 0);
6470     pos_T	prev_pos;
6471     pos_T	*pos = NULL;	    /* init for GCC */
6472     pos_T	old_pos;	    /* cursor position before command */
6473     int		flag;
6474     long	n;
6475     int		findc;
6476     int		c;
6477 
6478     cap->oap->motion_type = MCHAR;
6479     cap->oap->inclusive = FALSE;
6480     old_pos = curwin->w_cursor;
6481 #ifdef FEAT_VIRTUALEDIT
6482     curwin->w_cursor.coladd = 0;	    /* TODO: don't do this for an error. */
6483 #endif
6484 
6485 #ifdef FEAT_SEARCHPATH
6486     /*
6487      * "[f" or "]f" : Edit file under the cursor (same as "gf")
6488      */
6489     if (cap->nchar == 'f')
6490 	nv_gotofile(cap);
6491     else
6492 #endif
6493 
6494 #ifdef FEAT_FIND_ID
6495     /*
6496      * Find the occurrence(s) of the identifier or define under cursor
6497      * in current and included files or jump to the first occurrence.
6498      *
6499      *			search	     list	    jump
6500      *		      fwd   bwd    fwd	 bwd	 fwd	bwd
6501      * identifier     "]i"  "[i"   "]I"  "[I"	"]^I"  "[^I"
6502      * define	      "]d"  "[d"   "]D"  "[D"	"]^D"  "[^D"
6503      */
6504     if (vim_strchr((char_u *)
6505 #ifdef EBCDIC
6506 		"iI\005dD\067",
6507 #else
6508 		"iI\011dD\004",
6509 #endif
6510 		cap->nchar) != NULL)
6511     {
6512 	char_u	*ptr;
6513 	int	len;
6514 
6515 	if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
6516 	    clearop(cap->oap);
6517 	else
6518 	{
6519 	    find_pattern_in_path(ptr, 0, len, TRUE,
6520 		cap->count0 == 0 ? !isupper(cap->nchar) : FALSE,
6521 		((cap->nchar & 0xf) == ('d' & 0xf)) ?  FIND_DEFINE : FIND_ANY,
6522 		cap->count1,
6523 		isupper(cap->nchar) ? ACTION_SHOW_ALL :
6524 			    islower(cap->nchar) ? ACTION_SHOW : ACTION_GOTO,
6525 		cap->cmdchar == ']' ? curwin->w_cursor.lnum + 1 : (linenr_T)1,
6526 		(linenr_T)MAXLNUM);
6527 	    curwin->w_set_curswant = TRUE;
6528 	}
6529     }
6530     else
6531 #endif
6532 
6533     /*
6534      * "[{", "[(", "]}" or "])": go to Nth unclosed '{', '(', '}' or ')'
6535      * "[#", "]#": go to start/end of Nth innermost #if..#endif construct.
6536      * "[/", "[*", "]/", "]*": go to Nth comment start/end.
6537      * "[m" or "]m" search for prev/next start of (Java) method.
6538      * "[M" or "]M" search for prev/next end of (Java) method.
6539      */
6540     if (  (cap->cmdchar == '['
6541 		&& vim_strchr((char_u *)"{(*/#mM", cap->nchar) != NULL)
6542 	    || (cap->cmdchar == ']'
6543 		&& vim_strchr((char_u *)"})*/#mM", cap->nchar) != NULL))
6544     {
6545 	if (cap->nchar == '*')
6546 	    cap->nchar = '/';
6547 	prev_pos.lnum = 0;
6548 	if (cap->nchar == 'm' || cap->nchar == 'M')
6549 	{
6550 	    if (cap->cmdchar == '[')
6551 		findc = '{';
6552 	    else
6553 		findc = '}';
6554 	    n = 9999;
6555 	}
6556 	else
6557 	{
6558 	    findc = cap->nchar;
6559 	    n = cap->count1;
6560 	}
6561 	for ( ; n > 0; --n)
6562 	{
6563 	    if ((pos = findmatchlimit(cap->oap, findc,
6564 		(cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD, 0)) == NULL)
6565 	    {
6566 		if (new_pos.lnum == 0)	/* nothing found */
6567 		{
6568 		    if (cap->nchar != 'm' && cap->nchar != 'M')
6569 			clearopbeep(cap->oap);
6570 		}
6571 		else
6572 		    pos = &new_pos;	/* use last one found */
6573 		break;
6574 	    }
6575 	    prev_pos = new_pos;
6576 	    curwin->w_cursor = *pos;
6577 	    new_pos = *pos;
6578 	}
6579 	curwin->w_cursor = old_pos;
6580 
6581 	/*
6582 	 * Handle "[m", "]m", "[M" and "[M".  The findmatchlimit() only
6583 	 * brought us to the match for "[m" and "]M" when inside a method.
6584 	 * Try finding the '{' or '}' we want to be at.
6585 	 * Also repeat for the given count.
6586 	 */
6587 	if (cap->nchar == 'm' || cap->nchar == 'M')
6588 	{
6589 	    /* norm is TRUE for "]M" and "[m" */
6590 	    int	    norm = ((findc == '{') == (cap->nchar == 'm'));
6591 
6592 	    n = cap->count1;
6593 	    /* found a match: we were inside a method */
6594 	    if (prev_pos.lnum != 0)
6595 	    {
6596 		pos = &prev_pos;
6597 		curwin->w_cursor = prev_pos;
6598 		if (norm)
6599 		    --n;
6600 	    }
6601 	    else
6602 		pos = NULL;
6603 	    while (n > 0)
6604 	    {
6605 		for (;;)
6606 		{
6607 		    if ((findc == '{' ? dec_cursor() : inc_cursor()) < 0)
6608 		    {
6609 			/* if not found anything, that's an error */
6610 			if (pos == NULL)
6611 			    clearopbeep(cap->oap);
6612 			n = 0;
6613 			break;
6614 		    }
6615 		    c = gchar_cursor();
6616 		    if (c == '{' || c == '}')
6617 		    {
6618 			/* Must have found end/start of class: use it.
6619 			 * Or found the place to be at. */
6620 			if ((c == findc && norm) || (n == 1 && !norm))
6621 			{
6622 			    new_pos = curwin->w_cursor;
6623 			    pos = &new_pos;
6624 			    n = 0;
6625 			}
6626 			/* if no match found at all, we started outside of the
6627 			 * class and we're inside now.  Just go on. */
6628 			else if (new_pos.lnum == 0)
6629 			{
6630 			    new_pos = curwin->w_cursor;
6631 			    pos = &new_pos;
6632 			}
6633 			/* found start/end of other method: go to match */
6634 			else if ((pos = findmatchlimit(cap->oap, findc,
6635 			    (cap->cmdchar == '[') ? FM_BACKWARD : FM_FORWARD,
6636 								  0)) == NULL)
6637 			    n = 0;
6638 			else
6639 			    curwin->w_cursor = *pos;
6640 			break;
6641 		    }
6642 		}
6643 		--n;
6644 	    }
6645 	    curwin->w_cursor = old_pos;
6646 	    if (pos == NULL && new_pos.lnum != 0)
6647 		clearopbeep(cap->oap);
6648 	}
6649 	if (pos != NULL)
6650 	{
6651 	    setpcmark();
6652 	    curwin->w_cursor = *pos;
6653 	    curwin->w_set_curswant = TRUE;
6654 #ifdef FEAT_FOLDING
6655 	    if ((fdo_flags & FDO_BLOCK) && KeyTyped
6656 					       && cap->oap->op_type == OP_NOP)
6657 		foldOpenCursor();
6658 #endif
6659 	}
6660     }
6661 
6662     /*
6663      * "[[", "[]", "]]" and "][": move to start or end of function
6664      */
6665     else if (cap->nchar == '[' || cap->nchar == ']')
6666     {
6667 	if (cap->nchar == cap->cmdchar)		    /* "]]" or "[[" */
6668 	    flag = '{';
6669 	else
6670 	    flag = '}';		    /* "][" or "[]" */
6671 
6672 	curwin->w_set_curswant = TRUE;
6673 	/*
6674 	 * Imitate strange Vi behaviour: When using "]]" with an operator
6675 	 * we also stop at '}'.
6676 	 */
6677 	if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, flag,
6678 	      (cap->oap->op_type != OP_NOP
6679 				      && cap->arg == FORWARD && flag == '{')))
6680 	    clearopbeep(cap->oap);
6681 	else
6682 	{
6683 	    if (cap->oap->op_type == OP_NOP)
6684 		beginline(BL_WHITE | BL_FIX);
6685 #ifdef FEAT_FOLDING
6686 	    if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
6687 		foldOpenCursor();
6688 #endif
6689 	}
6690     }
6691 
6692     /*
6693      * "[p", "[P", "]P" and "]p": put with indent adjustment
6694      */
6695     else if (cap->nchar == 'p' || cap->nchar == 'P')
6696     {
6697 	if (!checkclearop(cap->oap))
6698 	{
6699 	    int	    dir = (cap->cmdchar == ']' && cap->nchar == 'p')
6700 							 ? FORWARD : BACKWARD;
6701 	    int	    regname = cap->oap->regname;
6702 	    int	    was_visual = VIsual_active;
6703 	    int	    line_count = curbuf->b_ml.ml_line_count;
6704 	    pos_T   start, end;
6705 
6706 	    if (VIsual_active)
6707 	    {
6708 		start = LTOREQ_POS(VIsual, curwin->w_cursor)
6709 						  ? VIsual : curwin->w_cursor;
6710 		end =  EQUAL_POS(start,VIsual) ? curwin->w_cursor : VIsual;
6711 		curwin->w_cursor = (dir == BACKWARD ? start : end);
6712 	    }
6713 # ifdef FEAT_CLIPBOARD
6714 	    adjust_clip_reg(&regname);
6715 # endif
6716 	    prep_redo_cmd(cap);
6717 
6718 	    do_put(regname, dir, cap->count1, PUT_FIXINDENT);
6719 	    if (was_visual)
6720 	    {
6721 		VIsual = start;
6722 		curwin->w_cursor = end;
6723 		if (dir == BACKWARD)
6724 		{
6725 		    /* adjust lines */
6726 		    VIsual.lnum += curbuf->b_ml.ml_line_count - line_count;
6727 		    curwin->w_cursor.lnum +=
6728 				      curbuf->b_ml.ml_line_count - line_count;
6729 		}
6730 
6731 		VIsual_active = TRUE;
6732 		if (VIsual_mode == 'V')
6733 		{
6734 		    /* delete visually selected lines */
6735 		    cap->cmdchar = 'd';
6736 		    cap->nchar = NUL;
6737 		    cap->oap->regname = regname;
6738 		    nv_operator(cap);
6739 		    do_pending_operator(cap, 0, FALSE);
6740 		}
6741 		if (VIsual_active)
6742 		{
6743 		    end_visual_mode();
6744 		    redraw_later(SOME_VALID);
6745 		}
6746 	    }
6747 	}
6748     }
6749 
6750     /*
6751      * "['", "[`", "]'" and "]`": jump to next mark
6752      */
6753     else if (cap->nchar == '\'' || cap->nchar == '`')
6754     {
6755 	pos = &curwin->w_cursor;
6756 	for (n = cap->count1; n > 0; --n)
6757 	{
6758 	    prev_pos = *pos;
6759 	    pos = getnextmark(pos, cap->cmdchar == '[' ? BACKWARD : FORWARD,
6760 							  cap->nchar == '\'');
6761 	    if (pos == NULL)
6762 		break;
6763 	}
6764 	if (pos == NULL)
6765 	    pos = &prev_pos;
6766 	nv_cursormark(cap, cap->nchar == '\'', pos);
6767     }
6768 
6769 #ifdef FEAT_MOUSE
6770     /*
6771      * [ or ] followed by a middle mouse click: put selected text with
6772      * indent adjustment.  Any other button just does as usual.
6773      */
6774     else if (cap->nchar >= K_RIGHTRELEASE && cap->nchar <= K_LEFTMOUSE)
6775     {
6776 	(void)do_mouse(cap->oap, cap->nchar,
6777 		       (cap->cmdchar == ']') ? FORWARD : BACKWARD,
6778 		       cap->count1, PUT_FIXINDENT);
6779     }
6780 #endif /* FEAT_MOUSE */
6781 
6782 #ifdef FEAT_FOLDING
6783     /*
6784      * "[z" and "]z": move to start or end of open fold.
6785      */
6786     else if (cap->nchar == 'z')
6787     {
6788 	if (foldMoveTo(FALSE, cap->cmdchar == ']' ? FORWARD : BACKWARD,
6789 							 cap->count1) == FAIL)
6790 	    clearopbeep(cap->oap);
6791     }
6792 #endif
6793 
6794 #ifdef FEAT_DIFF
6795     /*
6796      * "[c" and "]c": move to next or previous diff-change.
6797      */
6798     else if (cap->nchar == 'c')
6799     {
6800 	if (diff_move_to(cap->cmdchar == ']' ? FORWARD : BACKWARD,
6801 							 cap->count1) == FAIL)
6802 	    clearopbeep(cap->oap);
6803     }
6804 #endif
6805 
6806 #ifdef FEAT_SPELL
6807     /*
6808      * "[s", "[S", "]s" and "]S": move to next spell error.
6809      */
6810     else if (cap->nchar == 's' || cap->nchar == 'S')
6811     {
6812 	setpcmark();
6813 	for (n = 0; n < cap->count1; ++n)
6814 	    if (spell_move_to(curwin, cap->cmdchar == ']' ? FORWARD : BACKWARD,
6815 			  cap->nchar == 's' ? TRUE : FALSE, FALSE, NULL) == 0)
6816 	    {
6817 		clearopbeep(cap->oap);
6818 		break;
6819 	    }
6820 	    else
6821 		curwin->w_set_curswant = TRUE;
6822 # ifdef FEAT_FOLDING
6823 	if (cap->oap->op_type == OP_NOP && (fdo_flags & FDO_SEARCH) && KeyTyped)
6824 	    foldOpenCursor();
6825 # endif
6826     }
6827 #endif
6828 
6829     /* Not a valid cap->nchar. */
6830     else
6831 	clearopbeep(cap->oap);
6832 }
6833 
6834 /*
6835  * Handle Normal mode "%" command.
6836  */
6837     static void
6838 nv_percent(cmdarg_T *cap)
6839 {
6840     pos_T	*pos;
6841 #if defined(FEAT_FOLDING)
6842     linenr_T	lnum = curwin->w_cursor.lnum;
6843 #endif
6844 
6845     cap->oap->inclusive = TRUE;
6846     if (cap->count0)	    /* {cnt}% : goto {cnt} percentage in file */
6847     {
6848 	if (cap->count0 > 100)
6849 	    clearopbeep(cap->oap);
6850 	else
6851 	{
6852 	    cap->oap->motion_type = MLINE;
6853 	    setpcmark();
6854 	    /* Round up, so CTRL-G will give same value.  Watch out for a
6855 	     * large line count, the line number must not go negative! */
6856 	    if (curbuf->b_ml.ml_line_count > 1000000)
6857 		curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count + 99L)
6858 							 / 100L * cap->count0;
6859 	    else
6860 		curwin->w_cursor.lnum = (curbuf->b_ml.ml_line_count *
6861 						    cap->count0 + 99L) / 100L;
6862 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6863 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6864 	    beginline(BL_SOL | BL_FIX);
6865 	}
6866     }
6867     else		    /* "%" : go to matching paren */
6868     {
6869 	cap->oap->motion_type = MCHAR;
6870 	cap->oap->use_reg_one = TRUE;
6871 	if ((pos = findmatch(cap->oap, NUL)) == NULL)
6872 	    clearopbeep(cap->oap);
6873 	else
6874 	{
6875 	    setpcmark();
6876 	    curwin->w_cursor = *pos;
6877 	    curwin->w_set_curswant = TRUE;
6878 #ifdef FEAT_VIRTUALEDIT
6879 	    curwin->w_cursor.coladd = 0;
6880 #endif
6881 	    adjust_for_sel(cap);
6882 	}
6883     }
6884 #ifdef FEAT_FOLDING
6885     if (cap->oap->op_type == OP_NOP
6886 	    && lnum != curwin->w_cursor.lnum
6887 	    && (fdo_flags & FDO_PERCENT)
6888 	    && KeyTyped)
6889 	foldOpenCursor();
6890 #endif
6891 }
6892 
6893 /*
6894  * Handle "(" and ")" commands.
6895  * cap->arg is BACKWARD for "(" and FORWARD for ")".
6896  */
6897     static void
6898 nv_brace(cmdarg_T *cap)
6899 {
6900     cap->oap->motion_type = MCHAR;
6901     cap->oap->use_reg_one = TRUE;
6902     /* The motion used to be inclusive for "(", but that is not what Vi does. */
6903     cap->oap->inclusive = FALSE;
6904     curwin->w_set_curswant = TRUE;
6905 
6906     if (findsent(cap->arg, cap->count1) == FAIL)
6907 	clearopbeep(cap->oap);
6908     else
6909     {
6910 	/* Don't leave the cursor on the NUL past end of line. */
6911 	adjust_cursor(cap->oap);
6912 #ifdef FEAT_VIRTUALEDIT
6913 	curwin->w_cursor.coladd = 0;
6914 #endif
6915 #ifdef FEAT_FOLDING
6916 	if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
6917 	    foldOpenCursor();
6918 #endif
6919     }
6920 }
6921 
6922 /*
6923  * "m" command: Mark a position.
6924  */
6925     static void
6926 nv_mark(cmdarg_T *cap)
6927 {
6928     if (!checkclearop(cap->oap))
6929     {
6930 	if (setmark(cap->nchar) == FAIL)
6931 	    clearopbeep(cap->oap);
6932     }
6933 }
6934 
6935 /*
6936  * "{" and "}" commands.
6937  * cmd->arg is BACKWARD for "{" and FORWARD for "}".
6938  */
6939     static void
6940 nv_findpar(cmdarg_T *cap)
6941 {
6942     cap->oap->motion_type = MCHAR;
6943     cap->oap->inclusive = FALSE;
6944     cap->oap->use_reg_one = TRUE;
6945     curwin->w_set_curswant = TRUE;
6946     if (!findpar(&cap->oap->inclusive, cap->arg, cap->count1, NUL, FALSE))
6947 	clearopbeep(cap->oap);
6948     else
6949     {
6950 #ifdef FEAT_VIRTUALEDIT
6951 	curwin->w_cursor.coladd = 0;
6952 #endif
6953 #ifdef FEAT_FOLDING
6954 	if ((fdo_flags & FDO_BLOCK) && KeyTyped && cap->oap->op_type == OP_NOP)
6955 	    foldOpenCursor();
6956 #endif
6957     }
6958 }
6959 
6960 /*
6961  * "u" command: Undo or make lower case.
6962  */
6963     static void
6964 nv_undo(cmdarg_T *cap)
6965 {
6966     if (cap->oap->op_type == OP_LOWER || VIsual_active)
6967     {
6968 	/* translate "<Visual>u" to "<Visual>gu" and "guu" to "gugu" */
6969 	cap->cmdchar = 'g';
6970 	cap->nchar = 'u';
6971 	nv_operator(cap);
6972     }
6973     else
6974 	nv_kundo(cap);
6975 }
6976 
6977 /*
6978  * <Undo> command.
6979  */
6980     static void
6981 nv_kundo(cmdarg_T *cap)
6982 {
6983     if (!checkclearopq(cap->oap))
6984     {
6985 #ifdef FEAT_JOB_CHANNEL
6986 	if (bt_prompt(curbuf))
6987 	{
6988 	    clearopbeep(cap->oap);
6989 	    return;
6990 	}
6991 #endif
6992 	u_undo((int)cap->count1);
6993 	curwin->w_set_curswant = TRUE;
6994     }
6995 }
6996 
6997 /*
6998  * Handle the "r" command.
6999  */
7000     static void
7001 nv_replace(cmdarg_T *cap)
7002 {
7003     char_u	*ptr;
7004     int		had_ctrl_v;
7005     long	n;
7006 
7007     if (checkclearop(cap->oap))
7008 	return;
7009 #ifdef FEAT_JOB_CHANNEL
7010     if (bt_prompt(curbuf) && !prompt_curpos_editable())
7011     {
7012 	clearopbeep(cap->oap);
7013 	return;
7014     }
7015 #endif
7016 
7017     /* get another character */
7018     if (cap->nchar == Ctrl_V)
7019     {
7020 	had_ctrl_v = Ctrl_V;
7021 	cap->nchar = get_literal();
7022 	/* Don't redo a multibyte character with CTRL-V. */
7023 	if (cap->nchar > DEL)
7024 	    had_ctrl_v = NUL;
7025     }
7026     else
7027 	had_ctrl_v = NUL;
7028 
7029     /* Abort if the character is a special key. */
7030     if (IS_SPECIAL(cap->nchar))
7031     {
7032 	clearopbeep(cap->oap);
7033 	return;
7034     }
7035 
7036     /* Visual mode "r" */
7037     if (VIsual_active)
7038     {
7039 	if (got_int)
7040 	    reset_VIsual();
7041 	if (had_ctrl_v)
7042 	{
7043 	    /* Use a special (negative) number to make a difference between a
7044 	     * literal CR or NL and a line break. */
7045 	    if (cap->nchar == CAR)
7046 		cap->nchar = REPLACE_CR_NCHAR;
7047 	    else if (cap->nchar == NL)
7048 		cap->nchar = REPLACE_NL_NCHAR;
7049 	}
7050 	nv_operator(cap);
7051 	return;
7052     }
7053 
7054 #ifdef FEAT_VIRTUALEDIT
7055     /* Break tabs, etc. */
7056     if (virtual_active())
7057     {
7058 	if (u_save_cursor() == FAIL)
7059 	    return;
7060 	if (gchar_cursor() == NUL)
7061 	{
7062 	    /* Add extra space and put the cursor on the first one. */
7063 	    coladvance_force((colnr_T)(getviscol() + cap->count1));
7064 	    curwin->w_cursor.col -= cap->count1;
7065 	}
7066 	else if (gchar_cursor() == TAB)
7067 	    coladvance_force(getviscol());
7068     }
7069 #endif
7070 
7071     /* Abort if not enough characters to replace. */
7072     ptr = ml_get_cursor();
7073     if (STRLEN(ptr) < (unsigned)cap->count1
7074 #ifdef FEAT_MBYTE
7075 	    || (has_mbyte && mb_charlen(ptr) < cap->count1)
7076 #endif
7077 	    )
7078     {
7079 	clearopbeep(cap->oap);
7080 	return;
7081     }
7082 
7083     /*
7084      * Replacing with a TAB is done by edit() when it is complicated because
7085      * 'expandtab' or 'smarttab' is set.  CTRL-V TAB inserts a literal TAB.
7086      * Other characters are done below to avoid problems with things like
7087      * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC).
7088      */
7089     if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta))
7090     {
7091 	stuffnumReadbuff(cap->count1);
7092 	stuffcharReadbuff('R');
7093 	stuffcharReadbuff('\t');
7094 	stuffcharReadbuff(ESC);
7095 	return;
7096     }
7097 
7098     /* save line for undo */
7099     if (u_save_cursor() == FAIL)
7100 	return;
7101 
7102     if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n'))
7103     {
7104 	/*
7105 	 * Replace character(s) by a single newline.
7106 	 * Strange vi behaviour: Only one newline is inserted.
7107 	 * Delete the characters here.
7108 	 * Insert the newline with an insert command, takes care of
7109 	 * autoindent.	The insert command depends on being on the last
7110 	 * character of a line or not.
7111 	 */
7112 #ifdef FEAT_MBYTE
7113 	(void)del_chars(cap->count1, FALSE);	/* delete the characters */
7114 #else
7115 	(void)del_bytes(cap->count1, FALSE, FALSE); /* delete the characters */
7116 #endif
7117 	stuffcharReadbuff('\r');
7118 	stuffcharReadbuff(ESC);
7119 
7120 	/* Give 'r' to edit(), to get the redo command right. */
7121 	invoke_edit(cap, TRUE, 'r', FALSE);
7122     }
7123     else
7124     {
7125 	prep_redo(cap->oap->regname, cap->count1,
7126 				       NUL, 'r', NUL, had_ctrl_v, cap->nchar);
7127 
7128 	curbuf->b_op_start = curwin->w_cursor;
7129 #ifdef FEAT_MBYTE
7130 	if (has_mbyte)
7131 	{
7132 	    int		old_State = State;
7133 
7134 	    if (cap->ncharC1 != 0)
7135 		AppendCharToRedobuff(cap->ncharC1);
7136 	    if (cap->ncharC2 != 0)
7137 		AppendCharToRedobuff(cap->ncharC2);
7138 
7139 	    /* This is slow, but it handles replacing a single-byte with a
7140 	     * multi-byte and the other way around.  Also handles adding
7141 	     * composing characters for utf-8. */
7142 	    for (n = cap->count1; n > 0; --n)
7143 	    {
7144 		State = REPLACE;
7145 		if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
7146 		{
7147 		    int c = ins_copychar(curwin->w_cursor.lnum
7148 					   + (cap->nchar == Ctrl_Y ? -1 : 1));
7149 		    if (c != NUL)
7150 			ins_char(c);
7151 		    else
7152 			/* will be decremented further down */
7153 			++curwin->w_cursor.col;
7154 		}
7155 		else
7156 		    ins_char(cap->nchar);
7157 		State = old_State;
7158 		if (cap->ncharC1 != 0)
7159 		    ins_char(cap->ncharC1);
7160 		if (cap->ncharC2 != 0)
7161 		    ins_char(cap->ncharC2);
7162 	    }
7163 	}
7164 	else
7165 #endif
7166 	{
7167 	    /*
7168 	     * Replace the characters within one line.
7169 	     */
7170 	    for (n = cap->count1; n > 0; --n)
7171 	    {
7172 		/*
7173 		 * Get ptr again, because u_save and/or showmatch() will have
7174 		 * released the line.  At the same time we let know that the
7175 		 * line will be changed.
7176 		 */
7177 		ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE);
7178 		if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y)
7179 		{
7180 		  int c = ins_copychar(curwin->w_cursor.lnum
7181 					   + (cap->nchar == Ctrl_Y ? -1 : 1));
7182 		  if (c != NUL)
7183 		    ptr[curwin->w_cursor.col] = c;
7184 		}
7185 		else
7186 		    ptr[curwin->w_cursor.col] = cap->nchar;
7187 		if (p_sm && msg_silent == 0)
7188 		    showmatch(cap->nchar);
7189 		++curwin->w_cursor.col;
7190 	    }
7191 #ifdef FEAT_NETBEANS_INTG
7192 	    if (netbeans_active())
7193 	    {
7194 		colnr_T  start = (colnr_T)(curwin->w_cursor.col - cap->count1);
7195 
7196 		netbeans_removed(curbuf, curwin->w_cursor.lnum, start,
7197 							   (long)cap->count1);
7198 		netbeans_inserted(curbuf, curwin->w_cursor.lnum, start,
7199 					       &ptr[start], (int)cap->count1);
7200 	    }
7201 #endif
7202 
7203 	    /* mark the buffer as changed and prepare for displaying */
7204 	    changed_bytes(curwin->w_cursor.lnum,
7205 			       (colnr_T)(curwin->w_cursor.col - cap->count1));
7206 	}
7207 	--curwin->w_cursor.col;	    /* cursor on the last replaced char */
7208 #ifdef FEAT_MBYTE
7209 	/* if the character on the left of the current cursor is a multi-byte
7210 	 * character, move two characters left */
7211 	if (has_mbyte)
7212 	    mb_adjust_cursor();
7213 #endif
7214 	curbuf->b_op_end = curwin->w_cursor;
7215 	curwin->w_set_curswant = TRUE;
7216 	set_last_insert(cap->nchar);
7217     }
7218 }
7219 
7220 /*
7221  * 'o': Exchange start and end of Visual area.
7222  * 'O': same, but in block mode exchange left and right corners.
7223  */
7224     static void
7225 v_swap_corners(int cmdchar)
7226 {
7227     pos_T	old_cursor;
7228     colnr_T	left, right;
7229 
7230     if (cmdchar == 'O' && VIsual_mode == Ctrl_V)
7231     {
7232 	old_cursor = curwin->w_cursor;
7233 	getvcols(curwin, &old_cursor, &VIsual, &left, &right);
7234 	curwin->w_cursor.lnum = VIsual.lnum;
7235 	coladvance(left);
7236 	VIsual = curwin->w_cursor;
7237 
7238 	curwin->w_cursor.lnum = old_cursor.lnum;
7239 	curwin->w_curswant = right;
7240 	/* 'selection "exclusive" and cursor at right-bottom corner: move it
7241 	 * right one column */
7242 	if (old_cursor.lnum >= VIsual.lnum && *p_sel == 'e')
7243 	    ++curwin->w_curswant;
7244 	coladvance(curwin->w_curswant);
7245 	if (curwin->w_cursor.col == old_cursor.col
7246 #ifdef FEAT_VIRTUALEDIT
7247 		&& (!virtual_active()
7248 		    || curwin->w_cursor.coladd == old_cursor.coladd)
7249 #endif
7250 		)
7251 	{
7252 	    curwin->w_cursor.lnum = VIsual.lnum;
7253 	    if (old_cursor.lnum <= VIsual.lnum && *p_sel == 'e')
7254 		++right;
7255 	    coladvance(right);
7256 	    VIsual = curwin->w_cursor;
7257 
7258 	    curwin->w_cursor.lnum = old_cursor.lnum;
7259 	    coladvance(left);
7260 	    curwin->w_curswant = left;
7261 	}
7262     }
7263     else
7264     {
7265 	old_cursor = curwin->w_cursor;
7266 	curwin->w_cursor = VIsual;
7267 	VIsual = old_cursor;
7268 	curwin->w_set_curswant = TRUE;
7269     }
7270 }
7271 
7272 /*
7273  * "R" (cap->arg is FALSE) and "gR" (cap->arg is TRUE).
7274  */
7275     static void
7276 nv_Replace(cmdarg_T *cap)
7277 {
7278     if (VIsual_active)		/* "R" is replace lines */
7279     {
7280 	cap->cmdchar = 'c';
7281 	cap->nchar = NUL;
7282 	VIsual_mode_orig = VIsual_mode; /* remember original area for gv */
7283 	VIsual_mode = 'V';
7284 	nv_operator(cap);
7285     }
7286     else if (!checkclearopq(cap->oap))
7287     {
7288 	if (!curbuf->b_p_ma)
7289 	    EMSG(_(e_modifiable));
7290 	else
7291 	{
7292 #ifdef FEAT_VIRTUALEDIT
7293 	    if (virtual_active())
7294 		coladvance(getviscol());
7295 #endif
7296 	    invoke_edit(cap, FALSE, cap->arg ? 'V' : 'R', FALSE);
7297 	}
7298     }
7299 }
7300 
7301 /*
7302  * "gr".
7303  */
7304     static void
7305 nv_vreplace(cmdarg_T *cap)
7306 {
7307     if (VIsual_active)
7308     {
7309 	cap->cmdchar = 'r';
7310 	cap->nchar = cap->extra_char;
7311 	nv_replace(cap);	/* Do same as "r" in Visual mode for now */
7312     }
7313     else if (!checkclearopq(cap->oap))
7314     {
7315 	if (!curbuf->b_p_ma)
7316 	    EMSG(_(e_modifiable));
7317 	else
7318 	{
7319 	    if (cap->extra_char == Ctrl_V)	/* get another character */
7320 		cap->extra_char = get_literal();
7321 	    stuffcharReadbuff(cap->extra_char);
7322 	    stuffcharReadbuff(ESC);
7323 #ifdef FEAT_VIRTUALEDIT
7324 	    if (virtual_active())
7325 		coladvance(getviscol());
7326 #endif
7327 	    invoke_edit(cap, TRUE, 'v', FALSE);
7328 	}
7329     }
7330 }
7331 
7332 /*
7333  * Swap case for "~" command, when it does not work like an operator.
7334  */
7335     static void
7336 n_swapchar(cmdarg_T *cap)
7337 {
7338     long	n;
7339     pos_T	startpos;
7340     int		did_change = 0;
7341 #ifdef FEAT_NETBEANS_INTG
7342     pos_T	pos;
7343     char_u	*ptr;
7344     int		count;
7345 #endif
7346 
7347     if (checkclearopq(cap->oap))
7348 	return;
7349 
7350     if (LINEEMPTY(curwin->w_cursor.lnum) && vim_strchr(p_ww, '~') == NULL)
7351     {
7352 	clearopbeep(cap->oap);
7353 	return;
7354     }
7355 
7356     prep_redo_cmd(cap);
7357 
7358     if (u_save_cursor() == FAIL)
7359 	return;
7360 
7361     startpos = curwin->w_cursor;
7362 #ifdef FEAT_NETBEANS_INTG
7363     pos = startpos;
7364 #endif
7365     for (n = cap->count1; n > 0; --n)
7366     {
7367 	did_change |= swapchar(cap->oap->op_type, &curwin->w_cursor);
7368 	inc_cursor();
7369 	if (gchar_cursor() == NUL)
7370 	{
7371 	    if (vim_strchr(p_ww, '~') != NULL
7372 		    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
7373 	    {
7374 #ifdef FEAT_NETBEANS_INTG
7375 		if (netbeans_active())
7376 		{
7377 		    if (did_change)
7378 		    {
7379 			ptr = ml_get(pos.lnum);
7380 			count = (int)STRLEN(ptr) - pos.col;
7381 			netbeans_removed(curbuf, pos.lnum, pos.col,
7382 								 (long)count);
7383 			netbeans_inserted(curbuf, pos.lnum, pos.col,
7384 							&ptr[pos.col], count);
7385 		    }
7386 		    pos.col = 0;
7387 		    pos.lnum++;
7388 		}
7389 #endif
7390 		++curwin->w_cursor.lnum;
7391 		curwin->w_cursor.col = 0;
7392 		if (n > 1)
7393 		{
7394 		    if (u_savesub(curwin->w_cursor.lnum) == FAIL)
7395 			break;
7396 		    u_clearline();
7397 		}
7398 	    }
7399 	    else
7400 		break;
7401 	}
7402     }
7403 #ifdef FEAT_NETBEANS_INTG
7404     if (did_change && netbeans_active())
7405     {
7406 	ptr = ml_get(pos.lnum);
7407 	count = curwin->w_cursor.col - pos.col;
7408 	netbeans_removed(curbuf, pos.lnum, pos.col, (long)count);
7409 	netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count);
7410     }
7411 #endif
7412 
7413 
7414     check_cursor();
7415     curwin->w_set_curswant = TRUE;
7416     if (did_change)
7417     {
7418 	changed_lines(startpos.lnum, startpos.col, curwin->w_cursor.lnum + 1,
7419 									  0L);
7420 	curbuf->b_op_start = startpos;
7421 	curbuf->b_op_end = curwin->w_cursor;
7422 	if (curbuf->b_op_end.col > 0)
7423 	    --curbuf->b_op_end.col;
7424     }
7425 }
7426 
7427 /*
7428  * Move cursor to mark.
7429  */
7430     static void
7431 nv_cursormark(cmdarg_T *cap, int flag, pos_T *pos)
7432 {
7433     if (check_mark(pos) == FAIL)
7434 	clearop(cap->oap);
7435     else
7436     {
7437 	if (cap->cmdchar == '\''
7438 		|| cap->cmdchar == '`'
7439 		|| cap->cmdchar == '['
7440 		|| cap->cmdchar == ']')
7441 	    setpcmark();
7442 	curwin->w_cursor = *pos;
7443 	if (flag)
7444 	    beginline(BL_WHITE | BL_FIX);
7445 	else
7446 	    check_cursor();
7447     }
7448     cap->oap->motion_type = flag ? MLINE : MCHAR;
7449     if (cap->cmdchar == '`')
7450 	cap->oap->use_reg_one = TRUE;
7451     cap->oap->inclusive = FALSE;		/* ignored if not MCHAR */
7452     curwin->w_set_curswant = TRUE;
7453 }
7454 
7455 /*
7456  * Handle commands that are operators in Visual mode.
7457  */
7458     static void
7459 v_visop(cmdarg_T *cap)
7460 {
7461     static char_u trans[] = "YyDdCcxdXdAAIIrr";
7462 
7463     /* Uppercase means linewise, except in block mode, then "D" deletes till
7464      * the end of the line, and "C" replaces till EOL */
7465     if (isupper(cap->cmdchar))
7466     {
7467 	if (VIsual_mode != Ctrl_V)
7468 	{
7469 	    VIsual_mode_orig = VIsual_mode;
7470 	    VIsual_mode = 'V';
7471 	}
7472 	else if (cap->cmdchar == 'C' || cap->cmdchar == 'D')
7473 	    curwin->w_curswant = MAXCOL;
7474     }
7475     cap->cmdchar = *(vim_strchr(trans, cap->cmdchar) + 1);
7476     nv_operator(cap);
7477 }
7478 
7479 /*
7480  * "s" and "S" commands.
7481  */
7482     static void
7483 nv_subst(cmdarg_T *cap)
7484 {
7485 #ifdef FEAT_TERMINAL
7486     /* When showing output of term_dumpdiff() swap the top and botom. */
7487     if (term_swap_diff() == OK)
7488 	return;
7489 #endif
7490 #ifdef FEAT_JOB_CHANNEL
7491     if (bt_prompt(curbuf) && !prompt_curpos_editable())
7492     {
7493 	clearopbeep(cap->oap);
7494 	return;
7495     }
7496 #endif
7497     if (VIsual_active)	/* "vs" and "vS" are the same as "vc" */
7498     {
7499 	if (cap->cmdchar == 'S')
7500 	{
7501 	    VIsual_mode_orig = VIsual_mode;
7502 	    VIsual_mode = 'V';
7503 	}
7504 	cap->cmdchar = 'c';
7505 	nv_operator(cap);
7506     }
7507     else
7508 	nv_optrans(cap);
7509 }
7510 
7511 /*
7512  * Abbreviated commands.
7513  */
7514     static void
7515 nv_abbrev(cmdarg_T *cap)
7516 {
7517     if (cap->cmdchar == K_DEL || cap->cmdchar == K_KDEL)
7518 	cap->cmdchar = 'x';		/* DEL key behaves like 'x' */
7519 
7520     /* in Visual mode these commands are operators */
7521     if (VIsual_active)
7522 	v_visop(cap);
7523     else
7524 	nv_optrans(cap);
7525 }
7526 
7527 /*
7528  * Translate a command into another command.
7529  */
7530     static void
7531 nv_optrans(cmdarg_T *cap)
7532 {
7533     static char_u *(ar[8]) = {(char_u *)"dl", (char_u *)"dh",
7534 			      (char_u *)"d$", (char_u *)"c$",
7535 			      (char_u *)"cl", (char_u *)"cc",
7536 			      (char_u *)"yy", (char_u *)":s\r"};
7537     static char_u *str = (char_u *)"xXDCsSY&";
7538 
7539     if (!checkclearopq(cap->oap))
7540     {
7541 	/* In Vi "2D" doesn't delete the next line.  Can't translate it
7542 	 * either, because "2." should also not use the count. */
7543 	if (cap->cmdchar == 'D' && vim_strchr(p_cpo, CPO_HASH) != NULL)
7544 	{
7545 	    cap->oap->start = curwin->w_cursor;
7546 	    cap->oap->op_type = OP_DELETE;
7547 #ifdef FEAT_EVAL
7548 	    set_op_var(OP_DELETE);
7549 #endif
7550 	    cap->count1 = 1;
7551 	    nv_dollar(cap);
7552 	    finish_op = TRUE;
7553 	    ResetRedobuff();
7554 	    AppendCharToRedobuff('D');
7555 	}
7556 	else
7557 	{
7558 	    if (cap->count0)
7559 		stuffnumReadbuff(cap->count0);
7560 	    stuffReadbuff(ar[(int)(vim_strchr(str, cap->cmdchar) - str)]);
7561 	}
7562     }
7563     cap->opcount = 0;
7564 }
7565 
7566 /*
7567  * "'" and "`" commands.  Also for "g'" and "g`".
7568  * cap->arg is TRUE for "'" and "g'".
7569  */
7570     static void
7571 nv_gomark(cmdarg_T *cap)
7572 {
7573     pos_T	*pos;
7574     int		c;
7575 #ifdef FEAT_FOLDING
7576     pos_T	old_cursor = curwin->w_cursor;
7577     int		old_KeyTyped = KeyTyped;    /* getting file may reset it */
7578 #endif
7579 
7580     if (cap->cmdchar == 'g')
7581 	c = cap->extra_char;
7582     else
7583 	c = cap->nchar;
7584     pos = getmark(c, (cap->oap->op_type == OP_NOP));
7585     if (pos == (pos_T *)-1)	    /* jumped to other file */
7586     {
7587 	if (cap->arg)
7588 	{
7589 	    check_cursor_lnum();
7590 	    beginline(BL_WHITE | BL_FIX);
7591 	}
7592 	else
7593 	    check_cursor();
7594     }
7595     else
7596 	nv_cursormark(cap, cap->arg, pos);
7597 
7598 #ifdef FEAT_VIRTUALEDIT
7599     /* May need to clear the coladd that a mark includes. */
7600     if (!virtual_active())
7601 	curwin->w_cursor.coladd = 0;
7602 #endif
7603     check_cursor_col();
7604 #ifdef FEAT_FOLDING
7605     if (cap->oap->op_type == OP_NOP
7606 	    && pos != NULL
7607 	    && (pos == (pos_T *)-1 || !EQUAL_POS(old_cursor, *pos))
7608 	    && (fdo_flags & FDO_MARK)
7609 	    && old_KeyTyped)
7610 	foldOpenCursor();
7611 #endif
7612 }
7613 
7614 /*
7615  * Handle CTRL-O, CTRL-I, "g;" and "g," commands.
7616  */
7617     static void
7618 nv_pcmark(cmdarg_T *cap)
7619 {
7620 #ifdef FEAT_JUMPLIST
7621     pos_T	*pos;
7622 # ifdef FEAT_FOLDING
7623     linenr_T	lnum = curwin->w_cursor.lnum;
7624     int		old_KeyTyped = KeyTyped;    /* getting file may reset it */
7625 # endif
7626 
7627     if (!checkclearopq(cap->oap))
7628     {
7629 	if (cap->cmdchar == 'g')
7630 	    pos = movechangelist((int)cap->count1);
7631 	else
7632 	    pos = movemark((int)cap->count1);
7633 	if (pos == (pos_T *)-1)		/* jump to other file */
7634 	{
7635 	    curwin->w_set_curswant = TRUE;
7636 	    check_cursor();
7637 	}
7638 	else if (pos != NULL)		    /* can jump */
7639 	    nv_cursormark(cap, FALSE, pos);
7640 	else if (cap->cmdchar == 'g')
7641 	{
7642 	    if (curbuf->b_changelistlen == 0)
7643 		EMSG(_("E664: changelist is empty"));
7644 	    else if (cap->count1 < 0)
7645 		EMSG(_("E662: At start of changelist"));
7646 	    else
7647 		EMSG(_("E663: At end of changelist"));
7648 	}
7649 	else
7650 	    clearopbeep(cap->oap);
7651 # ifdef FEAT_FOLDING
7652 	if (cap->oap->op_type == OP_NOP
7653 		&& (pos == (pos_T *)-1 || lnum != curwin->w_cursor.lnum)
7654 		&& (fdo_flags & FDO_MARK)
7655 		&& old_KeyTyped)
7656 	    foldOpenCursor();
7657 # endif
7658     }
7659 #else
7660     clearopbeep(cap->oap);
7661 #endif
7662 }
7663 
7664 /*
7665  * Handle '"' command.
7666  */
7667     static void
7668 nv_regname(cmdarg_T *cap)
7669 {
7670     if (checkclearop(cap->oap))
7671 	return;
7672 #ifdef FEAT_EVAL
7673     if (cap->nchar == '=')
7674 	cap->nchar = get_expr_register();
7675 #endif
7676     if (cap->nchar != NUL && valid_yank_reg(cap->nchar, FALSE))
7677     {
7678 	cap->oap->regname = cap->nchar;
7679 	cap->opcount = cap->count0;	/* remember count before '"' */
7680 #ifdef FEAT_EVAL
7681 	set_reg_var(cap->oap->regname);
7682 #endif
7683     }
7684     else
7685 	clearopbeep(cap->oap);
7686 }
7687 
7688 /*
7689  * Handle "v", "V" and "CTRL-V" commands.
7690  * Also for "gh", "gH" and "g^H" commands: Always start Select mode, cap->arg
7691  * is TRUE.
7692  * Handle CTRL-Q just like CTRL-V.
7693  */
7694     static void
7695 nv_visual(cmdarg_T *cap)
7696 {
7697     if (cap->cmdchar == Ctrl_Q)
7698 	cap->cmdchar = Ctrl_V;
7699 
7700     /* 'v', 'V' and CTRL-V can be used while an operator is pending to make it
7701      * characterwise, linewise, or blockwise. */
7702     if (cap->oap->op_type != OP_NOP)
7703     {
7704 	cap->oap->motion_force = cap->cmdchar;
7705 	finish_op = FALSE;	/* operator doesn't finish now but later */
7706 	return;
7707     }
7708 
7709     VIsual_select = cap->arg;
7710     if (VIsual_active)	    /* change Visual mode */
7711     {
7712 	if (VIsual_mode == cap->cmdchar)    /* stop visual mode */
7713 	    end_visual_mode();
7714 	else				    /* toggle char/block mode */
7715 	{				    /*	   or char/line mode */
7716 	    VIsual_mode = cap->cmdchar;
7717 	    showmode();
7718 	}
7719 	redraw_curbuf_later(INVERTED);	    /* update the inversion */
7720     }
7721     else		    /* start Visual mode */
7722     {
7723 	check_visual_highlight();
7724 	if (cap->count0 > 0 && resel_VIsual_mode != NUL)
7725 	{
7726 	    /* use previously selected part */
7727 	    VIsual = curwin->w_cursor;
7728 
7729 	    VIsual_active = TRUE;
7730 	    VIsual_reselect = TRUE;
7731 	    if (!cap->arg)
7732 		/* start Select mode when 'selectmode' contains "cmd" */
7733 		may_start_select('c');
7734 #ifdef FEAT_MOUSE
7735 	    setmouse();
7736 #endif
7737 	    if (p_smd && msg_silent == 0)
7738 		redraw_cmdline = TRUE;	    /* show visual mode later */
7739 	    /*
7740 	     * For V and ^V, we multiply the number of lines even if there
7741 	     * was only one -- webb
7742 	     */
7743 	    if (resel_VIsual_mode != 'v' || resel_VIsual_line_count > 1)
7744 	    {
7745 		curwin->w_cursor.lnum +=
7746 				    resel_VIsual_line_count * cap->count0 - 1;
7747 		if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
7748 		    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7749 	    }
7750 	    VIsual_mode = resel_VIsual_mode;
7751 	    if (VIsual_mode == 'v')
7752 	    {
7753 		if (resel_VIsual_line_count <= 1)
7754 		{
7755 		    validate_virtcol();
7756 		    curwin->w_curswant = curwin->w_virtcol
7757 					+ resel_VIsual_vcol * cap->count0 - 1;
7758 		}
7759 		else
7760 		    curwin->w_curswant = resel_VIsual_vcol;
7761 		coladvance(curwin->w_curswant);
7762 	    }
7763 	    if (resel_VIsual_vcol == MAXCOL)
7764 	    {
7765 		curwin->w_curswant = MAXCOL;
7766 		coladvance((colnr_T)MAXCOL);
7767 	    }
7768 	    else if (VIsual_mode == Ctrl_V)
7769 	    {
7770 		validate_virtcol();
7771 		curwin->w_curswant = curwin->w_virtcol
7772 					+ resel_VIsual_vcol * cap->count0 - 1;
7773 		coladvance(curwin->w_curswant);
7774 	    }
7775 	    else
7776 		curwin->w_set_curswant = TRUE;
7777 	    redraw_curbuf_later(INVERTED);	/* show the inversion */
7778 	}
7779 	else
7780 	{
7781 	    if (!cap->arg)
7782 		/* start Select mode when 'selectmode' contains "cmd" */
7783 		may_start_select('c');
7784 	    n_start_visual_mode(cap->cmdchar);
7785 	    if (VIsual_mode != 'V' && *p_sel == 'e')
7786 		++cap->count1;  /* include one more char */
7787 	    if (cap->count0 > 0 && --cap->count1 > 0)
7788 	    {
7789 		/* With a count select that many characters or lines. */
7790 		if (VIsual_mode == 'v' || VIsual_mode == Ctrl_V)
7791 		    nv_right(cap);
7792 		else if (VIsual_mode == 'V')
7793 		    nv_down(cap);
7794 	    }
7795 	}
7796     }
7797 }
7798 
7799 /*
7800  * Start selection for Shift-movement keys.
7801  */
7802     void
7803 start_selection(void)
7804 {
7805     /* if 'selectmode' contains "key", start Select mode */
7806     may_start_select('k');
7807     n_start_visual_mode('v');
7808 }
7809 
7810 /*
7811  * Start Select mode, if "c" is in 'selectmode' and not in a mapping or menu.
7812  */
7813     void
7814 may_start_select(int c)
7815 {
7816     VIsual_select = (stuff_empty() && typebuf_typed()
7817 		    && (vim_strchr(p_slm, c) != NULL));
7818 }
7819 
7820 /*
7821  * Start Visual mode "c".
7822  * Should set VIsual_select before calling this.
7823  */
7824     static void
7825 n_start_visual_mode(int c)
7826 {
7827 #ifdef FEAT_CONCEAL
7828     /* Check for redraw before changing the state. */
7829     conceal_check_cursor_line();
7830 #endif
7831 
7832     VIsual_mode = c;
7833     VIsual_active = TRUE;
7834     VIsual_reselect = TRUE;
7835 #ifdef FEAT_VIRTUALEDIT
7836     /* Corner case: the 0 position in a tab may change when going into
7837      * virtualedit.  Recalculate curwin->w_cursor to avoid bad hilighting.
7838      */
7839     if (c == Ctrl_V && (ve_flags & VE_BLOCK) && gchar_cursor() == TAB)
7840     {
7841 	validate_virtcol();
7842 	coladvance(curwin->w_virtcol);
7843     }
7844 #endif
7845     VIsual = curwin->w_cursor;
7846 
7847 #ifdef FEAT_FOLDING
7848     foldAdjustVisual();
7849 #endif
7850 
7851 #ifdef FEAT_MOUSE
7852     setmouse();
7853 #endif
7854 #ifdef FEAT_CONCEAL
7855     /* Check for redraw after changing the state. */
7856     conceal_check_cursor_line();
7857 #endif
7858 
7859     if (p_smd && msg_silent == 0)
7860 	redraw_cmdline = TRUE;	/* show visual mode later */
7861 #ifdef FEAT_CLIPBOARD
7862     /* Make sure the clipboard gets updated.  Needed because start and
7863      * end may still be the same, and the selection needs to be owned */
7864     clip_star.vmode = NUL;
7865 #endif
7866 
7867     /* Only need to redraw this line, unless still need to redraw an old
7868      * Visual area (when 'lazyredraw' is set). */
7869     if (curwin->w_redr_type < INVERTED)
7870     {
7871 	curwin->w_old_cursor_lnum = curwin->w_cursor.lnum;
7872 	curwin->w_old_visual_lnum = curwin->w_cursor.lnum;
7873     }
7874 }
7875 
7876 
7877 /*
7878  * CTRL-W: Window commands
7879  */
7880     static void
7881 nv_window(cmdarg_T *cap)
7882 {
7883     if (cap->nchar == ':')
7884     {
7885 	/* "CTRL-W :" is the same as typing ":"; useful in a terminal window */
7886 	cap->cmdchar = ':';
7887 	cap->nchar = NUL;
7888 	nv_colon(cap);
7889     }
7890     else if (!checkclearop(cap->oap))
7891 	do_window(cap->nchar, cap->count0, NUL); /* everything is in window.c */
7892 }
7893 
7894 /*
7895  * CTRL-Z: Suspend
7896  */
7897     static void
7898 nv_suspend(cmdarg_T *cap)
7899 {
7900     clearop(cap->oap);
7901     if (VIsual_active)
7902 	end_visual_mode();		/* stop Visual mode */
7903     do_cmdline_cmd((char_u *)"st");
7904 }
7905 
7906 /*
7907  * Commands starting with "g".
7908  */
7909     static void
7910 nv_g_cmd(cmdarg_T *cap)
7911 {
7912     oparg_T	*oap = cap->oap;
7913     pos_T	tpos;
7914     int		i;
7915     int		flag = FALSE;
7916 
7917     switch (cap->nchar)
7918     {
7919     case Ctrl_A:
7920     case Ctrl_X:
7921 #ifdef MEM_PROFILE
7922     /*
7923      * "g^A": dump log of used memory.
7924      */
7925 	if (!VIsual_active && cap->nchar == Ctrl_A)
7926 	    vim_mem_profile_dump();
7927 	else
7928 #endif
7929     /*
7930      * "g^A/g^X": sequentially increment visually selected region
7931      */
7932 	     if (VIsual_active)
7933 	{
7934 	    cap->arg = TRUE;
7935 	    cap->cmdchar = cap->nchar;
7936 	    cap->nchar = NUL;
7937 	    nv_addsub(cap);
7938 	}
7939 	else
7940 	    clearopbeep(oap);
7941 	break;
7942 
7943     /*
7944      * "gR": Enter virtual replace mode.
7945      */
7946     case 'R':
7947 	cap->arg = TRUE;
7948 	nv_Replace(cap);
7949 	break;
7950 
7951     case 'r':
7952 	nv_vreplace(cap);
7953 	break;
7954 
7955     case '&':
7956 	do_cmdline_cmd((char_u *)"%s//~/&");
7957 	break;
7958 
7959     /*
7960      * "gv": Reselect the previous Visual area.  If Visual already active,
7961      *	     exchange previous and current Visual area.
7962      */
7963     case 'v':
7964 	if (checkclearop(oap))
7965 	    break;
7966 
7967 	if (	   curbuf->b_visual.vi_start.lnum == 0
7968 		|| curbuf->b_visual.vi_start.lnum > curbuf->b_ml.ml_line_count
7969 		|| curbuf->b_visual.vi_end.lnum == 0)
7970 	    beep_flush();
7971 	else
7972 	{
7973 	    /* set w_cursor to the start of the Visual area, tpos to the end */
7974 	    if (VIsual_active)
7975 	    {
7976 		i = VIsual_mode;
7977 		VIsual_mode = curbuf->b_visual.vi_mode;
7978 		curbuf->b_visual.vi_mode = i;
7979 # ifdef FEAT_EVAL
7980 		curbuf->b_visual_mode_eval = i;
7981 # endif
7982 		i = curwin->w_curswant;
7983 		curwin->w_curswant = curbuf->b_visual.vi_curswant;
7984 		curbuf->b_visual.vi_curswant = i;
7985 
7986 		tpos = curbuf->b_visual.vi_end;
7987 		curbuf->b_visual.vi_end = curwin->w_cursor;
7988 		curwin->w_cursor = curbuf->b_visual.vi_start;
7989 		curbuf->b_visual.vi_start = VIsual;
7990 	    }
7991 	    else
7992 	    {
7993 		VIsual_mode = curbuf->b_visual.vi_mode;
7994 		curwin->w_curswant = curbuf->b_visual.vi_curswant;
7995 		tpos = curbuf->b_visual.vi_end;
7996 		curwin->w_cursor = curbuf->b_visual.vi_start;
7997 	    }
7998 
7999 	    VIsual_active = TRUE;
8000 	    VIsual_reselect = TRUE;
8001 
8002 	    /* Set Visual to the start and w_cursor to the end of the Visual
8003 	     * area.  Make sure they are on an existing character. */
8004 	    check_cursor();
8005 	    VIsual = curwin->w_cursor;
8006 	    curwin->w_cursor = tpos;
8007 	    check_cursor();
8008 	    update_topline();
8009 	    /*
8010 	     * When called from normal "g" command: start Select mode when
8011 	     * 'selectmode' contains "cmd".  When called for K_SELECT, always
8012 	     * start Select mode.
8013 	     */
8014 	    if (cap->arg)
8015 		VIsual_select = TRUE;
8016 	    else
8017 		may_start_select('c');
8018 #ifdef FEAT_MOUSE
8019 	    setmouse();
8020 #endif
8021 #ifdef FEAT_CLIPBOARD
8022 	    /* Make sure the clipboard gets updated.  Needed because start and
8023 	     * end are still the same, and the selection needs to be owned */
8024 	    clip_star.vmode = NUL;
8025 #endif
8026 	    redraw_curbuf_later(INVERTED);
8027 	    showmode();
8028 	}
8029 	break;
8030     /*
8031      * "gV": Don't reselect the previous Visual area after a Select mode
8032      *	     mapping of menu.
8033      */
8034     case 'V':
8035 	VIsual_reselect = FALSE;
8036 	break;
8037 
8038     /*
8039      * "gh":  start Select mode.
8040      * "gH":  start Select line mode.
8041      * "g^H": start Select block mode.
8042      */
8043     case K_BS:
8044 	cap->nchar = Ctrl_H;
8045 	/* FALLTHROUGH */
8046     case 'h':
8047     case 'H':
8048     case Ctrl_H:
8049 # ifdef EBCDIC
8050 	/* EBCDIC: 'v'-'h' != '^v'-'^h' */
8051 	if (cap->nchar == Ctrl_H)
8052 	    cap->cmdchar = Ctrl_V;
8053 	else
8054 # endif
8055 	cap->cmdchar = cap->nchar + ('v' - 'h');
8056 	cap->arg = TRUE;
8057 	nv_visual(cap);
8058 	break;
8059 
8060     /* "gn", "gN" visually select next/previous search match
8061      * "gn" selects next match
8062      * "gN" selects previous match
8063      */
8064     case 'N':
8065     case 'n':
8066 	if (!current_search(cap->count1, cap->nchar == 'n'))
8067 	    clearopbeep(oap);
8068 	break;
8069 
8070     /*
8071      * "gj" and "gk" two new funny movement keys -- up and down
8072      * movement based on *screen* line rather than *file* line.
8073      */
8074     case 'j':
8075     case K_DOWN:
8076 	/* with 'nowrap' it works just like the normal "j" command; also when
8077 	 * in a closed fold */
8078 	if (!curwin->w_p_wrap
8079 #ifdef FEAT_FOLDING
8080 		|| hasFolding(curwin->w_cursor.lnum, NULL, NULL)
8081 #endif
8082 		)
8083 	{
8084 	    oap->motion_type = MLINE;
8085 	    i = cursor_down(cap->count1, oap->op_type == OP_NOP);
8086 	}
8087 	else
8088 	    i = nv_screengo(oap, FORWARD, cap->count1);
8089 	if (i == FAIL)
8090 	    clearopbeep(oap);
8091 	break;
8092 
8093     case 'k':
8094     case K_UP:
8095 	/* with 'nowrap' it works just like the normal "k" command; also when
8096 	 * in a closed fold */
8097 	if (!curwin->w_p_wrap
8098 #ifdef FEAT_FOLDING
8099 		|| hasFolding(curwin->w_cursor.lnum, NULL, NULL)
8100 #endif
8101 	   )
8102 	{
8103 	    oap->motion_type = MLINE;
8104 	    i = cursor_up(cap->count1, oap->op_type == OP_NOP);
8105 	}
8106 	else
8107 	    i = nv_screengo(oap, BACKWARD, cap->count1);
8108 	if (i == FAIL)
8109 	    clearopbeep(oap);
8110 	break;
8111 
8112     /*
8113      * "gJ": join two lines without inserting a space.
8114      */
8115     case 'J':
8116 	nv_join(cap);
8117 	break;
8118 
8119     /*
8120      * "g0", "g^" and "g$": Like "0", "^" and "$" but for screen lines.
8121      * "gm": middle of "g0" and "g$".
8122      */
8123     case '^':
8124 	flag = TRUE;
8125 	/* FALLTHROUGH */
8126 
8127     case '0':
8128     case 'm':
8129     case K_HOME:
8130     case K_KHOME:
8131 	oap->motion_type = MCHAR;
8132 	oap->inclusive = FALSE;
8133 	if (curwin->w_p_wrap && curwin->w_width != 0)
8134 	{
8135 	    int		width1 = curwin->w_width - curwin_col_off();
8136 	    int		width2 = width1 + curwin_col_off2();
8137 
8138 	    validate_virtcol();
8139 	    i = 0;
8140 	    if (curwin->w_virtcol >= (colnr_T)width1 && width2 > 0)
8141 		i = (curwin->w_virtcol - width1) / width2 * width2 + width1;
8142 	}
8143 	else
8144 	    i = curwin->w_leftcol;
8145 	/* Go to the middle of the screen line.  When 'number' or
8146 	 * 'relativenumber' is on and lines are wrapping the middle can be more
8147 	 * to the left. */
8148 	if (cap->nchar == 'm')
8149 	    i += (curwin->w_width - curwin_col_off()
8150 		    + ((curwin->w_p_wrap && i > 0)
8151 			? curwin_col_off2() : 0)) / 2;
8152 	coladvance((colnr_T)i);
8153 	if (flag)
8154 	{
8155 	    do
8156 		i = gchar_cursor();
8157 	    while (VIM_ISWHITE(i) && oneright() == OK);
8158 	}
8159 	curwin->w_set_curswant = TRUE;
8160 	break;
8161 
8162     case '_':
8163 	/* "g_": to the last non-blank character in the line or <count> lines
8164 	 * downward. */
8165 	cap->oap->motion_type = MCHAR;
8166 	cap->oap->inclusive = TRUE;
8167 	curwin->w_curswant = MAXCOL;
8168 	if (cursor_down((long)(cap->count1 - 1),
8169 					 cap->oap->op_type == OP_NOP) == FAIL)
8170 	    clearopbeep(cap->oap);
8171 	else
8172 	{
8173 	    char_u  *ptr = ml_get_curline();
8174 
8175 	    /* In Visual mode we may end up after the line. */
8176 	    if (curwin->w_cursor.col > 0 && ptr[curwin->w_cursor.col] == NUL)
8177 		--curwin->w_cursor.col;
8178 
8179 	    /* Decrease the cursor column until it's on a non-blank. */
8180 	    while (curwin->w_cursor.col > 0
8181 				    && VIM_ISWHITE(ptr[curwin->w_cursor.col]))
8182 		--curwin->w_cursor.col;
8183 	    curwin->w_set_curswant = TRUE;
8184 	    adjust_for_sel(cap);
8185 	}
8186 	break;
8187 
8188     case '$':
8189     case K_END:
8190     case K_KEND:
8191 	{
8192 	    int col_off = curwin_col_off();
8193 
8194 	    oap->motion_type = MCHAR;
8195 	    oap->inclusive = TRUE;
8196 	    if (curwin->w_p_wrap && curwin->w_width != 0)
8197 	    {
8198 		curwin->w_curswant = MAXCOL;    /* so we stay at the end */
8199 		if (cap->count1 == 1)
8200 		{
8201 		    int		width1 = curwin->w_width - col_off;
8202 		    int		width2 = width1 + curwin_col_off2();
8203 
8204 		    validate_virtcol();
8205 		    i = width1 - 1;
8206 		    if (curwin->w_virtcol >= (colnr_T)width1)
8207 			i += ((curwin->w_virtcol - width1) / width2 + 1)
8208 								     * width2;
8209 		    coladvance((colnr_T)i);
8210 
8211 		    /* Make sure we stick in this column. */
8212 		    validate_virtcol();
8213 		    curwin->w_curswant = curwin->w_virtcol;
8214 		    curwin->w_set_curswant = FALSE;
8215 #if defined(FEAT_LINEBREAK) || defined(FEAT_MBYTE)
8216 		    if (curwin->w_cursor.col > 0 && curwin->w_p_wrap)
8217 		    {
8218 			/*
8219 			 * Check for landing on a character that got split at
8220 			 * the end of the line.  We do not want to advance to
8221 			 * the next screen line.
8222 			 */
8223 			if (curwin->w_virtcol > (colnr_T)i)
8224 			    --curwin->w_cursor.col;
8225 		    }
8226 #endif
8227 		}
8228 		else if (nv_screengo(oap, FORWARD, cap->count1 - 1) == FAIL)
8229 		    clearopbeep(oap);
8230 	    }
8231 	    else
8232 	    {
8233 		i = curwin->w_leftcol + curwin->w_width - col_off - 1;
8234 		coladvance((colnr_T)i);
8235 
8236 		/* Make sure we stick in this column. */
8237 		validate_virtcol();
8238 		curwin->w_curswant = curwin->w_virtcol;
8239 		curwin->w_set_curswant = FALSE;
8240 	    }
8241 	}
8242 	break;
8243 
8244     /*
8245      * "g*" and "g#", like "*" and "#" but without using "\<" and "\>"
8246      */
8247     case '*':
8248     case '#':
8249 #if POUND != '#'
8250     case POUND:		/* pound sign (sometimes equal to '#') */
8251 #endif
8252     case Ctrl_RSB:		/* :tag or :tselect for current identifier */
8253     case ']':			/* :tselect for current identifier */
8254 	nv_ident(cap);
8255 	break;
8256 
8257     /*
8258      * ge and gE: go back to end of word
8259      */
8260     case 'e':
8261     case 'E':
8262 	oap->motion_type = MCHAR;
8263 	curwin->w_set_curswant = TRUE;
8264 	oap->inclusive = TRUE;
8265 	if (bckend_word(cap->count1, cap->nchar == 'E', FALSE) == FAIL)
8266 	    clearopbeep(oap);
8267 	break;
8268 
8269     /*
8270      * "g CTRL-G": display info about cursor position
8271      */
8272     case Ctrl_G:
8273 	cursor_pos_info(NULL);
8274 	break;
8275 
8276     /*
8277      * "gi": start Insert at the last position.
8278      */
8279     case 'i':
8280 	if (curbuf->b_last_insert.lnum != 0)
8281 	{
8282 	    curwin->w_cursor = curbuf->b_last_insert;
8283 	    check_cursor_lnum();
8284 	    i = (int)STRLEN(ml_get_curline());
8285 	    if (curwin->w_cursor.col > (colnr_T)i)
8286 	    {
8287 #ifdef FEAT_VIRTUALEDIT
8288 		if (virtual_active())
8289 		    curwin->w_cursor.coladd += curwin->w_cursor.col - i;
8290 #endif
8291 		curwin->w_cursor.col = i;
8292 	    }
8293 	}
8294 	cap->cmdchar = 'i';
8295 	nv_edit(cap);
8296 	break;
8297 
8298     /*
8299      * "gI": Start insert in column 1.
8300      */
8301     case 'I':
8302 	beginline(0);
8303 	if (!checkclearopq(oap))
8304 	    invoke_edit(cap, FALSE, 'g', FALSE);
8305 	break;
8306 
8307 #ifdef FEAT_SEARCHPATH
8308     /*
8309      * "gf": goto file, edit file under cursor
8310      * "]f" and "[f": can also be used.
8311      */
8312     case 'f':
8313     case 'F':
8314 	nv_gotofile(cap);
8315 	break;
8316 #endif
8317 
8318 	/* "g'm" and "g`m": jump to mark without setting pcmark */
8319     case '\'':
8320 	cap->arg = TRUE;
8321 	/* FALLTHROUGH */
8322     case '`':
8323 	nv_gomark(cap);
8324 	break;
8325 
8326     /*
8327      * "gs": Goto sleep.
8328      */
8329     case 's':
8330 	do_sleep(cap->count1 * 1000L);
8331 	break;
8332 
8333     /*
8334      * "ga": Display the ascii value of the character under the
8335      * cursor.	It is displayed in decimal, hex, and octal. -- webb
8336      */
8337     case 'a':
8338 	do_ascii(NULL);
8339 	break;
8340 
8341 #ifdef FEAT_MBYTE
8342     /*
8343      * "g8": Display the bytes used for the UTF-8 character under the
8344      * cursor.	It is displayed in hex.
8345      * "8g8" finds illegal byte sequence.
8346      */
8347     case '8':
8348 	if (cap->count0 == 8)
8349 	    utf_find_illegal();
8350 	else
8351 	    show_utf8();
8352 	break;
8353 #endif
8354 
8355     /* "g<": show scrollback text */
8356     case '<':
8357 	show_sb_text();
8358 	break;
8359 
8360     /*
8361      * "gg": Goto the first line in file.  With a count it goes to
8362      * that line number like for "G". -- webb
8363      */
8364     case 'g':
8365 	cap->arg = FALSE;
8366 	nv_goto(cap);
8367 	break;
8368 
8369     /*
8370      *	 Two-character operators:
8371      *	 "gq"	    Format text
8372      *	 "gw"	    Format text and keep cursor position
8373      *	 "g~"	    Toggle the case of the text.
8374      *	 "gu"	    Change text to lower case.
8375      *	 "gU"	    Change text to upper case.
8376      *   "g?"	    rot13 encoding
8377      *   "g@"	    call 'operatorfunc'
8378      */
8379     case 'q':
8380     case 'w':
8381 	oap->cursor_start = curwin->w_cursor;
8382 	/* FALLTHROUGH */
8383     case '~':
8384     case 'u':
8385     case 'U':
8386     case '?':
8387     case '@':
8388 	nv_operator(cap);
8389 	break;
8390 
8391     /*
8392      * "gd": Find first occurrence of pattern under the cursor in the
8393      *	 current function
8394      * "gD": idem, but in the current file.
8395      */
8396     case 'd':
8397     case 'D':
8398 	nv_gd(oap, cap->nchar, (int)cap->count0);
8399 	break;
8400 
8401 #ifdef FEAT_MOUSE
8402     /*
8403      * g<*Mouse> : <C-*mouse>
8404      */
8405     case K_MIDDLEMOUSE:
8406     case K_MIDDLEDRAG:
8407     case K_MIDDLERELEASE:
8408     case K_LEFTMOUSE:
8409     case K_LEFTDRAG:
8410     case K_LEFTRELEASE:
8411     case K_MOUSEMOVE:
8412     case K_RIGHTMOUSE:
8413     case K_RIGHTDRAG:
8414     case K_RIGHTRELEASE:
8415     case K_X1MOUSE:
8416     case K_X1DRAG:
8417     case K_X1RELEASE:
8418     case K_X2MOUSE:
8419     case K_X2DRAG:
8420     case K_X2RELEASE:
8421 	mod_mask = MOD_MASK_CTRL;
8422 	(void)do_mouse(oap, cap->nchar, BACKWARD, cap->count1, 0);
8423 	break;
8424 #endif
8425 
8426     case K_IGNORE:
8427 	break;
8428 
8429     /*
8430      * "gP" and "gp": same as "P" and "p" but leave cursor just after new text
8431      */
8432     case 'p':
8433     case 'P':
8434 	nv_put(cap);
8435 	break;
8436 
8437 #ifdef FEAT_BYTEOFF
8438     /* "go": goto byte count from start of buffer */
8439     case 'o':
8440 	goto_byte(cap->count0);
8441 	break;
8442 #endif
8443 
8444     /* "gQ": improved Ex mode */
8445     case 'Q':
8446 	if (text_locked())
8447 	{
8448 	    clearopbeep(cap->oap);
8449 	    text_locked_msg();
8450 	    break;
8451 	}
8452 
8453 	if (!checkclearopq(oap))
8454 	    do_exmode(TRUE);
8455 	break;
8456 
8457 #ifdef FEAT_JUMPLIST
8458     case ',':
8459 	nv_pcmark(cap);
8460 	break;
8461 
8462     case ';':
8463 	cap->count1 = -cap->count1;
8464 	nv_pcmark(cap);
8465 	break;
8466 #endif
8467 
8468     case 't':
8469 	if (!checkclearop(oap))
8470 	    goto_tabpage((int)cap->count0);
8471 	break;
8472     case 'T':
8473 	if (!checkclearop(oap))
8474 	    goto_tabpage(-(int)cap->count1);
8475 	break;
8476 
8477     case '+':
8478     case '-': /* "g+" and "g-": undo or redo along the timeline */
8479 	if (!checkclearopq(oap))
8480 	    undo_time(cap->nchar == '-' ? -cap->count1 : cap->count1,
8481 							 FALSE, FALSE, FALSE);
8482 	break;
8483 
8484     default:
8485 	clearopbeep(oap);
8486 	break;
8487     }
8488 }
8489 
8490 /*
8491  * Handle "o" and "O" commands.
8492  */
8493     static void
8494 n_opencmd(cmdarg_T *cap)
8495 {
8496 #ifdef FEAT_CONCEAL
8497     linenr_T	oldline = curwin->w_cursor.lnum;
8498 #endif
8499 
8500     if (!checkclearopq(cap->oap))
8501     {
8502 #ifdef FEAT_FOLDING
8503 	if (cap->cmdchar == 'O')
8504 	    /* Open above the first line of a folded sequence of lines */
8505 	    (void)hasFolding(curwin->w_cursor.lnum,
8506 						&curwin->w_cursor.lnum, NULL);
8507 	else
8508 	    /* Open below the last line of a folded sequence of lines */
8509 	    (void)hasFolding(curwin->w_cursor.lnum,
8510 						NULL, &curwin->w_cursor.lnum);
8511 #endif
8512 	if (u_save((linenr_T)(curwin->w_cursor.lnum -
8513 					       (cap->cmdchar == 'O' ? 1 : 0)),
8514 		   (linenr_T)(curwin->w_cursor.lnum +
8515 					       (cap->cmdchar == 'o' ? 1 : 0))
8516 		       ) == OK
8517 		&& open_line(cap->cmdchar == 'O' ? BACKWARD : FORWARD,
8518 #ifdef FEAT_COMMENTS
8519 		    has_format_option(FO_OPEN_COMS) ? OPENLINE_DO_COM :
8520 #endif
8521 		    0, 0) == OK)
8522 	{
8523 #ifdef FEAT_CONCEAL
8524 	    if (curwin->w_p_cole > 0 && oldline != curwin->w_cursor.lnum)
8525 		update_single_line(curwin, oldline);
8526 #endif
8527 	    /* When '#' is in 'cpoptions' ignore the count. */
8528 	    if (vim_strchr(p_cpo, CPO_HASH) != NULL)
8529 		cap->count1 = 1;
8530 #ifdef FEAT_SYN_HL
8531 	    if (curwin->w_p_cul)
8532 		/* force redraw of cursorline */
8533 		curwin->w_valid &= ~VALID_CROW;
8534 #endif
8535 	    invoke_edit(cap, FALSE, cap->cmdchar, TRUE);
8536 	}
8537     }
8538 }
8539 
8540 /*
8541  * "." command: redo last change.
8542  */
8543     static void
8544 nv_dot(cmdarg_T *cap)
8545 {
8546     if (!checkclearopq(cap->oap))
8547     {
8548 	/*
8549 	 * If "restart_edit" is TRUE, the last but one command is repeated
8550 	 * instead of the last command (inserting text). This is used for
8551 	 * CTRL-O <.> in insert mode.
8552 	 */
8553 	if (start_redo(cap->count0, restart_edit != 0 && !arrow_used) == FAIL)
8554 	    clearopbeep(cap->oap);
8555     }
8556 }
8557 
8558 /*
8559  * CTRL-R: undo undo
8560  */
8561     static void
8562 nv_redo(cmdarg_T *cap)
8563 {
8564     if (!checkclearopq(cap->oap))
8565     {
8566 	u_redo((int)cap->count1);
8567 	curwin->w_set_curswant = TRUE;
8568     }
8569 }
8570 
8571 /*
8572  * Handle "U" command.
8573  */
8574     static void
8575 nv_Undo(cmdarg_T *cap)
8576 {
8577     /* In Visual mode and typing "gUU" triggers an operator */
8578     if (cap->oap->op_type == OP_UPPER || VIsual_active)
8579     {
8580 	/* translate "gUU" to "gUgU" */
8581 	cap->cmdchar = 'g';
8582 	cap->nchar = 'U';
8583 	nv_operator(cap);
8584     }
8585     else if (!checkclearopq(cap->oap))
8586     {
8587 	u_undoline();
8588 	curwin->w_set_curswant = TRUE;
8589     }
8590 }
8591 
8592 /*
8593  * '~' command: If tilde is not an operator and Visual is off: swap case of a
8594  * single character.
8595  */
8596     static void
8597 nv_tilde(cmdarg_T *cap)
8598 {
8599     if (!p_to && !VIsual_active && cap->oap->op_type != OP_TILDE)
8600     {
8601 #ifdef FEAT_JOB_CHANNEL
8602 	if (bt_prompt(curbuf) && !prompt_curpos_editable())
8603 	{
8604 	    clearopbeep(cap->oap);
8605 	    return;
8606 	}
8607 #endif
8608 	n_swapchar(cap);
8609     }
8610     else
8611 	nv_operator(cap);
8612 }
8613 
8614 /*
8615  * Handle an operator command.
8616  * The actual work is done by do_pending_operator().
8617  */
8618     static void
8619 nv_operator(cmdarg_T *cap)
8620 {
8621     int	    op_type;
8622 
8623     op_type = get_op_type(cap->cmdchar, cap->nchar);
8624 #ifdef FEAT_JOB_CHANNEL
8625     if (bt_prompt(curbuf) && op_is_change(op_type) && !prompt_curpos_editable())
8626     {
8627 	clearopbeep(cap->oap);
8628 	return;
8629     }
8630 #endif
8631 
8632     if (op_type == cap->oap->op_type)	    /* double operator works on lines */
8633 	nv_lineop(cap);
8634     else if (!checkclearop(cap->oap))
8635     {
8636 	cap->oap->start = curwin->w_cursor;
8637 	cap->oap->op_type = op_type;
8638 #ifdef FEAT_EVAL
8639 	set_op_var(op_type);
8640 #endif
8641     }
8642 }
8643 
8644 #ifdef FEAT_EVAL
8645 /*
8646  * Set v:operator to the characters for "optype".
8647  */
8648     static void
8649 set_op_var(int optype)
8650 {
8651     char_u	opchars[3];
8652 
8653     if (optype == OP_NOP)
8654 	set_vim_var_string(VV_OP, NULL, 0);
8655     else
8656     {
8657 	opchars[0] = get_op_char(optype);
8658 	opchars[1] = get_extra_op_char(optype);
8659 	opchars[2] = NUL;
8660 	set_vim_var_string(VV_OP, opchars, -1);
8661     }
8662 }
8663 #endif
8664 
8665 /*
8666  * Handle linewise operator "dd", "yy", etc.
8667  *
8668  * "_" is is a strange motion command that helps make operators more logical.
8669  * It is actually implemented, but not documented in the real Vi.  This motion
8670  * command actually refers to "the current line".  Commands like "dd" and "yy"
8671  * are really an alternate form of "d_" and "y_".  It does accept a count, so
8672  * "d3_" works to delete 3 lines.
8673  */
8674     static void
8675 nv_lineop(cmdarg_T *cap)
8676 {
8677     cap->oap->motion_type = MLINE;
8678     if (cursor_down(cap->count1 - 1L, cap->oap->op_type == OP_NOP) == FAIL)
8679 	clearopbeep(cap->oap);
8680     else if (  (cap->oap->op_type == OP_DELETE /* only with linewise motions */
8681 		&& cap->oap->motion_force != 'v'
8682 		&& cap->oap->motion_force != Ctrl_V)
8683 	    || cap->oap->op_type == OP_LSHIFT
8684 	    || cap->oap->op_type == OP_RSHIFT)
8685 	beginline(BL_SOL | BL_FIX);
8686     else if (cap->oap->op_type != OP_YANK)	/* 'Y' does not move cursor */
8687 	beginline(BL_WHITE | BL_FIX);
8688 }
8689 
8690 /*
8691  * <Home> command.
8692  */
8693     static void
8694 nv_home(cmdarg_T *cap)
8695 {
8696     /* CTRL-HOME is like "gg" */
8697     if (mod_mask & MOD_MASK_CTRL)
8698 	nv_goto(cap);
8699     else
8700     {
8701 	cap->count0 = 1;
8702 	nv_pipe(cap);
8703     }
8704     ins_at_eol = FALSE;	    /* Don't move cursor past eol (only necessary in a
8705 			       one-character line). */
8706 }
8707 
8708 /*
8709  * "|" command.
8710  */
8711     static void
8712 nv_pipe(cmdarg_T *cap)
8713 {
8714     cap->oap->motion_type = MCHAR;
8715     cap->oap->inclusive = FALSE;
8716     beginline(0);
8717     if (cap->count0 > 0)
8718     {
8719 	coladvance((colnr_T)(cap->count0 - 1));
8720 	curwin->w_curswant = (colnr_T)(cap->count0 - 1);
8721     }
8722     else
8723 	curwin->w_curswant = 0;
8724     /* keep curswant at the column where we wanted to go, not where
8725      * we ended; differs if line is too short */
8726     curwin->w_set_curswant = FALSE;
8727 }
8728 
8729 /*
8730  * Handle back-word command "b" and "B".
8731  * cap->arg is 1 for "B"
8732  */
8733     static void
8734 nv_bck_word(cmdarg_T *cap)
8735 {
8736     cap->oap->motion_type = MCHAR;
8737     cap->oap->inclusive = FALSE;
8738     curwin->w_set_curswant = TRUE;
8739     if (bck_word(cap->count1, cap->arg, FALSE) == FAIL)
8740 	clearopbeep(cap->oap);
8741 #ifdef FEAT_FOLDING
8742     else if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
8743 	foldOpenCursor();
8744 #endif
8745 }
8746 
8747 /*
8748  * Handle word motion commands "e", "E", "w" and "W".
8749  * cap->arg is TRUE for "E" and "W".
8750  */
8751     static void
8752 nv_wordcmd(cmdarg_T *cap)
8753 {
8754     int		n;
8755     int		word_end;
8756     int		flag = FALSE;
8757     pos_T	startpos = curwin->w_cursor;
8758 
8759     /*
8760      * Set inclusive for the "E" and "e" command.
8761      */
8762     if (cap->cmdchar == 'e' || cap->cmdchar == 'E')
8763 	word_end = TRUE;
8764     else
8765 	word_end = FALSE;
8766     cap->oap->inclusive = word_end;
8767 
8768     /*
8769      * "cw" and "cW" are a special case.
8770      */
8771     if (!word_end && cap->oap->op_type == OP_CHANGE)
8772     {
8773 	n = gchar_cursor();
8774 	if (n != NUL)			/* not an empty line */
8775 	{
8776 	    if (VIM_ISWHITE(n))
8777 	    {
8778 		/*
8779 		 * Reproduce a funny Vi behaviour: "cw" on a blank only
8780 		 * changes one character, not all blanks until the start of
8781 		 * the next word.  Only do this when the 'w' flag is included
8782 		 * in 'cpoptions'.
8783 		 */
8784 		if (cap->count1 == 1 && vim_strchr(p_cpo, CPO_CW) != NULL)
8785 		{
8786 		    cap->oap->inclusive = TRUE;
8787 		    cap->oap->motion_type = MCHAR;
8788 		    return;
8789 		}
8790 	    }
8791 	    else
8792 	    {
8793 		/*
8794 		 * This is a little strange. To match what the real Vi does,
8795 		 * we effectively map 'cw' to 'ce', and 'cW' to 'cE', provided
8796 		 * that we are not on a space or a TAB.  This seems impolite
8797 		 * at first, but it's really more what we mean when we say
8798 		 * 'cw'.
8799 		 * Another strangeness: When standing on the end of a word
8800 		 * "ce" will change until the end of the next word, but "cw"
8801 		 * will change only one character! This is done by setting
8802 		 * flag.
8803 		 */
8804 		cap->oap->inclusive = TRUE;
8805 		word_end = TRUE;
8806 		flag = TRUE;
8807 	    }
8808 	}
8809     }
8810 
8811     cap->oap->motion_type = MCHAR;
8812     curwin->w_set_curswant = TRUE;
8813     if (word_end)
8814 	n = end_word(cap->count1, cap->arg, flag, FALSE);
8815     else
8816 	n = fwd_word(cap->count1, cap->arg, cap->oap->op_type != OP_NOP);
8817 
8818     /* Don't leave the cursor on the NUL past the end of line. Unless we
8819      * didn't move it forward. */
8820     if (LT_POS(startpos, curwin->w_cursor))
8821 	adjust_cursor(cap->oap);
8822 
8823     if (n == FAIL && cap->oap->op_type == OP_NOP)
8824 	clearopbeep(cap->oap);
8825     else
8826     {
8827 	adjust_for_sel(cap);
8828 #ifdef FEAT_FOLDING
8829 	if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
8830 	    foldOpenCursor();
8831 #endif
8832     }
8833 }
8834 
8835 /*
8836  * Used after a movement command: If the cursor ends up on the NUL after the
8837  * end of the line, may move it back to the last character and make the motion
8838  * inclusive.
8839  */
8840     static void
8841 adjust_cursor(oparg_T *oap)
8842 {
8843     /* The cursor cannot remain on the NUL when:
8844      * - the column is > 0
8845      * - not in Visual mode or 'selection' is "o"
8846      * - 'virtualedit' is not "all" and not "onemore".
8847      */
8848     if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL
8849 		&& (!VIsual_active || *p_sel == 'o')
8850 #ifdef FEAT_VIRTUALEDIT
8851 		&& !virtual_active() && (ve_flags & VE_ONEMORE) == 0
8852 #endif
8853 		)
8854     {
8855 	--curwin->w_cursor.col;
8856 #ifdef FEAT_MBYTE
8857 	/* prevent cursor from moving on the trail byte */
8858 	if (has_mbyte)
8859 	    mb_adjust_cursor();
8860 #endif
8861 	oap->inclusive = TRUE;
8862     }
8863 }
8864 
8865 /*
8866  * "0" and "^" commands.
8867  * cap->arg is the argument for beginline().
8868  */
8869     static void
8870 nv_beginline(cmdarg_T *cap)
8871 {
8872     cap->oap->motion_type = MCHAR;
8873     cap->oap->inclusive = FALSE;
8874     beginline(cap->arg);
8875 #ifdef FEAT_FOLDING
8876     if ((fdo_flags & FDO_HOR) && KeyTyped && cap->oap->op_type == OP_NOP)
8877 	foldOpenCursor();
8878 #endif
8879     ins_at_eol = FALSE;	    /* Don't move cursor past eol (only necessary in a
8880 			       one-character line). */
8881 }
8882 
8883 /*
8884  * In exclusive Visual mode, may include the last character.
8885  */
8886     static void
8887 adjust_for_sel(cmdarg_T *cap)
8888 {
8889     if (VIsual_active && cap->oap->inclusive && *p_sel == 'e'
8890 	    && gchar_cursor() != NUL && LT_POS(VIsual, curwin->w_cursor))
8891     {
8892 #ifdef FEAT_MBYTE
8893 	if (has_mbyte)
8894 	    inc_cursor();
8895 	else
8896 #endif
8897 	    ++curwin->w_cursor.col;
8898 	cap->oap->inclusive = FALSE;
8899     }
8900 }
8901 
8902 /*
8903  * Exclude last character at end of Visual area for 'selection' == "exclusive".
8904  * Should check VIsual_mode before calling this.
8905  * Returns TRUE when backed up to the previous line.
8906  */
8907     static int
8908 unadjust_for_sel(void)
8909 {
8910     pos_T	*pp;
8911 
8912     if (*p_sel == 'e' && !EQUAL_POS(VIsual, curwin->w_cursor))
8913     {
8914 	if (LT_POS(VIsual, curwin->w_cursor))
8915 	    pp = &curwin->w_cursor;
8916 	else
8917 	    pp = &VIsual;
8918 #ifdef FEAT_VIRTUALEDIT
8919 	if (pp->coladd > 0)
8920 	    --pp->coladd;
8921 	else
8922 #endif
8923 	if (pp->col > 0)
8924 	{
8925 	    --pp->col;
8926 #ifdef FEAT_MBYTE
8927 	    mb_adjustpos(curbuf, pp);
8928 #endif
8929 	}
8930 	else if (pp->lnum > 1)
8931 	{
8932 	    --pp->lnum;
8933 	    pp->col = (colnr_T)STRLEN(ml_get(pp->lnum));
8934 	    return TRUE;
8935 	}
8936     }
8937     return FALSE;
8938 }
8939 
8940 /*
8941  * SELECT key in Normal or Visual mode: end of Select mode mapping.
8942  */
8943     static void
8944 nv_select(cmdarg_T *cap)
8945 {
8946     if (VIsual_active)
8947 	VIsual_select = TRUE;
8948     else if (VIsual_reselect)
8949     {
8950 	cap->nchar = 'v';	    /* fake "gv" command */
8951 	cap->arg = TRUE;
8952 	nv_g_cmd(cap);
8953     }
8954 }
8955 
8956 
8957 /*
8958  * "G", "gg", CTRL-END, CTRL-HOME.
8959  * cap->arg is TRUE for "G".
8960  */
8961     static void
8962 nv_goto(cmdarg_T *cap)
8963 {
8964     linenr_T	lnum;
8965 
8966     if (cap->arg)
8967 	lnum = curbuf->b_ml.ml_line_count;
8968     else
8969 	lnum = 1L;
8970     cap->oap->motion_type = MLINE;
8971     setpcmark();
8972 
8973     /* When a count is given, use it instead of the default lnum */
8974     if (cap->count0 != 0)
8975 	lnum = cap->count0;
8976     if (lnum < 1L)
8977 	lnum = 1L;
8978     else if (lnum > curbuf->b_ml.ml_line_count)
8979 	lnum = curbuf->b_ml.ml_line_count;
8980     curwin->w_cursor.lnum = lnum;
8981     beginline(BL_SOL | BL_FIX);
8982 #ifdef FEAT_FOLDING
8983     if ((fdo_flags & FDO_JUMP) && KeyTyped && cap->oap->op_type == OP_NOP)
8984 	foldOpenCursor();
8985 #endif
8986 }
8987 
8988 /*
8989  * CTRL-\ in Normal mode.
8990  */
8991     static void
8992 nv_normal(cmdarg_T *cap)
8993 {
8994     if (cap->nchar == Ctrl_N || cap->nchar == Ctrl_G)
8995     {
8996 	clearop(cap->oap);
8997 	if (restart_edit != 0 && mode_displayed)
8998 	    clear_cmdline = TRUE;		/* unshow mode later */
8999 	restart_edit = 0;
9000 #ifdef FEAT_CMDWIN
9001 	if (cmdwin_type != 0)
9002 	    cmdwin_result = Ctrl_C;
9003 #endif
9004 	if (VIsual_active)
9005 	{
9006 	    end_visual_mode();		/* stop Visual */
9007 	    redraw_curbuf_later(INVERTED);
9008 	}
9009 	/* CTRL-\ CTRL-G restarts Insert mode when 'insertmode' is set. */
9010 	if (cap->nchar == Ctrl_G && p_im)
9011 	    restart_edit = 'a';
9012     }
9013     else
9014 	clearopbeep(cap->oap);
9015 }
9016 
9017 /*
9018  * ESC in Normal mode: beep, but don't flush buffers.
9019  * Don't even beep if we are canceling a command.
9020  */
9021     static void
9022 nv_esc(cmdarg_T *cap)
9023 {
9024     int		no_reason;
9025 
9026     no_reason = (cap->oap->op_type == OP_NOP
9027 		&& cap->opcount == 0
9028 		&& cap->count0 == 0
9029 		&& cap->oap->regname == 0
9030 		&& !p_im);
9031 
9032     if (cap->arg)		/* TRUE for CTRL-C */
9033     {
9034 	if (restart_edit == 0
9035 #ifdef FEAT_CMDWIN
9036 		&& cmdwin_type == 0
9037 #endif
9038 		&& !VIsual_active
9039 		&& no_reason)
9040 	    MSG(_("Type  :qa!  and press <Enter> to abandon all changes and exit Vim"));
9041 
9042 	/* Don't reset "restart_edit" when 'insertmode' is set, it won't be
9043 	 * set again below when halfway a mapping. */
9044 	if (!p_im)
9045 	    restart_edit = 0;
9046 #ifdef FEAT_CMDWIN
9047 	if (cmdwin_type != 0)
9048 	{
9049 	    cmdwin_result = K_IGNORE;
9050 	    got_int = FALSE;	/* don't stop executing autocommands et al. */
9051 	    return;
9052 	}
9053 #endif
9054     }
9055 
9056     if (VIsual_active)
9057     {
9058 	end_visual_mode();	/* stop Visual */
9059 	check_cursor_col();	/* make sure cursor is not beyond EOL */
9060 	curwin->w_set_curswant = TRUE;
9061 	redraw_curbuf_later(INVERTED);
9062     }
9063     else if (no_reason)
9064 	vim_beep(BO_ESC);
9065     clearop(cap->oap);
9066 
9067     /* A CTRL-C is often used at the start of a menu.  When 'insertmode' is
9068      * set return to Insert mode afterwards. */
9069     if (restart_edit == 0 && goto_im() && ex_normal_busy == 0)
9070 	restart_edit = 'a';
9071 }
9072 
9073 /*
9074  * Handle "A", "a", "I", "i" and <Insert> commands.
9075  * Also handle K_PS, start bracketed paste.
9076  */
9077     static void
9078 nv_edit(cmdarg_T *cap)
9079 {
9080     /* <Insert> is equal to "i" */
9081     if (cap->cmdchar == K_INS || cap->cmdchar == K_KINS)
9082 	cap->cmdchar = 'i';
9083 
9084     /* in Visual mode "A" and "I" are an operator */
9085     if (VIsual_active && (cap->cmdchar == 'A' || cap->cmdchar == 'I'))
9086     {
9087 #ifdef FEAT_TERMINAL
9088 	if (term_in_normal_mode())
9089 	{
9090 	    end_visual_mode();
9091 	    clearop(cap->oap);
9092 	    term_enter_job_mode();
9093 	    return;
9094 	}
9095 #endif
9096 	v_visop(cap);
9097     }
9098 
9099     /* in Visual mode and after an operator "a" and "i" are for text objects */
9100     else if ((cap->cmdchar == 'a' || cap->cmdchar == 'i')
9101 	    && (cap->oap->op_type != OP_NOP || VIsual_active))
9102     {
9103 #ifdef FEAT_TEXTOBJ
9104 	nv_object(cap);
9105 #else
9106 	clearopbeep(cap->oap);
9107 #endif
9108     }
9109 #ifdef FEAT_TERMINAL
9110     else if (term_in_normal_mode())
9111     {
9112 	clearop(cap->oap);
9113 	term_enter_job_mode();
9114 	return;
9115     }
9116 #endif
9117     else if (!curbuf->b_p_ma && !p_im)
9118     {
9119 	/* Only give this error when 'insertmode' is off. */
9120 	EMSG(_(e_modifiable));
9121 	clearop(cap->oap);
9122 	if (cap->cmdchar == K_PS)
9123 	    /* drop the pasted text */
9124 	    bracketed_paste(PASTE_INSERT, TRUE, NULL);
9125     }
9126     else if (cap->cmdchar == K_PS && VIsual_active)
9127     {
9128 	pos_T old_pos = curwin->w_cursor;
9129 	pos_T old_visual = VIsual;
9130 
9131 	/* In Visual mode the selected text is deleted. */
9132 	if (VIsual_mode == 'V' || curwin->w_cursor.lnum != VIsual.lnum)
9133 	{
9134 	    shift_delete_registers();
9135 	    cap->oap->regname = '1';
9136 	}
9137 	else
9138 	    cap->oap->regname = '-';
9139 	cap->cmdchar = 'd';
9140 	cap->nchar = NUL;
9141 	nv_operator(cap);
9142 	do_pending_operator(cap, 0, FALSE);
9143 	cap->cmdchar = K_PS;
9144 
9145 	/* When the last char in the line was deleted then append. Detect this
9146 	 * by checking if the cursor moved to before the Visual area. */
9147 	if (*ml_get_cursor() != NUL && LT_POS(curwin->w_cursor, old_pos)
9148 				       && LT_POS(curwin->w_cursor, old_visual))
9149 	    inc_cursor();
9150 
9151 	/* Insert to replace the deleted text with the pasted text. */
9152 	invoke_edit(cap, FALSE, cap->cmdchar, FALSE);
9153     }
9154     else if (!checkclearopq(cap->oap))
9155     {
9156 	switch (cap->cmdchar)
9157 	{
9158 	    case 'A':	/* "A"ppend after the line */
9159 		curwin->w_set_curswant = TRUE;
9160 #ifdef FEAT_VIRTUALEDIT
9161 		if (ve_flags == VE_ALL)
9162 		{
9163 		    int save_State = State;
9164 
9165 		    /* Pretend Insert mode here to allow the cursor on the
9166 		     * character past the end of the line */
9167 		    State = INSERT;
9168 		    coladvance((colnr_T)MAXCOL);
9169 		    State = save_State;
9170 		}
9171 		else
9172 #endif
9173 		    curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9174 		break;
9175 
9176 	    case 'I':	/* "I"nsert before the first non-blank */
9177 		if (vim_strchr(p_cpo, CPO_INSEND) == NULL)
9178 		    beginline(BL_WHITE);
9179 		else
9180 		    beginline(BL_WHITE|BL_FIX);
9181 		break;
9182 
9183 	    case K_PS:
9184 		/* Bracketed paste works like "a"ppend, unless the cursor is in
9185 		 * the first column, then it inserts. */
9186 		if (curwin->w_cursor.col == 0)
9187 		    break;
9188 		/* FALLTHROUGH */
9189 
9190 	    case 'a':	/* "a"ppend is like "i"nsert on the next character. */
9191 #ifdef FEAT_VIRTUALEDIT
9192 		/* increment coladd when in virtual space, increment the
9193 		 * column otherwise, also to append after an unprintable char */
9194 		if (virtual_active()
9195 			&& (curwin->w_cursor.coladd > 0
9196 			    || *ml_get_cursor() == NUL
9197 			    || *ml_get_cursor() == TAB))
9198 		    curwin->w_cursor.coladd++;
9199 		else
9200 #endif
9201 		if (*ml_get_cursor() != NUL)
9202 		    inc_cursor();
9203 		break;
9204 	}
9205 
9206 #ifdef FEAT_VIRTUALEDIT
9207 	if (curwin->w_cursor.coladd && cap->cmdchar != 'A')
9208 	{
9209 	    int save_State = State;
9210 
9211 	    /* Pretend Insert mode here to allow the cursor on the
9212 	     * character past the end of the line */
9213 	    State = INSERT;
9214 	    coladvance(getviscol());
9215 	    State = save_State;
9216 	}
9217 #endif
9218 
9219 	invoke_edit(cap, FALSE, cap->cmdchar, FALSE);
9220     }
9221     else if (cap->cmdchar == K_PS)
9222 	/* drop the pasted text */
9223 	bracketed_paste(PASTE_INSERT, TRUE, NULL);
9224 }
9225 
9226 /*
9227  * Invoke edit() and take care of "restart_edit" and the return value.
9228  */
9229     static void
9230 invoke_edit(
9231     cmdarg_T	*cap,
9232     int		repl,		/* "r" or "gr" command */
9233     int		cmd,
9234     int		startln)
9235 {
9236     int		restart_edit_save = 0;
9237 
9238     /* Complicated: When the user types "a<C-O>a" we don't want to do Insert
9239      * mode recursively.  But when doing "a<C-O>." or "a<C-O>rx" we do allow
9240      * it. */
9241     if (repl || !stuff_empty())
9242 	restart_edit_save = restart_edit;
9243     else
9244 	restart_edit_save = 0;
9245 
9246     /* Always reset "restart_edit", this is not a restarted edit. */
9247     restart_edit = 0;
9248 
9249     if (edit(cmd, startln, cap->count1))
9250 	cap->retval |= CA_COMMAND_BUSY;
9251 
9252     if (restart_edit == 0)
9253 	restart_edit = restart_edit_save;
9254 }
9255 
9256 #ifdef FEAT_TEXTOBJ
9257 /*
9258  * "a" or "i" while an operator is pending or in Visual mode: object motion.
9259  */
9260     static void
9261 nv_object(
9262     cmdarg_T	*cap)
9263 {
9264     int		flag;
9265     int		include;
9266     char_u	*mps_save;
9267 
9268     if (cap->cmdchar == 'i')
9269 	include = FALSE;    /* "ix" = inner object: exclude white space */
9270     else
9271 	include = TRUE;	    /* "ax" = an object: include white space */
9272 
9273     /* Make sure (), [], {} and <> are in 'matchpairs' */
9274     mps_save = curbuf->b_p_mps;
9275     curbuf->b_p_mps = (char_u *)"(:),{:},[:],<:>";
9276 
9277     switch (cap->nchar)
9278     {
9279 	case 'w': /* "aw" = a word */
9280 		flag = current_word(cap->oap, cap->count1, include, FALSE);
9281 		break;
9282 	case 'W': /* "aW" = a WORD */
9283 		flag = current_word(cap->oap, cap->count1, include, TRUE);
9284 		break;
9285 	case 'b': /* "ab" = a braces block */
9286 	case '(':
9287 	case ')':
9288 		flag = current_block(cap->oap, cap->count1, include, '(', ')');
9289 		break;
9290 	case 'B': /* "aB" = a Brackets block */
9291 	case '{':
9292 	case '}':
9293 		flag = current_block(cap->oap, cap->count1, include, '{', '}');
9294 		break;
9295 	case '[': /* "a[" = a [] block */
9296 	case ']':
9297 		flag = current_block(cap->oap, cap->count1, include, '[', ']');
9298 		break;
9299 	case '<': /* "a<" = a <> block */
9300 	case '>':
9301 		flag = current_block(cap->oap, cap->count1, include, '<', '>');
9302 		break;
9303 	case 't': /* "at" = a tag block (xml and html) */
9304 		/* Do not adjust oap->end in do_pending_operator()
9305 		 * otherwise there are different results for 'dit'
9306 		 * (note leading whitespace in last line):
9307 		 * 1) <b>      2) <b>
9308 		 *    foobar      foobar
9309 		 *    </b>            </b>
9310 		 */
9311 		cap->retval |= CA_NO_ADJ_OP_END;
9312 		flag = current_tagblock(cap->oap, cap->count1, include);
9313 		break;
9314 	case 'p': /* "ap" = a paragraph */
9315 		flag = current_par(cap->oap, cap->count1, include, 'p');
9316 		break;
9317 	case 's': /* "as" = a sentence */
9318 		flag = current_sent(cap->oap, cap->count1, include);
9319 		break;
9320 	case '"': /* "a"" = a double quoted string */
9321 	case '\'': /* "a'" = a single quoted string */
9322 	case '`': /* "a`" = a backtick quoted string */
9323 		flag = current_quote(cap->oap, cap->count1, include,
9324 								  cap->nchar);
9325 		break;
9326 #if 0	/* TODO */
9327 	case 'S': /* "aS" = a section */
9328 	case 'f': /* "af" = a filename */
9329 	case 'u': /* "au" = a URL */
9330 #endif
9331 	default:
9332 		flag = FAIL;
9333 		break;
9334     }
9335 
9336     curbuf->b_p_mps = mps_save;
9337     if (flag == FAIL)
9338 	clearopbeep(cap->oap);
9339     adjust_cursor_col();
9340     curwin->w_set_curswant = TRUE;
9341 }
9342 #endif
9343 
9344 /*
9345  * "q" command: Start/stop recording.
9346  * "q:", "q/", "q?": edit command-line in command-line window.
9347  */
9348     static void
9349 nv_record(cmdarg_T *cap)
9350 {
9351     if (cap->oap->op_type == OP_FORMAT)
9352     {
9353 	/* "gqq" is the same as "gqgq": format line */
9354 	cap->cmdchar = 'g';
9355 	cap->nchar = 'q';
9356 	nv_operator(cap);
9357     }
9358     else if (!checkclearop(cap->oap))
9359     {
9360 #ifdef FEAT_CMDWIN
9361 	if (cap->nchar == ':' || cap->nchar == '/' || cap->nchar == '?')
9362 	{
9363 	    stuffcharReadbuff(cap->nchar);
9364 	    stuffcharReadbuff(K_CMDWIN);
9365 	}
9366 	else
9367 #endif
9368 	    /* (stop) recording into a named register, unless executing a
9369 	     * register */
9370 	    if (reg_executing == 0 && do_record(cap->nchar) == FAIL)
9371 		clearopbeep(cap->oap);
9372     }
9373 }
9374 
9375 /*
9376  * Handle the "@r" command.
9377  */
9378     static void
9379 nv_at(cmdarg_T *cap)
9380 {
9381     if (checkclearop(cap->oap))
9382 	return;
9383 #ifdef FEAT_EVAL
9384     if (cap->nchar == '=')
9385     {
9386 	if (get_expr_register() == NUL)
9387 	    return;
9388     }
9389 #endif
9390     while (cap->count1-- && !got_int)
9391     {
9392 	if (do_execreg(cap->nchar, FALSE, FALSE, FALSE) == FAIL)
9393 	{
9394 	    clearopbeep(cap->oap);
9395 	    break;
9396 	}
9397 	line_breakcheck();
9398     }
9399 }
9400 
9401 /*
9402  * Handle the CTRL-U and CTRL-D commands.
9403  */
9404     static void
9405 nv_halfpage(cmdarg_T *cap)
9406 {
9407     if ((cap->cmdchar == Ctrl_U && curwin->w_cursor.lnum == 1)
9408 	    || (cap->cmdchar == Ctrl_D
9409 		&& curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count))
9410 	clearopbeep(cap->oap);
9411     else if (!checkclearop(cap->oap))
9412 	halfpage(cap->cmdchar == Ctrl_D, cap->count0);
9413 }
9414 
9415 /*
9416  * Handle "J" or "gJ" command.
9417  */
9418     static void
9419 nv_join(cmdarg_T *cap)
9420 {
9421     if (VIsual_active)	/* join the visual lines */
9422 	nv_operator(cap);
9423     else if (!checkclearop(cap->oap))
9424     {
9425 	if (cap->count0 <= 1)
9426 	    cap->count0 = 2;	    /* default for join is two lines! */
9427 	if (curwin->w_cursor.lnum + cap->count0 - 1 >
9428 						   curbuf->b_ml.ml_line_count)
9429 	{
9430 	    /* can't join when on the last line */
9431 	    if (cap->count0 <= 2)
9432 	    {
9433 		clearopbeep(cap->oap);
9434 		return;
9435 	    }
9436 	    cap->count0 = curbuf->b_ml.ml_line_count
9437 						  - curwin->w_cursor.lnum + 1;
9438 	}
9439 
9440 	prep_redo(cap->oap->regname, cap->count0,
9441 				     NUL, cap->cmdchar, NUL, NUL, cap->nchar);
9442 	(void)do_join(cap->count0, cap->nchar == NUL, TRUE, TRUE, TRUE);
9443     }
9444 }
9445 
9446 /*
9447  * "P", "gP", "p" and "gp" commands.
9448  */
9449     static void
9450 nv_put(cmdarg_T *cap)
9451 {
9452     int		regname = 0;
9453     void	*reg1 = NULL, *reg2 = NULL;
9454     int		empty = FALSE;
9455     int		was_visual = FALSE;
9456     int		dir;
9457     int		flags = 0;
9458 
9459     if (cap->oap->op_type != OP_NOP)
9460     {
9461 #ifdef FEAT_DIFF
9462 	/* "dp" is ":diffput" */
9463 	if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'p')
9464 	{
9465 	    clearop(cap->oap);
9466 	    nv_diffgetput(TRUE, cap->opcount);
9467 	}
9468 	else
9469 #endif
9470 	clearopbeep(cap->oap);
9471     }
9472 #ifdef FEAT_JOB_CHANNEL
9473     else if (bt_prompt(curbuf) && !prompt_curpos_editable())
9474     {
9475 	clearopbeep(cap->oap);
9476     }
9477 #endif
9478     else
9479     {
9480 	dir = (cap->cmdchar == 'P'
9481 		|| (cap->cmdchar == 'g' && cap->nchar == 'P'))
9482 							 ? BACKWARD : FORWARD;
9483 	prep_redo_cmd(cap);
9484 	if (cap->cmdchar == 'g')
9485 	    flags |= PUT_CURSEND;
9486 
9487 	if (VIsual_active)
9488 	{
9489 	    /* Putting in Visual mode: The put text replaces the selected
9490 	     * text.  First delete the selected text, then put the new text.
9491 	     * Need to save and restore the registers that the delete
9492 	     * overwrites if the old contents is being put.
9493 	     */
9494 	    was_visual = TRUE;
9495 	    regname = cap->oap->regname;
9496 #ifdef FEAT_CLIPBOARD
9497 	    adjust_clip_reg(&regname);
9498 #endif
9499 	   if (regname == 0 || regname == '"'
9500 				     || VIM_ISDIGIT(regname) || regname == '-'
9501 #ifdef FEAT_CLIPBOARD
9502 		    || (clip_unnamed && (regname == '*' || regname == '+'))
9503 #endif
9504 
9505 		    )
9506 	    {
9507 		/* The delete is going to overwrite the register we want to
9508 		 * put, save it first. */
9509 		reg1 = get_register(regname, TRUE);
9510 	    }
9511 
9512 	    /* Now delete the selected text. */
9513 	    cap->cmdchar = 'd';
9514 	    cap->nchar = NUL;
9515 	    cap->oap->regname = NUL;
9516 	    nv_operator(cap);
9517 	    do_pending_operator(cap, 0, FALSE);
9518 	    empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
9519 
9520 	    /* delete PUT_LINE_BACKWARD; */
9521 	    cap->oap->regname = regname;
9522 
9523 	    if (reg1 != NULL)
9524 	    {
9525 		/* Delete probably changed the register we want to put, save
9526 		 * it first. Then put back what was there before the delete. */
9527 		reg2 = get_register(regname, FALSE);
9528 		put_register(regname, reg1);
9529 	    }
9530 
9531 	    /* When deleted a linewise Visual area, put the register as
9532 	     * lines to avoid it joined with the next line.  When deletion was
9533 	     * characterwise, split a line when putting lines. */
9534 	    if (VIsual_mode == 'V')
9535 		flags |= PUT_LINE;
9536 	    else if (VIsual_mode == 'v')
9537 		flags |= PUT_LINE_SPLIT;
9538 	    if (VIsual_mode == Ctrl_V && dir == FORWARD)
9539 		flags |= PUT_LINE_FORWARD;
9540 	    dir = BACKWARD;
9541 	    if ((VIsual_mode != 'V'
9542 			&& curwin->w_cursor.col < curbuf->b_op_start.col)
9543 		    || (VIsual_mode == 'V'
9544 			&& curwin->w_cursor.lnum < curbuf->b_op_start.lnum))
9545 		/* cursor is at the end of the line or end of file, put
9546 		 * forward. */
9547 		dir = FORWARD;
9548 	    /* May have been reset in do_put(). */
9549 	    VIsual_active = TRUE;
9550 	}
9551 	do_put(cap->oap->regname, dir, cap->count1, flags);
9552 
9553 	/* If a register was saved, put it back now. */
9554 	if (reg2 != NULL)
9555 	    put_register(regname, reg2);
9556 
9557 	/* What to reselect with "gv"?  Selecting the just put text seems to
9558 	 * be the most useful, since the original text was removed. */
9559 	if (was_visual)
9560 	{
9561 	    curbuf->b_visual.vi_start = curbuf->b_op_start;
9562 	    curbuf->b_visual.vi_end = curbuf->b_op_end;
9563 	    /* need to adjust cursor position */
9564 	    if (*p_sel == 'e')
9565 		inc(&curbuf->b_visual.vi_end);
9566 	}
9567 
9568 	/* When all lines were selected and deleted do_put() leaves an empty
9569 	 * line that needs to be deleted now. */
9570 	if (empty && *ml_get(curbuf->b_ml.ml_line_count) == NUL)
9571 	{
9572 	    ml_delete(curbuf->b_ml.ml_line_count, TRUE);
9573 
9574 	    /* If the cursor was in that line, move it to the end of the last
9575 	     * line. */
9576 	    if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
9577 	    {
9578 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9579 		coladvance((colnr_T)MAXCOL);
9580 	    }
9581 	}
9582 	auto_format(FALSE, TRUE);
9583     }
9584 }
9585 
9586 /*
9587  * "o" and "O" commands.
9588  */
9589     static void
9590 nv_open(cmdarg_T *cap)
9591 {
9592 #ifdef FEAT_DIFF
9593     /* "do" is ":diffget" */
9594     if (cap->oap->op_type == OP_DELETE && cap->cmdchar == 'o')
9595     {
9596 	clearop(cap->oap);
9597 	nv_diffgetput(FALSE, cap->opcount);
9598     }
9599     else
9600 #endif
9601     if (VIsual_active)  /* switch start and end of visual */
9602 	v_swap_corners(cap->cmdchar);
9603 #ifdef FEAT_JOB_CHANNEL
9604     else if (bt_prompt(curbuf))
9605     {
9606 	clearopbeep(cap->oap);
9607     }
9608 #endif
9609     else
9610 	n_opencmd(cap);
9611 }
9612 
9613 #ifdef FEAT_NETBEANS_INTG
9614     static void
9615 nv_nbcmd(cmdarg_T *cap)
9616 {
9617     netbeans_keycommand(cap->nchar);
9618 }
9619 #endif
9620 
9621 #ifdef FEAT_DND
9622     static void
9623 nv_drop(cmdarg_T *cap UNUSED)
9624 {
9625     do_put('~', BACKWARD, 1L, PUT_CURSEND);
9626 }
9627 #endif
9628 
9629 /*
9630  * Trigger CursorHold event.
9631  * When waiting for a character for 'updatetime' K_CURSORHOLD is put in the
9632  * input buffer.  "did_cursorhold" is set to avoid retriggering.
9633  */
9634     static void
9635 nv_cursorhold(cmdarg_T *cap)
9636 {
9637     apply_autocmds(EVENT_CURSORHOLD, NULL, NULL, FALSE, curbuf);
9638     did_cursorhold = TRUE;
9639     cap->retval |= CA_COMMAND_BUSY;	/* don't call edit() now */
9640 }
9641 
9642 /*
9643  * Calculate start/end virtual columns for operating in block mode.
9644  */
9645     static void
9646 get_op_vcol(
9647     oparg_T	*oap,
9648     colnr_T	redo_VIsual_vcol,
9649     int		initial)    /* when TRUE adjust position for 'selectmode' */
9650 {
9651     colnr_T	    start, end;
9652 
9653     if (VIsual_mode != Ctrl_V
9654 	    || (!initial && oap->end.col < curwin->w_width))
9655 	return;
9656 
9657     oap->block_mode = TRUE;
9658 
9659 #ifdef FEAT_MBYTE
9660     /* prevent from moving onto a trail byte */
9661     if (has_mbyte)
9662 	mb_adjustpos(curwin->w_buffer, &oap->end);
9663 #endif
9664 
9665     getvvcol(curwin, &(oap->start), &oap->start_vcol, NULL, &oap->end_vcol);
9666 
9667     if (!redo_VIsual_busy)
9668     {
9669 	getvvcol(curwin, &(oap->end), &start, NULL, &end);
9670 
9671 	if (start < oap->start_vcol)
9672 	    oap->start_vcol = start;
9673 	if (end > oap->end_vcol)
9674 	{
9675 	    if (initial && *p_sel == 'e' && start >= 1
9676 				    && start - 1 >= oap->end_vcol)
9677 		oap->end_vcol = start - 1;
9678 	    else
9679 		oap->end_vcol = end;
9680 	}
9681     }
9682 
9683     /* if '$' was used, get oap->end_vcol from longest line */
9684     if (curwin->w_curswant == MAXCOL)
9685     {
9686 	curwin->w_cursor.col = MAXCOL;
9687 	oap->end_vcol = 0;
9688 	for (curwin->w_cursor.lnum = oap->start.lnum;
9689 		curwin->w_cursor.lnum <= oap->end.lnum;
9690 					++curwin->w_cursor.lnum)
9691 	{
9692 	    getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &end);
9693 	    if (end > oap->end_vcol)
9694 		oap->end_vcol = end;
9695 	}
9696     }
9697     else if (redo_VIsual_busy)
9698 	oap->end_vcol = oap->start_vcol + redo_VIsual_vcol - 1;
9699     /*
9700     * Correct oap->end.col and oap->start.col to be the
9701     * upper-left and lower-right corner of the block area.
9702     *
9703     * (Actually, this does convert column positions into character
9704     * positions)
9705     */
9706     curwin->w_cursor.lnum = oap->end.lnum;
9707     coladvance(oap->end_vcol);
9708     oap->end = curwin->w_cursor;
9709 
9710     curwin->w_cursor = oap->start;
9711     coladvance(oap->start_vcol);
9712     oap->start = curwin->w_cursor;
9713 }
9714