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