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