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