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