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