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