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