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