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