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