xref: /vim-8.2.3635/src/edit.c (revision 57e4ee4d)
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 /*
11  * edit.c: functions for Insert mode
12  */
13 
14 #include "vim.h"
15 
16 #ifdef FEAT_INS_EXPAND
17 /*
18  * definitions used for CTRL-X submode
19  */
20 #define CTRL_X_WANT_IDENT	0x100
21 
22 #define CTRL_X_NOT_DEFINED_YET	1
23 #define CTRL_X_SCROLL		2
24 #define CTRL_X_WHOLE_LINE	3
25 #define CTRL_X_FILES		4
26 #define CTRL_X_TAGS		(5 + CTRL_X_WANT_IDENT)
27 #define CTRL_X_PATH_PATTERNS	(6 + CTRL_X_WANT_IDENT)
28 #define CTRL_X_PATH_DEFINES	(7 + CTRL_X_WANT_IDENT)
29 #define CTRL_X_FINISHED		8
30 #define CTRL_X_DICTIONARY	(9 + CTRL_X_WANT_IDENT)
31 #define CTRL_X_THESAURUS	(10 + CTRL_X_WANT_IDENT)
32 #define CTRL_X_CMDLINE		11
33 #define CTRL_X_FUNCTION		12
34 #define CTRL_X_OMNI		13
35 #define CTRL_X_SPELL		14
36 #define CTRL_X_LOCAL_MSG	15	/* only used in "ctrl_x_msgs" */
37 
38 #define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
39 
40 static char *ctrl_x_msgs[] =
41 {
42     N_(" Keyword completion (^N^P)"), /* ctrl_x_mode == 0, ^P/^N compl. */
43     N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
44     NULL,
45     N_(" Whole line completion (^L^N^P)"),
46     N_(" File name completion (^F^N^P)"),
47     N_(" Tag completion (^]^N^P)"),
48     N_(" Path pattern completion (^N^P)"),
49     N_(" Definition completion (^D^N^P)"),
50     NULL,
51     N_(" Dictionary completion (^K^N^P)"),
52     N_(" Thesaurus completion (^T^N^P)"),
53     N_(" Command-line completion (^V^N^P)"),
54     N_(" User defined completion (^U^N^P)"),
55     N_(" Omni completion (^O^N^P)"),
56     N_(" Spelling suggestion (s^N^P)"),
57     N_(" Keyword Local completion (^N^P)"),
58 };
59 
60 static char e_hitend[] = N_("Hit end of paragraph");
61 #ifdef FEAT_COMPL_FUNC
62 static char e_complwin[] = N_("E839: Completion function changed window");
63 static char e_compldel[] = N_("E840: Completion function deleted text");
64 #endif
65 
66 /*
67  * Structure used to store one match for insert completion.
68  */
69 typedef struct compl_S compl_T;
70 struct compl_S
71 {
72     compl_T	*cp_next;
73     compl_T	*cp_prev;
74     char_u	*cp_str;	/* matched text */
75     char	cp_icase;	/* TRUE or FALSE: ignore case */
76     char_u	*(cp_text[CPT_COUNT]);	/* text for the menu */
77     char_u	*cp_fname;	/* file containing the match, allocated when
78 				 * cp_flags has FREE_FNAME */
79     int		cp_flags;	/* ORIGINAL_TEXT, CONT_S_IPOS or FREE_FNAME */
80     int		cp_number;	/* sequence number */
81 };
82 
83 #define ORIGINAL_TEXT	(1)   /* the original text when the expansion begun */
84 #define FREE_FNAME	(2)
85 
86 /*
87  * All the current matches are stored in a list.
88  * "compl_first_match" points to the start of the list.
89  * "compl_curr_match" points to the currently selected entry.
90  * "compl_shown_match" is different from compl_curr_match during
91  * ins_compl_get_exp().
92  */
93 static compl_T    *compl_first_match = NULL;
94 static compl_T    *compl_curr_match = NULL;
95 static compl_T    *compl_shown_match = NULL;
96 
97 /* After using a cursor key <Enter> selects a match in the popup menu,
98  * otherwise it inserts a line break. */
99 static int	  compl_enter_selects = FALSE;
100 
101 /* When "compl_leader" is not NULL only matches that start with this string
102  * are used. */
103 static char_u	  *compl_leader = NULL;
104 
105 static int	  compl_get_longest = FALSE;	/* put longest common string
106 						   in compl_leader */
107 
108 static int	  compl_used_match;	/* Selected one of the matches.  When
109 					   FALSE the match was edited or using
110 					   the longest common string. */
111 
112 static int	  compl_was_interrupted = FALSE;  /* didn't finish finding
113 						     completions. */
114 
115 static int	  compl_restarting = FALSE;	/* don't insert match */
116 
117 /* When the first completion is done "compl_started" is set.  When it's
118  * FALSE the word to be completed must be located. */
119 static int	  compl_started = FALSE;
120 
121 /* Set when doing something for completion that may call edit() recursively,
122  * which is not allowed. */
123 static int	  compl_busy = FALSE;
124 
125 static int	  compl_matches = 0;
126 static char_u	  *compl_pattern = NULL;
127 static int	  compl_direction = FORWARD;
128 static int	  compl_shows_dir = FORWARD;
129 static int	  compl_pending = 0;	    /* > 1 for postponed CTRL-N */
130 static pos_T	  compl_startpos;
131 static colnr_T	  compl_col = 0;	    /* column where the text starts
132 					     * that is being completed */
133 static char_u	  *compl_orig_text = NULL;  /* text as it was before
134 					     * completion started */
135 static int	  compl_cont_mode = 0;
136 static expand_T	  compl_xp;
137 
138 static int	  compl_opt_refresh_always = FALSE;
139 
140 static void ins_ctrl_x __ARGS((void));
141 static int  has_compl_option __ARGS((int dict_opt));
142 static int  ins_compl_accept_char __ARGS((int c));
143 static int ins_compl_add __ARGS((char_u *str, int len, int icase, char_u *fname, char_u **cptext, int cdir, int flags, int adup));
144 static int  ins_compl_equal __ARGS((compl_T *match, char_u *str, int len));
145 static void ins_compl_longest_match __ARGS((compl_T *match));
146 static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int icase));
147 static int  ins_compl_make_cyclic __ARGS((void));
148 static void ins_compl_upd_pum __ARGS((void));
149 static void ins_compl_del_pum __ARGS((void));
150 static int  pum_wanted __ARGS((void));
151 static int  pum_enough_matches __ARGS((void));
152 static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int flags, int thesaurus));
153 static void ins_compl_files __ARGS((int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir));
154 static char_u *find_line_end __ARGS((char_u *ptr));
155 static void ins_compl_free __ARGS((void));
156 static void ins_compl_clear __ARGS((void));
157 static int  ins_compl_bs __ARGS((void));
158 static int  ins_compl_need_restart __ARGS((void));
159 static void ins_compl_new_leader __ARGS((void));
160 static void ins_compl_addleader __ARGS((int c));
161 static int  ins_compl_len __ARGS((void));
162 static void ins_compl_restart __ARGS((void));
163 static void ins_compl_set_original_text __ARGS((char_u *str));
164 static void ins_compl_addfrommatch __ARGS((void));
165 static int  ins_compl_prep __ARGS((int c));
166 static void ins_compl_fixRedoBufForLeader __ARGS((char_u *ptr_arg));
167 static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag));
168 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
169 static void ins_compl_add_list __ARGS((list_T *list));
170 static void ins_compl_add_dict __ARGS((dict_T *dict));
171 #endif
172 static int  ins_compl_get_exp __ARGS((pos_T *ini));
173 static void ins_compl_delete __ARGS((void));
174 static void ins_compl_insert __ARGS((void));
175 static int  ins_compl_next __ARGS((int allow_get_expansion, int count, int insert_match));
176 static int  ins_compl_key2dir __ARGS((int c));
177 static int  ins_compl_pum_key __ARGS((int c));
178 static int  ins_compl_key2count __ARGS((int c));
179 static int  ins_compl_use_match __ARGS((int c));
180 static int  ins_complete __ARGS((int c));
181 static unsigned  quote_meta __ARGS((char_u *dest, char_u *str, int len));
182 #endif /* FEAT_INS_EXPAND */
183 
184 #define BACKSPACE_CHAR		    1
185 #define BACKSPACE_WORD		    2
186 #define BACKSPACE_WORD_NOT_SPACE    3
187 #define BACKSPACE_LINE		    4
188 
189 static void ins_redraw __ARGS((int ready));
190 static void ins_ctrl_v __ARGS((void));
191 static void undisplay_dollar __ARGS((void));
192 static void insert_special __ARGS((int, int, int));
193 static void internal_format __ARGS((int textwidth, int second_indent, int flags, int format_only, int c));
194 static void check_auto_format __ARGS((int));
195 static void redo_literal __ARGS((int c));
196 static void start_arrow __ARGS((pos_T *end_insert_pos));
197 #ifdef FEAT_SPELL
198 static void check_spell_redraw __ARGS((void));
199 static void spell_back_to_badword __ARGS((void));
200 static int  spell_bad_len = 0;	/* length of located bad word */
201 #endif
202 static void stop_insert __ARGS((pos_T *end_insert_pos, int esc));
203 static int  echeck_abbr __ARGS((int));
204 static int  replace_pop __ARGS((void));
205 static void replace_join __ARGS((int off));
206 static void replace_pop_ins __ARGS((void));
207 #ifdef FEAT_MBYTE
208 static void mb_replace_pop_ins __ARGS((int cc));
209 #endif
210 static void replace_flush __ARGS((void));
211 static void replace_do_bs __ARGS((int limit_col));
212 static int del_char_after_col __ARGS((int limit_col));
213 #ifdef FEAT_CINDENT
214 static int cindent_on __ARGS((void));
215 #endif
216 static void ins_reg __ARGS((void));
217 static void ins_ctrl_g __ARGS((void));
218 static void ins_ctrl_hat __ARGS((void));
219 static int  ins_esc __ARGS((long *count, int cmdchar, int nomove));
220 #ifdef FEAT_RIGHTLEFT
221 static void ins_ctrl_ __ARGS((void));
222 #endif
223 #ifdef FEAT_VISUAL
224 static int ins_start_select __ARGS((int c));
225 #endif
226 static void ins_insert __ARGS((int replaceState));
227 static void ins_ctrl_o __ARGS((void));
228 static void ins_shift __ARGS((int c, int lastc));
229 static void ins_del __ARGS((void));
230 static int  ins_bs __ARGS((int c, int mode, int *inserted_space_p));
231 #ifdef FEAT_MOUSE
232 static void ins_mouse __ARGS((int c));
233 static void ins_mousescroll __ARGS((int dir));
234 #endif
235 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
236 static void ins_tabline __ARGS((int c));
237 #endif
238 static void ins_left __ARGS((void));
239 static void ins_home __ARGS((int c));
240 static void ins_end __ARGS((int c));
241 static void ins_s_left __ARGS((void));
242 static void ins_right __ARGS((void));
243 static void ins_s_right __ARGS((void));
244 static void ins_up __ARGS((int startcol));
245 static void ins_pageup __ARGS((void));
246 static void ins_down __ARGS((int startcol));
247 static void ins_pagedown __ARGS((void));
248 #ifdef FEAT_DND
249 static void ins_drop __ARGS((void));
250 #endif
251 static int  ins_tab __ARGS((void));
252 static int  ins_eol __ARGS((int c));
253 #ifdef FEAT_DIGRAPHS
254 static int  ins_digraph __ARGS((void));
255 #endif
256 static int  ins_ctrl_ey __ARGS((int tc));
257 #ifdef FEAT_SMARTINDENT
258 static void ins_try_si __ARGS((int c));
259 #endif
260 static colnr_T get_nolist_virtcol __ARGS((void));
261 #ifdef FEAT_AUTOCMD
262 static char_u *do_insert_char_pre __ARGS((int c));
263 #endif
264 
265 static colnr_T	Insstart_textlen;	/* length of line when insert started */
266 static colnr_T	Insstart_blank_vcol;	/* vcol for first inserted blank */
267 
268 static char_u	*last_insert = NULL;	/* the text of the previous insert,
269 					   K_SPECIAL and CSI are escaped */
270 static int	last_insert_skip; /* nr of chars in front of previous insert */
271 static int	new_insert_skip;  /* nr of chars in front of current insert */
272 static int	did_restart_edit;	/* "restart_edit" when calling edit() */
273 
274 #ifdef FEAT_CINDENT
275 static int	can_cindent;		/* may do cindenting on this line */
276 #endif
277 
278 static int	old_indent = 0;		/* for ^^D command in insert mode */
279 
280 #ifdef FEAT_RIGHTLEFT
281 static int	revins_on;		/* reverse insert mode on */
282 static int	revins_chars;		/* how much to skip after edit */
283 static int	revins_legal;		/* was the last char 'legal'? */
284 static int	revins_scol;		/* start column of revins session */
285 #endif
286 
287 static int	ins_need_undo;		/* call u_save() before inserting a
288 					   char.  Set when edit() is called.
289 					   after that arrow_used is used. */
290 
291 static int	did_add_space = FALSE;	/* auto_format() added an extra space
292 					   under the cursor */
293 
294 /*
295  * edit(): Start inserting text.
296  *
297  * "cmdchar" can be:
298  * 'i'	normal insert command
299  * 'a'	normal append command
300  * 'R'	replace command
301  * 'r'	"r<CR>" command: insert one <CR>.  Note: count can be > 1, for redo,
302  *	but still only one <CR> is inserted.  The <Esc> is not used for redo.
303  * 'g'	"gI" command.
304  * 'V'	"gR" command for Virtual Replace mode.
305  * 'v'	"gr" command for single character Virtual Replace mode.
306  *
307  * This function is not called recursively.  For CTRL-O commands, it returns
308  * and lets the caller handle the Normal-mode command.
309  *
310  * Return TRUE if a CTRL-O command caused the return (insert mode pending).
311  */
312     int
313 edit(cmdchar, startln, count)
314     int		cmdchar;
315     int		startln;	/* if set, insert at start of line */
316     long	count;
317 {
318     int		c = 0;
319     char_u	*ptr;
320     int		lastc;
321     int		mincol;
322     static linenr_T o_lnum = 0;
323     int		i;
324     int		did_backspace = TRUE;	    /* previous char was backspace */
325 #ifdef FEAT_CINDENT
326     int		line_is_white = FALSE;	    /* line is empty before insert */
327 #endif
328     linenr_T	old_topline = 0;	    /* topline before insertion */
329 #ifdef FEAT_DIFF
330     int		old_topfill = -1;
331 #endif
332     int		inserted_space = FALSE;     /* just inserted a space */
333     int		replaceState = REPLACE;
334     int		nomove = FALSE;		    /* don't move cursor on return */
335 
336     /* Remember whether editing was restarted after CTRL-O. */
337     did_restart_edit = restart_edit;
338 
339     /* sleep before redrawing, needed for "CTRL-O :" that results in an
340      * error message */
341     check_for_delay(TRUE);
342 
343 #ifdef HAVE_SANDBOX
344     /* Don't allow inserting in the sandbox. */
345     if (sandbox != 0)
346     {
347 	EMSG(_(e_sandbox));
348 	return FALSE;
349     }
350 #endif
351     /* Don't allow changes in the buffer while editing the cmdline.  The
352      * caller of getcmdline() may get confused. */
353     if (textlock != 0)
354     {
355 	EMSG(_(e_secure));
356 	return FALSE;
357     }
358 
359 #ifdef FEAT_INS_EXPAND
360     /* Don't allow recursive insert mode when busy with completion. */
361     if (compl_started || compl_busy || pum_visible())
362     {
363 	EMSG(_(e_secure));
364 	return FALSE;
365     }
366     ins_compl_clear();	    /* clear stuff for CTRL-X mode */
367 #endif
368 
369 #ifdef FEAT_AUTOCMD
370     /*
371      * Trigger InsertEnter autocommands.  Do not do this for "r<CR>" or "grx".
372      */
373     if (cmdchar != 'r' && cmdchar != 'v')
374     {
375 # ifdef FEAT_EVAL
376 	if (cmdchar == 'R')
377 	    ptr = (char_u *)"r";
378 	else if (cmdchar == 'V')
379 	    ptr = (char_u *)"v";
380 	else
381 	    ptr = (char_u *)"i";
382 	set_vim_var_string(VV_INSERTMODE, ptr, 1);
383 # endif
384 	apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf);
385     }
386 #endif
387 
388 #ifdef FEAT_CONCEAL
389     /* Check if the cursor line needs redrawing before changing State.  If
390      * 'concealcursor' is "n" it needs to be redrawn without concealing. */
391     conceal_check_cursur_line();
392 #endif
393 
394 #ifdef FEAT_MOUSE
395     /*
396      * When doing a paste with the middle mouse button, Insstart is set to
397      * where the paste started.
398      */
399     if (where_paste_started.lnum != 0)
400 	Insstart = where_paste_started;
401     else
402 #endif
403     {
404 	Insstart = curwin->w_cursor;
405 	if (startln)
406 	    Insstart.col = 0;
407     }
408     Insstart_textlen = (colnr_T)linetabsize(ml_get_curline());
409     Insstart_blank_vcol = MAXCOL;
410     if (!did_ai)
411 	ai_col = 0;
412 
413     if (cmdchar != NUL && restart_edit == 0)
414     {
415 	ResetRedobuff();
416 	AppendNumberToRedobuff(count);
417 #ifdef FEAT_VREPLACE
418 	if (cmdchar == 'V' || cmdchar == 'v')
419 	{
420 	    /* "gR" or "gr" command */
421 	    AppendCharToRedobuff('g');
422 	    AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R');
423 	}
424 	else
425 #endif
426 	{
427 	    AppendCharToRedobuff(cmdchar);
428 	    if (cmdchar == 'g')		    /* "gI" command */
429 		AppendCharToRedobuff('I');
430 	    else if (cmdchar == 'r')	    /* "r<CR>" command */
431 		count = 1;		    /* insert only one <CR> */
432 	}
433     }
434 
435     if (cmdchar == 'R')
436     {
437 #ifdef FEAT_FKMAP
438 	if (p_fkmap && p_ri)
439 	{
440 	    beep_flush();
441 	    EMSG(farsi_text_3);	    /* encoded in Farsi */
442 	    State = INSERT;
443 	}
444 	else
445 #endif
446 	State = REPLACE;
447     }
448 #ifdef FEAT_VREPLACE
449     else if (cmdchar == 'V' || cmdchar == 'v')
450     {
451 	State = VREPLACE;
452 	replaceState = VREPLACE;
453 	orig_line_count = curbuf->b_ml.ml_line_count;
454 	vr_lines_changed = 1;
455     }
456 #endif
457     else
458 	State = INSERT;
459 
460     stop_insert_mode = FALSE;
461 
462     /*
463      * Need to recompute the cursor position, it might move when the cursor is
464      * on a TAB or special character.
465      */
466     curs_columns(TRUE);
467 
468     /*
469      * Enable langmap or IME, indicated by 'iminsert'.
470      * Note that IME may enabled/disabled without us noticing here, thus the
471      * 'iminsert' value may not reflect what is actually used.  It is updated
472      * when hitting <Esc>.
473      */
474     if (curbuf->b_p_iminsert == B_IMODE_LMAP)
475 	State |= LANGMAP;
476 #ifdef USE_IM_CONTROL
477     im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
478 #endif
479 
480 #ifdef FEAT_MOUSE
481     setmouse();
482 #endif
483 #ifdef FEAT_CMDL_INFO
484     clear_showcmd();
485 #endif
486 #ifdef FEAT_RIGHTLEFT
487     /* there is no reverse replace mode */
488     revins_on = (State == INSERT && p_ri);
489     if (revins_on)
490 	undisplay_dollar();
491     revins_chars = 0;
492     revins_legal = 0;
493     revins_scol = -1;
494 #endif
495 
496     /*
497      * Handle restarting Insert mode.
498      * Don't do this for "CTRL-O ." (repeat an insert): we get here with
499      * restart_edit non-zero, and something in the stuff buffer.
500      */
501     if (restart_edit != 0 && stuff_empty())
502     {
503 #ifdef FEAT_MOUSE
504 	/*
505 	 * After a paste we consider text typed to be part of the insert for
506 	 * the pasted text. You can backspace over the pasted text too.
507 	 */
508 	if (where_paste_started.lnum)
509 	    arrow_used = FALSE;
510 	else
511 #endif
512 	    arrow_used = TRUE;
513 	restart_edit = 0;
514 
515 	/*
516 	 * If the cursor was after the end-of-line before the CTRL-O and it is
517 	 * now at the end-of-line, put it after the end-of-line (this is not
518 	 * correct in very rare cases).
519 	 * Also do this if curswant is greater than the current virtual
520 	 * column.  Eg after "^O$" or "^O80|".
521 	 */
522 	validate_virtcol();
523 	update_curswant();
524 	if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
525 		    || curwin->w_curswant > curwin->w_virtcol)
526 		&& *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL)
527 	{
528 	    if (ptr[1] == NUL)
529 		++curwin->w_cursor.col;
530 #ifdef FEAT_MBYTE
531 	    else if (has_mbyte)
532 	    {
533 		i = (*mb_ptr2len)(ptr);
534 		if (ptr[i] == NUL)
535 		    curwin->w_cursor.col += i;
536 	    }
537 #endif
538 	}
539 	ins_at_eol = FALSE;
540     }
541     else
542 	arrow_used = FALSE;
543 
544     /* we are in insert mode now, don't need to start it anymore */
545     need_start_insertmode = FALSE;
546 
547     /* Need to save the line for undo before inserting the first char. */
548     ins_need_undo = TRUE;
549 
550 #ifdef FEAT_MOUSE
551     where_paste_started.lnum = 0;
552 #endif
553 #ifdef FEAT_CINDENT
554     can_cindent = TRUE;
555 #endif
556 #ifdef FEAT_FOLDING
557     /* The cursor line is not in a closed fold, unless 'insertmode' is set or
558      * restarting. */
559     if (!p_im && did_restart_edit == 0)
560 	foldOpenCursor();
561 #endif
562 
563     /*
564      * If 'showmode' is set, show the current (insert/replace/..) mode.
565      * A warning message for changing a readonly file is given here, before
566      * actually changing anything.  It's put after the mode, if any.
567      */
568     i = 0;
569     if (p_smd && msg_silent == 0)
570 	i = showmode();
571 
572     if (!p_im && did_restart_edit == 0)
573 	change_warning(i == 0 ? 0 : i + 1);
574 
575 #ifdef CURSOR_SHAPE
576     ui_cursor_shape();		/* may show different cursor shape */
577 #endif
578 #ifdef FEAT_DIGRAPHS
579     do_digraph(-1);		/* clear digraphs */
580 #endif
581 
582     /*
583      * Get the current length of the redo buffer, those characters have to be
584      * skipped if we want to get to the inserted characters.
585      */
586     ptr = get_inserted();
587     if (ptr == NULL)
588 	new_insert_skip = 0;
589     else
590     {
591 	new_insert_skip = (int)STRLEN(ptr);
592 	vim_free(ptr);
593     }
594 
595     old_indent = 0;
596 
597     /*
598      * Main loop in Insert mode: repeat until Insert mode is left.
599      */
600     for (;;)
601     {
602 #ifdef FEAT_RIGHTLEFT
603 	if (!revins_legal)
604 	    revins_scol = -1;	    /* reset on illegal motions */
605 	else
606 	    revins_legal = 0;
607 #endif
608 	if (arrow_used)	    /* don't repeat insert when arrow key used */
609 	    count = 0;
610 
611 	if (stop_insert_mode)
612 	{
613 	    /* ":stopinsert" used or 'insertmode' reset */
614 	    count = 0;
615 	    goto doESCkey;
616 	}
617 
618 	/* set curwin->w_curswant for next K_DOWN or K_UP */
619 	if (!arrow_used)
620 	    curwin->w_set_curswant = TRUE;
621 
622 	/* If there is no typeahead may check for timestamps (e.g., for when a
623 	 * menu invoked a shell command). */
624 	if (stuff_empty())
625 	{
626 	    did_check_timestamps = FALSE;
627 	    if (need_check_timestamps)
628 		check_timestamps(FALSE);
629 	}
630 
631 	/*
632 	 * When emsg() was called msg_scroll will have been set.
633 	 */
634 	msg_scroll = FALSE;
635 
636 #ifdef FEAT_GUI
637 	/* When 'mousefocus' is set a mouse movement may have taken us to
638 	 * another window.  "need_mouse_correct" may then be set because of an
639 	 * autocommand. */
640 	if (need_mouse_correct)
641 	    gui_mouse_correct();
642 #endif
643 
644 #ifdef FEAT_FOLDING
645 	/* Open fold at the cursor line, according to 'foldopen'. */
646 	if (fdo_flags & FDO_INSERT)
647 	    foldOpenCursor();
648 	/* Close folds where the cursor isn't, according to 'foldclose' */
649 	if (!char_avail())
650 	    foldCheckClose();
651 #endif
652 
653 	/*
654 	 * If we inserted a character at the last position of the last line in
655 	 * the window, scroll the window one line up. This avoids an extra
656 	 * redraw.
657 	 * This is detected when the cursor column is smaller after inserting
658 	 * something.
659 	 * Don't do this when the topline changed already, it has
660 	 * already been adjusted (by insertchar() calling open_line())).
661 	 */
662 	if (curbuf->b_mod_set
663 		&& curwin->w_p_wrap
664 		&& !did_backspace
665 		&& curwin->w_topline == old_topline
666 #ifdef FEAT_DIFF
667 		&& curwin->w_topfill == old_topfill
668 #endif
669 		)
670 	{
671 	    mincol = curwin->w_wcol;
672 	    validate_cursor_col();
673 
674 	    if ((int)curwin->w_wcol < mincol - curbuf->b_p_ts
675 		    && curwin->w_wrow == W_WINROW(curwin)
676 						 + curwin->w_height - 1 - p_so
677 		    && (curwin->w_cursor.lnum != curwin->w_topline
678 #ifdef FEAT_DIFF
679 			|| curwin->w_topfill > 0
680 #endif
681 		    ))
682 	    {
683 #ifdef FEAT_DIFF
684 		if (curwin->w_topfill > 0)
685 		    --curwin->w_topfill;
686 		else
687 #endif
688 #ifdef FEAT_FOLDING
689 		if (hasFolding(curwin->w_topline, NULL, &old_topline))
690 		    set_topline(curwin, old_topline + 1);
691 		else
692 #endif
693 		    set_topline(curwin, curwin->w_topline + 1);
694 	    }
695 	}
696 
697 	/* May need to adjust w_topline to show the cursor. */
698 	update_topline();
699 
700 	did_backspace = FALSE;
701 
702 	validate_cursor();		/* may set must_redraw */
703 
704 	/*
705 	 * Redraw the display when no characters are waiting.
706 	 * Also shows mode, ruler and positions cursor.
707 	 */
708 	ins_redraw(TRUE);
709 
710 #ifdef FEAT_SCROLLBIND
711 	if (curwin->w_p_scb)
712 	    do_check_scrollbind(TRUE);
713 #endif
714 
715 #ifdef FEAT_CURSORBIND
716 	if (curwin->w_p_crb)
717 	    do_check_cursorbind();
718 #endif
719 	update_curswant();
720 	old_topline = curwin->w_topline;
721 #ifdef FEAT_DIFF
722 	old_topfill = curwin->w_topfill;
723 #endif
724 
725 #ifdef USE_ON_FLY_SCROLL
726 	dont_scroll = FALSE;		/* allow scrolling here */
727 #endif
728 
729 	/*
730 	 * Get a character for Insert mode.  Ignore K_IGNORE.
731 	 */
732 	lastc = c;			/* remember previous char for CTRL-D */
733 	do
734 	{
735 	    c = safe_vgetc();
736 	} while (c == K_IGNORE);
737 
738 #ifdef FEAT_AUTOCMD
739 	/* Don't want K_CURSORHOLD for the second key, e.g., after CTRL-V. */
740 	did_cursorhold = TRUE;
741 #endif
742 
743 #ifdef FEAT_RIGHTLEFT
744 	if (p_hkmap && KeyTyped)
745 	    c = hkmap(c);		/* Hebrew mode mapping */
746 #endif
747 #ifdef FEAT_FKMAP
748 	if (p_fkmap && KeyTyped)
749 	    c = fkmap(c);		/* Farsi mode mapping */
750 #endif
751 
752 #ifdef FEAT_INS_EXPAND
753 	/*
754 	 * Special handling of keys while the popup menu is visible or wanted
755 	 * and the cursor is still in the completed word.  Only when there is
756 	 * a match, skip this when no matches were found.
757 	 */
758 	if (compl_started
759 		&& pum_wanted()
760 		&& curwin->w_cursor.col >= compl_col
761 		&& (compl_shown_match == NULL
762 		    || compl_shown_match != compl_shown_match->cp_next))
763 	{
764 	    /* BS: Delete one character from "compl_leader". */
765 	    if ((c == K_BS || c == Ctrl_H)
766 			&& curwin->w_cursor.col > compl_col
767 			&& (c = ins_compl_bs()) == NUL)
768 		continue;
769 
770 	    /* When no match was selected or it was edited. */
771 	    if (!compl_used_match)
772 	    {
773 		/* CTRL-L: Add one character from the current match to
774 		 * "compl_leader".  Except when at the original match and
775 		 * there is nothing to add, CTRL-L works like CTRL-P then. */
776 		if (c == Ctrl_L
777 			&& (ctrl_x_mode != CTRL_X_WHOLE_LINE
778 			    || (int)STRLEN(compl_shown_match->cp_str)
779 					  > curwin->w_cursor.col - compl_col))
780 		{
781 		    ins_compl_addfrommatch();
782 		    continue;
783 		}
784 
785 		/* A non-white character that fits in with the current
786 		 * completion: Add to "compl_leader". */
787 		if (ins_compl_accept_char(c))
788 		{
789 #ifdef FEAT_AUTOCMD
790 		    /* Trigger InsertCharPre. */
791 		    char_u *str = do_insert_char_pre(c);
792 		    char_u *p;
793 
794 		    if (str != NULL)
795 		    {
796 			for (p = str; *p != NUL; mb_ptr_adv(p))
797 			    ins_compl_addleader(PTR2CHAR(p));
798 			vim_free(str);
799 		    }
800 		    else
801 #endif
802 			ins_compl_addleader(c);
803 		    continue;
804 		}
805 
806 		/* Pressing CTRL-Y selects the current match.  When
807 		 * compl_enter_selects is set the Enter key does the same. */
808 		if (c == Ctrl_Y || (compl_enter_selects
809 				   && (c == CAR || c == K_KENTER || c == NL)))
810 		{
811 		    ins_compl_delete();
812 		    ins_compl_insert();
813 		}
814 	    }
815 	}
816 
817 	/* Prepare for or stop CTRL-X mode.  This doesn't do completion, but
818 	 * it does fix up the text when finishing completion. */
819 	compl_get_longest = FALSE;
820 	if (ins_compl_prep(c))
821 	    continue;
822 #endif
823 
824 	/* CTRL-\ CTRL-N goes to Normal mode,
825 	 * CTRL-\ CTRL-G goes to mode selected with 'insertmode',
826 	 * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor.  */
827 	if (c == Ctrl_BSL)
828 	{
829 	    /* may need to redraw when no more chars available now */
830 	    ins_redraw(FALSE);
831 	    ++no_mapping;
832 	    ++allow_keys;
833 	    c = plain_vgetc();
834 	    --no_mapping;
835 	    --allow_keys;
836 	    if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O)
837 	    {
838 		/* it's something else */
839 		vungetc(c);
840 		c = Ctrl_BSL;
841 	    }
842 	    else if (c == Ctrl_G && p_im)
843 		continue;
844 	    else
845 	    {
846 		if (c == Ctrl_O)
847 		{
848 		    ins_ctrl_o();
849 		    ins_at_eol = FALSE;	/* cursor keeps its column */
850 		    nomove = TRUE;
851 		}
852 		count = 0;
853 		goto doESCkey;
854 	    }
855 	}
856 
857 #ifdef FEAT_DIGRAPHS
858 	c = do_digraph(c);
859 #endif
860 
861 #ifdef FEAT_INS_EXPAND
862 	if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
863 	    goto docomplete;
864 #endif
865 	if (c == Ctrl_V || c == Ctrl_Q)
866 	{
867 	    ins_ctrl_v();
868 	    c = Ctrl_V;	/* pretend CTRL-V is last typed character */
869 	    continue;
870 	}
871 
872 #ifdef FEAT_CINDENT
873 	if (cindent_on()
874 # ifdef FEAT_INS_EXPAND
875 		&& ctrl_x_mode == 0
876 # endif
877 	   )
878 	{
879 	    /* A key name preceded by a bang means this key is not to be
880 	     * inserted.  Skip ahead to the re-indenting below.
881 	     * A key name preceded by a star means that indenting has to be
882 	     * done before inserting the key. */
883 	    line_is_white = inindent(0);
884 	    if (in_cinkeys(c, '!', line_is_white))
885 		goto force_cindent;
886 	    if (can_cindent && in_cinkeys(c, '*', line_is_white)
887 							&& stop_arrow() == OK)
888 		do_c_expr_indent();
889 	}
890 #endif
891 
892 #ifdef FEAT_RIGHTLEFT
893 	if (curwin->w_p_rl)
894 	    switch (c)
895 	    {
896 		case K_LEFT:	c = K_RIGHT; break;
897 		case K_S_LEFT:	c = K_S_RIGHT; break;
898 		case K_C_LEFT:	c = K_C_RIGHT; break;
899 		case K_RIGHT:	c = K_LEFT; break;
900 		case K_S_RIGHT: c = K_S_LEFT; break;
901 		case K_C_RIGHT: c = K_C_LEFT; break;
902 	    }
903 #endif
904 
905 #ifdef FEAT_VISUAL
906 	/*
907 	 * If 'keymodel' contains "startsel", may start selection.  If it
908 	 * does, a CTRL-O and c will be stuffed, we need to get these
909 	 * characters.
910 	 */
911 	if (ins_start_select(c))
912 	    continue;
913 #endif
914 
915 	/*
916 	 * The big switch to handle a character in insert mode.
917 	 */
918 	switch (c)
919 	{
920 	case ESC:	/* End input mode */
921 	    if (echeck_abbr(ESC + ABBR_OFF))
922 		break;
923 	    /*FALLTHROUGH*/
924 
925 	case Ctrl_C:	/* End input mode */
926 #ifdef FEAT_CMDWIN
927 	    if (c == Ctrl_C && cmdwin_type != 0)
928 	    {
929 		/* Close the cmdline window. */
930 		cmdwin_result = K_IGNORE;
931 		got_int = FALSE; /* don't stop executing autocommands et al. */
932 		nomove = TRUE;
933 		goto doESCkey;
934 	    }
935 #endif
936 
937 #ifdef UNIX
938 do_intr:
939 #endif
940 	    /* when 'insertmode' set, and not halfway a mapping, don't leave
941 	     * Insert mode */
942 	    if (goto_im())
943 	    {
944 		if (got_int)
945 		{
946 		    (void)vgetc();		/* flush all buffers */
947 		    got_int = FALSE;
948 		}
949 		else
950 		    vim_beep();
951 		break;
952 	    }
953 doESCkey:
954 	    /*
955 	     * This is the ONLY return from edit()!
956 	     */
957 	    /* Always update o_lnum, so that a "CTRL-O ." that adds a line
958 	     * still puts the cursor back after the inserted text. */
959 	    if (ins_at_eol && gchar_cursor() == NUL)
960 		o_lnum = curwin->w_cursor.lnum;
961 
962 	    if (ins_esc(&count, cmdchar, nomove))
963 	    {
964 #ifdef FEAT_AUTOCMD
965 		if (cmdchar != 'r' && cmdchar != 'v')
966 		    apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
967 							       FALSE, curbuf);
968 		did_cursorhold = FALSE;
969 #endif
970 		return (c == Ctrl_O);
971 	    }
972 	    continue;
973 
974 	case Ctrl_Z:	/* suspend when 'insertmode' set */
975 	    if (!p_im)
976 		goto normalchar;	/* insert CTRL-Z as normal char */
977 	    stuffReadbuff((char_u *)":st\r");
978 	    c = Ctrl_O;
979 	    /*FALLTHROUGH*/
980 
981 	case Ctrl_O:	/* execute one command */
982 #ifdef FEAT_COMPL_FUNC
983 	    if (ctrl_x_mode == CTRL_X_OMNI)
984 		goto docomplete;
985 #endif
986 	    if (echeck_abbr(Ctrl_O + ABBR_OFF))
987 		break;
988 	    ins_ctrl_o();
989 
990 #ifdef FEAT_VIRTUALEDIT
991 	    /* don't move the cursor left when 'virtualedit' has "onemore". */
992 	    if (ve_flags & VE_ONEMORE)
993 	    {
994 		ins_at_eol = FALSE;
995 		nomove = TRUE;
996 	    }
997 #endif
998 	    count = 0;
999 	    goto doESCkey;
1000 
1001 	case K_INS:	/* toggle insert/replace mode */
1002 	case K_KINS:
1003 	    ins_insert(replaceState);
1004 	    break;
1005 
1006 	case K_SELECT:	/* end of Select mode mapping - ignore */
1007 	    break;
1008 
1009 #ifdef FEAT_SNIFF
1010 	case K_SNIFF:	/* Sniff command received */
1011 	    stuffcharReadbuff(K_SNIFF);
1012 	    goto doESCkey;
1013 #endif
1014 
1015 	case K_HELP:	/* Help key works like <ESC> <Help> */
1016 	case K_F1:
1017 	case K_XF1:
1018 	    stuffcharReadbuff(K_HELP);
1019 	    if (p_im)
1020 		need_start_insertmode = TRUE;
1021 	    goto doESCkey;
1022 
1023 #ifdef FEAT_NETBEANS_INTG
1024 	case K_F21:	/* NetBeans command */
1025 	    ++no_mapping;		/* don't map the next key hits */
1026 	    i = plain_vgetc();
1027 	    --no_mapping;
1028 	    netbeans_keycommand(i);
1029 	    break;
1030 #endif
1031 
1032 	case K_ZERO:	/* Insert the previously inserted text. */
1033 	case NUL:
1034 	case Ctrl_A:
1035 	    /* For ^@ the trailing ESC will end the insert, unless there is an
1036 	     * error.  */
1037 	    if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
1038 						   && c != Ctrl_A && !p_im)
1039 		goto doESCkey;		/* quit insert mode */
1040 	    inserted_space = FALSE;
1041 	    break;
1042 
1043 	case Ctrl_R:	/* insert the contents of a register */
1044 	    ins_reg();
1045 	    auto_format(FALSE, TRUE);
1046 	    inserted_space = FALSE;
1047 	    break;
1048 
1049 	case Ctrl_G:	/* commands starting with CTRL-G */
1050 	    ins_ctrl_g();
1051 	    break;
1052 
1053 	case Ctrl_HAT:	/* switch input mode and/or langmap */
1054 	    ins_ctrl_hat();
1055 	    break;
1056 
1057 #ifdef FEAT_RIGHTLEFT
1058 	case Ctrl__:	/* switch between languages */
1059 	    if (!p_ari)
1060 		goto normalchar;
1061 	    ins_ctrl_();
1062 	    break;
1063 #endif
1064 
1065 	case Ctrl_D:	/* Make indent one shiftwidth smaller. */
1066 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1067 	    if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
1068 		goto docomplete;
1069 #endif
1070 	    /* FALLTHROUGH */
1071 
1072 	case Ctrl_T:	/* Make indent one shiftwidth greater. */
1073 # ifdef FEAT_INS_EXPAND
1074 	    if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
1075 	    {
1076 		if (has_compl_option(FALSE))
1077 		    goto docomplete;
1078 		break;
1079 	    }
1080 # endif
1081 	    ins_shift(c, lastc);
1082 	    auto_format(FALSE, TRUE);
1083 	    inserted_space = FALSE;
1084 	    break;
1085 
1086 	case K_DEL:	/* delete character under the cursor */
1087 	case K_KDEL:
1088 	    ins_del();
1089 	    auto_format(FALSE, TRUE);
1090 	    break;
1091 
1092 	case K_BS:	/* delete character before the cursor */
1093 	case Ctrl_H:
1094 	    did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1095 	    auto_format(FALSE, TRUE);
1096 	    break;
1097 
1098 	case Ctrl_W:	/* delete word before the cursor */
1099 	    did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1100 	    auto_format(FALSE, TRUE);
1101 	    break;
1102 
1103 	case Ctrl_U:	/* delete all inserted text in current line */
1104 # ifdef FEAT_COMPL_FUNC
1105 	    /* CTRL-X CTRL-U completes with 'completefunc'. */
1106 	    if (ctrl_x_mode == CTRL_X_FUNCTION)
1107 		goto docomplete;
1108 # endif
1109 	    did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1110 	    auto_format(FALSE, TRUE);
1111 	    inserted_space = FALSE;
1112 	    break;
1113 
1114 #ifdef FEAT_MOUSE
1115 	case K_LEFTMOUSE:   /* mouse keys */
1116 	case K_LEFTMOUSE_NM:
1117 	case K_LEFTDRAG:
1118 	case K_LEFTRELEASE:
1119 	case K_LEFTRELEASE_NM:
1120 	case K_MIDDLEMOUSE:
1121 	case K_MIDDLEDRAG:
1122 	case K_MIDDLERELEASE:
1123 	case K_RIGHTMOUSE:
1124 	case K_RIGHTDRAG:
1125 	case K_RIGHTRELEASE:
1126 	case K_X1MOUSE:
1127 	case K_X1DRAG:
1128 	case K_X1RELEASE:
1129 	case K_X2MOUSE:
1130 	case K_X2DRAG:
1131 	case K_X2RELEASE:
1132 	    ins_mouse(c);
1133 	    break;
1134 
1135 	case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */
1136 	    ins_mousescroll(MSCR_DOWN);
1137 	    break;
1138 
1139 	case K_MOUSEUP:	/* Default action for scroll wheel down: scroll down */
1140 	    ins_mousescroll(MSCR_UP);
1141 	    break;
1142 
1143 	case K_MOUSELEFT: /* Scroll wheel left */
1144 	    ins_mousescroll(MSCR_LEFT);
1145 	    break;
1146 
1147 	case K_MOUSERIGHT: /* Scroll wheel right */
1148 	    ins_mousescroll(MSCR_RIGHT);
1149 	    break;
1150 #endif
1151 #ifdef FEAT_GUI_TABLINE
1152 	case K_TABLINE:
1153 	case K_TABMENU:
1154 	    ins_tabline(c);
1155 	    break;
1156 #endif
1157 
1158 	case K_IGNORE:	/* Something mapped to nothing */
1159 	    break;
1160 
1161 #ifdef FEAT_AUTOCMD
1162 	case K_CURSORHOLD:	/* Didn't type something for a while. */
1163 	    apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf);
1164 	    did_cursorhold = TRUE;
1165 	    break;
1166 #endif
1167 
1168 #ifdef FEAT_GUI_W32
1169 	    /* On Win32 ignore <M-F4>, we get it when closing the window was
1170 	     * cancelled. */
1171 	case K_F4:
1172 	    if (mod_mask != MOD_MASK_ALT)
1173 		goto normalchar;
1174 	    break;
1175 #endif
1176 
1177 #ifdef FEAT_GUI
1178 	case K_VER_SCROLLBAR:
1179 	    ins_scroll();
1180 	    break;
1181 
1182 	case K_HOR_SCROLLBAR:
1183 	    ins_horscroll();
1184 	    break;
1185 #endif
1186 
1187 	case K_HOME:	/* <Home> */
1188 	case K_KHOME:
1189 	case K_S_HOME:
1190 	case K_C_HOME:
1191 	    ins_home(c);
1192 	    break;
1193 
1194 	case K_END:	/* <End> */
1195 	case K_KEND:
1196 	case K_S_END:
1197 	case K_C_END:
1198 	    ins_end(c);
1199 	    break;
1200 
1201 	case K_LEFT:	/* <Left> */
1202 	    if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1203 		ins_s_left();
1204 	    else
1205 		ins_left();
1206 	    break;
1207 
1208 	case K_S_LEFT:	/* <S-Left> */
1209 	case K_C_LEFT:
1210 	    ins_s_left();
1211 	    break;
1212 
1213 	case K_RIGHT:	/* <Right> */
1214 	    if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1215 		ins_s_right();
1216 	    else
1217 		ins_right();
1218 	    break;
1219 
1220 	case K_S_RIGHT:	/* <S-Right> */
1221 	case K_C_RIGHT:
1222 	    ins_s_right();
1223 	    break;
1224 
1225 	case K_UP:	/* <Up> */
1226 #ifdef FEAT_INS_EXPAND
1227 	    if (pum_visible())
1228 		goto docomplete;
1229 #endif
1230 	    if (mod_mask & MOD_MASK_SHIFT)
1231 		ins_pageup();
1232 	    else
1233 		ins_up(FALSE);
1234 	    break;
1235 
1236 	case K_S_UP:	/* <S-Up> */
1237 	case K_PAGEUP:
1238 	case K_KPAGEUP:
1239 #ifdef FEAT_INS_EXPAND
1240 	    if (pum_visible())
1241 		goto docomplete;
1242 #endif
1243 	    ins_pageup();
1244 	    break;
1245 
1246 	case K_DOWN:	/* <Down> */
1247 #ifdef FEAT_INS_EXPAND
1248 	    if (pum_visible())
1249 		goto docomplete;
1250 #endif
1251 	    if (mod_mask & MOD_MASK_SHIFT)
1252 		ins_pagedown();
1253 	    else
1254 		ins_down(FALSE);
1255 	    break;
1256 
1257 	case K_S_DOWN:	/* <S-Down> */
1258 	case K_PAGEDOWN:
1259 	case K_KPAGEDOWN:
1260 #ifdef FEAT_INS_EXPAND
1261 	    if (pum_visible())
1262 		goto docomplete;
1263 #endif
1264 	    ins_pagedown();
1265 	    break;
1266 
1267 #ifdef FEAT_DND
1268 	case K_DROP:	/* drag-n-drop event */
1269 	    ins_drop();
1270 	    break;
1271 #endif
1272 
1273 	case K_S_TAB:	/* When not mapped, use like a normal TAB */
1274 	    c = TAB;
1275 	    /* FALLTHROUGH */
1276 
1277 	case TAB:	/* TAB or Complete patterns along path */
1278 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1279 	    if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1280 		goto docomplete;
1281 #endif
1282 	    inserted_space = FALSE;
1283 	    if (ins_tab())
1284 		goto normalchar;	/* insert TAB as a normal char */
1285 	    auto_format(FALSE, TRUE);
1286 	    break;
1287 
1288 	case K_KENTER:	/* <Enter> */
1289 	    c = CAR;
1290 	    /* FALLTHROUGH */
1291 	case CAR:
1292 	case NL:
1293 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1294 	    /* In a quickfix window a <CR> jumps to the error under the
1295 	     * cursor. */
1296 	    if (bt_quickfix(curbuf) && c == CAR)
1297 	    {
1298 		if (curwin->w_llist_ref == NULL)    /* quickfix window */
1299 		    do_cmdline_cmd((char_u *)".cc");
1300 		else				    /* location list window */
1301 		    do_cmdline_cmd((char_u *)".ll");
1302 		break;
1303 	    }
1304 #endif
1305 #ifdef FEAT_CMDWIN
1306 	    if (cmdwin_type != 0)
1307 	    {
1308 		/* Execute the command in the cmdline window. */
1309 		cmdwin_result = CAR;
1310 		goto doESCkey;
1311 	    }
1312 #endif
1313 	    if (ins_eol(c) && !p_im)
1314 		goto doESCkey;	    /* out of memory */
1315 	    auto_format(FALSE, FALSE);
1316 	    inserted_space = FALSE;
1317 	    break;
1318 
1319 #if defined(FEAT_DIGRAPHS) || defined(FEAT_INS_EXPAND)
1320 	case Ctrl_K:	    /* digraph or keyword completion */
1321 # ifdef FEAT_INS_EXPAND
1322 	    if (ctrl_x_mode == CTRL_X_DICTIONARY)
1323 	    {
1324 		if (has_compl_option(TRUE))
1325 		    goto docomplete;
1326 		break;
1327 	    }
1328 # endif
1329 # ifdef FEAT_DIGRAPHS
1330 	    c = ins_digraph();
1331 	    if (c == NUL)
1332 		break;
1333 # endif
1334 	    goto normalchar;
1335 #endif
1336 
1337 #ifdef FEAT_INS_EXPAND
1338 	case Ctrl_X:	/* Enter CTRL-X mode */
1339 	    ins_ctrl_x();
1340 	    break;
1341 
1342 	case Ctrl_RSB:	/* Tag name completion after ^X */
1343 	    if (ctrl_x_mode != CTRL_X_TAGS)
1344 		goto normalchar;
1345 	    goto docomplete;
1346 
1347 	case Ctrl_F:	/* File name completion after ^X */
1348 	    if (ctrl_x_mode != CTRL_X_FILES)
1349 		goto normalchar;
1350 	    goto docomplete;
1351 
1352 	case 's':	/* Spelling completion after ^X */
1353 	case Ctrl_S:
1354 	    if (ctrl_x_mode != CTRL_X_SPELL)
1355 		goto normalchar;
1356 	    goto docomplete;
1357 #endif
1358 
1359 	case Ctrl_L:	/* Whole line completion after ^X */
1360 #ifdef FEAT_INS_EXPAND
1361 	    if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1362 #endif
1363 	    {
1364 		/* CTRL-L with 'insertmode' set: Leave Insert mode */
1365 		if (p_im)
1366 		{
1367 		    if (echeck_abbr(Ctrl_L + ABBR_OFF))
1368 			break;
1369 		    goto doESCkey;
1370 		}
1371 		goto normalchar;
1372 	    }
1373 #ifdef FEAT_INS_EXPAND
1374 	    /* FALLTHROUGH */
1375 
1376 	case Ctrl_P:	/* Do previous/next pattern completion */
1377 	case Ctrl_N:
1378 	    /* if 'complete' is empty then plain ^P is no longer special,
1379 	     * but it is under other ^X modes */
1380 	    if (*curbuf->b_p_cpt == NUL
1381 		    && ctrl_x_mode != 0
1382 		    && !(compl_cont_status & CONT_LOCAL))
1383 		goto normalchar;
1384 
1385 docomplete:
1386 	    compl_busy = TRUE;
1387 	    if (ins_complete(c) == FAIL)
1388 		compl_cont_status = 0;
1389 	    compl_busy = FALSE;
1390 	    break;
1391 #endif /* FEAT_INS_EXPAND */
1392 
1393 	case Ctrl_Y:	/* copy from previous line or scroll down */
1394 	case Ctrl_E:	/* copy from next line	   or scroll up */
1395 	    c = ins_ctrl_ey(c);
1396 	    break;
1397 
1398 	  default:
1399 #ifdef UNIX
1400 	    if (c == intr_char)		/* special interrupt char */
1401 		goto do_intr;
1402 #endif
1403 
1404 normalchar:
1405 	    /*
1406 	     * Insert a nomal character.
1407 	     */
1408 #ifdef FEAT_AUTOCMD
1409 	    if (!p_paste)
1410 	    {
1411 		/* Trigger InsertCharPre. */
1412 		char_u *str = do_insert_char_pre(c);
1413 		char_u *p;
1414 
1415 		if (str != NULL)
1416 		{
1417 		    if (*str != NUL && stop_arrow() != FAIL)
1418 		    {
1419 			/* Insert the new value of v:char literally. */
1420 			for (p = str; *p != NUL; mb_ptr_adv(p))
1421 			{
1422 			    c = PTR2CHAR(p);
1423 			    if (c == CAR || c == K_KENTER || c == NL)
1424 				ins_eol(c);
1425 			    else
1426 				ins_char(c);
1427 			}
1428 			AppendToRedobuffLit(str, -1);
1429 		    }
1430 		    vim_free(str);
1431 		    c = NUL;
1432 		}
1433 
1434 		/* If the new value is already inserted or an empty string
1435 		 * then don't insert any character. */
1436 		if (c == NUL)
1437 		    break;
1438 	    }
1439 #endif
1440 #ifdef FEAT_SMARTINDENT
1441 	    /* Try to perform smart-indenting. */
1442 	    ins_try_si(c);
1443 #endif
1444 
1445 	    if (c == ' ')
1446 	    {
1447 		inserted_space = TRUE;
1448 #ifdef FEAT_CINDENT
1449 		if (inindent(0))
1450 		    can_cindent = FALSE;
1451 #endif
1452 		if (Insstart_blank_vcol == MAXCOL
1453 			&& curwin->w_cursor.lnum == Insstart.lnum)
1454 		    Insstart_blank_vcol = get_nolist_virtcol();
1455 	    }
1456 
1457 	    /* Insert a normal character and check for abbreviations on a
1458 	     * special character.  Let CTRL-] expand abbreviations without
1459 	     * inserting it. */
1460 	    if (vim_iswordc(c) || (!echeck_abbr(
1461 #ifdef FEAT_MBYTE
1462 			/* Add ABBR_OFF for characters above 0x100, this is
1463 			 * what check_abbr() expects. */
1464 			(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1465 #endif
1466 		       c) && c != Ctrl_RSB))
1467 	    {
1468 		insert_special(c, FALSE, FALSE);
1469 #ifdef FEAT_RIGHTLEFT
1470 		revins_legal++;
1471 		revins_chars++;
1472 #endif
1473 	    }
1474 
1475 	    auto_format(FALSE, TRUE);
1476 
1477 #ifdef FEAT_FOLDING
1478 	    /* When inserting a character the cursor line must never be in a
1479 	     * closed fold. */
1480 	    foldOpenCursor();
1481 #endif
1482 	    break;
1483 	}   /* end of switch (c) */
1484 
1485 #ifdef FEAT_AUTOCMD
1486 	/* If typed something may trigger CursorHoldI again. */
1487 	if (c != K_CURSORHOLD)
1488 	    did_cursorhold = FALSE;
1489 #endif
1490 
1491 	/* If the cursor was moved we didn't just insert a space */
1492 	if (arrow_used)
1493 	    inserted_space = FALSE;
1494 
1495 #ifdef FEAT_CINDENT
1496 	if (can_cindent && cindent_on()
1497 # ifdef FEAT_INS_EXPAND
1498 		&& ctrl_x_mode == 0
1499 # endif
1500 	   )
1501 	{
1502 force_cindent:
1503 	    /*
1504 	     * Indent now if a key was typed that is in 'cinkeys'.
1505 	     */
1506 	    if (in_cinkeys(c, ' ', line_is_white))
1507 	    {
1508 		if (stop_arrow() == OK)
1509 		    /* re-indent the current line */
1510 		    do_c_expr_indent();
1511 	    }
1512 	}
1513 #endif /* FEAT_CINDENT */
1514 
1515     }	/* for (;;) */
1516     /* NOTREACHED */
1517 }
1518 
1519 /*
1520  * Redraw for Insert mode.
1521  * This is postponed until getting the next character to make '$' in the 'cpo'
1522  * option work correctly.
1523  * Only redraw when there are no characters available.  This speeds up
1524  * inserting sequences of characters (e.g., for CTRL-R).
1525  */
1526     static void
1527 ins_redraw(ready)
1528     int		ready UNUSED;	    /* not busy with something */
1529 {
1530 #ifdef FEAT_CONCEAL
1531     linenr_T	conceal_old_cursor_line = 0;
1532     linenr_T	conceal_new_cursor_line = 0;
1533     int		conceal_update_lines = FALSE;
1534 #endif
1535 
1536     if (!char_avail())
1537     {
1538 #if defined(FEAT_AUTOCMD) || defined(FEAT_CONCEAL)
1539 	/* Trigger CursorMoved if the cursor moved.  Not when the popup menu is
1540 	 * visible, the command might delete it. */
1541 	if (ready && (
1542 # ifdef FEAT_AUTOCMD
1543 		    has_cursormovedI()
1544 # endif
1545 # if defined(FEAT_AUTOCMD) && defined(FEAT_CONCEAL)
1546 		    ||
1547 # endif
1548 # ifdef FEAT_CONCEAL
1549 		    curwin->w_p_cole > 0
1550 # endif
1551 		    )
1552 	    && !equalpos(last_cursormoved, curwin->w_cursor)
1553 # ifdef FEAT_INS_EXPAND
1554 	    && !pum_visible()
1555 # endif
1556 	   )
1557 	{
1558 # ifdef FEAT_SYN_HL
1559 	    /* Need to update the screen first, to make sure syntax
1560 	     * highlighting is correct after making a change (e.g., inserting
1561 	     * a "(".  The autocommand may also require a redraw, so it's done
1562 	     * again below, unfortunately. */
1563 	    if (syntax_present(curwin) && must_redraw)
1564 		update_screen(0);
1565 # endif
1566 # ifdef FEAT_AUTOCMD
1567 	    if (has_cursormovedI())
1568 		apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf);
1569 # endif
1570 # ifdef FEAT_CONCEAL
1571 	    if (curwin->w_p_cole > 0)
1572 	    {
1573 		conceal_old_cursor_line = last_cursormoved.lnum;
1574 		conceal_new_cursor_line = curwin->w_cursor.lnum;
1575 		conceal_update_lines = TRUE;
1576 	    }
1577 # endif
1578 	    last_cursormoved = curwin->w_cursor;
1579 	}
1580 #endif
1581 	if (must_redraw)
1582 	    update_screen(0);
1583 	else if (clear_cmdline || redraw_cmdline)
1584 	    showmode();		/* clear cmdline and show mode */
1585 # if defined(FEAT_CONCEAL)
1586 	if ((conceal_update_lines
1587 		&& (conceal_old_cursor_line != conceal_new_cursor_line
1588 		    || conceal_cursor_line(curwin)))
1589 		|| need_cursor_line_redraw)
1590 	{
1591 	    if (conceal_old_cursor_line != conceal_new_cursor_line)
1592 		update_single_line(curwin, conceal_old_cursor_line);
1593 	    update_single_line(curwin, conceal_new_cursor_line == 0
1594 			   ? curwin->w_cursor.lnum : conceal_new_cursor_line);
1595 	    curwin->w_valid &= ~VALID_CROW;
1596 	}
1597 # endif
1598 	showruler(FALSE);
1599 	setcursor();
1600 	emsg_on_display = FALSE;	/* may remove error message now */
1601     }
1602 }
1603 
1604 /*
1605  * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1606  */
1607     static void
1608 ins_ctrl_v()
1609 {
1610     int		c;
1611     int		did_putchar = FALSE;
1612 
1613     /* may need to redraw when no more chars available now */
1614     ins_redraw(FALSE);
1615 
1616     if (redrawing() && !char_avail())
1617     {
1618 	edit_putchar('^', TRUE);
1619 	did_putchar = TRUE;
1620     }
1621     AppendToRedobuff((char_u *)CTRL_V_STR);	/* CTRL-V */
1622 
1623 #ifdef FEAT_CMDL_INFO
1624     add_to_showcmd_c(Ctrl_V);
1625 #endif
1626 
1627     c = get_literal();
1628     if (did_putchar)
1629 	/* when the line fits in 'columns' the '^' is at the start of the next
1630 	 * line and will not removed by the redraw */
1631 	edit_unputchar();
1632 #ifdef FEAT_CMDL_INFO
1633     clear_showcmd();
1634 #endif
1635     insert_special(c, FALSE, TRUE);
1636 #ifdef FEAT_RIGHTLEFT
1637     revins_chars++;
1638     revins_legal++;
1639 #endif
1640 }
1641 
1642 /*
1643  * Put a character directly onto the screen.  It's not stored in a buffer.
1644  * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1645  */
1646 static int  pc_status;
1647 #define PC_STATUS_UNSET	0	/* pc_bytes was not set */
1648 #define PC_STATUS_RIGHT	1	/* right halve of double-wide char */
1649 #define PC_STATUS_LEFT	2	/* left halve of double-wide char */
1650 #define PC_STATUS_SET	3	/* pc_bytes was filled */
1651 static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1652 static int  pc_attr;
1653 static int  pc_row;
1654 static int  pc_col;
1655 
1656     void
1657 edit_putchar(c, highlight)
1658     int	    c;
1659     int	    highlight;
1660 {
1661     int	    attr;
1662 
1663     if (ScreenLines != NULL)
1664     {
1665 	update_topline();	/* just in case w_topline isn't valid */
1666 	validate_cursor();
1667 	if (highlight)
1668 	    attr = hl_attr(HLF_8);
1669 	else
1670 	    attr = 0;
1671 	pc_row = W_WINROW(curwin) + curwin->w_wrow;
1672 	pc_col = W_WINCOL(curwin);
1673 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1674 	pc_status = PC_STATUS_UNSET;
1675 #endif
1676 #ifdef FEAT_RIGHTLEFT
1677 	if (curwin->w_p_rl)
1678 	{
1679 	    pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1680 # ifdef FEAT_MBYTE
1681 	    if (has_mbyte)
1682 	    {
1683 		int fix_col = mb_fix_col(pc_col, pc_row);
1684 
1685 		if (fix_col != pc_col)
1686 		{
1687 		    screen_putchar(' ', pc_row, fix_col, attr);
1688 		    --curwin->w_wcol;
1689 		    pc_status = PC_STATUS_RIGHT;
1690 		}
1691 	    }
1692 # endif
1693 	}
1694 	else
1695 #endif
1696 	{
1697 	    pc_col += curwin->w_wcol;
1698 #ifdef FEAT_MBYTE
1699 	    if (mb_lefthalve(pc_row, pc_col))
1700 		pc_status = PC_STATUS_LEFT;
1701 #endif
1702 	}
1703 
1704 	/* save the character to be able to put it back */
1705 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1706 	if (pc_status == PC_STATUS_UNSET)
1707 #endif
1708 	{
1709 	    screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1710 	    pc_status = PC_STATUS_SET;
1711 	}
1712 	screen_putchar(c, pc_row, pc_col, attr);
1713     }
1714 }
1715 
1716 /*
1717  * Undo the previous edit_putchar().
1718  */
1719     void
1720 edit_unputchar()
1721 {
1722     if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1723     {
1724 #if defined(FEAT_MBYTE)
1725 	if (pc_status == PC_STATUS_RIGHT)
1726 	    ++curwin->w_wcol;
1727 	if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1728 	    redrawWinline(curwin->w_cursor.lnum, FALSE);
1729 	else
1730 #endif
1731 	    screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1732     }
1733 }
1734 
1735 /*
1736  * Called when p_dollar is set: display a '$' at the end of the changed text
1737  * Only works when cursor is in the line that changes.
1738  */
1739     void
1740 display_dollar(col)
1741     colnr_T	col;
1742 {
1743     colnr_T save_col;
1744 
1745     if (!redrawing())
1746 	return;
1747 
1748     cursor_off();
1749     save_col = curwin->w_cursor.col;
1750     curwin->w_cursor.col = col;
1751 #ifdef FEAT_MBYTE
1752     if (has_mbyte)
1753     {
1754 	char_u *p;
1755 
1756 	/* If on the last byte of a multi-byte move to the first byte. */
1757 	p = ml_get_curline();
1758 	curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1759     }
1760 #endif
1761     curs_columns(FALSE);	    /* recompute w_wrow and w_wcol */
1762     if (curwin->w_wcol < W_WIDTH(curwin))
1763     {
1764 	edit_putchar('$', FALSE);
1765 	dollar_vcol = curwin->w_virtcol;
1766     }
1767     curwin->w_cursor.col = save_col;
1768 }
1769 
1770 /*
1771  * Call this function before moving the cursor from the normal insert position
1772  * in insert mode.
1773  */
1774     static void
1775 undisplay_dollar()
1776 {
1777     if (dollar_vcol >= 0)
1778     {
1779 	dollar_vcol = -1;
1780 	redrawWinline(curwin->w_cursor.lnum, FALSE);
1781     }
1782 }
1783 
1784 /*
1785  * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1786  * Keep the cursor on the same character.
1787  * type == INDENT_INC	increase indent (for CTRL-T or <Tab>)
1788  * type == INDENT_DEC	decrease indent (for CTRL-D)
1789  * type == INDENT_SET	set indent to "amount"
1790  * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1791  */
1792     void
1793 change_indent(type, amount, round, replaced, call_changed_bytes)
1794     int		type;
1795     int		amount;
1796     int		round;
1797     int		replaced;	/* replaced character, put on replace stack */
1798     int		call_changed_bytes;	/* call changed_bytes() */
1799 {
1800     int		vcol;
1801     int		last_vcol;
1802     int		insstart_less;		/* reduction for Insstart.col */
1803     int		new_cursor_col;
1804     int		i;
1805     char_u	*ptr;
1806     int		save_p_list;
1807     int		start_col;
1808     colnr_T	vc;
1809 #ifdef FEAT_VREPLACE
1810     colnr_T	orig_col = 0;		/* init for GCC */
1811     char_u	*new_line, *orig_line = NULL;	/* init for GCC */
1812 
1813     /* VREPLACE mode needs to know what the line was like before changing */
1814     if (State & VREPLACE_FLAG)
1815     {
1816 	orig_line = vim_strsave(ml_get_curline());  /* Deal with NULL below */
1817 	orig_col = curwin->w_cursor.col;
1818     }
1819 #endif
1820 
1821     /* for the following tricks we don't want list mode */
1822     save_p_list = curwin->w_p_list;
1823     curwin->w_p_list = FALSE;
1824     vc = getvcol_nolist(&curwin->w_cursor);
1825     vcol = vc;
1826 
1827     /*
1828      * For Replace mode we need to fix the replace stack later, which is only
1829      * possible when the cursor is in the indent.  Remember the number of
1830      * characters before the cursor if it's possible.
1831      */
1832     start_col = curwin->w_cursor.col;
1833 
1834     /* determine offset from first non-blank */
1835     new_cursor_col = curwin->w_cursor.col;
1836     beginline(BL_WHITE);
1837     new_cursor_col -= curwin->w_cursor.col;
1838 
1839     insstart_less = curwin->w_cursor.col;
1840 
1841     /*
1842      * If the cursor is in the indent, compute how many screen columns the
1843      * cursor is to the left of the first non-blank.
1844      */
1845     if (new_cursor_col < 0)
1846 	vcol = get_indent() - vcol;
1847 
1848     if (new_cursor_col > 0)	    /* can't fix replace stack */
1849 	start_col = -1;
1850 
1851     /*
1852      * Set the new indent.  The cursor will be put on the first non-blank.
1853      */
1854     if (type == INDENT_SET)
1855 	(void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
1856     else
1857     {
1858 #ifdef FEAT_VREPLACE
1859 	int	save_State = State;
1860 
1861 	/* Avoid being called recursively. */
1862 	if (State & VREPLACE_FLAG)
1863 	    State = INSERT;
1864 #endif
1865 	shift_line(type == INDENT_DEC, round, 1, call_changed_bytes);
1866 #ifdef FEAT_VREPLACE
1867 	State = save_State;
1868 #endif
1869     }
1870     insstart_less -= curwin->w_cursor.col;
1871 
1872     /*
1873      * Try to put cursor on same character.
1874      * If the cursor is at or after the first non-blank in the line,
1875      * compute the cursor column relative to the column of the first
1876      * non-blank character.
1877      * If we are not in insert mode, leave the cursor on the first non-blank.
1878      * If the cursor is before the first non-blank, position it relative
1879      * to the first non-blank, counted in screen columns.
1880      */
1881     if (new_cursor_col >= 0)
1882     {
1883 	/*
1884 	 * When changing the indent while the cursor is touching it, reset
1885 	 * Insstart_col to 0.
1886 	 */
1887 	if (new_cursor_col == 0)
1888 	    insstart_less = MAXCOL;
1889 	new_cursor_col += curwin->w_cursor.col;
1890     }
1891     else if (!(State & INSERT))
1892 	new_cursor_col = curwin->w_cursor.col;
1893     else
1894     {
1895 	/*
1896 	 * Compute the screen column where the cursor should be.
1897 	 */
1898 	vcol = get_indent() - vcol;
1899 	curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);
1900 
1901 	/*
1902 	 * Advance the cursor until we reach the right screen column.
1903 	 */
1904 	vcol = last_vcol = 0;
1905 	new_cursor_col = -1;
1906 	ptr = ml_get_curline();
1907 	while (vcol <= (int)curwin->w_virtcol)
1908 	{
1909 	    last_vcol = vcol;
1910 #ifdef FEAT_MBYTE
1911 	    if (has_mbyte && new_cursor_col >= 0)
1912 		new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1913 	    else
1914 #endif
1915 		++new_cursor_col;
1916 	    vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol);
1917 	}
1918 	vcol = last_vcol;
1919 
1920 	/*
1921 	 * May need to insert spaces to be able to position the cursor on
1922 	 * the right screen column.
1923 	 */
1924 	if (vcol != (int)curwin->w_virtcol)
1925 	{
1926 	    curwin->w_cursor.col = (colnr_T)new_cursor_col;
1927 	    i = (int)curwin->w_virtcol - vcol;
1928 	    ptr = alloc((unsigned)(i + 1));
1929 	    if (ptr != NULL)
1930 	    {
1931 		new_cursor_col += i;
1932 		ptr[i] = NUL;
1933 		while (--i >= 0)
1934 		    ptr[i] = ' ';
1935 		ins_str(ptr);
1936 		vim_free(ptr);
1937 	    }
1938 	}
1939 
1940 	/*
1941 	 * When changing the indent while the cursor is in it, reset
1942 	 * Insstart_col to 0.
1943 	 */
1944 	insstart_less = MAXCOL;
1945     }
1946 
1947     curwin->w_p_list = save_p_list;
1948 
1949     if (new_cursor_col <= 0)
1950 	curwin->w_cursor.col = 0;
1951     else
1952 	curwin->w_cursor.col = (colnr_T)new_cursor_col;
1953     curwin->w_set_curswant = TRUE;
1954     changed_cline_bef_curs();
1955 
1956     /*
1957      * May have to adjust the start of the insert.
1958      */
1959     if (State & INSERT)
1960     {
1961 	if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1962 	{
1963 	    if ((int)Insstart.col <= insstart_less)
1964 		Insstart.col = 0;
1965 	    else
1966 		Insstart.col -= insstart_less;
1967 	}
1968 	if ((int)ai_col <= insstart_less)
1969 	    ai_col = 0;
1970 	else
1971 	    ai_col -= insstart_less;
1972     }
1973 
1974     /*
1975      * For REPLACE mode, may have to fix the replace stack, if it's possible.
1976      * If the number of characters before the cursor decreased, need to pop a
1977      * few characters from the replace stack.
1978      * If the number of characters before the cursor increased, need to push a
1979      * few NULs onto the replace stack.
1980      */
1981     if (REPLACE_NORMAL(State) && start_col >= 0)
1982     {
1983 	while (start_col > (int)curwin->w_cursor.col)
1984 	{
1985 	    replace_join(0);	    /* remove a NUL from the replace stack */
1986 	    --start_col;
1987 	}
1988 	while (start_col < (int)curwin->w_cursor.col || replaced)
1989 	{
1990 	    replace_push(NUL);
1991 	    if (replaced)
1992 	    {
1993 		replace_push(replaced);
1994 		replaced = NUL;
1995 	    }
1996 	    ++start_col;
1997 	}
1998     }
1999 
2000 #ifdef FEAT_VREPLACE
2001     /*
2002      * For VREPLACE mode, we also have to fix the replace stack.  In this case
2003      * it is always possible because we backspace over the whole line and then
2004      * put it back again the way we wanted it.
2005      */
2006     if (State & VREPLACE_FLAG)
2007     {
2008 	/* If orig_line didn't allocate, just return.  At least we did the job,
2009 	 * even if you can't backspace. */
2010 	if (orig_line == NULL)
2011 	    return;
2012 
2013 	/* Save new line */
2014 	new_line = vim_strsave(ml_get_curline());
2015 	if (new_line == NULL)
2016 	    return;
2017 
2018 	/* We only put back the new line up to the cursor */
2019 	new_line[curwin->w_cursor.col] = NUL;
2020 
2021 	/* Put back original line */
2022 	ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
2023 	curwin->w_cursor.col = orig_col;
2024 
2025 	/* Backspace from cursor to start of line */
2026 	backspace_until_column(0);
2027 
2028 	/* Insert new stuff into line again */
2029 	ins_bytes(new_line);
2030 
2031 	vim_free(new_line);
2032     }
2033 #endif
2034 }
2035 
2036 /*
2037  * Truncate the space at the end of a line.  This is to be used only in an
2038  * insert mode.  It handles fixing the replace stack for REPLACE and VREPLACE
2039  * modes.
2040  */
2041     void
2042 truncate_spaces(line)
2043     char_u  *line;
2044 {
2045     int	    i;
2046 
2047     /* find start of trailing white space */
2048     for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
2049     {
2050 	if (State & REPLACE_FLAG)
2051 	    replace_join(0);	    /* remove a NUL from the replace stack */
2052     }
2053     line[i + 1] = NUL;
2054 }
2055 
2056 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2057 	|| defined(FEAT_COMMENTS) || defined(PROTO)
2058 /*
2059  * Backspace the cursor until the given column.  Handles REPLACE and VREPLACE
2060  * modes correctly.  May also be used when not in insert mode at all.
2061  * Will attempt not to go before "col" even when there is a composing
2062  * character.
2063  */
2064     void
2065 backspace_until_column(col)
2066     int	    col;
2067 {
2068     while ((int)curwin->w_cursor.col > col)
2069     {
2070 	curwin->w_cursor.col--;
2071 	if (State & REPLACE_FLAG)
2072 	    replace_do_bs(col);
2073 	else if (!del_char_after_col(col))
2074 	    break;
2075     }
2076 }
2077 #endif
2078 
2079 /*
2080  * Like del_char(), but make sure not to go before column "limit_col".
2081  * Only matters when there are composing characters.
2082  * Return TRUE when something was deleted.
2083  */
2084    static int
2085 del_char_after_col(limit_col)
2086     int limit_col UNUSED;
2087 {
2088 #ifdef FEAT_MBYTE
2089     if (enc_utf8 && limit_col >= 0)
2090     {
2091 	colnr_T ecol = curwin->w_cursor.col + 1;
2092 
2093 	/* Make sure the cursor is at the start of a character, but
2094 	 * skip forward again when going too far back because of a
2095 	 * composing character. */
2096 	mb_adjust_cursor();
2097 	while (curwin->w_cursor.col < (colnr_T)limit_col)
2098 	{
2099 	    int l = utf_ptr2len(ml_get_cursor());
2100 
2101 	    if (l == 0)  /* end of line */
2102 		break;
2103 	    curwin->w_cursor.col += l;
2104 	}
2105 	if (*ml_get_cursor() == NUL || curwin->w_cursor.col == ecol)
2106 	    return FALSE;
2107 	del_bytes((long)((int)ecol - curwin->w_cursor.col), FALSE, TRUE);
2108     }
2109     else
2110 #endif
2111 	(void)del_char(FALSE);
2112     return TRUE;
2113 }
2114 
2115 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
2116 /*
2117  * CTRL-X pressed in Insert mode.
2118  */
2119     static void
2120 ins_ctrl_x()
2121 {
2122     /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
2123      * CTRL-V works like CTRL-N */
2124     if (ctrl_x_mode != CTRL_X_CMDLINE)
2125     {
2126 	/* if the next ^X<> won't ADD nothing, then reset
2127 	 * compl_cont_status */
2128 	if (compl_cont_status & CONT_N_ADDS)
2129 	    compl_cont_status |= CONT_INTRPT;
2130 	else
2131 	    compl_cont_status = 0;
2132 	/* We're not sure which CTRL-X mode it will be yet */
2133 	ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2134 	edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
2135 	edit_submode_pre = NULL;
2136 	showmode();
2137     }
2138 }
2139 
2140 /*
2141  * Return TRUE if the 'dict' or 'tsr' option can be used.
2142  */
2143     static int
2144 has_compl_option(dict_opt)
2145     int	    dict_opt;
2146 {
2147     if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
2148 # ifdef FEAT_SPELL
2149 							&& !curwin->w_p_spell
2150 # endif
2151 							)
2152 		 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
2153     {
2154 	ctrl_x_mode = 0;
2155 	edit_submode = NULL;
2156 	msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty")
2157 			  : (char_u *)_("'thesaurus' option is empty"),
2158 							      hl_attr(HLF_E));
2159 	if (emsg_silent == 0)
2160 	{
2161 	    vim_beep();
2162 	    setcursor();
2163 	    out_flush();
2164 	    ui_delay(2000L, FALSE);
2165 	}
2166 	return FALSE;
2167     }
2168     return TRUE;
2169 }
2170 
2171 /*
2172  * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
2173  * This depends on the current mode.
2174  */
2175     int
2176 vim_is_ctrl_x_key(c)
2177     int	    c;
2178 {
2179     /* Always allow ^R - let it's results then be checked */
2180     if (c == Ctrl_R)
2181 	return TRUE;
2182 
2183     /* Accept <PageUp> and <PageDown> if the popup menu is visible. */
2184     if (ins_compl_pum_key(c))
2185 	return TRUE;
2186 
2187     switch (ctrl_x_mode)
2188     {
2189 	case 0:		    /* Not in any CTRL-X mode */
2190 	    return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
2191 	case CTRL_X_NOT_DEFINED_YET:
2192 	    return (   c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
2193 		    || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
2194 		    || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
2195 		    || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
2196 		    || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
2197 		    || c == Ctrl_S || c == Ctrl_K || c == 's');
2198 	case CTRL_X_SCROLL:
2199 	    return (c == Ctrl_Y || c == Ctrl_E);
2200 	case CTRL_X_WHOLE_LINE:
2201 	    return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
2202 	case CTRL_X_FILES:
2203 	    return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
2204 	case CTRL_X_DICTIONARY:
2205 	    return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
2206 	case CTRL_X_THESAURUS:
2207 	    return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
2208 	case CTRL_X_TAGS:
2209 	    return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
2210 #ifdef FEAT_FIND_ID
2211 	case CTRL_X_PATH_PATTERNS:
2212 	    return (c == Ctrl_P || c == Ctrl_N);
2213 	case CTRL_X_PATH_DEFINES:
2214 	    return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
2215 #endif
2216 	case CTRL_X_CMDLINE:
2217 	    return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
2218 		    || c == Ctrl_X);
2219 #ifdef FEAT_COMPL_FUNC
2220 	case CTRL_X_FUNCTION:
2221 	    return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
2222 	case CTRL_X_OMNI:
2223 	    return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
2224 #endif
2225 	case CTRL_X_SPELL:
2226 	    return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
2227     }
2228     EMSG(_(e_internal));
2229     return FALSE;
2230 }
2231 
2232 /*
2233  * Return TRUE when character "c" is part of the item currently being
2234  * completed.  Used to decide whether to abandon complete mode when the menu
2235  * is visible.
2236  */
2237     static int
2238 ins_compl_accept_char(c)
2239     int c;
2240 {
2241     if (ctrl_x_mode & CTRL_X_WANT_IDENT)
2242 	/* When expanding an identifier only accept identifier chars. */
2243 	return vim_isIDc(c);
2244 
2245     switch (ctrl_x_mode)
2246     {
2247 	case CTRL_X_FILES:
2248 	    /* When expanding file name only accept file name chars. But not
2249 	     * path separators, so that "proto/<Tab>" expands files in
2250 	     * "proto", not "proto/" as a whole */
2251 	    return vim_isfilec(c) && !vim_ispathsep(c);
2252 
2253 	case CTRL_X_CMDLINE:
2254 	case CTRL_X_OMNI:
2255 	    /* Command line and Omni completion can work with just about any
2256 	     * printable character, but do stop at white space. */
2257 	    return vim_isprintc(c) && !vim_iswhite(c);
2258 
2259 	case CTRL_X_WHOLE_LINE:
2260 	    /* For while line completion a space can be part of the line. */
2261 	    return vim_isprintc(c);
2262     }
2263     return vim_iswordc(c);
2264 }
2265 
2266 /*
2267  * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
2268  * case of the originally typed text is used, and the case of the completed
2269  * text is inferred, ie this tries to work out what case you probably wanted
2270  * the rest of the word to be in -- webb
2271  */
2272     int
2273 ins_compl_add_infercase(str, len, icase, fname, dir, flags)
2274     char_u	*str;
2275     int		len;
2276     int		icase;
2277     char_u	*fname;
2278     int		dir;
2279     int		flags;
2280 {
2281     char_u	*p;
2282     int		i, c;
2283     int		actual_len;		/* Take multi-byte characters */
2284     int		actual_compl_length;	/* into account. */
2285     int		min_len;
2286     int		*wca;			/* Wide character array. */
2287     int		has_lower = FALSE;
2288     int		was_letter = FALSE;
2289 
2290     if (p_ic && curbuf->b_p_inf && len > 0)
2291     {
2292 	/* Infer case of completed part. */
2293 
2294 	/* Find actual length of completion. */
2295 #ifdef FEAT_MBYTE
2296 	if (has_mbyte)
2297 	{
2298 	    p = str;
2299 	    actual_len = 0;
2300 	    while (*p != NUL)
2301 	    {
2302 		mb_ptr_adv(p);
2303 		++actual_len;
2304 	    }
2305 	}
2306 	else
2307 #endif
2308 	    actual_len = len;
2309 
2310 	/* Find actual length of original text. */
2311 #ifdef FEAT_MBYTE
2312 	if (has_mbyte)
2313 	{
2314 	    p = compl_orig_text;
2315 	    actual_compl_length = 0;
2316 	    while (*p != NUL)
2317 	    {
2318 		mb_ptr_adv(p);
2319 		++actual_compl_length;
2320 	    }
2321 	}
2322 	else
2323 #endif
2324 	    actual_compl_length = compl_length;
2325 
2326 	/* "actual_len" may be smaller than "actual_compl_length" when using
2327 	 * thesaurus, only use the minimum when comparing. */
2328 	min_len = actual_len < actual_compl_length
2329 					   ? actual_len : actual_compl_length;
2330 
2331 	/* Allocate wide character array for the completion and fill it. */
2332 	wca = (int *)alloc((unsigned)(actual_len * sizeof(int)));
2333 	if (wca != NULL)
2334 	{
2335 	    p = str;
2336 	    for (i = 0; i < actual_len; ++i)
2337 #ifdef FEAT_MBYTE
2338 		if (has_mbyte)
2339 		    wca[i] = mb_ptr2char_adv(&p);
2340 		else
2341 #endif
2342 		    wca[i] = *(p++);
2343 
2344 	    /* Rule 1: Were any chars converted to lower? */
2345 	    p = compl_orig_text;
2346 	    for (i = 0; i < min_len; ++i)
2347 	    {
2348 #ifdef FEAT_MBYTE
2349 		if (has_mbyte)
2350 		    c = mb_ptr2char_adv(&p);
2351 		else
2352 #endif
2353 		    c = *(p++);
2354 		if (MB_ISLOWER(c))
2355 		{
2356 		    has_lower = TRUE;
2357 		    if (MB_ISUPPER(wca[i]))
2358 		    {
2359 			/* Rule 1 is satisfied. */
2360 			for (i = actual_compl_length; i < actual_len; ++i)
2361 			    wca[i] = MB_TOLOWER(wca[i]);
2362 			break;
2363 		    }
2364 		}
2365 	    }
2366 
2367 	    /*
2368 	     * Rule 2: No lower case, 2nd consecutive letter converted to
2369 	     * upper case.
2370 	     */
2371 	    if (!has_lower)
2372 	    {
2373 		p = compl_orig_text;
2374 		for (i = 0; i < min_len; ++i)
2375 		{
2376 #ifdef FEAT_MBYTE
2377 		    if (has_mbyte)
2378 			c = mb_ptr2char_adv(&p);
2379 		    else
2380 #endif
2381 			c = *(p++);
2382 		    if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
2383 		    {
2384 			/* Rule 2 is satisfied. */
2385 			for (i = actual_compl_length; i < actual_len; ++i)
2386 			    wca[i] = MB_TOUPPER(wca[i]);
2387 			break;
2388 		    }
2389 		    was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
2390 		}
2391 	    }
2392 
2393 	    /* Copy the original case of the part we typed. */
2394 	    p = compl_orig_text;
2395 	    for (i = 0; i < min_len; ++i)
2396 	    {
2397 #ifdef FEAT_MBYTE
2398 		if (has_mbyte)
2399 		    c = mb_ptr2char_adv(&p);
2400 		else
2401 #endif
2402 		    c = *(p++);
2403 		if (MB_ISLOWER(c))
2404 		    wca[i] = MB_TOLOWER(wca[i]);
2405 		else if (MB_ISUPPER(c))
2406 		    wca[i] = MB_TOUPPER(wca[i]);
2407 	    }
2408 
2409 	    /*
2410 	     * Generate encoding specific output from wide character array.
2411 	     * Multi-byte characters can occupy up to five bytes more than
2412 	     * ASCII characters, and we also need one byte for NUL, so stay
2413 	     * six bytes away from the edge of IObuff.
2414 	     */
2415 	    p = IObuff;
2416 	    i = 0;
2417 	    while (i < actual_len && (p - IObuff + 6) < IOSIZE)
2418 #ifdef FEAT_MBYTE
2419 		if (has_mbyte)
2420 		    p += (*mb_char2bytes)(wca[i++], p);
2421 		else
2422 #endif
2423 		    *(p++) = wca[i++];
2424 	    *p = NUL;
2425 
2426 	    vim_free(wca);
2427 	}
2428 
2429 	return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2430 								flags, FALSE);
2431     }
2432     return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2433 }
2434 
2435 /*
2436  * Add a match to the list of matches.
2437  * If the given string is already in the list of completions, then return
2438  * NOTDONE, otherwise add it to the list and return OK.  If there is an error,
2439  * maybe because alloc() returns NULL, then FAIL is returned.
2440  */
2441     static int
2442 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup)
2443     char_u	*str;
2444     int		len;
2445     int		icase;
2446     char_u	*fname;
2447     char_u	**cptext;   /* extra text for popup menu or NULL */
2448     int		cdir;
2449     int		flags;
2450     int		adup;	    /* accept duplicate match */
2451 {
2452     compl_T	*match;
2453     int		dir = (cdir == 0 ? compl_direction : cdir);
2454 
2455     ui_breakcheck();
2456     if (got_int)
2457 	return FAIL;
2458     if (len < 0)
2459 	len = (int)STRLEN(str);
2460 
2461     /*
2462      * If the same match is already present, don't add it.
2463      */
2464     if (compl_first_match != NULL && !adup)
2465     {
2466 	match = compl_first_match;
2467 	do
2468 	{
2469 	    if (    !(match->cp_flags & ORIGINAL_TEXT)
2470 		    && STRNCMP(match->cp_str, str, len) == 0
2471 		    && match->cp_str[len] == NUL)
2472 		return NOTDONE;
2473 	    match = match->cp_next;
2474 	} while (match != NULL && match != compl_first_match);
2475     }
2476 
2477     /* Remove any popup menu before changing the list of matches. */
2478     ins_compl_del_pum();
2479 
2480     /*
2481      * Allocate a new match structure.
2482      * Copy the values to the new match structure.
2483      */
2484     match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2485     if (match == NULL)
2486 	return FAIL;
2487     match->cp_number = -1;
2488     if (flags & ORIGINAL_TEXT)
2489 	match->cp_number = 0;
2490     if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2491     {
2492 	vim_free(match);
2493 	return FAIL;
2494     }
2495     match->cp_icase = icase;
2496 
2497     /* match-fname is:
2498      * - compl_curr_match->cp_fname if it is a string equal to fname.
2499      * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2500      * - NULL otherwise.	--Acevedo */
2501     if (fname != NULL
2502 	    && compl_curr_match != NULL
2503 	    && compl_curr_match->cp_fname != NULL
2504 	    && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2505 	match->cp_fname = compl_curr_match->cp_fname;
2506     else if (fname != NULL)
2507     {
2508 	match->cp_fname = vim_strsave(fname);
2509 	flags |= FREE_FNAME;
2510     }
2511     else
2512 	match->cp_fname = NULL;
2513     match->cp_flags = flags;
2514 
2515     if (cptext != NULL)
2516     {
2517 	int i;
2518 
2519 	for (i = 0; i < CPT_COUNT; ++i)
2520 	    if (cptext[i] != NULL && *cptext[i] != NUL)
2521 		match->cp_text[i] = vim_strsave(cptext[i]);
2522     }
2523 
2524     /*
2525      * Link the new match structure in the list of matches.
2526      */
2527     if (compl_first_match == NULL)
2528 	match->cp_next = match->cp_prev = NULL;
2529     else if (dir == FORWARD)
2530     {
2531 	match->cp_next = compl_curr_match->cp_next;
2532 	match->cp_prev = compl_curr_match;
2533     }
2534     else	/* BACKWARD */
2535     {
2536 	match->cp_next = compl_curr_match;
2537 	match->cp_prev = compl_curr_match->cp_prev;
2538     }
2539     if (match->cp_next)
2540 	match->cp_next->cp_prev = match;
2541     if (match->cp_prev)
2542 	match->cp_prev->cp_next = match;
2543     else	/* if there's nothing before, it is the first match */
2544 	compl_first_match = match;
2545     compl_curr_match = match;
2546 
2547     /*
2548      * Find the longest common string if still doing that.
2549      */
2550     if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2551 	ins_compl_longest_match(match);
2552 
2553     return OK;
2554 }
2555 
2556 /*
2557  * Return TRUE if "str[len]" matches with match->cp_str, considering
2558  * match->cp_icase.
2559  */
2560     static int
2561 ins_compl_equal(match, str, len)
2562     compl_T	*match;
2563     char_u	*str;
2564     int		len;
2565 {
2566     if (match->cp_icase)
2567 	return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2568     return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2569 }
2570 
2571 /*
2572  * Reduce the longest common string for match "match".
2573  */
2574     static void
2575 ins_compl_longest_match(match)
2576     compl_T	*match;
2577 {
2578     char_u	*p, *s;
2579     int		c1, c2;
2580     int		had_match;
2581 
2582     if (compl_leader == NULL)
2583     {
2584 	/* First match, use it as a whole. */
2585 	compl_leader = vim_strsave(match->cp_str);
2586 	if (compl_leader != NULL)
2587 	{
2588 	    had_match = (curwin->w_cursor.col > compl_col);
2589 	    ins_compl_delete();
2590 	    ins_bytes(compl_leader + ins_compl_len());
2591 	    ins_redraw(FALSE);
2592 
2593 	    /* When the match isn't there (to avoid matching itself) remove it
2594 	     * again after redrawing. */
2595 	    if (!had_match)
2596 		ins_compl_delete();
2597 	    compl_used_match = FALSE;
2598 	}
2599     }
2600     else
2601     {
2602 	/* Reduce the text if this match differs from compl_leader. */
2603 	p = compl_leader;
2604 	s = match->cp_str;
2605 	while (*p != NUL)
2606 	{
2607 #ifdef FEAT_MBYTE
2608 	    if (has_mbyte)
2609 	    {
2610 		c1 = mb_ptr2char(p);
2611 		c2 = mb_ptr2char(s);
2612 	    }
2613 	    else
2614 #endif
2615 	    {
2616 		c1 = *p;
2617 		c2 = *s;
2618 	    }
2619 	    if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2620 								 : (c1 != c2))
2621 		break;
2622 #ifdef FEAT_MBYTE
2623 	    if (has_mbyte)
2624 	    {
2625 		mb_ptr_adv(p);
2626 		mb_ptr_adv(s);
2627 	    }
2628 	    else
2629 #endif
2630 	    {
2631 		++p;
2632 		++s;
2633 	    }
2634 	}
2635 
2636 	if (*p != NUL)
2637 	{
2638 	    /* Leader was shortened, need to change the inserted text. */
2639 	    *p = NUL;
2640 	    had_match = (curwin->w_cursor.col > compl_col);
2641 	    ins_compl_delete();
2642 	    ins_bytes(compl_leader + ins_compl_len());
2643 	    ins_redraw(FALSE);
2644 
2645 	    /* When the match isn't there (to avoid matching itself) remove it
2646 	     * again after redrawing. */
2647 	    if (!had_match)
2648 		ins_compl_delete();
2649 	}
2650 
2651 	compl_used_match = FALSE;
2652     }
2653 }
2654 
2655 /*
2656  * Add an array of matches to the list of matches.
2657  * Frees matches[].
2658  */
2659     static void
2660 ins_compl_add_matches(num_matches, matches, icase)
2661     int		num_matches;
2662     char_u	**matches;
2663     int		icase;
2664 {
2665     int		i;
2666     int		add_r = OK;
2667     int		dir = compl_direction;
2668 
2669     for (i = 0; i < num_matches && add_r != FAIL; i++)
2670 	if ((add_r = ins_compl_add(matches[i], -1, icase,
2671 					    NULL, NULL, dir, 0, FALSE)) == OK)
2672 	    /* if dir was BACKWARD then honor it just once */
2673 	    dir = FORWARD;
2674     FreeWild(num_matches, matches);
2675 }
2676 
2677 /* Make the completion list cyclic.
2678  * Return the number of matches (excluding the original).
2679  */
2680     static int
2681 ins_compl_make_cyclic()
2682 {
2683     compl_T *match;
2684     int	    count = 0;
2685 
2686     if (compl_first_match != NULL)
2687     {
2688 	/*
2689 	 * Find the end of the list.
2690 	 */
2691 	match = compl_first_match;
2692 	/* there's always an entry for the compl_orig_text, it doesn't count. */
2693 	while (match->cp_next != NULL && match->cp_next != compl_first_match)
2694 	{
2695 	    match = match->cp_next;
2696 	    ++count;
2697 	}
2698 	match->cp_next = compl_first_match;
2699 	compl_first_match->cp_prev = match;
2700     }
2701     return count;
2702 }
2703 
2704 /*
2705  * Start completion for the complete() function.
2706  * "startcol" is where the matched text starts (1 is first column).
2707  * "list" is the list of matches.
2708  */
2709     void
2710 set_completion(startcol, list)
2711     colnr_T startcol;
2712     list_T  *list;
2713 {
2714     /* If already doing completions stop it. */
2715     if (ctrl_x_mode != 0)
2716 	ins_compl_prep(' ');
2717     ins_compl_clear();
2718 
2719     if (stop_arrow() == FAIL)
2720 	return;
2721 
2722     compl_direction = FORWARD;
2723     if (startcol > curwin->w_cursor.col)
2724 	startcol = curwin->w_cursor.col;
2725     compl_col = startcol;
2726     compl_length = (int)curwin->w_cursor.col - (int)startcol;
2727     /* compl_pattern doesn't need to be set */
2728     compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2729     if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2730 			-1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2731 	return;
2732 
2733     /* Handle like dictionary completion. */
2734     ctrl_x_mode = CTRL_X_WHOLE_LINE;
2735 
2736     ins_compl_add_list(list);
2737     compl_matches = ins_compl_make_cyclic();
2738     compl_started = TRUE;
2739     compl_used_match = TRUE;
2740     compl_cont_status = 0;
2741 
2742     compl_curr_match = compl_first_match;
2743     ins_complete(Ctrl_N);
2744     out_flush();
2745 }
2746 
2747 
2748 /* "compl_match_array" points the currently displayed list of entries in the
2749  * popup menu.  It is NULL when there is no popup menu. */
2750 static pumitem_T *compl_match_array = NULL;
2751 static int compl_match_arraysize;
2752 
2753 /*
2754  * Update the screen and when there is any scrolling remove the popup menu.
2755  */
2756     static void
2757 ins_compl_upd_pum()
2758 {
2759     int		h;
2760 
2761     if (compl_match_array != NULL)
2762     {
2763 	h = curwin->w_cline_height;
2764 	update_screen(0);
2765 	if (h != curwin->w_cline_height)
2766 	    ins_compl_del_pum();
2767     }
2768 }
2769 
2770 /*
2771  * Remove any popup menu.
2772  */
2773     static void
2774 ins_compl_del_pum()
2775 {
2776     if (compl_match_array != NULL)
2777     {
2778 	pum_undisplay();
2779 	vim_free(compl_match_array);
2780 	compl_match_array = NULL;
2781     }
2782 }
2783 
2784 /*
2785  * Return TRUE if the popup menu should be displayed.
2786  */
2787     static int
2788 pum_wanted()
2789 {
2790     /* 'completeopt' must contain "menu" or "menuone" */
2791     if (vim_strchr(p_cot, 'm') == NULL)
2792 	return FALSE;
2793 
2794     /* The display looks bad on a B&W display. */
2795     if (t_colors < 8
2796 #ifdef FEAT_GUI
2797 	    && !gui.in_use
2798 #endif
2799 	    )
2800 	return FALSE;
2801     return TRUE;
2802 }
2803 
2804 /*
2805  * Return TRUE if there are two or more matches to be shown in the popup menu.
2806  * One if 'completopt' contains "menuone".
2807  */
2808     static int
2809 pum_enough_matches()
2810 {
2811     compl_T     *compl;
2812     int		i;
2813 
2814     /* Don't display the popup menu if there are no matches or there is only
2815      * one (ignoring the original text). */
2816     compl = compl_first_match;
2817     i = 0;
2818     do
2819     {
2820 	if (compl == NULL
2821 		      || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2822 	    break;
2823 	compl = compl->cp_next;
2824     } while (compl != compl_first_match);
2825 
2826     if (strstr((char *)p_cot, "menuone") != NULL)
2827 	return (i >= 1);
2828     return (i >= 2);
2829 }
2830 
2831 /*
2832  * Show the popup menu for the list of matches.
2833  * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2834  */
2835     void
2836 ins_compl_show_pum()
2837 {
2838     compl_T     *compl;
2839     compl_T     *shown_compl = NULL;
2840     int		did_find_shown_match = FALSE;
2841     int		shown_match_ok = FALSE;
2842     int		i;
2843     int		cur = -1;
2844     colnr_T	col;
2845     int		lead_len = 0;
2846 
2847     if (!pum_wanted() || !pum_enough_matches())
2848 	return;
2849 
2850 #if defined(FEAT_EVAL)
2851     /* Dirty hard-coded hack: remove any matchparen highlighting. */
2852     do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2853 #endif
2854 
2855     /* Update the screen before drawing the popup menu over it. */
2856     update_screen(0);
2857 
2858     if (compl_match_array == NULL)
2859     {
2860 	/* Need to build the popup menu list. */
2861 	compl_match_arraysize = 0;
2862 	compl = compl_first_match;
2863 	if (compl_leader != NULL)
2864 	    lead_len = (int)STRLEN(compl_leader);
2865 	do
2866 	{
2867 	    if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2868 		    && (compl_leader == NULL
2869 			|| ins_compl_equal(compl, compl_leader, lead_len)))
2870 		++compl_match_arraysize;
2871 	    compl = compl->cp_next;
2872 	} while (compl != NULL && compl != compl_first_match);
2873 	if (compl_match_arraysize == 0)
2874 	    return;
2875 	compl_match_array = (pumitem_T *)alloc_clear(
2876 				    (unsigned)(sizeof(pumitem_T)
2877 						    * compl_match_arraysize));
2878 	if (compl_match_array != NULL)
2879 	{
2880 	    /* If the current match is the original text don't find the first
2881 	     * match after it, don't highlight anything. */
2882 	    if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2883 		shown_match_ok = TRUE;
2884 
2885 	    i = 0;
2886 	    compl = compl_first_match;
2887 	    do
2888 	    {
2889 		if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2890 			&& (compl_leader == NULL
2891 			    || ins_compl_equal(compl, compl_leader, lead_len)))
2892 		{
2893 		    if (!shown_match_ok)
2894 		    {
2895 			if (compl == compl_shown_match || did_find_shown_match)
2896 			{
2897 			    /* This item is the shown match or this is the
2898 			     * first displayed item after the shown match. */
2899 			    compl_shown_match = compl;
2900 			    did_find_shown_match = TRUE;
2901 			    shown_match_ok = TRUE;
2902 			}
2903 			else
2904 			    /* Remember this displayed match for when the
2905 			     * shown match is just below it. */
2906 			    shown_compl = compl;
2907 			cur = i;
2908 		    }
2909 
2910 		    if (compl->cp_text[CPT_ABBR] != NULL)
2911 			compl_match_array[i].pum_text =
2912 						     compl->cp_text[CPT_ABBR];
2913 		    else
2914 			compl_match_array[i].pum_text = compl->cp_str;
2915 		    compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2916 		    compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2917 		    if (compl->cp_text[CPT_MENU] != NULL)
2918 			compl_match_array[i++].pum_extra =
2919 						     compl->cp_text[CPT_MENU];
2920 		    else
2921 			compl_match_array[i++].pum_extra = compl->cp_fname;
2922 		}
2923 
2924 		if (compl == compl_shown_match)
2925 		{
2926 		    did_find_shown_match = TRUE;
2927 
2928 		    /* When the original text is the shown match don't set
2929 		     * compl_shown_match. */
2930 		    if (compl->cp_flags & ORIGINAL_TEXT)
2931 			shown_match_ok = TRUE;
2932 
2933 		    if (!shown_match_ok && shown_compl != NULL)
2934 		    {
2935 			/* The shown match isn't displayed, set it to the
2936 			 * previously displayed match. */
2937 			compl_shown_match = shown_compl;
2938 			shown_match_ok = TRUE;
2939 		    }
2940 		}
2941 		compl = compl->cp_next;
2942 	    } while (compl != NULL && compl != compl_first_match);
2943 
2944 	    if (!shown_match_ok)    /* no displayed match at all */
2945 		cur = -1;
2946 	}
2947     }
2948     else
2949     {
2950 	/* popup menu already exists, only need to find the current item.*/
2951 	for (i = 0; i < compl_match_arraysize; ++i)
2952 	    if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2953 		    || compl_match_array[i].pum_text
2954 				      == compl_shown_match->cp_text[CPT_ABBR])
2955 	    {
2956 		cur = i;
2957 		break;
2958 	    }
2959     }
2960 
2961     if (compl_match_array != NULL)
2962     {
2963 	/* Compute the screen column of the start of the completed text.
2964 	 * Use the cursor to get all wrapping and other settings right. */
2965 	col = curwin->w_cursor.col;
2966 	curwin->w_cursor.col = compl_col;
2967 	pum_display(compl_match_array, compl_match_arraysize, cur);
2968 	curwin->w_cursor.col = col;
2969     }
2970 }
2971 
2972 #define DICT_FIRST	(1)	/* use just first element in "dict" */
2973 #define DICT_EXACT	(2)	/* "dict" is the exact name of a file */
2974 
2975 /*
2976  * Add any identifiers that match the given pattern in the list of dictionary
2977  * files "dict_start" to the list of completions.
2978  */
2979     static void
2980 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2981     char_u	*dict_start;
2982     char_u	*pat;
2983     int		flags;		/* DICT_FIRST and/or DICT_EXACT */
2984     int		thesaurus;	/* Thesaurus completion */
2985 {
2986     char_u	*dict = dict_start;
2987     char_u	*ptr;
2988     char_u	*buf;
2989     regmatch_T	regmatch;
2990     char_u	**files;
2991     int		count;
2992     int		save_p_scs;
2993     int		dir = compl_direction;
2994 
2995     if (*dict == NUL)
2996     {
2997 #ifdef FEAT_SPELL
2998 	/* When 'dictionary' is empty and spell checking is enabled use
2999 	 * "spell". */
3000 	if (!thesaurus && curwin->w_p_spell)
3001 	    dict = (char_u *)"spell";
3002 	else
3003 #endif
3004 	    return;
3005     }
3006 
3007     buf = alloc(LSIZE);
3008     if (buf == NULL)
3009 	return;
3010     regmatch.regprog = NULL;	/* so that we can goto theend */
3011 
3012     /* If 'infercase' is set, don't use 'smartcase' here */
3013     save_p_scs = p_scs;
3014     if (curbuf->b_p_inf)
3015 	p_scs = FALSE;
3016 
3017     /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
3018      * to only match at the start of a line.  Otherwise just match the
3019      * pattern. Also need to double backslashes. */
3020     if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3021     {
3022 	char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
3023 	size_t len;
3024 
3025 	if (pat_esc == NULL)
3026 	    goto theend;
3027 	len = STRLEN(pat_esc) + 10;
3028 	ptr = alloc((unsigned)len);
3029 	if (ptr == NULL)
3030 	{
3031 	    vim_free(pat_esc);
3032 	    goto theend;
3033 	}
3034 	vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
3035 	regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
3036 	vim_free(pat_esc);
3037 	vim_free(ptr);
3038     }
3039     else
3040     {
3041 	regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
3042 	if (regmatch.regprog == NULL)
3043 	    goto theend;
3044     }
3045 
3046     /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
3047     regmatch.rm_ic = ignorecase(pat);
3048     while (*dict != NUL && !got_int && !compl_interrupted)
3049     {
3050 	/* copy one dictionary file name into buf */
3051 	if (flags == DICT_EXACT)
3052 	{
3053 	    count = 1;
3054 	    files = &dict;
3055 	}
3056 	else
3057 	{
3058 	    /* Expand wildcards in the dictionary name, but do not allow
3059 	     * backticks (for security, the 'dict' option may have been set in
3060 	     * a modeline). */
3061 	    copy_option_part(&dict, buf, LSIZE, ",");
3062 # ifdef FEAT_SPELL
3063 	    if (!thesaurus && STRCMP(buf, "spell") == 0)
3064 		count = -1;
3065 	    else
3066 # endif
3067 		if (vim_strchr(buf, '`') != NULL
3068 		    || expand_wildcards(1, &buf, &count, &files,
3069 						     EW_FILE|EW_SILENT) != OK)
3070 		count = 0;
3071 	}
3072 
3073 # ifdef FEAT_SPELL
3074 	if (count == -1)
3075 	{
3076 	    /* Complete from active spelling.  Skip "\<" in the pattern, we
3077 	     * don't use it as a RE. */
3078 	    if (pat[0] == '\\' && pat[1] == '<')
3079 		ptr = pat + 2;
3080 	    else
3081 		ptr = pat;
3082 	    spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
3083 	}
3084 	else
3085 # endif
3086 	    if (count > 0)	/* avoid warning for using "files" uninit */
3087 	{
3088 	    ins_compl_files(count, files, thesaurus, flags,
3089 							&regmatch, buf, &dir);
3090 	    if (flags != DICT_EXACT)
3091 		FreeWild(count, files);
3092 	}
3093 	if (flags != 0)
3094 	    break;
3095     }
3096 
3097 theend:
3098     p_scs = save_p_scs;
3099     vim_free(regmatch.regprog);
3100     vim_free(buf);
3101 }
3102 
3103     static void
3104 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
3105     int		count;
3106     char_u	**files;
3107     int		thesaurus;
3108     int		flags;
3109     regmatch_T	*regmatch;
3110     char_u	*buf;
3111     int		*dir;
3112 {
3113     char_u	*ptr;
3114     int		i;
3115     FILE	*fp;
3116     int		add_r;
3117 
3118     for (i = 0; i < count && !got_int && !compl_interrupted; i++)
3119     {
3120 	fp = mch_fopen((char *)files[i], "r");  /* open dictionary file */
3121 	if (flags != DICT_EXACT)
3122 	{
3123 	    vim_snprintf((char *)IObuff, IOSIZE,
3124 			      _("Scanning dictionary: %s"), (char *)files[i]);
3125 	    (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3126 	}
3127 
3128 	if (fp != NULL)
3129 	{
3130 	    /*
3131 	     * Read dictionary file line by line.
3132 	     * Check each line for a match.
3133 	     */
3134 	    while (!got_int && !compl_interrupted
3135 					    && !vim_fgets(buf, LSIZE, fp))
3136 	    {
3137 		ptr = buf;
3138 		while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
3139 		{
3140 		    ptr = regmatch->startp[0];
3141 		    if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3142 			ptr = find_line_end(ptr);
3143 		    else
3144 			ptr = find_word_end(ptr);
3145 		    add_r = ins_compl_add_infercase(regmatch->startp[0],
3146 					  (int)(ptr - regmatch->startp[0]),
3147 						     p_ic, files[i], *dir, 0);
3148 		    if (thesaurus)
3149 		    {
3150 			char_u *wstart;
3151 
3152 			/*
3153 			 * Add the other matches on the line
3154 			 */
3155 			ptr = buf;
3156 			while (!got_int)
3157 			{
3158 			    /* Find start of the next word.  Skip white
3159 			     * space and punctuation. */
3160 			    ptr = find_word_start(ptr);
3161 			    if (*ptr == NUL || *ptr == NL)
3162 				break;
3163 			    wstart = ptr;
3164 
3165 			    /* Find end of the word. */
3166 #ifdef FEAT_MBYTE
3167 			    if (has_mbyte)
3168 				/* Japanese words may have characters in
3169 				 * different classes, only separate words
3170 				 * with single-byte non-word characters. */
3171 				while (*ptr != NUL)
3172 				{
3173 				    int l = (*mb_ptr2len)(ptr);
3174 
3175 				    if (l < 2 && !vim_iswordc(*ptr))
3176 					break;
3177 				    ptr += l;
3178 				}
3179 			    else
3180 #endif
3181 				ptr = find_word_end(ptr);
3182 
3183 			    /* Add the word. Skip the regexp match. */
3184 			    if (wstart != regmatch->startp[0])
3185 				add_r = ins_compl_add_infercase(wstart,
3186 					(int)(ptr - wstart),
3187 					p_ic, files[i], *dir, 0);
3188 			}
3189 		    }
3190 		    if (add_r == OK)
3191 			/* if dir was BACKWARD then honor it just once */
3192 			*dir = FORWARD;
3193 		    else if (add_r == FAIL)
3194 			break;
3195 		    /* avoid expensive call to vim_regexec() when at end
3196 		     * of line */
3197 		    if (*ptr == '\n' || got_int)
3198 			break;
3199 		}
3200 		line_breakcheck();
3201 		ins_compl_check_keys(50);
3202 	    }
3203 	    fclose(fp);
3204 	}
3205     }
3206 }
3207 
3208 /*
3209  * Find the start of the next word.
3210  * Returns a pointer to the first char of the word.  Also stops at a NUL.
3211  */
3212     char_u *
3213 find_word_start(ptr)
3214     char_u	*ptr;
3215 {
3216 #ifdef FEAT_MBYTE
3217     if (has_mbyte)
3218 	while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
3219 	    ptr += (*mb_ptr2len)(ptr);
3220     else
3221 #endif
3222 	while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
3223 	    ++ptr;
3224     return ptr;
3225 }
3226 
3227 /*
3228  * Find the end of the word.  Assumes it starts inside a word.
3229  * Returns a pointer to just after the word.
3230  */
3231     char_u *
3232 find_word_end(ptr)
3233     char_u	*ptr;
3234 {
3235 #ifdef FEAT_MBYTE
3236     int		start_class;
3237 
3238     if (has_mbyte)
3239     {
3240 	start_class = mb_get_class(ptr);
3241 	if (start_class > 1)
3242 	    while (*ptr != NUL)
3243 	    {
3244 		ptr += (*mb_ptr2len)(ptr);
3245 		if (mb_get_class(ptr) != start_class)
3246 		    break;
3247 	    }
3248     }
3249     else
3250 #endif
3251 	while (vim_iswordc(*ptr))
3252 	    ++ptr;
3253     return ptr;
3254 }
3255 
3256 /*
3257  * Find the end of the line, omitting CR and NL at the end.
3258  * Returns a pointer to just after the line.
3259  */
3260     static char_u *
3261 find_line_end(ptr)
3262     char_u	*ptr;
3263 {
3264     char_u	*s;
3265 
3266     s = ptr + STRLEN(ptr);
3267     while (s > ptr && (s[-1] == CAR || s[-1] == NL))
3268 	--s;
3269     return s;
3270 }
3271 
3272 /*
3273  * Free the list of completions
3274  */
3275     static void
3276 ins_compl_free()
3277 {
3278     compl_T *match;
3279     int	    i;
3280 
3281     vim_free(compl_pattern);
3282     compl_pattern = NULL;
3283     vim_free(compl_leader);
3284     compl_leader = NULL;
3285 
3286     if (compl_first_match == NULL)
3287 	return;
3288 
3289     ins_compl_del_pum();
3290     pum_clear();
3291 
3292     compl_curr_match = compl_first_match;
3293     do
3294     {
3295 	match = compl_curr_match;
3296 	compl_curr_match = compl_curr_match->cp_next;
3297 	vim_free(match->cp_str);
3298 	/* several entries may use the same fname, free it just once. */
3299 	if (match->cp_flags & FREE_FNAME)
3300 	    vim_free(match->cp_fname);
3301 	for (i = 0; i < CPT_COUNT; ++i)
3302 	    vim_free(match->cp_text[i]);
3303 	vim_free(match);
3304     } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
3305     compl_first_match = compl_curr_match = NULL;
3306     compl_shown_match = NULL;
3307 }
3308 
3309     static void
3310 ins_compl_clear()
3311 {
3312     compl_cont_status = 0;
3313     compl_started = FALSE;
3314     compl_matches = 0;
3315     vim_free(compl_pattern);
3316     compl_pattern = NULL;
3317     vim_free(compl_leader);
3318     compl_leader = NULL;
3319     edit_submode_extra = NULL;
3320     vim_free(compl_orig_text);
3321     compl_orig_text = NULL;
3322     compl_enter_selects = FALSE;
3323 }
3324 
3325 /*
3326  * Return TRUE when Insert completion is active.
3327  */
3328     int
3329 ins_compl_active()
3330 {
3331     return compl_started;
3332 }
3333 
3334 /*
3335  * Delete one character before the cursor and show the subset of the matches
3336  * that match the word that is now before the cursor.
3337  * Returns the character to be used, NUL if the work is done and another char
3338  * to be got from the user.
3339  */
3340     static int
3341 ins_compl_bs()
3342 {
3343     char_u	*line;
3344     char_u	*p;
3345 
3346     line = ml_get_curline();
3347     p = line + curwin->w_cursor.col;
3348     mb_ptr_back(line, p);
3349 
3350     /* Stop completion when the whole word was deleted.  For Omni completion
3351      * allow the word to be deleted, we won't match everything. */
3352     if ((int)(p - line) - (int)compl_col < 0
3353 	    || ((int)(p - line) - (int)compl_col == 0
3354 		&& (ctrl_x_mode & CTRL_X_OMNI) == 0))
3355 	return K_BS;
3356 
3357     /* Deleted more than what was used to find matches or didn't finish
3358      * finding all matches: need to look for matches all over again. */
3359     if (curwin->w_cursor.col <= compl_col + compl_length
3360 						  || ins_compl_need_restart())
3361 	ins_compl_restart();
3362 
3363     vim_free(compl_leader);
3364     compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3365     if (compl_leader != NULL)
3366     {
3367 	ins_compl_new_leader();
3368 	return NUL;
3369     }
3370     return K_BS;
3371 }
3372 
3373 /*
3374  * Return TRUE when we need to find matches again, ins_compl_restart() is to
3375  * be called.
3376  */
3377     static int
3378 ins_compl_need_restart()
3379 {
3380     /* Return TRUE if we didn't complete finding matches or when the
3381      * 'completefunc' returned "always" in the "refresh" dictionary item. */
3382     return compl_was_interrupted
3383 	|| ((ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
3384 						  && compl_opt_refresh_always);
3385 }
3386 
3387 /*
3388  * Called after changing "compl_leader".
3389  * Show the popup menu with a different set of matches.
3390  * May also search for matches again if the previous search was interrupted.
3391  */
3392     static void
3393 ins_compl_new_leader()
3394 {
3395     ins_compl_del_pum();
3396     ins_compl_delete();
3397     ins_bytes(compl_leader + ins_compl_len());
3398     compl_used_match = FALSE;
3399 
3400     if (compl_started)
3401 	ins_compl_set_original_text(compl_leader);
3402     else
3403     {
3404 #ifdef FEAT_SPELL
3405 	spell_bad_len = 0;	/* need to redetect bad word */
3406 #endif
3407 	/*
3408 	 * Matches were cleared, need to search for them now.  First display
3409 	 * the changed text before the cursor.  Set "compl_restarting" to
3410 	 * avoid that the first match is inserted.
3411 	 */
3412 	update_screen(0);
3413 #ifdef FEAT_GUI
3414 	if (gui.in_use)
3415 	{
3416 	    /* Show the cursor after the match, not after the redrawn text. */
3417 	    setcursor();
3418 	    out_flush();
3419 	    gui_update_cursor(FALSE, FALSE);
3420 	}
3421 #endif
3422 	compl_restarting = TRUE;
3423 	if (ins_complete(Ctrl_N) == FAIL)
3424 	    compl_cont_status = 0;
3425 	compl_restarting = FALSE;
3426     }
3427 
3428     compl_enter_selects = !compl_used_match;
3429 
3430     /* Show the popup menu with a different set of matches. */
3431     ins_compl_show_pum();
3432 
3433     /* Don't let Enter select the original text when there is no popup menu. */
3434     if (compl_match_array == NULL)
3435 	compl_enter_selects = FALSE;
3436 }
3437 
3438 /*
3439  * Return the length of the completion, from the completion start column to
3440  * the cursor column.  Making sure it never goes below zero.
3441  */
3442     static int
3443 ins_compl_len()
3444 {
3445     int off = (int)curwin->w_cursor.col - (int)compl_col;
3446 
3447     if (off < 0)
3448 	return 0;
3449     return off;
3450 }
3451 
3452 /*
3453  * Append one character to the match leader.  May reduce the number of
3454  * matches.
3455  */
3456     static void
3457 ins_compl_addleader(c)
3458     int		c;
3459 {
3460 #ifdef FEAT_MBYTE
3461     int		cc;
3462 
3463     if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3464     {
3465 	char_u	buf[MB_MAXBYTES + 1];
3466 
3467 	(*mb_char2bytes)(c, buf);
3468 	buf[cc] = NUL;
3469 	ins_char_bytes(buf, cc);
3470 	if (compl_opt_refresh_always)
3471 	    AppendToRedobuff(buf);
3472     }
3473     else
3474 #endif
3475     {
3476 	ins_char(c);
3477 	if (compl_opt_refresh_always)
3478 	    AppendCharToRedobuff(c);
3479     }
3480 
3481     /* If we didn't complete finding matches we must search again. */
3482     if (ins_compl_need_restart())
3483 	ins_compl_restart();
3484 
3485     /* When 'always' is set, don't reset compl_leader. While completing,
3486      * cursor doesn't point original position, changing compl_leader would
3487      * break redo. */
3488     if (!compl_opt_refresh_always)
3489     {
3490 	vim_free(compl_leader);
3491 	compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3492 				     (int)(curwin->w_cursor.col - compl_col));
3493 	if (compl_leader != NULL)
3494 	    ins_compl_new_leader();
3495     }
3496 }
3497 
3498 /*
3499  * Setup for finding completions again without leaving CTRL-X mode.  Used when
3500  * BS or a key was typed while still searching for matches.
3501  */
3502     static void
3503 ins_compl_restart()
3504 {
3505     ins_compl_free();
3506     compl_started = FALSE;
3507     compl_matches = 0;
3508     compl_cont_status = 0;
3509     compl_cont_mode = 0;
3510 }
3511 
3512 /*
3513  * Set the first match, the original text.
3514  */
3515     static void
3516 ins_compl_set_original_text(str)
3517     char_u	*str;
3518 {
3519     char_u	*p;
3520 
3521     /* Replace the original text entry. */
3522     if (compl_first_match->cp_flags & ORIGINAL_TEXT)	/* safety check */
3523     {
3524 	p = vim_strsave(str);
3525 	if (p != NULL)
3526 	{
3527 	    vim_free(compl_first_match->cp_str);
3528 	    compl_first_match->cp_str = p;
3529 	}
3530     }
3531 }
3532 
3533 /*
3534  * Append one character to the match leader.  May reduce the number of
3535  * matches.
3536  */
3537     static void
3538 ins_compl_addfrommatch()
3539 {
3540     char_u	*p;
3541     int		len = (int)curwin->w_cursor.col - (int)compl_col;
3542     int		c;
3543     compl_T	*cp;
3544 
3545     p = compl_shown_match->cp_str;
3546     if ((int)STRLEN(p) <= len)   /* the match is too short */
3547     {
3548 	/* When still at the original match use the first entry that matches
3549 	 * the leader. */
3550 	if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
3551 	{
3552 	    p = NULL;
3553 	    for (cp = compl_shown_match->cp_next; cp != NULL
3554 				 && cp != compl_first_match; cp = cp->cp_next)
3555 	    {
3556 		if (compl_leader == NULL
3557 			|| ins_compl_equal(cp, compl_leader,
3558 						   (int)STRLEN(compl_leader)))
3559 		{
3560 		    p = cp->cp_str;
3561 		    break;
3562 		}
3563 	    }
3564 	    if (p == NULL || (int)STRLEN(p) <= len)
3565 		return;
3566 	}
3567 	else
3568 	    return;
3569     }
3570     p += len;
3571     c = PTR2CHAR(p);
3572     ins_compl_addleader(c);
3573 }
3574 
3575 /*
3576  * Prepare for Insert mode completion, or stop it.
3577  * Called just after typing a character in Insert mode.
3578  * Returns TRUE when the character is not to be inserted;
3579  */
3580     static int
3581 ins_compl_prep(c)
3582     int	    c;
3583 {
3584     char_u	*ptr;
3585     int		want_cindent;
3586     int		retval = FALSE;
3587 
3588     /* Forget any previous 'special' messages if this is actually
3589      * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3590      */
3591     if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3592 	edit_submode_extra = NULL;
3593 
3594     /* Ignore end of Select mode mapping and mouse scroll buttons. */
3595     if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
3596 	    || c == K_MOUSELEFT || c == K_MOUSERIGHT)
3597 	return retval;
3598 
3599     /* Set "compl_get_longest" when finding the first matches. */
3600     if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3601 				      || (ctrl_x_mode == 0 && !compl_started))
3602     {
3603 	compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3604 	compl_used_match = TRUE;
3605     }
3606 
3607     if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3608     {
3609 	/*
3610 	 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3611 	 * it will be yet.  Now we decide.
3612 	 */
3613 	switch (c)
3614 	{
3615 	    case Ctrl_E:
3616 	    case Ctrl_Y:
3617 		ctrl_x_mode = CTRL_X_SCROLL;
3618 		if (!(State & REPLACE_FLAG))
3619 		    edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3620 		else
3621 		    edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3622 		edit_submode_pre = NULL;
3623 		showmode();
3624 		break;
3625 	    case Ctrl_L:
3626 		ctrl_x_mode = CTRL_X_WHOLE_LINE;
3627 		break;
3628 	    case Ctrl_F:
3629 		ctrl_x_mode = CTRL_X_FILES;
3630 		break;
3631 	    case Ctrl_K:
3632 		ctrl_x_mode = CTRL_X_DICTIONARY;
3633 		break;
3634 	    case Ctrl_R:
3635 		/* Simply allow ^R to happen without affecting ^X mode */
3636 		break;
3637 	    case Ctrl_T:
3638 		ctrl_x_mode = CTRL_X_THESAURUS;
3639 		break;
3640 #ifdef FEAT_COMPL_FUNC
3641 	    case Ctrl_U:
3642 		ctrl_x_mode = CTRL_X_FUNCTION;
3643 		break;
3644 	    case Ctrl_O:
3645 		ctrl_x_mode = CTRL_X_OMNI;
3646 		break;
3647 #endif
3648 	    case 's':
3649 	    case Ctrl_S:
3650 		ctrl_x_mode = CTRL_X_SPELL;
3651 #ifdef FEAT_SPELL
3652 		++emsg_off;	/* Avoid getting the E756 error twice. */
3653 		spell_back_to_badword();
3654 		--emsg_off;
3655 #endif
3656 		break;
3657 	    case Ctrl_RSB:
3658 		ctrl_x_mode = CTRL_X_TAGS;
3659 		break;
3660 #ifdef FEAT_FIND_ID
3661 	    case Ctrl_I:
3662 	    case K_S_TAB:
3663 		ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3664 		break;
3665 	    case Ctrl_D:
3666 		ctrl_x_mode = CTRL_X_PATH_DEFINES;
3667 		break;
3668 #endif
3669 	    case Ctrl_V:
3670 	    case Ctrl_Q:
3671 		ctrl_x_mode = CTRL_X_CMDLINE;
3672 		break;
3673 	    case Ctrl_P:
3674 	    case Ctrl_N:
3675 		/* ^X^P means LOCAL expansion if nothing interrupted (eg we
3676 		 * just started ^X mode, or there were enough ^X's to cancel
3677 		 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3678 		 * do normal expansion when interrupting a different mode (say
3679 		 * ^X^F^X^P or ^P^X^X^P, see below)
3680 		 * nothing changes if interrupting mode 0, (eg, the flag
3681 		 * doesn't change when going to ADDING mode  -- Acevedo */
3682 		if (!(compl_cont_status & CONT_INTRPT))
3683 		    compl_cont_status |= CONT_LOCAL;
3684 		else if (compl_cont_mode != 0)
3685 		    compl_cont_status &= ~CONT_LOCAL;
3686 		/* FALLTHROUGH */
3687 	    default:
3688 		/* If we have typed at least 2 ^X's... for modes != 0, we set
3689 		 * compl_cont_status = 0 (eg, as if we had just started ^X
3690 		 * mode).
3691 		 * For mode 0, we set "compl_cont_mode" to an impossible
3692 		 * value, in both cases ^X^X can be used to restart the same
3693 		 * mode (avoiding ADDING mode).
3694 		 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3695 		 * 'complete' and local ^P expansions respectively.
3696 		 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3697 		 * mode  -- Acevedo */
3698 		if (c == Ctrl_X)
3699 		{
3700 		    if (compl_cont_mode != 0)
3701 			compl_cont_status = 0;
3702 		    else
3703 			compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3704 		}
3705 		ctrl_x_mode = 0;
3706 		edit_submode = NULL;
3707 		showmode();
3708 		break;
3709 	}
3710     }
3711     else if (ctrl_x_mode != 0)
3712     {
3713 	/* We're already in CTRL-X mode, do we stay in it? */
3714 	if (!vim_is_ctrl_x_key(c))
3715 	{
3716 	    if (ctrl_x_mode == CTRL_X_SCROLL)
3717 		ctrl_x_mode = 0;
3718 	    else
3719 		ctrl_x_mode = CTRL_X_FINISHED;
3720 	    edit_submode = NULL;
3721 	}
3722 	showmode();
3723     }
3724 
3725     if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3726     {
3727 	/* Show error message from attempted keyword completion (probably
3728 	 * 'Pattern not found') until another key is hit, then go back to
3729 	 * showing what mode we are in. */
3730 	showmode();
3731 	if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3732 						     && !ins_compl_pum_key(c))
3733 		|| ctrl_x_mode == CTRL_X_FINISHED)
3734 	{
3735 	    /* Get here when we have finished typing a sequence of ^N and
3736 	     * ^P or other completion characters in CTRL-X mode.  Free up
3737 	     * memory that was used, and make sure we can redo the insert. */
3738 	    if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3739 	    {
3740 		/*
3741 		 * If any of the original typed text has been changed, eg when
3742 		 * ignorecase is set, we must add back-spaces to the redo
3743 		 * buffer.  We add as few as necessary to delete just the part
3744 		 * of the original text that has changed.
3745 		 * When using the longest match, edited the match or used
3746 		 * CTRL-E then don't use the current match.
3747 		 */
3748 		if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3749 		    ptr = compl_curr_match->cp_str;
3750 		else
3751 		    ptr = NULL;
3752 		ins_compl_fixRedoBufForLeader(ptr);
3753 	    }
3754 
3755 #ifdef FEAT_CINDENT
3756 	    want_cindent = (can_cindent && cindent_on());
3757 #endif
3758 	    /*
3759 	     * When completing whole lines: fix indent for 'cindent'.
3760 	     * Otherwise, break line if it's too long.
3761 	     */
3762 	    if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3763 	    {
3764 #ifdef FEAT_CINDENT
3765 		/* re-indent the current line */
3766 		if (want_cindent)
3767 		{
3768 		    do_c_expr_indent();
3769 		    want_cindent = FALSE;	/* don't do it again */
3770 		}
3771 #endif
3772 	    }
3773 	    else
3774 	    {
3775 		int prev_col = curwin->w_cursor.col;
3776 
3777 		/* put the cursor on the last char, for 'tw' formatting */
3778 		if (prev_col > 0)
3779 		    dec_cursor();
3780 		if (stop_arrow() == OK)
3781 		    insertchar(NUL, 0, -1);
3782 		if (prev_col > 0
3783 			     && ml_get_curline()[curwin->w_cursor.col] != NUL)
3784 		    inc_cursor();
3785 	    }
3786 
3787 	    /* If the popup menu is displayed pressing CTRL-Y means accepting
3788 	     * the selection without inserting anything.  When
3789 	     * compl_enter_selects is set the Enter key does the same. */
3790 	    if ((c == Ctrl_Y || (compl_enter_selects
3791 				   && (c == CAR || c == K_KENTER || c == NL)))
3792 		    && pum_visible())
3793 		retval = TRUE;
3794 
3795 	    /* CTRL-E means completion is Ended, go back to the typed text. */
3796 	    if (c == Ctrl_E)
3797 	    {
3798 		ins_compl_delete();
3799 		if (compl_leader != NULL)
3800 		    ins_bytes(compl_leader + ins_compl_len());
3801 		else if (compl_first_match != NULL)
3802 		    ins_bytes(compl_orig_text + ins_compl_len());
3803 		retval = TRUE;
3804 	    }
3805 
3806 	    auto_format(FALSE, TRUE);
3807 
3808 	    ins_compl_free();
3809 	    compl_started = FALSE;
3810 	    compl_matches = 0;
3811 	    msg_clr_cmdline();		/* necessary for "noshowmode" */
3812 	    ctrl_x_mode = 0;
3813 	    compl_enter_selects = FALSE;
3814 	    if (edit_submode != NULL)
3815 	    {
3816 		edit_submode = NULL;
3817 		showmode();
3818 	    }
3819 
3820 #ifdef FEAT_CINDENT
3821 	    /*
3822 	     * Indent now if a key was typed that is in 'cinkeys'.
3823 	     */
3824 	    if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3825 		do_c_expr_indent();
3826 #endif
3827 #ifdef FEAT_AUTOCMD
3828 	    /* Trigger the CompleteDone event to give scripts a chance to act
3829 	     * upon the completion. */
3830 	    apply_autocmds(EVENT_COMPLETEDONE, NULL, NULL, FALSE, curbuf);
3831 #endif
3832 	}
3833     }
3834 
3835     /* reset continue_* if we left expansion-mode, if we stay they'll be
3836      * (re)set properly in ins_complete() */
3837     if (!vim_is_ctrl_x_key(c))
3838     {
3839 	compl_cont_status = 0;
3840 	compl_cont_mode = 0;
3841     }
3842 
3843     return retval;
3844 }
3845 
3846 /*
3847  * Fix the redo buffer for the completion leader replacing some of the typed
3848  * text.  This inserts backspaces and appends the changed text.
3849  * "ptr" is the known leader text or NUL.
3850  */
3851     static void
3852 ins_compl_fixRedoBufForLeader(ptr_arg)
3853     char_u *ptr_arg;
3854 {
3855     int	    len;
3856     char_u  *p;
3857     char_u  *ptr = ptr_arg;
3858 
3859     if (ptr == NULL)
3860     {
3861 	if (compl_leader != NULL)
3862 	    ptr = compl_leader;
3863 	else
3864 	    return;  /* nothing to do */
3865     }
3866     if (compl_orig_text != NULL)
3867     {
3868 	p = compl_orig_text;
3869 	for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
3870 	    ;
3871 #ifdef FEAT_MBYTE
3872 	if (len > 0)
3873 	    len -= (*mb_head_off)(p, p + len);
3874 #endif
3875 	for (p += len; *p != NUL; mb_ptr_adv(p))
3876 	    AppendCharToRedobuff(K_BS);
3877     }
3878     else
3879 	len = 0;
3880     if (ptr != NULL)
3881 	AppendToRedobuffLit(ptr + len, -1);
3882 }
3883 
3884 /*
3885  * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3886  * (depending on flag) starting from buf and looking for a non-scanned
3887  * buffer (other than curbuf).	curbuf is special, if it is called with
3888  * buf=curbuf then it has to be the first call for a given flag/expansion.
3889  *
3890  * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3891  */
3892     static buf_T *
3893 ins_compl_next_buf(buf, flag)
3894     buf_T	*buf;
3895     int		flag;
3896 {
3897 #ifdef FEAT_WINDOWS
3898     static win_T *wp;
3899 #endif
3900 
3901     if (flag == 'w')		/* just windows */
3902     {
3903 #ifdef FEAT_WINDOWS
3904 	if (buf == curbuf)	/* first call for this flag/expansion */
3905 	    wp = curwin;
3906 	while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3907 		&& wp->w_buffer->b_scanned)
3908 	    ;
3909 	buf = wp->w_buffer;
3910 #else
3911 	buf = curbuf;
3912 #endif
3913     }
3914     else
3915 	/* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3916 	 * (unlisted buffers)
3917 	 * When completing whole lines skip unloaded buffers. */
3918 	while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3919 		&& ((flag == 'U'
3920 			? buf->b_p_bl
3921 			: (!buf->b_p_bl
3922 			    || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3923 		    || buf->b_scanned))
3924 	    ;
3925     return buf;
3926 }
3927 
3928 #ifdef FEAT_COMPL_FUNC
3929 static void expand_by_function __ARGS((int type, char_u *base));
3930 
3931 /*
3932  * Execute user defined complete function 'completefunc' or 'omnifunc', and
3933  * get matches in "matches".
3934  */
3935     static void
3936 expand_by_function(type, base)
3937     int		type;	    /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3938     char_u	*base;
3939 {
3940     list_T      *matchlist = NULL;
3941     dict_T	*matchdict = NULL;
3942     char_u	*args[2];
3943     char_u	*funcname;
3944     pos_T	pos;
3945     win_T	*curwin_save;
3946     buf_T	*curbuf_save;
3947     typval_T	rettv;
3948 
3949     funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3950     if (*funcname == NUL)
3951 	return;
3952 
3953     /* Call 'completefunc' to obtain the list of matches. */
3954     args[0] = (char_u *)"0";
3955     args[1] = base;
3956 
3957     pos = curwin->w_cursor;
3958     curwin_save = curwin;
3959     curbuf_save = curbuf;
3960 
3961     /* Call a function, which returns a list or dict. */
3962     if (call_vim_function(funcname, 2, args, FALSE, FALSE, &rettv) == OK)
3963     {
3964 	switch (rettv.v_type)
3965 	{
3966 	    case VAR_LIST:
3967 		matchlist = rettv.vval.v_list;
3968 		break;
3969 	    case VAR_DICT:
3970 		matchdict = rettv.vval.v_dict;
3971 		break;
3972 	    default:
3973 		/* TODO: Give error message? */
3974 		clear_tv(&rettv);
3975 		break;
3976 	}
3977     }
3978 
3979     if (curwin_save != curwin || curbuf_save != curbuf)
3980     {
3981 	EMSG(_(e_complwin));
3982 	goto theend;
3983     }
3984     curwin->w_cursor = pos;	/* restore the cursor position */
3985     check_cursor();
3986     if (!equalpos(curwin->w_cursor, pos))
3987     {
3988 	EMSG(_(e_compldel));
3989 	goto theend;
3990     }
3991 
3992     if (matchlist != NULL)
3993 	ins_compl_add_list(matchlist);
3994     else if (matchdict != NULL)
3995 	ins_compl_add_dict(matchdict);
3996 
3997 theend:
3998     if (matchdict != NULL)
3999 	dict_unref(matchdict);
4000     if (matchlist != NULL)
4001 	list_unref(matchlist);
4002 }
4003 #endif /* FEAT_COMPL_FUNC */
4004 
4005 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
4006 /*
4007  * Add completions from a list.
4008  */
4009     static void
4010 ins_compl_add_list(list)
4011     list_T	*list;
4012 {
4013     listitem_T	*li;
4014     int		dir = compl_direction;
4015 
4016     /* Go through the List with matches and add each of them. */
4017     for (li = list->lv_first; li != NULL; li = li->li_next)
4018     {
4019 	if (ins_compl_add_tv(&li->li_tv, dir) == OK)
4020 	    /* if dir was BACKWARD then honor it just once */
4021 	    dir = FORWARD;
4022 	else if (did_emsg)
4023 	    break;
4024     }
4025 }
4026 
4027 /*
4028  * Add completions from a dict.
4029  */
4030     static void
4031 ins_compl_add_dict(dict)
4032     dict_T	*dict;
4033 {
4034     dictitem_T	*di_refresh;
4035     dictitem_T	*di_words;
4036 
4037     /* Check for optional "refresh" item. */
4038     compl_opt_refresh_always = FALSE;
4039     di_refresh = dict_find(dict, (char_u *)"refresh", 7);
4040     if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
4041     {
4042 	char_u	*v = di_refresh->di_tv.vval.v_string;
4043 
4044 	if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
4045 	    compl_opt_refresh_always = TRUE;
4046     }
4047 
4048     /* Add completions from a "words" list. */
4049     di_words = dict_find(dict, (char_u *)"words", 5);
4050     if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
4051 	ins_compl_add_list(di_words->di_tv.vval.v_list);
4052 }
4053 
4054 /*
4055  * Add a match to the list of matches from a typeval_T.
4056  * If the given string is already in the list of completions, then return
4057  * NOTDONE, otherwise add it to the list and return OK.  If there is an error,
4058  * maybe because alloc() returns NULL, then FAIL is returned.
4059  */
4060     int
4061 ins_compl_add_tv(tv, dir)
4062     typval_T	*tv;
4063     int		dir;
4064 {
4065     char_u	*word;
4066     int		icase = FALSE;
4067     int		adup = FALSE;
4068     int		aempty = FALSE;
4069     char_u	*(cptext[CPT_COUNT]);
4070 
4071     if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
4072     {
4073 	word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
4074 	cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
4075 						     (char_u *)"abbr", FALSE);
4076 	cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
4077 						     (char_u *)"menu", FALSE);
4078 	cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
4079 						     (char_u *)"kind", FALSE);
4080 	cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
4081 						     (char_u *)"info", FALSE);
4082 	if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
4083 	    icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
4084 	if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
4085 	    adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
4086 	if (get_dict_string(tv->vval.v_dict, (char_u *)"empty", FALSE) != NULL)
4087 	    aempty = get_dict_number(tv->vval.v_dict, (char_u *)"empty");
4088     }
4089     else
4090     {
4091 	word = get_tv_string_chk(tv);
4092 	vim_memset(cptext, 0, sizeof(cptext));
4093     }
4094     if (word == NULL || (!aempty && *word == NUL))
4095 	return FAIL;
4096     return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup);
4097 }
4098 #endif
4099 
4100 /*
4101  * Get the next expansion(s), using "compl_pattern".
4102  * The search starts at position "ini" in curbuf and in the direction
4103  * compl_direction.
4104  * When "compl_started" is FALSE start at that position, otherwise continue
4105  * where we stopped searching before.
4106  * This may return before finding all the matches.
4107  * Return the total number of matches or -1 if still unknown -- Acevedo
4108  */
4109     static int
4110 ins_compl_get_exp(ini)
4111     pos_T	*ini;
4112 {
4113     static pos_T	first_match_pos;
4114     static pos_T	last_match_pos;
4115     static char_u	*e_cpt = (char_u *)"";	/* curr. entry in 'complete' */
4116     static int		found_all = FALSE;	/* Found all matches of a
4117 						   certain type. */
4118     static buf_T	*ins_buf = NULL;	/* buffer being scanned */
4119 
4120     pos_T	*pos;
4121     char_u	**matches;
4122     int		save_p_scs;
4123     int		save_p_ws;
4124     int		save_p_ic;
4125     int		i;
4126     int		num_matches;
4127     int		len;
4128     int		found_new_match;
4129     int		type = ctrl_x_mode;
4130     char_u	*ptr;
4131     char_u	*dict = NULL;
4132     int		dict_f = 0;
4133     compl_T	*old_match;
4134 
4135     if (!compl_started)
4136     {
4137 	for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
4138 	    ins_buf->b_scanned = 0;
4139 	found_all = FALSE;
4140 	ins_buf = curbuf;
4141 	e_cpt = (compl_cont_status & CONT_LOCAL)
4142 					    ? (char_u *)"." : curbuf->b_p_cpt;
4143 	last_match_pos = first_match_pos = *ini;
4144     }
4145 
4146     old_match = compl_curr_match;	/* remember the last current match */
4147     pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
4148     /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
4149     for (;;)
4150     {
4151 	found_new_match = FAIL;
4152 
4153 	/* For ^N/^P pick a new entry from e_cpt if compl_started is off,
4154 	 * or if found_all says this entry is done.  For ^X^L only use the
4155 	 * entries from 'complete' that look in loaded buffers. */
4156 	if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4157 					&& (!compl_started || found_all))
4158 	{
4159 	    found_all = FALSE;
4160 	    while (*e_cpt == ',' || *e_cpt == ' ')
4161 		e_cpt++;
4162 	    if (*e_cpt == '.' && !curbuf->b_scanned)
4163 	    {
4164 		ins_buf = curbuf;
4165 		first_match_pos = *ini;
4166 		/* So that ^N can match word immediately after cursor */
4167 		if (ctrl_x_mode == 0)
4168 		    dec(&first_match_pos);
4169 		last_match_pos = first_match_pos;
4170 		type = 0;
4171 	    }
4172 	    else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
4173 		 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
4174 	    {
4175 		/* Scan a buffer, but not the current one. */
4176 		if (ins_buf->b_ml.ml_mfp != NULL)   /* loaded buffer */
4177 		{
4178 		    compl_started = TRUE;
4179 		    first_match_pos.col = last_match_pos.col = 0;
4180 		    first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
4181 		    last_match_pos.lnum = 0;
4182 		    type = 0;
4183 		}
4184 		else	/* unloaded buffer, scan like dictionary */
4185 		{
4186 		    found_all = TRUE;
4187 		    if (ins_buf->b_fname == NULL)
4188 			continue;
4189 		    type = CTRL_X_DICTIONARY;
4190 		    dict = ins_buf->b_fname;
4191 		    dict_f = DICT_EXACT;
4192 		}
4193 		vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4194 			ins_buf->b_fname == NULL
4195 			    ? buf_spname(ins_buf)
4196 			    : ins_buf->b_sfname == NULL
4197 				? ins_buf->b_fname
4198 				: ins_buf->b_sfname);
4199 		(void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
4200 	    }
4201 	    else if (*e_cpt == NUL)
4202 		break;
4203 	    else
4204 	    {
4205 		if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4206 		    type = -1;
4207 		else if (*e_cpt == 'k' || *e_cpt == 's')
4208 		{
4209 		    if (*e_cpt == 'k')
4210 			type = CTRL_X_DICTIONARY;
4211 		    else
4212 			type = CTRL_X_THESAURUS;
4213 		    if (*++e_cpt != ',' && *e_cpt != NUL)
4214 		    {
4215 			dict = e_cpt;
4216 			dict_f = DICT_FIRST;
4217 		    }
4218 		}
4219 #ifdef FEAT_FIND_ID
4220 		else if (*e_cpt == 'i')
4221 		    type = CTRL_X_PATH_PATTERNS;
4222 		else if (*e_cpt == 'd')
4223 		    type = CTRL_X_PATH_DEFINES;
4224 #endif
4225 		else if (*e_cpt == ']' || *e_cpt == 't')
4226 		{
4227 		    type = CTRL_X_TAGS;
4228 		    vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4229 		    (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
4230 		}
4231 		else
4232 		    type = -1;
4233 
4234 		/* in any case e_cpt is advanced to the next entry */
4235 		(void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
4236 
4237 		found_all = TRUE;
4238 		if (type == -1)
4239 		    continue;
4240 	    }
4241 	}
4242 
4243 	switch (type)
4244 	{
4245 	case -1:
4246 	    break;
4247 #ifdef FEAT_FIND_ID
4248 	case CTRL_X_PATH_PATTERNS:
4249 	case CTRL_X_PATH_DEFINES:
4250 	    find_pattern_in_path(compl_pattern, compl_direction,
4251 				 (int)STRLEN(compl_pattern), FALSE, FALSE,
4252 				 (type == CTRL_X_PATH_DEFINES
4253 				  && !(compl_cont_status & CONT_SOL))
4254 				 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
4255 				 (linenr_T)1, (linenr_T)MAXLNUM);
4256 	    break;
4257 #endif
4258 
4259 	case CTRL_X_DICTIONARY:
4260 	case CTRL_X_THESAURUS:
4261 	    ins_compl_dictionaries(
4262 		    dict != NULL ? dict
4263 			 : (type == CTRL_X_THESAURUS
4264 			     ? (*curbuf->b_p_tsr == NUL
4265 				 ? p_tsr
4266 				 : curbuf->b_p_tsr)
4267 			     : (*curbuf->b_p_dict == NUL
4268 				 ? p_dict
4269 				 : curbuf->b_p_dict)),
4270 			    compl_pattern,
4271 				 dict != NULL ? dict_f
4272 					       : 0, type == CTRL_X_THESAURUS);
4273 	    dict = NULL;
4274 	    break;
4275 
4276 	case CTRL_X_TAGS:
4277 	    /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
4278 	    save_p_ic = p_ic;
4279 	    p_ic = ignorecase(compl_pattern);
4280 
4281 	    /* Find up to TAG_MANY matches.  Avoids that an enormous number
4282 	     * of matches is found when compl_pattern is empty */
4283 	    if (find_tags(compl_pattern, &num_matches, &matches,
4284 		    TAG_REGEXP | TAG_NAMES | TAG_NOIC |
4285 		    TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
4286 		    TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4287 	    {
4288 		ins_compl_add_matches(num_matches, matches, p_ic);
4289 	    }
4290 	    p_ic = save_p_ic;
4291 	    break;
4292 
4293 	case CTRL_X_FILES:
4294 	    if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
4295 				  EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
4296 	    {
4297 
4298 		/* May change home directory back to "~". */
4299 		tilde_replace(compl_pattern, num_matches, matches);
4300 		ins_compl_add_matches(num_matches, matches,
4301 #ifdef CASE_INSENSITIVE_FILENAME
4302 			TRUE
4303 #else
4304 			FALSE
4305 #endif
4306 			);
4307 	    }
4308 	    break;
4309 
4310 	case CTRL_X_CMDLINE:
4311 	    if (expand_cmdline(&compl_xp, compl_pattern,
4312 			(int)STRLEN(compl_pattern),
4313 					 &num_matches, &matches) == EXPAND_OK)
4314 		ins_compl_add_matches(num_matches, matches, FALSE);
4315 	    break;
4316 
4317 #ifdef FEAT_COMPL_FUNC
4318 	case CTRL_X_FUNCTION:
4319 	case CTRL_X_OMNI:
4320 	    expand_by_function(type, compl_pattern);
4321 	    break;
4322 #endif
4323 
4324 	case CTRL_X_SPELL:
4325 #ifdef FEAT_SPELL
4326 	    num_matches = expand_spelling(first_match_pos.lnum,
4327 						     compl_pattern, &matches);
4328 	    if (num_matches > 0)
4329 		ins_compl_add_matches(num_matches, matches, p_ic);
4330 #endif
4331 	    break;
4332 
4333 	default:	/* normal ^P/^N and ^X^L */
4334 	    /*
4335 	     * If 'infercase' is set, don't use 'smartcase' here
4336 	     */
4337 	    save_p_scs = p_scs;
4338 	    if (ins_buf->b_p_inf)
4339 		p_scs = FALSE;
4340 
4341 	    /*	buffers other than curbuf are scanned from the beginning or the
4342 	     *	end but never from the middle, thus setting nowrapscan in this
4343 	     *	buffers is a good idea, on the other hand, we always set
4344 	     *	wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
4345 	    save_p_ws = p_ws;
4346 	    if (ins_buf != curbuf)
4347 		p_ws = FALSE;
4348 	    else if (*e_cpt == '.')
4349 		p_ws = TRUE;
4350 	    for (;;)
4351 	    {
4352 		int	flags = 0;
4353 
4354 		++msg_silent;  /* Don't want messages for wrapscan. */
4355 
4356 		/* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
4357 		 * has added a word that was at the beginning of the line */
4358 		if (	ctrl_x_mode == CTRL_X_WHOLE_LINE
4359 			|| (compl_cont_status & CONT_SOL))
4360 		    found_new_match = search_for_exact_line(ins_buf, pos,
4361 					      compl_direction, compl_pattern);
4362 		else
4363 		    found_new_match = searchit(NULL, ins_buf, pos,
4364 							      compl_direction,
4365 				 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
4366 						  RE_LAST, (linenr_T)0, NULL);
4367 		--msg_silent;
4368 		if (!compl_started)
4369 		{
4370 		    /* set "compl_started" even on fail */
4371 		    compl_started = TRUE;
4372 		    first_match_pos = *pos;
4373 		    last_match_pos = *pos;
4374 		}
4375 		else if (first_match_pos.lnum == last_match_pos.lnum
4376 				 && first_match_pos.col == last_match_pos.col)
4377 		    found_new_match = FAIL;
4378 		if (found_new_match == FAIL)
4379 		{
4380 		    if (ins_buf == curbuf)
4381 			found_all = TRUE;
4382 		    break;
4383 		}
4384 
4385 		/* when ADDING, the text before the cursor matches, skip it */
4386 		if (	(compl_cont_status & CONT_ADDING) && ins_buf == curbuf
4387 			&& ini->lnum == pos->lnum
4388 			&& ini->col  == pos->col)
4389 		    continue;
4390 		ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
4391 		if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4392 		{
4393 		    if (compl_cont_status & CONT_ADDING)
4394 		    {
4395 			if (pos->lnum >= ins_buf->b_ml.ml_line_count)
4396 			    continue;
4397 			ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4398 			if (!p_paste)
4399 			    ptr = skipwhite(ptr);
4400 		    }
4401 		    len = (int)STRLEN(ptr);
4402 		}
4403 		else
4404 		{
4405 		    char_u	*tmp_ptr = ptr;
4406 
4407 		    if (compl_cont_status & CONT_ADDING)
4408 		    {
4409 			tmp_ptr += compl_length;
4410 			/* Skip if already inside a word. */
4411 			if (vim_iswordp(tmp_ptr))
4412 			    continue;
4413 			/* Find start of next word. */
4414 			tmp_ptr = find_word_start(tmp_ptr);
4415 		    }
4416 		    /* Find end of this word. */
4417 		    tmp_ptr = find_word_end(tmp_ptr);
4418 		    len = (int)(tmp_ptr - ptr);
4419 
4420 		    if ((compl_cont_status & CONT_ADDING)
4421 						       && len == compl_length)
4422 		    {
4423 			if (pos->lnum < ins_buf->b_ml.ml_line_count)
4424 			{
4425 			    /* Try next line, if any. the new word will be
4426 			     * "join" as if the normal command "J" was used.
4427 			     * IOSIZE is always greater than
4428 			     * compl_length, so the next STRNCPY always
4429 			     * works -- Acevedo */
4430 			    STRNCPY(IObuff, ptr, len);
4431 			    ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4432 			    tmp_ptr = ptr = skipwhite(ptr);
4433 			    /* Find start of next word. */
4434 			    tmp_ptr = find_word_start(tmp_ptr);
4435 			    /* Find end of next word. */
4436 			    tmp_ptr = find_word_end(tmp_ptr);
4437 			    if (tmp_ptr > ptr)
4438 			    {
4439 				if (*ptr != ')' && IObuff[len - 1] != TAB)
4440 				{
4441 				    if (IObuff[len - 1] != ' ')
4442 					IObuff[len++] = ' ';
4443 				    /* IObuf =~ "\k.* ", thus len >= 2 */
4444 				    if (p_js
4445 					&& (IObuff[len - 2] == '.'
4446 					    || (vim_strchr(p_cpo, CPO_JOINSP)
4447 								       == NULL
4448 						&& (IObuff[len - 2] == '?'
4449 						 || IObuff[len - 2] == '!'))))
4450 					IObuff[len++] = ' ';
4451 				}
4452 				/* copy as much as possible of the new word */
4453 				if (tmp_ptr - ptr >= IOSIZE - len)
4454 				    tmp_ptr = ptr + IOSIZE - len - 1;
4455 				STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4456 				len += (int)(tmp_ptr - ptr);
4457 				flags |= CONT_S_IPOS;
4458 			    }
4459 			    IObuff[len] = NUL;
4460 			    ptr = IObuff;
4461 			}
4462 			if (len == compl_length)
4463 			    continue;
4464 		    }
4465 		}
4466 		if (ins_compl_add_infercase(ptr, len, p_ic,
4467 				 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
4468 					   0, flags) != NOTDONE)
4469 		{
4470 		    found_new_match = OK;
4471 		    break;
4472 		}
4473 	    }
4474 	    p_scs = save_p_scs;
4475 	    p_ws = save_p_ws;
4476 	}
4477 
4478 	/* check if compl_curr_match has changed, (e.g. other type of
4479 	 * expansion added something) */
4480 	if (type != 0 && compl_curr_match != old_match)
4481 	    found_new_match = OK;
4482 
4483 	/* break the loop for specialized modes (use 'complete' just for the
4484 	 * generic ctrl_x_mode == 0) or when we've found a new match */
4485 	if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4486 						   || found_new_match != FAIL)
4487 	{
4488 	    if (got_int)
4489 		break;
4490 	    /* Fill the popup menu as soon as possible. */
4491 	    if (type != -1)
4492 		ins_compl_check_keys(0);
4493 
4494 	    if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4495 							 || compl_interrupted)
4496 		break;
4497 	    compl_started = TRUE;
4498 	}
4499 	else
4500 	{
4501 	    /* Mark a buffer scanned when it has been scanned completely */
4502 	    if (type == 0 || type == CTRL_X_PATH_PATTERNS)
4503 		ins_buf->b_scanned = TRUE;
4504 
4505 	    compl_started = FALSE;
4506 	}
4507     }
4508     compl_started = TRUE;
4509 
4510     if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4511 	    && *e_cpt == NUL)		/* Got to end of 'complete' */
4512 	found_new_match = FAIL;
4513 
4514     i = -1;		/* total of matches, unknown */
4515     if (found_new_match == FAIL
4516 	    || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
4517 	i = ins_compl_make_cyclic();
4518 
4519     /* If several matches were added (FORWARD) or the search failed and has
4520      * just been made cyclic then we have to move compl_curr_match to the next
4521      * or previous entry (if any) -- Acevedo */
4522     compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
4523 							 : old_match->cp_prev;
4524     if (compl_curr_match == NULL)
4525 	compl_curr_match = old_match;
4526     return i;
4527 }
4528 
4529 /* Delete the old text being completed. */
4530     static void
4531 ins_compl_delete()
4532 {
4533     int	    i;
4534 
4535     /*
4536      * In insert mode: Delete the typed part.
4537      * In replace mode: Put the old characters back, if any.
4538      */
4539     i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
4540     backspace_until_column(i);
4541     changed_cline_bef_curs();
4542 }
4543 
4544 /* Insert the new text being completed. */
4545     static void
4546 ins_compl_insert()
4547 {
4548     ins_bytes(compl_shown_match->cp_str + ins_compl_len());
4549     if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4550 	compl_used_match = FALSE;
4551     else
4552 	compl_used_match = TRUE;
4553 }
4554 
4555 /*
4556  * Fill in the next completion in the current direction.
4557  * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4558  * get more completions.  If it is FALSE, then we just do nothing when there
4559  * are no more completions in a given direction.  The latter case is used when
4560  * we are still in the middle of finding completions, to allow browsing
4561  * through the ones found so far.
4562  * Return the total number of matches, or -1 if still unknown -- webb.
4563  *
4564  * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4565  * compl_shown_match here.
4566  *
4567  * Note that this function may be called recursively once only.  First with
4568  * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4569  * calls this function with "allow_get_expansion" FALSE.
4570  */
4571     static int
4572 ins_compl_next(allow_get_expansion, count, insert_match)
4573     int	    allow_get_expansion;
4574     int	    count;		/* repeat completion this many times; should
4575 				   be at least 1 */
4576     int	    insert_match;	/* Insert the newly selected match */
4577 {
4578     int	    num_matches = -1;
4579     int	    i;
4580     int	    todo = count;
4581     compl_T *found_compl = NULL;
4582     int	    found_end = FALSE;
4583     int	    advance;
4584 
4585     /* When user complete function return -1 for findstart which is next
4586      * time of 'always', compl_shown_match become NULL. */
4587     if (compl_shown_match == NULL)
4588 	return -1;
4589 
4590     if (compl_leader != NULL
4591 			&& (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4592     {
4593 	/* Set "compl_shown_match" to the actually shown match, it may differ
4594 	 * when "compl_leader" is used to omit some of the matches. */
4595 	while (!ins_compl_equal(compl_shown_match,
4596 				      compl_leader, (int)STRLEN(compl_leader))
4597 		&& compl_shown_match->cp_next != NULL
4598 		&& compl_shown_match->cp_next != compl_first_match)
4599 	    compl_shown_match = compl_shown_match->cp_next;
4600 
4601 	/* If we didn't find it searching forward, and compl_shows_dir is
4602 	 * backward, find the last match. */
4603 	if (compl_shows_dir == BACKWARD
4604 		&& !ins_compl_equal(compl_shown_match,
4605 				      compl_leader, (int)STRLEN(compl_leader))
4606 		&& (compl_shown_match->cp_next == NULL
4607 		    || compl_shown_match->cp_next == compl_first_match))
4608 	{
4609 	    while (!ins_compl_equal(compl_shown_match,
4610 				      compl_leader, (int)STRLEN(compl_leader))
4611 		    && compl_shown_match->cp_prev != NULL
4612 		    && compl_shown_match->cp_prev != compl_first_match)
4613 		compl_shown_match = compl_shown_match->cp_prev;
4614 	}
4615     }
4616 
4617     if (allow_get_expansion && insert_match
4618 	    && (!(compl_get_longest || compl_restarting) || compl_used_match))
4619 	/* Delete old text to be replaced */
4620 	ins_compl_delete();
4621 
4622     /* When finding the longest common text we stick at the original text,
4623      * don't let CTRL-N or CTRL-P move to the first match. */
4624     advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4625 
4626     /* When restarting the search don't insert the first match either. */
4627     if (compl_restarting)
4628     {
4629 	advance = FALSE;
4630 	compl_restarting = FALSE;
4631     }
4632 
4633     /* Repeat this for when <PageUp> or <PageDown> is typed.  But don't wrap
4634      * around. */
4635     while (--todo >= 0)
4636     {
4637 	if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4638 	{
4639 	    compl_shown_match = compl_shown_match->cp_next;
4640 	    found_end = (compl_first_match != NULL
4641 			   && (compl_shown_match->cp_next == compl_first_match
4642 			       || compl_shown_match == compl_first_match));
4643 	}
4644 	else if (compl_shows_dir == BACKWARD
4645 					&& compl_shown_match->cp_prev != NULL)
4646 	{
4647 	    found_end = (compl_shown_match == compl_first_match);
4648 	    compl_shown_match = compl_shown_match->cp_prev;
4649 	    found_end |= (compl_shown_match == compl_first_match);
4650 	}
4651 	else
4652 	{
4653 	    if (!allow_get_expansion)
4654 	    {
4655 		if (advance)
4656 		{
4657 		    if (compl_shows_dir == BACKWARD)
4658 			compl_pending -= todo + 1;
4659 		    else
4660 			compl_pending += todo + 1;
4661 		}
4662 		return -1;
4663 	    }
4664 
4665 	    if (advance)
4666 	    {
4667 		if (compl_shows_dir == BACKWARD)
4668 		    --compl_pending;
4669 		else
4670 		    ++compl_pending;
4671 	    }
4672 
4673 	    /* Find matches. */
4674 	    num_matches = ins_compl_get_exp(&compl_startpos);
4675 
4676 	    /* handle any pending completions */
4677 	    while (compl_pending != 0 && compl_direction == compl_shows_dir
4678 								   && advance)
4679 	    {
4680 		if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4681 		{
4682 		    compl_shown_match = compl_shown_match->cp_next;
4683 		    --compl_pending;
4684 		}
4685 		if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4686 		{
4687 		    compl_shown_match = compl_shown_match->cp_prev;
4688 		    ++compl_pending;
4689 		}
4690 		else
4691 		    break;
4692 	    }
4693 	    found_end = FALSE;
4694 	}
4695 	if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4696 		&& compl_leader != NULL
4697 		&& !ins_compl_equal(compl_shown_match,
4698 				     compl_leader, (int)STRLEN(compl_leader)))
4699 	    ++todo;
4700 	else
4701 	    /* Remember a matching item. */
4702 	    found_compl = compl_shown_match;
4703 
4704 	/* Stop at the end of the list when we found a usable match. */
4705 	if (found_end)
4706 	{
4707 	    if (found_compl != NULL)
4708 	    {
4709 		compl_shown_match = found_compl;
4710 		break;
4711 	    }
4712 	    todo = 1;	    /* use first usable match after wrapping around */
4713 	}
4714     }
4715 
4716     /* Insert the text of the new completion, or the compl_leader. */
4717     if (insert_match)
4718     {
4719 	if (!compl_get_longest || compl_used_match)
4720 	    ins_compl_insert();
4721 	else
4722 	    ins_bytes(compl_leader + ins_compl_len());
4723     }
4724     else
4725 	compl_used_match = FALSE;
4726 
4727     if (!allow_get_expansion)
4728     {
4729 	/* may undisplay the popup menu first */
4730 	ins_compl_upd_pum();
4731 
4732 	/* redraw to show the user what was inserted */
4733 	update_screen(0);
4734 
4735 	/* display the updated popup menu */
4736 	ins_compl_show_pum();
4737 #ifdef FEAT_GUI
4738 	if (gui.in_use)
4739 	{
4740 	    /* Show the cursor after the match, not after the redrawn text. */
4741 	    setcursor();
4742 	    out_flush();
4743 	    gui_update_cursor(FALSE, FALSE);
4744 	}
4745 #endif
4746 
4747 	/* Delete old text to be replaced, since we're still searching and
4748 	 * don't want to match ourselves!  */
4749 	ins_compl_delete();
4750     }
4751 
4752     /* Enter will select a match when the match wasn't inserted and the popup
4753      * menu is visible. */
4754     compl_enter_selects = !insert_match && compl_match_array != NULL;
4755 
4756     /*
4757      * Show the file name for the match (if any)
4758      * Truncate the file name to avoid a wait for return.
4759      */
4760     if (compl_shown_match->cp_fname != NULL)
4761     {
4762 	STRCPY(IObuff, "match in file ");
4763 	i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4764 	if (i <= 0)
4765 	    i = 0;
4766 	else
4767 	    STRCAT(IObuff, "<");
4768 	STRCAT(IObuff, compl_shown_match->cp_fname + i);
4769 	msg(IObuff);
4770 	redraw_cmdline = FALSE;	    /* don't overwrite! */
4771     }
4772 
4773     return num_matches;
4774 }
4775 
4776 /*
4777  * Call this while finding completions, to check whether the user has hit a key
4778  * that should change the currently displayed completion, or exit completion
4779  * mode.  Also, when compl_pending is not zero, show a completion as soon as
4780  * possible. -- webb
4781  * "frequency" specifies out of how many calls we actually check.
4782  */
4783     void
4784 ins_compl_check_keys(frequency)
4785     int		frequency;
4786 {
4787     static int	count = 0;
4788 
4789     int	    c;
4790 
4791     /* Don't check when reading keys from a script.  That would break the test
4792      * scripts */
4793     if (using_script())
4794 	return;
4795 
4796     /* Only do this at regular intervals */
4797     if (++count < frequency)
4798 	return;
4799     count = 0;
4800 
4801     /* Check for a typed key.  Do use mappings, otherwise vim_is_ctrl_x_key()
4802      * can't do its work correctly. */
4803     c = vpeekc_any();
4804     if (c != NUL)
4805     {
4806 	if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4807 	{
4808 	    c = safe_vgetc();	/* Eat the character */
4809 	    compl_shows_dir = ins_compl_key2dir(c);
4810 	    (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4811 						    c != K_UP && c != K_DOWN);
4812 	}
4813 	else
4814 	{
4815 	    /* Need to get the character to have KeyTyped set.  We'll put it
4816 	     * back with vungetc() below.  But skip K_IGNORE. */
4817 	    c = safe_vgetc();
4818 	    if (c != K_IGNORE)
4819 	    {
4820 		/* Don't interrupt completion when the character wasn't typed,
4821 		 * e.g., when doing @q to replay keys. */
4822 		if (c != Ctrl_R && KeyTyped)
4823 		    compl_interrupted = TRUE;
4824 
4825 		vungetc(c);
4826 	    }
4827 	}
4828     }
4829     if (compl_pending != 0 && !got_int)
4830     {
4831 	int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4832 
4833 	compl_pending = 0;
4834 	(void)ins_compl_next(FALSE, todo, TRUE);
4835     }
4836 }
4837 
4838 /*
4839  * Decide the direction of Insert mode complete from the key typed.
4840  * Returns BACKWARD or FORWARD.
4841  */
4842     static int
4843 ins_compl_key2dir(c)
4844     int		c;
4845 {
4846     if (c == Ctrl_P || c == Ctrl_L
4847 	    || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4848 						|| c == K_S_UP || c == K_UP)))
4849 	return BACKWARD;
4850     return FORWARD;
4851 }
4852 
4853 /*
4854  * Return TRUE for keys that are used for completion only when the popup menu
4855  * is visible.
4856  */
4857     static int
4858 ins_compl_pum_key(c)
4859     int		c;
4860 {
4861     return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4862 		     || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4863 		     || c == K_UP || c == K_DOWN);
4864 }
4865 
4866 /*
4867  * Decide the number of completions to move forward.
4868  * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4869  */
4870     static int
4871 ins_compl_key2count(c)
4872     int		c;
4873 {
4874     int		h;
4875 
4876     if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4877     {
4878 	h = pum_get_height();
4879 	if (h > 3)
4880 	    h -= 2; /* keep some context */
4881 	return h;
4882     }
4883     return 1;
4884 }
4885 
4886 /*
4887  * Return TRUE if completion with "c" should insert the match, FALSE if only
4888  * to change the currently selected completion.
4889  */
4890     static int
4891 ins_compl_use_match(c)
4892     int		c;
4893 {
4894     switch (c)
4895     {
4896 	case K_UP:
4897 	case K_DOWN:
4898 	case K_PAGEDOWN:
4899 	case K_KPAGEDOWN:
4900 	case K_S_DOWN:
4901 	case K_PAGEUP:
4902 	case K_KPAGEUP:
4903 	case K_S_UP:
4904 	    return FALSE;
4905     }
4906     return TRUE;
4907 }
4908 
4909 /*
4910  * Do Insert mode completion.
4911  * Called when character "c" was typed, which has a meaning for completion.
4912  * Returns OK if completion was done, FAIL if something failed (out of mem).
4913  */
4914     static int
4915 ins_complete(c)
4916     int		c;
4917 {
4918     char_u	*line;
4919     int		startcol = 0;	    /* column where searched text starts */
4920     colnr_T	curs_col;	    /* cursor column */
4921     int		n;
4922     int		save_w_wrow;
4923 
4924     compl_direction = ins_compl_key2dir(c);
4925     if (!compl_started)
4926     {
4927 	/* First time we hit ^N or ^P (in a row, I mean) */
4928 
4929 	did_ai = FALSE;
4930 #ifdef FEAT_SMARTINDENT
4931 	did_si = FALSE;
4932 	can_si = FALSE;
4933 	can_si_back = FALSE;
4934 #endif
4935 	if (stop_arrow() == FAIL)
4936 	    return FAIL;
4937 
4938 	line = ml_get(curwin->w_cursor.lnum);
4939 	curs_col = curwin->w_cursor.col;
4940 	compl_pending = 0;
4941 
4942 	/* If this same ctrl_x_mode has been interrupted use the text from
4943 	 * "compl_startpos" to the cursor as a pattern to add a new word
4944 	 * instead of expand the one before the cursor, in word-wise if
4945 	 * "compl_startpos" is not in the same line as the cursor then fix it
4946 	 * (the line has been split because it was longer than 'tw').  if SOL
4947 	 * is set then skip the previous pattern, a word at the beginning of
4948 	 * the line has been inserted, we'll look for that  -- Acevedo. */
4949 	if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4950 					    && compl_cont_mode == ctrl_x_mode)
4951 	{
4952 	    /*
4953 	     * it is a continued search
4954 	     */
4955 	    compl_cont_status &= ~CONT_INTRPT;	/* remove INTRPT */
4956 	    if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4957 					|| ctrl_x_mode == CTRL_X_PATH_DEFINES)
4958 	    {
4959 		if (compl_startpos.lnum != curwin->w_cursor.lnum)
4960 		{
4961 		    /* line (probably) wrapped, set compl_startpos to the
4962 		     * first non_blank in the line, if it is not a wordchar
4963 		     * include it to get a better pattern, but then we don't
4964 		     * want the "\\<" prefix, check it bellow */
4965 		    compl_col = (colnr_T)(skipwhite(line) - line);
4966 		    compl_startpos.col = compl_col;
4967 		    compl_startpos.lnum = curwin->w_cursor.lnum;
4968 		    compl_cont_status &= ~CONT_SOL;   /* clear SOL if present */
4969 		}
4970 		else
4971 		{
4972 		    /* S_IPOS was set when we inserted a word that was at the
4973 		     * beginning of the line, which means that we'll go to SOL
4974 		     * mode but first we need to redefine compl_startpos */
4975 		    if (compl_cont_status & CONT_S_IPOS)
4976 		    {
4977 			compl_cont_status |= CONT_SOL;
4978 			compl_startpos.col = (colnr_T)(skipwhite(
4979 						line + compl_length
4980 						+ compl_startpos.col) - line);
4981 		    }
4982 		    compl_col = compl_startpos.col;
4983 		}
4984 		compl_length = curwin->w_cursor.col - (int)compl_col;
4985 		/* IObuff is used to add a "word from the next line" would we
4986 		 * have enough space?  just being paranoid */
4987 #define	MIN_SPACE 75
4988 		if (compl_length > (IOSIZE - MIN_SPACE))
4989 		{
4990 		    compl_cont_status &= ~CONT_SOL;
4991 		    compl_length = (IOSIZE - MIN_SPACE);
4992 		    compl_col = curwin->w_cursor.col - compl_length;
4993 		}
4994 		compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4995 		if (compl_length < 1)
4996 		    compl_cont_status &= CONT_LOCAL;
4997 	    }
4998 	    else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4999 		compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5000 	    else
5001 		compl_cont_status = 0;
5002 	}
5003 	else
5004 	    compl_cont_status &= CONT_LOCAL;
5005 
5006 	if (!(compl_cont_status & CONT_ADDING))	/* normal expansion */
5007 	{
5008 	    compl_cont_mode = ctrl_x_mode;
5009 	    if (ctrl_x_mode != 0)	/* Remove LOCAL if ctrl_x_mode != 0 */
5010 		compl_cont_status = 0;
5011 	    compl_cont_status |= CONT_N_ADDS;
5012 	    compl_startpos = curwin->w_cursor;
5013 	    startcol = (int)curs_col;
5014 	    compl_col = 0;
5015 	}
5016 
5017 	/* Work out completion pattern and original text -- webb */
5018 	if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
5019 	{
5020 	    if ((compl_cont_status & CONT_SOL)
5021 		    || ctrl_x_mode == CTRL_X_PATH_DEFINES)
5022 	    {
5023 		if (!(compl_cont_status & CONT_ADDING))
5024 		{
5025 		    while (--startcol >= 0 && vim_isIDc(line[startcol]))
5026 			;
5027 		    compl_col += ++startcol;
5028 		    compl_length = curs_col - startcol;
5029 		}
5030 		if (p_ic)
5031 		    compl_pattern = str_foldcase(line + compl_col,
5032 						       compl_length, NULL, 0);
5033 		else
5034 		    compl_pattern = vim_strnsave(line + compl_col,
5035 								compl_length);
5036 		if (compl_pattern == NULL)
5037 		    return FAIL;
5038 	    }
5039 	    else if (compl_cont_status & CONT_ADDING)
5040 	    {
5041 		char_u	    *prefix = (char_u *)"\\<";
5042 
5043 		/* we need up to 2 extra chars for the prefix */
5044 		compl_pattern = alloc(quote_meta(NULL, line + compl_col,
5045 							   compl_length) + 2);
5046 		if (compl_pattern == NULL)
5047 		    return FAIL;
5048 		if (!vim_iswordp(line + compl_col)
5049 			|| (compl_col > 0
5050 			    && (
5051 #ifdef FEAT_MBYTE
5052 				vim_iswordp(mb_prevptr(line, line + compl_col))
5053 #else
5054 				vim_iswordc(line[compl_col - 1])
5055 #endif
5056 				)))
5057 		    prefix = (char_u *)"";
5058 		STRCPY((char *)compl_pattern, prefix);
5059 		(void)quote_meta(compl_pattern + STRLEN(prefix),
5060 					      line + compl_col, compl_length);
5061 	    }
5062 	    else if (--startcol < 0 ||
5063 #ifdef FEAT_MBYTE
5064 			   !vim_iswordp(mb_prevptr(line, line + startcol + 1))
5065 #else
5066 			   !vim_iswordc(line[startcol])
5067 #endif
5068 		    )
5069 	    {
5070 		/* Match any word of at least two chars */
5071 		compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
5072 		if (compl_pattern == NULL)
5073 		    return FAIL;
5074 		compl_col += curs_col;
5075 		compl_length = 0;
5076 	    }
5077 	    else
5078 	    {
5079 #ifdef FEAT_MBYTE
5080 		/* Search the point of change class of multibyte character
5081 		 * or not a word single byte character backward.  */
5082 		if (has_mbyte)
5083 		{
5084 		    int base_class;
5085 		    int head_off;
5086 
5087 		    startcol -= (*mb_head_off)(line, line + startcol);
5088 		    base_class = mb_get_class(line + startcol);
5089 		    while (--startcol >= 0)
5090 		    {
5091 			head_off = (*mb_head_off)(line, line + startcol);
5092 			if (base_class != mb_get_class(line + startcol
5093 								  - head_off))
5094 			    break;
5095 			startcol -= head_off;
5096 		    }
5097 		}
5098 		else
5099 #endif
5100 		    while (--startcol >= 0 && vim_iswordc(line[startcol]))
5101 			;
5102 		compl_col += ++startcol;
5103 		compl_length = (int)curs_col - startcol;
5104 		if (compl_length == 1)
5105 		{
5106 		    /* Only match word with at least two chars -- webb
5107 		     * there's no need to call quote_meta,
5108 		     * alloc(7) is enough  -- Acevedo
5109 		     */
5110 		    compl_pattern = alloc(7);
5111 		    if (compl_pattern == NULL)
5112 			return FAIL;
5113 		    STRCPY((char *)compl_pattern, "\\<");
5114 		    (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
5115 		    STRCAT((char *)compl_pattern, "\\k");
5116 		}
5117 		else
5118 		{
5119 		    compl_pattern = alloc(quote_meta(NULL, line + compl_col,
5120 							   compl_length) + 2);
5121 		    if (compl_pattern == NULL)
5122 			return FAIL;
5123 		    STRCPY((char *)compl_pattern, "\\<");
5124 		    (void)quote_meta(compl_pattern + 2, line + compl_col,
5125 								compl_length);
5126 		}
5127 	    }
5128 	}
5129 	else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
5130 	{
5131 	    compl_col = (colnr_T)(skipwhite(line) - line);
5132 	    compl_length = (int)curs_col - (int)compl_col;
5133 	    if (compl_length < 0)	/* cursor in indent: empty pattern */
5134 		compl_length = 0;
5135 	    if (p_ic)
5136 		compl_pattern = str_foldcase(line + compl_col, compl_length,
5137 								     NULL, 0);
5138 	    else
5139 		compl_pattern = vim_strnsave(line + compl_col, compl_length);
5140 	    if (compl_pattern == NULL)
5141 		return FAIL;
5142 	}
5143 	else if (ctrl_x_mode == CTRL_X_FILES)
5144 	{
5145 	    while (--startcol >= 0 && vim_isfilec(line[startcol]))
5146 		;
5147 	    compl_col += ++startcol;
5148 	    compl_length = (int)curs_col - startcol;
5149 	    compl_pattern = addstar(line + compl_col, compl_length,
5150 								EXPAND_FILES);
5151 	    if (compl_pattern == NULL)
5152 		return FAIL;
5153 	}
5154 	else if (ctrl_x_mode == CTRL_X_CMDLINE)
5155 	{
5156 	    compl_pattern = vim_strnsave(line, curs_col);
5157 	    if (compl_pattern == NULL)
5158 		return FAIL;
5159 	    set_cmd_context(&compl_xp, compl_pattern,
5160 				     (int)STRLEN(compl_pattern), curs_col);
5161 	    if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5162 		    || compl_xp.xp_context == EXPAND_NOTHING)
5163 		/* No completion possible, use an empty pattern to get a
5164 		 * "pattern not found" message. */
5165 		compl_col = curs_col;
5166 	    else
5167 		compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
5168 	    compl_length = curs_col - compl_col;
5169 	}
5170 	else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
5171 	{
5172 #ifdef FEAT_COMPL_FUNC
5173 	    /*
5174 	     * Call user defined function 'completefunc' with "a:findstart"
5175 	     * set to 1 to obtain the length of text to use for completion.
5176 	     */
5177 	    char_u	*args[2];
5178 	    int		col;
5179 	    char_u	*funcname;
5180 	    pos_T	pos;
5181 	    win_T	*curwin_save;
5182 	    buf_T	*curbuf_save;
5183 
5184 	    /* Call 'completefunc' or 'omnifunc' and get pattern length as a
5185 	     * string */
5186 	    funcname = ctrl_x_mode == CTRL_X_FUNCTION
5187 					  ? curbuf->b_p_cfu : curbuf->b_p_ofu;
5188 	    if (*funcname == NUL)
5189 	    {
5190 		EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
5191 					     ? "completefunc" : "omnifunc");
5192 		return FAIL;
5193 	    }
5194 
5195 	    args[0] = (char_u *)"1";
5196 	    args[1] = NULL;
5197 	    pos = curwin->w_cursor;
5198 	    curwin_save = curwin;
5199 	    curbuf_save = curbuf;
5200 	    col = call_func_retnr(funcname, 2, args, FALSE);
5201 	    if (curwin_save != curwin || curbuf_save != curbuf)
5202 	    {
5203 		EMSG(_(e_complwin));
5204 		return FAIL;
5205 	    }
5206 	    curwin->w_cursor = pos;	/* restore the cursor position */
5207 	    check_cursor();
5208 	    if (!equalpos(curwin->w_cursor, pos))
5209 	    {
5210 		EMSG(_(e_compldel));
5211 		return FAIL;
5212 	    }
5213 
5214 	    /* Return value -2 means the user complete function wants to
5215 	     * cancel the complete without an error.
5216 	     * Return value -3 does the same as -2 and leaves CTRL-X mode.*/
5217 	    if (col == -2)
5218 		return FAIL;
5219 	    if (col == -3)
5220 	    {
5221 		ctrl_x_mode = 0;
5222 		edit_submode = NULL;
5223 		msg_clr_cmdline();
5224 		return FAIL;
5225 	    }
5226 
5227 	    /*
5228 	     * Reset extended parameters of completion, when start new
5229 	     * completion.
5230 	     */
5231 	    compl_opt_refresh_always = FALSE;
5232 
5233 	    if (col < 0)
5234 		col = curs_col;
5235 	    compl_col = col;
5236 	    if (compl_col > curs_col)
5237 		compl_col = curs_col;
5238 
5239 	    /* Setup variables for completion.  Need to obtain "line" again,
5240 	     * it may have become invalid. */
5241 	    line = ml_get(curwin->w_cursor.lnum);
5242 	    compl_length = curs_col - compl_col;
5243 	    compl_pattern = vim_strnsave(line + compl_col, compl_length);
5244 	    if (compl_pattern == NULL)
5245 #endif
5246 		return FAIL;
5247 	}
5248 	else if (ctrl_x_mode == CTRL_X_SPELL)
5249 	{
5250 #ifdef FEAT_SPELL
5251 	    if (spell_bad_len > 0)
5252 		compl_col = curs_col - spell_bad_len;
5253 	    else
5254 		compl_col = spell_word_start(startcol);
5255 	    if (compl_col >= (colnr_T)startcol)
5256 	    {
5257 		compl_length = 0;
5258 		compl_col = curs_col;
5259 	    }
5260 	    else
5261 	    {
5262 		spell_expand_check_cap(compl_col);
5263 		compl_length = (int)curs_col - compl_col;
5264 	    }
5265 	    /* Need to obtain "line" again, it may have become invalid. */
5266 	    line = ml_get(curwin->w_cursor.lnum);
5267 	    compl_pattern = vim_strnsave(line + compl_col, compl_length);
5268 	    if (compl_pattern == NULL)
5269 #endif
5270 		return FAIL;
5271 	}
5272 	else
5273 	{
5274 	    EMSG2(_(e_intern2), "ins_complete()");
5275 	    return FAIL;
5276 	}
5277 
5278 	if (compl_cont_status & CONT_ADDING)
5279 	{
5280 	    edit_submode_pre = (char_u *)_(" Adding");
5281 	    if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
5282 	    {
5283 		/* Insert a new line, keep indentation but ignore 'comments' */
5284 #ifdef FEAT_COMMENTS
5285 		char_u *old = curbuf->b_p_com;
5286 
5287 		curbuf->b_p_com = (char_u *)"";
5288 #endif
5289 		compl_startpos.lnum = curwin->w_cursor.lnum;
5290 		compl_startpos.col = compl_col;
5291 		ins_eol('\r');
5292 #ifdef FEAT_COMMENTS
5293 		curbuf->b_p_com = old;
5294 #endif
5295 		compl_length = 0;
5296 		compl_col = curwin->w_cursor.col;
5297 	    }
5298 	}
5299 	else
5300 	{
5301 	    edit_submode_pre = NULL;
5302 	    compl_startpos.col = compl_col;
5303 	}
5304 
5305 	if (compl_cont_status & CONT_LOCAL)
5306 	    edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5307 	else
5308 	    edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5309 
5310 	/* If any of the original typed text has been changed we need to fix
5311 	 * the redo buffer. */
5312 	ins_compl_fixRedoBufForLeader(NULL);
5313 
5314 	/* Always add completion for the original text. */
5315 	vim_free(compl_orig_text);
5316 	compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5317 	if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5318 			-1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
5319 	{
5320 	    vim_free(compl_pattern);
5321 	    compl_pattern = NULL;
5322 	    vim_free(compl_orig_text);
5323 	    compl_orig_text = NULL;
5324 	    return FAIL;
5325 	}
5326 
5327 	/* showmode might reset the internal line pointers, so it must
5328 	 * be called before line = ml_get(), or when this address is no
5329 	 * longer needed.  -- Acevedo.
5330 	 */
5331 	edit_submode_extra = (char_u *)_("-- Searching...");
5332 	edit_submode_highl = HLF_COUNT;
5333 	showmode();
5334 	edit_submode_extra = NULL;
5335 	out_flush();
5336     }
5337 
5338     compl_shown_match = compl_curr_match;
5339     compl_shows_dir = compl_direction;
5340 
5341     /*
5342      * Find next match (and following matches).
5343      */
5344     save_w_wrow = curwin->w_wrow;
5345     n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
5346 
5347     /* may undisplay the popup menu */
5348     ins_compl_upd_pum();
5349 
5350     if (n > 1)		/* all matches have been found */
5351 	compl_matches = n;
5352     compl_curr_match = compl_shown_match;
5353     compl_direction = compl_shows_dir;
5354 
5355     /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5356      * mode. */
5357     if (got_int && !global_busy)
5358     {
5359 	(void)vgetc();
5360 	got_int = FALSE;
5361     }
5362 
5363     /* we found no match if the list has only the "compl_orig_text"-entry */
5364     if (compl_first_match == compl_first_match->cp_next)
5365     {
5366 	edit_submode_extra = (compl_cont_status & CONT_ADDING)
5367 			&& compl_length > 1
5368 			     ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
5369 	edit_submode_highl = HLF_E;
5370 	/* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5371 	 * because we couldn't expand anything at first place, but if we used
5372 	 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5373 	 * (such as M in M'exico) if not tried already.  -- Acevedo */
5374 	if (	   compl_length > 1
5375 		|| (compl_cont_status & CONT_ADDING)
5376 		|| (ctrl_x_mode != 0
5377 		    && ctrl_x_mode != CTRL_X_PATH_PATTERNS
5378 		    && ctrl_x_mode != CTRL_X_PATH_DEFINES))
5379 	    compl_cont_status &= ~CONT_N_ADDS;
5380     }
5381 
5382     if (compl_curr_match->cp_flags & CONT_S_IPOS)
5383 	compl_cont_status |= CONT_S_IPOS;
5384     else
5385 	compl_cont_status &= ~CONT_S_IPOS;
5386 
5387     if (edit_submode_extra == NULL)
5388     {
5389 	if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
5390 	{
5391 	    edit_submode_extra = (char_u *)_("Back at original");
5392 	    edit_submode_highl = HLF_W;
5393 	}
5394 	else if (compl_cont_status & CONT_S_IPOS)
5395 	{
5396 	    edit_submode_extra = (char_u *)_("Word from other line");
5397 	    edit_submode_highl = HLF_COUNT;
5398 	}
5399 	else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5400 	{
5401 	    edit_submode_extra = (char_u *)_("The only match");
5402 	    edit_submode_highl = HLF_COUNT;
5403 	}
5404 	else
5405 	{
5406 	    /* Update completion sequence number when needed. */
5407 	    if (compl_curr_match->cp_number == -1)
5408 	    {
5409 		int		number = 0;
5410 		compl_T		*match;
5411 
5412 		if (compl_direction == FORWARD)
5413 		{
5414 		    /* search backwards for the first valid (!= -1) number.
5415 		     * This should normally succeed already at the first loop
5416 		     * cycle, so it's fast! */
5417 		    for (match = compl_curr_match->cp_prev; match != NULL
5418 			    && match != compl_first_match;
5419 						       match = match->cp_prev)
5420 			if (match->cp_number != -1)
5421 			{
5422 			    number = match->cp_number;
5423 			    break;
5424 			}
5425 		    if (match != NULL)
5426 			/* go up and assign all numbers which are not assigned
5427 			 * yet */
5428 			for (match = match->cp_next;
5429 				match != NULL && match->cp_number == -1;
5430 						       match = match->cp_next)
5431 			    match->cp_number = ++number;
5432 		}
5433 		else /* BACKWARD */
5434 		{
5435 		    /* search forwards (upwards) for the first valid (!= -1)
5436 		     * number.  This should normally succeed already at the
5437 		     * first loop cycle, so it's fast! */
5438 		    for (match = compl_curr_match->cp_next; match != NULL
5439 			    && match != compl_first_match;
5440 						       match = match->cp_next)
5441 			if (match->cp_number != -1)
5442 			{
5443 			    number = match->cp_number;
5444 			    break;
5445 			}
5446 		    if (match != NULL)
5447 			/* go down and assign all numbers which are not
5448 			 * assigned yet */
5449 			for (match = match->cp_prev; match
5450 				&& match->cp_number == -1;
5451 						       match = match->cp_prev)
5452 			    match->cp_number = ++number;
5453 		}
5454 	    }
5455 
5456 	    /* The match should always have a sequence number now, this is
5457 	     * just a safety check. */
5458 	    if (compl_curr_match->cp_number != -1)
5459 	    {
5460 		/* Space for 10 text chars. + 2x10-digit no.s = 31.
5461 		 * Translations may need more than twice that. */
5462 		static char_u match_ref[81];
5463 
5464 		if (compl_matches > 0)
5465 		    vim_snprintf((char *)match_ref, sizeof(match_ref),
5466 				_("match %d of %d"),
5467 				compl_curr_match->cp_number, compl_matches);
5468 		else
5469 		    vim_snprintf((char *)match_ref, sizeof(match_ref),
5470 				_("match %d"),
5471 				compl_curr_match->cp_number);
5472 		edit_submode_extra = match_ref;
5473 		edit_submode_highl = HLF_R;
5474 		if (dollar_vcol >= 0)
5475 		    curs_columns(FALSE);
5476 	    }
5477 	}
5478     }
5479 
5480     /* Show a message about what (completion) mode we're in. */
5481     showmode();
5482     if (edit_submode_extra != NULL)
5483     {
5484 	if (!p_smd)
5485 	    msg_attr(edit_submode_extra,
5486 		    edit_submode_highl < HLF_COUNT
5487 		    ? hl_attr(edit_submode_highl) : 0);
5488     }
5489     else
5490 	msg_clr_cmdline();	/* necessary for "noshowmode" */
5491 
5492     /* Show the popup menu, unless we got interrupted. */
5493     if (!compl_interrupted)
5494     {
5495 	/* RedrawingDisabled may be set when invoked through complete(). */
5496 	n = RedrawingDisabled;
5497 	RedrawingDisabled = 0;
5498 
5499 	/* If the cursor moved we need to remove the pum first. */
5500 	setcursor();
5501 	if (save_w_wrow != curwin->w_wrow)
5502 	    ins_compl_del_pum();
5503 
5504 	ins_compl_show_pum();
5505 	setcursor();
5506 	RedrawingDisabled = n;
5507     }
5508     compl_was_interrupted = compl_interrupted;
5509     compl_interrupted = FALSE;
5510 
5511     return OK;
5512 }
5513 
5514 /*
5515  * Looks in the first "len" chars. of "src" for search-metachars.
5516  * If dest is not NULL the chars. are copied there quoting (with
5517  * a backslash) the metachars, and dest would be NUL terminated.
5518  * Returns the length (needed) of dest
5519  */
5520     static unsigned
5521 quote_meta(dest, src, len)
5522     char_u	*dest;
5523     char_u	*src;
5524     int		len;
5525 {
5526     unsigned	m = (unsigned)len + 1;  /* one extra for the NUL */
5527 
5528     for ( ; --len >= 0; src++)
5529     {
5530 	switch (*src)
5531 	{
5532 	    case '.':
5533 	    case '*':
5534 	    case '[':
5535 		if (ctrl_x_mode == CTRL_X_DICTIONARY
5536 					   || ctrl_x_mode == CTRL_X_THESAURUS)
5537 		    break;
5538 	    case '~':
5539 		if (!p_magic)	/* quote these only if magic is set */
5540 		    break;
5541 	    case '\\':
5542 		if (ctrl_x_mode == CTRL_X_DICTIONARY
5543 					   || ctrl_x_mode == CTRL_X_THESAURUS)
5544 		    break;
5545 	    case '^':		/* currently it's not needed. */
5546 	    case '$':
5547 		m++;
5548 		if (dest != NULL)
5549 		    *dest++ = '\\';
5550 		break;
5551 	}
5552 	if (dest != NULL)
5553 	    *dest++ = *src;
5554 # ifdef FEAT_MBYTE
5555 	/* Copy remaining bytes of a multibyte character. */
5556 	if (has_mbyte)
5557 	{
5558 	    int i, mb_len;
5559 
5560 	    mb_len = (*mb_ptr2len)(src) - 1;
5561 	    if (mb_len > 0 && len >= mb_len)
5562 		for (i = 0; i < mb_len; ++i)
5563 		{
5564 		    --len;
5565 		    ++src;
5566 		    if (dest != NULL)
5567 			*dest++ = *src;
5568 		}
5569 	}
5570 # endif
5571     }
5572     if (dest != NULL)
5573 	*dest = NUL;
5574 
5575     return m;
5576 }
5577 #endif /* FEAT_INS_EXPAND */
5578 
5579 /*
5580  * Next character is interpreted literally.
5581  * A one, two or three digit decimal number is interpreted as its byte value.
5582  * If one or two digits are entered, the next character is given to vungetc().
5583  * For Unicode a character > 255 may be returned.
5584  */
5585     int
5586 get_literal()
5587 {
5588     int		cc;
5589     int		nc;
5590     int		i;
5591     int		hex = FALSE;
5592     int		octal = FALSE;
5593 #ifdef FEAT_MBYTE
5594     int		unicode = 0;
5595 #endif
5596 
5597     if (got_int)
5598 	return Ctrl_C;
5599 
5600 #ifdef FEAT_GUI
5601     /*
5602      * In GUI there is no point inserting the internal code for a special key.
5603      * It is more useful to insert the string "<KEY>" instead.	This would
5604      * probably be useful in a text window too, but it would not be
5605      * vi-compatible (maybe there should be an option for it?) -- webb
5606      */
5607     if (gui.in_use)
5608 	++allow_keys;
5609 #endif
5610 #ifdef USE_ON_FLY_SCROLL
5611     dont_scroll = TRUE;		/* disallow scrolling here */
5612 #endif
5613     ++no_mapping;		/* don't map the next key hits */
5614     cc = 0;
5615     i = 0;
5616     for (;;)
5617     {
5618 	nc = plain_vgetc();
5619 #ifdef FEAT_CMDL_INFO
5620 	if (!(State & CMDLINE)
5621 # ifdef FEAT_MBYTE
5622 		&& MB_BYTE2LEN_CHECK(nc) == 1
5623 # endif
5624 	   )
5625 	    add_to_showcmd(nc);
5626 #endif
5627 	if (nc == 'x' || nc == 'X')
5628 	    hex = TRUE;
5629 	else if (nc == 'o' || nc == 'O')
5630 	    octal = TRUE;
5631 #ifdef FEAT_MBYTE
5632 	else if (nc == 'u' || nc == 'U')
5633 	    unicode = nc;
5634 #endif
5635 	else
5636 	{
5637 	    if (hex
5638 #ifdef FEAT_MBYTE
5639 		    || unicode != 0
5640 #endif
5641 		    )
5642 	    {
5643 		if (!vim_isxdigit(nc))
5644 		    break;
5645 		cc = cc * 16 + hex2nr(nc);
5646 	    }
5647 	    else if (octal)
5648 	    {
5649 		if (nc < '0' || nc > '7')
5650 		    break;
5651 		cc = cc * 8 + nc - '0';
5652 	    }
5653 	    else
5654 	    {
5655 		if (!VIM_ISDIGIT(nc))
5656 		    break;
5657 		cc = cc * 10 + nc - '0';
5658 	    }
5659 
5660 	    ++i;
5661 	}
5662 
5663 	if (cc > 255
5664 #ifdef FEAT_MBYTE
5665 		&& unicode == 0
5666 #endif
5667 		)
5668 	    cc = 255;		/* limit range to 0-255 */
5669 	nc = 0;
5670 
5671 	if (hex)		/* hex: up to two chars */
5672 	{
5673 	    if (i >= 2)
5674 		break;
5675 	}
5676 #ifdef FEAT_MBYTE
5677 	else if (unicode)	/* Unicode: up to four or eight chars */
5678 	{
5679 	    if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
5680 		break;
5681 	}
5682 #endif
5683 	else if (i >= 3)	/* decimal or octal: up to three chars */
5684 	    break;
5685     }
5686     if (i == 0)	    /* no number entered */
5687     {
5688 	if (nc == K_ZERO)   /* NUL is stored as NL */
5689 	{
5690 	    cc = '\n';
5691 	    nc = 0;
5692 	}
5693 	else
5694 	{
5695 	    cc = nc;
5696 	    nc = 0;
5697 	}
5698     }
5699 
5700     if (cc == 0)	/* NUL is stored as NL */
5701 	cc = '\n';
5702 #ifdef FEAT_MBYTE
5703     if (enc_dbcs && (cc & 0xff) == 0)
5704 	cc = '?';	/* don't accept an illegal DBCS char, the NUL in the
5705 			   second byte will cause trouble! */
5706 #endif
5707 
5708     --no_mapping;
5709 #ifdef FEAT_GUI
5710     if (gui.in_use)
5711 	--allow_keys;
5712 #endif
5713     if (nc)
5714 	vungetc(nc);
5715     got_int = FALSE;	    /* CTRL-C typed after CTRL-V is not an interrupt */
5716     return cc;
5717 }
5718 
5719 /*
5720  * Insert character, taking care of special keys and mod_mask
5721  */
5722     static void
5723 insert_special(c, allow_modmask, ctrlv)
5724     int	    c;
5725     int	    allow_modmask;
5726     int	    ctrlv;	    /* c was typed after CTRL-V */
5727 {
5728     char_u  *p;
5729     int	    len;
5730 
5731     /*
5732      * Special function key, translate into "<Key>". Up to the last '>' is
5733      * inserted with ins_str(), so as not to replace characters in replace
5734      * mode.
5735      * Only use mod_mask for special keys, to avoid things like <S-Space>,
5736      * unless 'allow_modmask' is TRUE.
5737      */
5738 #ifdef MACOS
5739     /* Command-key never produces a normal key */
5740     if (mod_mask & MOD_MASK_CMD)
5741 	allow_modmask = TRUE;
5742 #endif
5743     if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5744     {
5745 	p = get_special_key_name(c, mod_mask);
5746 	len = (int)STRLEN(p);
5747 	c = p[len - 1];
5748 	if (len > 2)
5749 	{
5750 	    if (stop_arrow() == FAIL)
5751 		return;
5752 	    p[len - 1] = NUL;
5753 	    ins_str(p);
5754 	    AppendToRedobuffLit(p, -1);
5755 	    ctrlv = FALSE;
5756 	}
5757     }
5758     if (stop_arrow() == OK)
5759 	insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5760 }
5761 
5762 /*
5763  * Special characters in this context are those that need processing other
5764  * than the simple insertion that can be performed here. This includes ESC
5765  * which terminates the insert, and CR/NL which need special processing to
5766  * open up a new line. This routine tries to optimize insertions performed by
5767  * the "redo", "undo" or "put" commands, so it needs to know when it should
5768  * stop and defer processing to the "normal" mechanism.
5769  * '0' and '^' are special, because they can be followed by CTRL-D.
5770  */
5771 #ifdef EBCDIC
5772 # define ISSPECIAL(c)	((c) < ' ' || (c) == '0' || (c) == '^')
5773 #else
5774 # define ISSPECIAL(c)	((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5775 #endif
5776 
5777 #ifdef FEAT_MBYTE
5778 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5779 #else
5780 # define WHITECHAR(cc) vim_iswhite(cc)
5781 #endif
5782 
5783 /*
5784  * "flags": INSCHAR_FORMAT - force formatting
5785  *	    INSCHAR_CTRLV  - char typed just after CTRL-V
5786  *	    INSCHAR_NO_FEX - don't use 'formatexpr'
5787  *
5788  *   NOTE: passes the flags value straight through to internal_format() which,
5789  *	   beside INSCHAR_FORMAT (above), is also looking for these:
5790  *	    INSCHAR_DO_COM   - format comments
5791  *	    INSCHAR_COM_LIST - format comments with num list or 2nd line indent
5792  */
5793     void
5794 insertchar(c, flags, second_indent)
5795     int		c;			/* character to insert or NUL */
5796     int		flags;			/* INSCHAR_FORMAT, etc. */
5797     int		second_indent;		/* indent for second line if >= 0 */
5798 {
5799     int		textwidth;
5800 #ifdef FEAT_COMMENTS
5801     char_u	*p;
5802 #endif
5803     int		fo_ins_blank;
5804 
5805     textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5806     fo_ins_blank = has_format_option(FO_INS_BLANK);
5807 
5808     /*
5809      * Try to break the line in two or more pieces when:
5810      * - Always do this if we have been called to do formatting only.
5811      * - Always do this when 'formatoptions' has the 'a' flag and the line
5812      *   ends in white space.
5813      * - Otherwise:
5814      *	 - Don't do this if inserting a blank
5815      *	 - Don't do this if an existing character is being replaced, unless
5816      *	   we're in VREPLACE mode.
5817      *	 - Do this if the cursor is not on the line where insert started
5818      *	 or - 'formatoptions' doesn't have 'l' or the line was not too long
5819      *	       before the insert.
5820      *	    - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5821      *	      before 'textwidth'
5822      */
5823     if (textwidth > 0
5824 	    && ((flags & INSCHAR_FORMAT)
5825 		|| (!vim_iswhite(c)
5826 		    && !((State & REPLACE_FLAG)
5827 #ifdef FEAT_VREPLACE
5828 			&& !(State & VREPLACE_FLAG)
5829 #endif
5830 			&& *ml_get_cursor() != NUL)
5831 		    && (curwin->w_cursor.lnum != Insstart.lnum
5832 			|| ((!has_format_option(FO_INS_LONG)
5833 				|| Insstart_textlen <= (colnr_T)textwidth)
5834 			    && (!fo_ins_blank
5835 				|| Insstart_blank_vcol <= (colnr_T)textwidth
5836 			    ))))))
5837     {
5838 	/* Format with 'formatexpr' when it's set.  Use internal formatting
5839 	 * when 'formatexpr' isn't set or it returns non-zero. */
5840 #if defined(FEAT_EVAL)
5841 	int do_internal = TRUE;
5842 
5843 	if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0)
5844 	{
5845 	    do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0);
5846 	    /* It may be required to save for undo again, e.g. when setline()
5847 	     * was called. */
5848 	    ins_need_undo = TRUE;
5849 	}
5850 	if (do_internal)
5851 #endif
5852 	    internal_format(textwidth, second_indent, flags, c == NUL, c);
5853     }
5854 
5855     if (c == NUL)	    /* only formatting was wanted */
5856 	return;
5857 
5858 #ifdef FEAT_COMMENTS
5859     /* Check whether this character should end a comment. */
5860     if (did_ai && (int)c == end_comment_pending)
5861     {
5862 	char_u  *line;
5863 	char_u	lead_end[COM_MAX_LEN];	    /* end-comment string */
5864 	int	middle_len, end_len;
5865 	int	i;
5866 
5867 	/*
5868 	 * Need to remove existing (middle) comment leader and insert end
5869 	 * comment leader.  First, check what comment leader we can find.
5870 	 */
5871 	i = get_leader_len(line = ml_get_curline(), &p, FALSE, TRUE);
5872 	if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL)	/* Just checking */
5873 	{
5874 	    /* Skip middle-comment string */
5875 	    while (*p && p[-1] != ':')	/* find end of middle flags */
5876 		++p;
5877 	    middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5878 	    /* Don't count trailing white space for middle_len */
5879 	    while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5880 		--middle_len;
5881 
5882 	    /* Find the end-comment string */
5883 	    while (*p && p[-1] != ':')	/* find end of end flags */
5884 		++p;
5885 	    end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5886 
5887 	    /* Skip white space before the cursor */
5888 	    i = curwin->w_cursor.col;
5889 	    while (--i >= 0 && vim_iswhite(line[i]))
5890 		;
5891 	    i++;
5892 
5893 	    /* Skip to before the middle leader */
5894 	    i -= middle_len;
5895 
5896 	    /* Check some expected things before we go on */
5897 	    if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5898 	    {
5899 		/* Backspace over all the stuff we want to replace */
5900 		backspace_until_column(i);
5901 
5902 		/*
5903 		 * Insert the end-comment string, except for the last
5904 		 * character, which will get inserted as normal later.
5905 		 */
5906 		ins_bytes_len(lead_end, end_len - 1);
5907 	    }
5908 	}
5909     }
5910     end_comment_pending = NUL;
5911 #endif
5912 
5913     did_ai = FALSE;
5914 #ifdef FEAT_SMARTINDENT
5915     did_si = FALSE;
5916     can_si = FALSE;
5917     can_si_back = FALSE;
5918 #endif
5919 
5920     /*
5921      * If there's any pending input, grab up to INPUT_BUFLEN at once.
5922      * This speeds up normal text input considerably.
5923      * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5924      * need to re-indent at a ':', or any other character (but not what
5925      * 'paste' is set)..
5926      * Don't do this when there an InsertCharPre autocommand is defined,
5927      * because we need to fire the event for every character.
5928      */
5929 #ifdef USE_ON_FLY_SCROLL
5930     dont_scroll = FALSE;		/* allow scrolling here */
5931 #endif
5932 
5933     if (       !ISSPECIAL(c)
5934 #ifdef FEAT_MBYTE
5935 	    && (!has_mbyte || (*mb_char2len)(c) == 1)
5936 #endif
5937 	    && vpeekc() != NUL
5938 	    && !(State & REPLACE_FLAG)
5939 #ifdef FEAT_CINDENT
5940 	    && !cindent_on()
5941 #endif
5942 #ifdef FEAT_RIGHTLEFT
5943 	    && !p_ri
5944 #endif
5945 #ifdef FEAT_AUTOCMD
5946 	    && !has_insertcharpre()
5947 #endif
5948 	       )
5949     {
5950 #define INPUT_BUFLEN 100
5951 	char_u		buf[INPUT_BUFLEN + 1];
5952 	int		i;
5953 	colnr_T		virtcol = 0;
5954 
5955 	buf[0] = c;
5956 	i = 1;
5957 	if (textwidth > 0)
5958 	    virtcol = get_nolist_virtcol();
5959 	/*
5960 	 * Stop the string when:
5961 	 * - no more chars available
5962 	 * - finding a special character (command key)
5963 	 * - buffer is full
5964 	 * - running into the 'textwidth' boundary
5965 	 * - need to check for abbreviation: A non-word char after a word-char
5966 	 */
5967 	while (	   (c = vpeekc()) != NUL
5968 		&& !ISSPECIAL(c)
5969 #ifdef FEAT_MBYTE
5970 		&& (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5971 #endif
5972 		&& i < INPUT_BUFLEN
5973 		&& (textwidth == 0
5974 		    || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5975 		&& !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5976 	{
5977 #ifdef FEAT_RIGHTLEFT
5978 	    c = vgetc();
5979 	    if (p_hkmap && KeyTyped)
5980 		c = hkmap(c);		    /* Hebrew mode mapping */
5981 # ifdef FEAT_FKMAP
5982 	    if (p_fkmap && KeyTyped)
5983 		c = fkmap(c);		    /* Farsi mode mapping */
5984 # endif
5985 	    buf[i++] = c;
5986 #else
5987 	    buf[i++] = vgetc();
5988 #endif
5989 	}
5990 
5991 #ifdef FEAT_DIGRAPHS
5992 	do_digraph(-1);			/* clear digraphs */
5993 	do_digraph(buf[i-1]);		/* may be the start of a digraph */
5994 #endif
5995 	buf[i] = NUL;
5996 	ins_str(buf);
5997 	if (flags & INSCHAR_CTRLV)
5998 	{
5999 	    redo_literal(*buf);
6000 	    i = 1;
6001 	}
6002 	else
6003 	    i = 0;
6004 	if (buf[i] != NUL)
6005 	    AppendToRedobuffLit(buf + i, -1);
6006     }
6007     else
6008     {
6009 #ifdef FEAT_MBYTE
6010 	int		cc;
6011 
6012 	if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
6013 	{
6014 	    char_u	buf[MB_MAXBYTES + 1];
6015 
6016 	    (*mb_char2bytes)(c, buf);
6017 	    buf[cc] = NUL;
6018 	    ins_char_bytes(buf, cc);
6019 	    AppendCharToRedobuff(c);
6020 	}
6021 	else
6022 #endif
6023 	{
6024 	    ins_char(c);
6025 	    if (flags & INSCHAR_CTRLV)
6026 		redo_literal(c);
6027 	    else
6028 		AppendCharToRedobuff(c);
6029 	}
6030     }
6031 }
6032 
6033 /*
6034  * Format text at the current insert position.
6035  *
6036  * If the INSCHAR_COM_LIST flag is present, then the value of second_indent
6037  * will be the comment leader length sent to open_line().
6038  */
6039     static void
6040 internal_format(textwidth, second_indent, flags, format_only, c)
6041     int		textwidth;
6042     int		second_indent;
6043     int		flags;
6044     int		format_only;
6045     int		c; /* character to be inserted (can be NUL) */
6046 {
6047     int		cc;
6048     int		save_char = NUL;
6049     int		haveto_redraw = FALSE;
6050     int		fo_ins_blank = has_format_option(FO_INS_BLANK);
6051 #ifdef FEAT_MBYTE
6052     int		fo_multibyte = has_format_option(FO_MBYTE_BREAK);
6053 #endif
6054     int		fo_white_par = has_format_option(FO_WHITE_PAR);
6055     int		first_line = TRUE;
6056 #ifdef FEAT_COMMENTS
6057     colnr_T	leader_len;
6058     int		no_leader = FALSE;
6059     int		do_comments = (flags & INSCHAR_DO_COM);
6060 #endif
6061 
6062     /*
6063      * When 'ai' is off we don't want a space under the cursor to be
6064      * deleted.  Replace it with an 'x' temporarily.
6065      */
6066     if (!curbuf->b_p_ai
6067 #ifdef FEAT_VREPLACE
6068 	    && !(State & VREPLACE_FLAG)
6069 #endif
6070 	    )
6071     {
6072 	cc = gchar_cursor();
6073 	if (vim_iswhite(cc))
6074 	{
6075 	    save_char = cc;
6076 	    pchar_cursor('x');
6077 	}
6078     }
6079 
6080     /*
6081      * Repeat breaking lines, until the current line is not too long.
6082      */
6083     while (!got_int)
6084     {
6085 	int	startcol;		/* Cursor column at entry */
6086 	int	wantcol;		/* column at textwidth border */
6087 	int	foundcol;		/* column for start of spaces */
6088 	int	end_foundcol = 0;	/* column for start of word */
6089 	colnr_T	len;
6090 	colnr_T	virtcol;
6091 #ifdef FEAT_VREPLACE
6092 	int	orig_col = 0;
6093 	char_u	*saved_text = NULL;
6094 #endif
6095 	colnr_T	col;
6096 	colnr_T	end_col;
6097 
6098 	virtcol = get_nolist_virtcol()
6099 		+ char2cells(c != NUL ? c : gchar_cursor());
6100 	if (virtcol <= (colnr_T)textwidth)
6101 	    break;
6102 
6103 #ifdef FEAT_COMMENTS
6104 	if (no_leader)
6105 	    do_comments = FALSE;
6106 	else if (!(flags & INSCHAR_FORMAT)
6107 				       && has_format_option(FO_WRAP_COMS))
6108 	    do_comments = TRUE;
6109 
6110 	/* Don't break until after the comment leader */
6111 	if (do_comments)
6112 	    leader_len = get_leader_len(ml_get_curline(), NULL, FALSE, TRUE);
6113 	else
6114 	    leader_len = 0;
6115 
6116 	/* If the line doesn't start with a comment leader, then don't
6117 	 * start one in a following broken line.  Avoids that a %word
6118 	 * moved to the start of the next line causes all following lines
6119 	 * to start with %. */
6120 	if (leader_len == 0)
6121 	    no_leader = TRUE;
6122 #endif
6123 	if (!(flags & INSCHAR_FORMAT)
6124 #ifdef FEAT_COMMENTS
6125 		&& leader_len == 0
6126 #endif
6127 		&& !has_format_option(FO_WRAP))
6128 
6129 	    break;
6130 	if ((startcol = curwin->w_cursor.col) == 0)
6131 	    break;
6132 
6133 	/* find column of textwidth border */
6134 	coladvance((colnr_T)textwidth);
6135 	wantcol = curwin->w_cursor.col;
6136 
6137 	curwin->w_cursor.col = startcol;
6138 	foundcol = 0;
6139 
6140 	/*
6141 	 * Find position to break at.
6142 	 * Stop at first entered white when 'formatoptions' has 'v'
6143 	 */
6144 	while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
6145 		    || (flags & INSCHAR_FORMAT)
6146 		    || curwin->w_cursor.lnum != Insstart.lnum
6147 		    || curwin->w_cursor.col >= Insstart.col)
6148 	{
6149 	    if (curwin->w_cursor.col == startcol && c != NUL)
6150 		cc = c;
6151 	    else
6152 		cc = gchar_cursor();
6153 	    if (WHITECHAR(cc))
6154 	    {
6155 		/* remember position of blank just before text */
6156 		end_col = curwin->w_cursor.col;
6157 
6158 		/* find start of sequence of blanks */
6159 		while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
6160 		{
6161 		    dec_cursor();
6162 		    cc = gchar_cursor();
6163 		}
6164 		if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
6165 		    break;		/* only spaces in front of text */
6166 #ifdef FEAT_COMMENTS
6167 		/* Don't break until after the comment leader */
6168 		if (curwin->w_cursor.col < leader_len)
6169 		    break;
6170 #endif
6171 		if (has_format_option(FO_ONE_LETTER))
6172 		{
6173 		    /* do not break after one-letter words */
6174 		    if (curwin->w_cursor.col == 0)
6175 			break;	/* one-letter word at begin */
6176 #ifdef FEAT_COMMENTS
6177 		    /* do not break "#a b" when 'tw' is 2 */
6178 		    if (curwin->w_cursor.col <= leader_len)
6179 			break;
6180 #endif
6181 		    col = curwin->w_cursor.col;
6182 		    dec_cursor();
6183 		    cc = gchar_cursor();
6184 
6185 		    if (WHITECHAR(cc))
6186 			continue;	/* one-letter, continue */
6187 		    curwin->w_cursor.col = col;
6188 		}
6189 
6190 		inc_cursor();
6191 
6192 		end_foundcol = end_col + 1;
6193 		foundcol = curwin->w_cursor.col;
6194 		if (curwin->w_cursor.col <= (colnr_T)wantcol)
6195 		    break;
6196 	    }
6197 #ifdef FEAT_MBYTE
6198 	    else if (cc >= 0x100 && fo_multibyte)
6199 	    {
6200 		/* Break after or before a multi-byte character. */
6201 		if (curwin->w_cursor.col != startcol)
6202 		{
6203 #ifdef FEAT_COMMENTS
6204 		    /* Don't break until after the comment leader */
6205 		    if (curwin->w_cursor.col < leader_len)
6206 			break;
6207 #endif
6208 		    col = curwin->w_cursor.col;
6209 		    inc_cursor();
6210 		    /* Don't change end_foundcol if already set. */
6211 		    if (foundcol != curwin->w_cursor.col)
6212 		    {
6213 			foundcol = curwin->w_cursor.col;
6214 			end_foundcol = foundcol;
6215 			if (curwin->w_cursor.col <= (colnr_T)wantcol)
6216 			    break;
6217 		    }
6218 		    curwin->w_cursor.col = col;
6219 		}
6220 
6221 		if (curwin->w_cursor.col == 0)
6222 		    break;
6223 
6224 		col = curwin->w_cursor.col;
6225 
6226 		dec_cursor();
6227 		cc = gchar_cursor();
6228 
6229 		if (WHITECHAR(cc))
6230 		    continue;		/* break with space */
6231 #ifdef FEAT_COMMENTS
6232 		/* Don't break until after the comment leader */
6233 		if (curwin->w_cursor.col < leader_len)
6234 		    break;
6235 #endif
6236 
6237 		curwin->w_cursor.col = col;
6238 
6239 		foundcol = curwin->w_cursor.col;
6240 		end_foundcol = foundcol;
6241 		if (curwin->w_cursor.col <= (colnr_T)wantcol)
6242 		    break;
6243 	    }
6244 #endif
6245 	    if (curwin->w_cursor.col == 0)
6246 		break;
6247 	    dec_cursor();
6248 	}
6249 
6250 	if (foundcol == 0)		/* no spaces, cannot break line */
6251 	{
6252 	    curwin->w_cursor.col = startcol;
6253 	    break;
6254 	}
6255 
6256 	/* Going to break the line, remove any "$" now. */
6257 	undisplay_dollar();
6258 
6259 	/*
6260 	 * Offset between cursor position and line break is used by replace
6261 	 * stack functions.  VREPLACE does not use this, and backspaces
6262 	 * over the text instead.
6263 	 */
6264 #ifdef FEAT_VREPLACE
6265 	if (State & VREPLACE_FLAG)
6266 	    orig_col = startcol;	/* Will start backspacing from here */
6267 	else
6268 #endif
6269 	    replace_offset = startcol - end_foundcol;
6270 
6271 	/*
6272 	 * adjust startcol for spaces that will be deleted and
6273 	 * characters that will remain on top line
6274 	 */
6275 	curwin->w_cursor.col = foundcol;
6276 	while ((cc = gchar_cursor(), WHITECHAR(cc))
6277 		    && (!fo_white_par || curwin->w_cursor.col < startcol))
6278 	    inc_cursor();
6279 	startcol -= curwin->w_cursor.col;
6280 	if (startcol < 0)
6281 	    startcol = 0;
6282 
6283 #ifdef FEAT_VREPLACE
6284 	if (State & VREPLACE_FLAG)
6285 	{
6286 	    /*
6287 	     * In VREPLACE mode, we will backspace over the text to be
6288 	     * wrapped, so save a copy now to put on the next line.
6289 	     */
6290 	    saved_text = vim_strsave(ml_get_cursor());
6291 	    curwin->w_cursor.col = orig_col;
6292 	    if (saved_text == NULL)
6293 		break;	/* Can't do it, out of memory */
6294 	    saved_text[startcol] = NUL;
6295 
6296 	    /* Backspace over characters that will move to the next line */
6297 	    if (!fo_white_par)
6298 		backspace_until_column(foundcol);
6299 	}
6300 	else
6301 #endif
6302 	{
6303 	    /* put cursor after pos. to break line */
6304 	    if (!fo_white_par)
6305 		curwin->w_cursor.col = foundcol;
6306 	}
6307 
6308 	/*
6309 	 * Split the line just before the margin.
6310 	 * Only insert/delete lines, but don't really redraw the window.
6311 	 */
6312 	open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
6313 		+ (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
6314 #ifdef FEAT_COMMENTS
6315 		+ (do_comments ? OPENLINE_DO_COM : 0)
6316 		+ ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0)
6317 #endif
6318 		, ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent));
6319 	if (!(flags & INSCHAR_COM_LIST))
6320 	    old_indent = 0;
6321 
6322 	replace_offset = 0;
6323 	if (first_line)
6324 	{
6325 	    if (!(flags & INSCHAR_COM_LIST))
6326 	    {
6327 		/*
6328 		 * This section is for auto-wrap of numeric lists.  When not
6329 		 * in insert mode (i.e. format_lines()), the INSCHAR_COM_LIST
6330 		 * flag will be set and open_line() will handle it (as seen
6331 		 * above).  The code here (and in get_number_indent()) will
6332 		 * recognize comments if needed...
6333 		 */
6334 		if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
6335 		    second_indent =
6336 				 get_number_indent(curwin->w_cursor.lnum - 1);
6337 		if (second_indent >= 0)
6338 		{
6339 #ifdef FEAT_VREPLACE
6340 		    if (State & VREPLACE_FLAG)
6341 			change_indent(INDENT_SET, second_indent,
6342 							    FALSE, NUL, TRUE);
6343 		    else
6344 #endif
6345 #ifdef FEAT_COMMENTS
6346 			if (leader_len > 0 && second_indent - leader_len > 0)
6347 		    {
6348 			int i;
6349 			int padding = second_indent - leader_len;
6350 
6351 			/* We started at the first_line of a numbered list
6352 			 * that has a comment.  the open_line() function has
6353 			 * inserted the proper comment leader and positioned
6354 			 * the cursor at the end of the split line.  Now we
6355 			 * add the additional whitespace needed after the
6356 			 * comment leader for the numbered list.  */
6357 			for (i = 0; i < padding; i++)
6358 			    ins_str((char_u *)" ");
6359 			changed_bytes(curwin->w_cursor.lnum, leader_len);
6360 		    }
6361 		    else
6362 		    {
6363 #endif
6364 			(void)set_indent(second_indent, SIN_CHANGED);
6365 #ifdef FEAT_COMMENTS
6366 		    }
6367 #endif
6368 		}
6369 	    }
6370 	    first_line = FALSE;
6371 	}
6372 
6373 #ifdef FEAT_VREPLACE
6374 	if (State & VREPLACE_FLAG)
6375 	{
6376 	    /*
6377 	     * In VREPLACE mode we have backspaced over the text to be
6378 	     * moved, now we re-insert it into the new line.
6379 	     */
6380 	    ins_bytes(saved_text);
6381 	    vim_free(saved_text);
6382 	}
6383 	else
6384 #endif
6385 	{
6386 	    /*
6387 	     * Check if cursor is not past the NUL off the line, cindent
6388 	     * may have added or removed indent.
6389 	     */
6390 	    curwin->w_cursor.col += startcol;
6391 	    len = (colnr_T)STRLEN(ml_get_curline());
6392 	    if (curwin->w_cursor.col > len)
6393 		curwin->w_cursor.col = len;
6394 	}
6395 
6396 	haveto_redraw = TRUE;
6397 #ifdef FEAT_CINDENT
6398 	can_cindent = TRUE;
6399 #endif
6400 	/* moved the cursor, don't autoindent or cindent now */
6401 	did_ai = FALSE;
6402 #ifdef FEAT_SMARTINDENT
6403 	did_si = FALSE;
6404 	can_si = FALSE;
6405 	can_si_back = FALSE;
6406 #endif
6407 	line_breakcheck();
6408     }
6409 
6410     if (save_char != NUL)		/* put back space after cursor */
6411 	pchar_cursor(save_char);
6412 
6413     if (!format_only && haveto_redraw)
6414     {
6415 	update_topline();
6416 	redraw_curbuf_later(VALID);
6417     }
6418 }
6419 
6420 /*
6421  * Called after inserting or deleting text: When 'formatoptions' includes the
6422  * 'a' flag format from the current line until the end of the paragraph.
6423  * Keep the cursor at the same position relative to the text.
6424  * The caller must have saved the cursor line for undo, following ones will be
6425  * saved here.
6426  */
6427     void
6428 auto_format(trailblank, prev_line)
6429     int		trailblank;	/* when TRUE also format with trailing blank */
6430     int		prev_line;	/* may start in previous line */
6431 {
6432     pos_T	pos;
6433     colnr_T	len;
6434     char_u	*old;
6435     char_u	*new, *pnew;
6436     int		wasatend;
6437     int		cc;
6438 
6439     if (!has_format_option(FO_AUTO))
6440 	return;
6441 
6442     pos = curwin->w_cursor;
6443     old = ml_get_curline();
6444 
6445     /* may remove added space */
6446     check_auto_format(FALSE);
6447 
6448     /* Don't format in Insert mode when the cursor is on a trailing blank, the
6449      * user might insert normal text next.  Also skip formatting when "1" is
6450      * in 'formatoptions' and there is a single character before the cursor.
6451      * Otherwise the line would be broken and when typing another non-white
6452      * next they are not joined back together. */
6453     wasatend = (pos.col == (colnr_T)STRLEN(old));
6454     if (*old != NUL && !trailblank && wasatend)
6455     {
6456 	dec_cursor();
6457 	cc = gchar_cursor();
6458 	if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
6459 					  && has_format_option(FO_ONE_LETTER))
6460 	    dec_cursor();
6461 	cc = gchar_cursor();
6462 	if (WHITECHAR(cc))
6463 	{
6464 	    curwin->w_cursor = pos;
6465 	    return;
6466 	}
6467 	curwin->w_cursor = pos;
6468     }
6469 
6470 #ifdef FEAT_COMMENTS
6471     /* With the 'c' flag in 'formatoptions' and 't' missing: only format
6472      * comments. */
6473     if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
6474 				     && get_leader_len(old, NULL, FALSE, TRUE) == 0)
6475 	return;
6476 #endif
6477 
6478     /*
6479      * May start formatting in a previous line, so that after "x" a word is
6480      * moved to the previous line if it fits there now.  Only when this is not
6481      * the start of a paragraph.
6482      */
6483     if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
6484     {
6485 	--curwin->w_cursor.lnum;
6486 	if (u_save_cursor() == FAIL)
6487 	    return;
6488     }
6489 
6490     /*
6491      * Do the formatting and restore the cursor position.  "saved_cursor" will
6492      * be adjusted for the text formatting.
6493      */
6494     saved_cursor = pos;
6495     format_lines((linenr_T)-1, FALSE);
6496     curwin->w_cursor = saved_cursor;
6497     saved_cursor.lnum = 0;
6498 
6499     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6500     {
6501 	/* "cannot happen" */
6502 	curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6503 	coladvance((colnr_T)MAXCOL);
6504     }
6505     else
6506 	check_cursor_col();
6507 
6508     /* Insert mode: If the cursor is now after the end of the line while it
6509      * previously wasn't, the line was broken.  Because of the rule above we
6510      * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
6511      * formatted. */
6512     if (!wasatend && has_format_option(FO_WHITE_PAR))
6513     {
6514 	new = ml_get_curline();
6515 	len = (colnr_T)STRLEN(new);
6516 	if (curwin->w_cursor.col == len)
6517 	{
6518 	    pnew = vim_strnsave(new, len + 2);
6519 	    pnew[len] = ' ';
6520 	    pnew[len + 1] = NUL;
6521 	    ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
6522 	    /* remove the space later */
6523 	    did_add_space = TRUE;
6524 	}
6525 	else
6526 	    /* may remove added space */
6527 	    check_auto_format(FALSE);
6528     }
6529 
6530     check_cursor();
6531 }
6532 
6533 /*
6534  * When an extra space was added to continue a paragraph for auto-formatting,
6535  * delete it now.  The space must be under the cursor, just after the insert
6536  * position.
6537  */
6538     static void
6539 check_auto_format(end_insert)
6540     int		end_insert;	    /* TRUE when ending Insert mode */
6541 {
6542     int		c = ' ';
6543     int		cc;
6544 
6545     if (did_add_space)
6546     {
6547 	cc = gchar_cursor();
6548 	if (!WHITECHAR(cc))
6549 	    /* Somehow the space was removed already. */
6550 	    did_add_space = FALSE;
6551 	else
6552 	{
6553 	    if (!end_insert)
6554 	    {
6555 		inc_cursor();
6556 		c = gchar_cursor();
6557 		dec_cursor();
6558 	    }
6559 	    if (c != NUL)
6560 	    {
6561 		/* The space is no longer at the end of the line, delete it. */
6562 		del_char(FALSE);
6563 		did_add_space = FALSE;
6564 	    }
6565 	}
6566     }
6567 }
6568 
6569 /*
6570  * Find out textwidth to be used for formatting:
6571  *	if 'textwidth' option is set, use it
6572  *	else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
6573  *	if invalid value, use 0.
6574  *	Set default to window width (maximum 79) for "gq" operator.
6575  */
6576     int
6577 comp_textwidth(ff)
6578     int		ff;	/* force formatting (for "gq" command) */
6579 {
6580     int		textwidth;
6581 
6582     textwidth = curbuf->b_p_tw;
6583     if (textwidth == 0 && curbuf->b_p_wm)
6584     {
6585 	/* The width is the window width minus 'wrapmargin' minus all the
6586 	 * things that add to the margin. */
6587 	textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
6588 #ifdef FEAT_CMDWIN
6589 	if (cmdwin_type != 0)
6590 	    textwidth -= 1;
6591 #endif
6592 #ifdef FEAT_FOLDING
6593 	textwidth -= curwin->w_p_fdc;
6594 #endif
6595 #ifdef FEAT_SIGNS
6596 	if (curwin->w_buffer->b_signlist != NULL
6597 # ifdef FEAT_NETBEANS_INTG
6598 			    || netbeans_active()
6599 # endif
6600 		    )
6601 	    textwidth -= 1;
6602 #endif
6603 	if (curwin->w_p_nu || curwin->w_p_rnu)
6604 	    textwidth -= 8;
6605     }
6606     if (textwidth < 0)
6607 	textwidth = 0;
6608     if (ff && textwidth == 0)
6609     {
6610 	textwidth = W_WIDTH(curwin) - 1;
6611 	if (textwidth > 79)
6612 	    textwidth = 79;
6613     }
6614     return textwidth;
6615 }
6616 
6617 /*
6618  * Put a character in the redo buffer, for when just after a CTRL-V.
6619  */
6620     static void
6621 redo_literal(c)
6622     int	    c;
6623 {
6624     char_u	buf[10];
6625 
6626     /* Only digits need special treatment.  Translate them into a string of
6627      * three digits. */
6628     if (VIM_ISDIGIT(c))
6629     {
6630 	vim_snprintf((char *)buf, sizeof(buf), "%03d", c);
6631 	AppendToRedobuff(buf);
6632     }
6633     else
6634 	AppendCharToRedobuff(c);
6635 }
6636 
6637 /*
6638  * start_arrow() is called when an arrow key is used in insert mode.
6639  * For undo/redo it resembles hitting the <ESC> key.
6640  */
6641     static void
6642 start_arrow(end_insert_pos)
6643     pos_T    *end_insert_pos;	    /* can be NULL */
6644 {
6645     if (!arrow_used)	    /* something has been inserted */
6646     {
6647 	AppendToRedobuff(ESC_STR);
6648 	stop_insert(end_insert_pos, FALSE);
6649 	arrow_used = TRUE;	/* this means we stopped the current insert */
6650     }
6651 #ifdef FEAT_SPELL
6652     check_spell_redraw();
6653 #endif
6654 }
6655 
6656 #ifdef FEAT_SPELL
6657 /*
6658  * If we skipped highlighting word at cursor, do it now.
6659  * It may be skipped again, thus reset spell_redraw_lnum first.
6660  */
6661     static void
6662 check_spell_redraw()
6663 {
6664     if (spell_redraw_lnum != 0)
6665     {
6666 	linenr_T	lnum = spell_redraw_lnum;
6667 
6668 	spell_redraw_lnum = 0;
6669 	redrawWinline(lnum, FALSE);
6670     }
6671 }
6672 
6673 /*
6674  * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6675  * spelled word, if there is one.
6676  */
6677     static void
6678 spell_back_to_badword()
6679 {
6680     pos_T	tpos = curwin->w_cursor;
6681 
6682     spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
6683     if (curwin->w_cursor.col != tpos.col)
6684 	start_arrow(&tpos);
6685 }
6686 #endif
6687 
6688 /*
6689  * stop_arrow() is called before a change is made in insert mode.
6690  * If an arrow key has been used, start a new insertion.
6691  * Returns FAIL if undo is impossible, shouldn't insert then.
6692  */
6693     int
6694 stop_arrow()
6695 {
6696     if (arrow_used)
6697     {
6698 	if (u_save_cursor() == OK)
6699 	{
6700 	    arrow_used = FALSE;
6701 	    ins_need_undo = FALSE;
6702 	}
6703 	Insstart = curwin->w_cursor;	/* new insertion starts here */
6704 	Insstart_textlen = (colnr_T)linetabsize(ml_get_curline());
6705 	ai_col = 0;
6706 #ifdef FEAT_VREPLACE
6707 	if (State & VREPLACE_FLAG)
6708 	{
6709 	    orig_line_count = curbuf->b_ml.ml_line_count;
6710 	    vr_lines_changed = 1;
6711 	}
6712 #endif
6713 	ResetRedobuff();
6714 	AppendToRedobuff((char_u *)"1i");   /* pretend we start an insertion */
6715 	new_insert_skip = 2;
6716     }
6717     else if (ins_need_undo)
6718     {
6719 	if (u_save_cursor() == OK)
6720 	    ins_need_undo = FALSE;
6721     }
6722 
6723 #ifdef FEAT_FOLDING
6724     /* Always open fold at the cursor line when inserting something. */
6725     foldOpenCursor();
6726 #endif
6727 
6728     return (arrow_used || ins_need_undo ? FAIL : OK);
6729 }
6730 
6731 /*
6732  * Do a few things to stop inserting.
6733  * "end_insert_pos" is where insert ended.  It is NULL when we already jumped
6734  * to another window/buffer.
6735  */
6736     static void
6737 stop_insert(end_insert_pos, esc)
6738     pos_T	*end_insert_pos;
6739     int		esc;			/* called by ins_esc() */
6740 {
6741     int		cc;
6742     char_u	*ptr;
6743 
6744     stop_redo_ins();
6745     replace_flush();		/* abandon replace stack */
6746 
6747     /*
6748      * Save the inserted text for later redo with ^@ and CTRL-A.
6749      * Don't do it when "restart_edit" was set and nothing was inserted,
6750      * otherwise CTRL-O w and then <Left> will clear "last_insert".
6751      */
6752     ptr = get_inserted();
6753     if (did_restart_edit == 0 || (ptr != NULL
6754 				       && (int)STRLEN(ptr) > new_insert_skip))
6755     {
6756 	vim_free(last_insert);
6757 	last_insert = ptr;
6758 	last_insert_skip = new_insert_skip;
6759     }
6760     else
6761 	vim_free(ptr);
6762 
6763     if (!arrow_used && end_insert_pos != NULL)
6764     {
6765 	/* Auto-format now.  It may seem strange to do this when stopping an
6766 	 * insertion (or moving the cursor), but it's required when appending
6767 	 * a line and having it end in a space.  But only do it when something
6768 	 * was actually inserted, otherwise undo won't work. */
6769 	if (!ins_need_undo && has_format_option(FO_AUTO))
6770 	{
6771 	    pos_T   tpos = curwin->w_cursor;
6772 
6773 	    /* When the cursor is at the end of the line after a space the
6774 	     * formatting will move it to the following word.  Avoid that by
6775 	     * moving the cursor onto the space. */
6776 	    cc = 'x';
6777 	    if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
6778 	    {
6779 		dec_cursor();
6780 		cc = gchar_cursor();
6781 		if (!vim_iswhite(cc))
6782 		    curwin->w_cursor = tpos;
6783 	    }
6784 
6785 	    auto_format(TRUE, FALSE);
6786 
6787 	    if (vim_iswhite(cc))
6788 	    {
6789 		if (gchar_cursor() != NUL)
6790 		    inc_cursor();
6791 #ifdef FEAT_VIRTUALEDIT
6792 		/* If the cursor is still at the same character, also keep
6793 		 * the "coladd". */
6794 		if (gchar_cursor() == NUL
6795 			&& curwin->w_cursor.lnum == tpos.lnum
6796 			&& curwin->w_cursor.col == tpos.col)
6797 		    curwin->w_cursor.coladd = tpos.coladd;
6798 #endif
6799 	    }
6800 	}
6801 
6802 	/* If a space was inserted for auto-formatting, remove it now. */
6803 	check_auto_format(TRUE);
6804 
6805 	/* If we just did an auto-indent, remove the white space from the end
6806 	 * of the line, and put the cursor back.
6807 	 * Do this when ESC was used or moving the cursor up/down.
6808 	 * Check for the old position still being valid, just in case the text
6809 	 * got changed unexpectedly. */
6810 	if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6811 			&& curwin->w_cursor.lnum != end_insert_pos->lnum))
6812 		&& end_insert_pos->lnum <= curbuf->b_ml.ml_line_count)
6813 	{
6814 	    pos_T	tpos = curwin->w_cursor;
6815 
6816 	    curwin->w_cursor = *end_insert_pos;
6817 	    check_cursor_col();  /* make sure it is not past the line */
6818 	    for (;;)
6819 	    {
6820 		if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6821 		    --curwin->w_cursor.col;
6822 		cc = gchar_cursor();
6823 		if (!vim_iswhite(cc))
6824 		    break;
6825 		if (del_char(TRUE) == FAIL)
6826 		    break;  /* should not happen */
6827 	    }
6828 	    if (curwin->w_cursor.lnum != tpos.lnum)
6829 		curwin->w_cursor = tpos;
6830 	    else if (cc != NUL)
6831 		++curwin->w_cursor.col;	/* put cursor back on the NUL */
6832 
6833 #ifdef FEAT_VISUAL
6834 	    /* <C-S-Right> may have started Visual mode, adjust the position for
6835 	     * deleted characters. */
6836 	    if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6837 	    {
6838 		int len = (int)STRLEN(ml_get_curline());
6839 
6840 		if (VIsual.col > len)
6841 		{
6842 		    VIsual.col = len;
6843 # ifdef FEAT_VIRTUALEDIT
6844 		    VIsual.coladd = 0;
6845 # endif
6846 		}
6847 	    }
6848 #endif
6849 	}
6850     }
6851     did_ai = FALSE;
6852 #ifdef FEAT_SMARTINDENT
6853     did_si = FALSE;
6854     can_si = FALSE;
6855     can_si_back = FALSE;
6856 #endif
6857 
6858     /* Set '[ and '] to the inserted text.  When end_insert_pos is NULL we are
6859      * now in a different buffer. */
6860     if (end_insert_pos != NULL)
6861     {
6862 	curbuf->b_op_start = Insstart;
6863 	curbuf->b_op_end = *end_insert_pos;
6864     }
6865 }
6866 
6867 /*
6868  * Set the last inserted text to a single character.
6869  * Used for the replace command.
6870  */
6871     void
6872 set_last_insert(c)
6873     int		c;
6874 {
6875     char_u	*s;
6876 
6877     vim_free(last_insert);
6878     last_insert = alloc(MB_MAXBYTES * 3 + 5);
6879     if (last_insert != NULL)
6880     {
6881 	s = last_insert;
6882 	/* Use the CTRL-V only when entering a special char */
6883 	if (c < ' ' || c == DEL)
6884 	    *s++ = Ctrl_V;
6885 	s = add_char2buf(c, s);
6886 	*s++ = ESC;
6887 	*s++ = NUL;
6888 	last_insert_skip = 0;
6889     }
6890 }
6891 
6892 #if defined(EXITFREE) || defined(PROTO)
6893     void
6894 free_last_insert()
6895 {
6896     vim_free(last_insert);
6897     last_insert = NULL;
6898 # ifdef FEAT_INS_EXPAND
6899     vim_free(compl_orig_text);
6900     compl_orig_text = NULL;
6901 # endif
6902 }
6903 #endif
6904 
6905 /*
6906  * Add character "c" to buffer "s".  Escape the special meaning of K_SPECIAL
6907  * and CSI.  Handle multi-byte characters.
6908  * Returns a pointer to after the added bytes.
6909  */
6910     char_u *
6911 add_char2buf(c, s)
6912     int		c;
6913     char_u	*s;
6914 {
6915 #ifdef FEAT_MBYTE
6916     char_u	temp[MB_MAXBYTES + 1];
6917     int		i;
6918     int		len;
6919 
6920     len = (*mb_char2bytes)(c, temp);
6921     for (i = 0; i < len; ++i)
6922     {
6923 	c = temp[i];
6924 #endif
6925 	/* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6926 	if (c == K_SPECIAL)
6927 	{
6928 	    *s++ = K_SPECIAL;
6929 	    *s++ = KS_SPECIAL;
6930 	    *s++ = KE_FILLER;
6931 	}
6932 #ifdef FEAT_GUI
6933 	else if (c == CSI)
6934 	{
6935 	    *s++ = CSI;
6936 	    *s++ = KS_EXTRA;
6937 	    *s++ = (int)KE_CSI;
6938 	}
6939 #endif
6940 	else
6941 	    *s++ = c;
6942 #ifdef FEAT_MBYTE
6943     }
6944 #endif
6945     return s;
6946 }
6947 
6948 /*
6949  * move cursor to start of line
6950  * if flags & BL_WHITE	move to first non-white
6951  * if flags & BL_SOL	move to first non-white if startofline is set,
6952  *			    otherwise keep "curswant" column
6953  * if flags & BL_FIX	don't leave the cursor on a NUL.
6954  */
6955     void
6956 beginline(flags)
6957     int		flags;
6958 {
6959     if ((flags & BL_SOL) && !p_sol)
6960 	coladvance(curwin->w_curswant);
6961     else
6962     {
6963 	curwin->w_cursor.col = 0;
6964 #ifdef FEAT_VIRTUALEDIT
6965 	curwin->w_cursor.coladd = 0;
6966 #endif
6967 
6968 	if (flags & (BL_WHITE | BL_SOL))
6969 	{
6970 	    char_u  *ptr;
6971 
6972 	    for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6973 			       && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6974 		++curwin->w_cursor.col;
6975 	}
6976 	curwin->w_set_curswant = TRUE;
6977     }
6978 }
6979 
6980 /*
6981  * oneright oneleft cursor_down cursor_up
6982  *
6983  * Move one char {right,left,down,up}.
6984  * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6985  * Return OK when successful, FAIL when we hit a line of file boundary.
6986  */
6987 
6988     int
6989 oneright()
6990 {
6991     char_u	*ptr;
6992     int		l;
6993 
6994 #ifdef FEAT_VIRTUALEDIT
6995     if (virtual_active())
6996     {
6997 	pos_T	prevpos = curwin->w_cursor;
6998 
6999 	/* Adjust for multi-wide char (excluding TAB) */
7000 	ptr = ml_get_cursor();
7001 	coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
7002 # ifdef FEAT_MBYTE
7003 			    (*mb_ptr2char)(ptr)
7004 # else
7005 			    *ptr
7006 # endif
7007 			    ))
7008 		    ? ptr2cells(ptr) : 1));
7009 	curwin->w_set_curswant = TRUE;
7010 	/* Return OK if the cursor moved, FAIL otherwise (at window edge). */
7011 	return (prevpos.col != curwin->w_cursor.col
7012 		    || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
7013     }
7014 #endif
7015 
7016     ptr = ml_get_cursor();
7017     if (*ptr == NUL)
7018 	return FAIL;	    /* already at the very end */
7019 
7020 #ifdef FEAT_MBYTE
7021     if (has_mbyte)
7022 	l = (*mb_ptr2len)(ptr);
7023     else
7024 #endif
7025 	l = 1;
7026 
7027     /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
7028      * contains "onemore". */
7029     if (ptr[l] == NUL
7030 #ifdef FEAT_VIRTUALEDIT
7031 	    && (ve_flags & VE_ONEMORE) == 0
7032 #endif
7033 	    )
7034 	return FAIL;
7035     curwin->w_cursor.col += l;
7036 
7037     curwin->w_set_curswant = TRUE;
7038     return OK;
7039 }
7040 
7041     int
7042 oneleft()
7043 {
7044 #ifdef FEAT_VIRTUALEDIT
7045     if (virtual_active())
7046     {
7047 	int width;
7048 	int v = getviscol();
7049 
7050 	if (v == 0)
7051 	    return FAIL;
7052 
7053 # ifdef FEAT_LINEBREAK
7054 	/* We might get stuck on 'showbreak', skip over it. */
7055 	width = 1;
7056 	for (;;)
7057 	{
7058 	    coladvance(v - width);
7059 	    /* getviscol() is slow, skip it when 'showbreak' is empty and
7060 	     * there are no multi-byte characters */
7061 	    if ((*p_sbr == NUL
7062 #  ifdef FEAT_MBYTE
7063 			&& !has_mbyte
7064 #  endif
7065 			) || getviscol() < v)
7066 		break;
7067 	    ++width;
7068 	}
7069 # else
7070 	coladvance(v - 1);
7071 # endif
7072 
7073 	if (curwin->w_cursor.coladd == 1)
7074 	{
7075 	    char_u *ptr;
7076 
7077 	    /* Adjust for multi-wide char (not a TAB) */
7078 	    ptr = ml_get_cursor();
7079 	    if (*ptr != TAB && vim_isprintc(
7080 #  ifdef FEAT_MBYTE
7081 			    (*mb_ptr2char)(ptr)
7082 #  else
7083 			    *ptr
7084 #  endif
7085 			    ) && ptr2cells(ptr) > 1)
7086 		curwin->w_cursor.coladd = 0;
7087 	}
7088 
7089 	curwin->w_set_curswant = TRUE;
7090 	return OK;
7091     }
7092 #endif
7093 
7094     if (curwin->w_cursor.col == 0)
7095 	return FAIL;
7096 
7097     curwin->w_set_curswant = TRUE;
7098     --curwin->w_cursor.col;
7099 
7100 #ifdef FEAT_MBYTE
7101     /* if the character on the left of the current cursor is a multi-byte
7102      * character, move to its first byte */
7103     if (has_mbyte)
7104 	mb_adjust_cursor();
7105 #endif
7106     return OK;
7107 }
7108 
7109     int
7110 cursor_up(n, upd_topline)
7111     long	n;
7112     int		upd_topline;	    /* When TRUE: update topline */
7113 {
7114     linenr_T	lnum;
7115 
7116     if (n > 0)
7117     {
7118 	lnum = curwin->w_cursor.lnum;
7119 	/* This fails if the cursor is already in the first line or the count
7120 	 * is larger than the line number and '-' is in 'cpoptions' */
7121 	if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
7122 	    return FAIL;
7123 	if (n >= lnum)
7124 	    lnum = 1;
7125 	else
7126 #ifdef FEAT_FOLDING
7127 	    if (hasAnyFolding(curwin))
7128 	{
7129 	    /*
7130 	     * Count each sequence of folded lines as one logical line.
7131 	     */
7132 	    /* go to the the start of the current fold */
7133 	    (void)hasFolding(lnum, &lnum, NULL);
7134 
7135 	    while (n--)
7136 	    {
7137 		/* move up one line */
7138 		--lnum;
7139 		if (lnum <= 1)
7140 		    break;
7141 		/* If we entered a fold, move to the beginning, unless in
7142 		 * Insert mode or when 'foldopen' contains "all": it will open
7143 		 * in a moment. */
7144 		if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
7145 		    (void)hasFolding(lnum, &lnum, NULL);
7146 	    }
7147 	    if (lnum < 1)
7148 		lnum = 1;
7149 	}
7150 	else
7151 #endif
7152 	    lnum -= n;
7153 	curwin->w_cursor.lnum = lnum;
7154     }
7155 
7156     /* try to advance to the column we want to be at */
7157     coladvance(curwin->w_curswant);
7158 
7159     if (upd_topline)
7160 	update_topline();	/* make sure curwin->w_topline is valid */
7161 
7162     return OK;
7163 }
7164 
7165 /*
7166  * Cursor down a number of logical lines.
7167  */
7168     int
7169 cursor_down(n, upd_topline)
7170     long	n;
7171     int		upd_topline;	    /* When TRUE: update topline */
7172 {
7173     linenr_T	lnum;
7174 
7175     if (n > 0)
7176     {
7177 	lnum = curwin->w_cursor.lnum;
7178 #ifdef FEAT_FOLDING
7179 	/* Move to last line of fold, will fail if it's the end-of-file. */
7180 	(void)hasFolding(lnum, NULL, &lnum);
7181 #endif
7182 	/* This fails if the cursor is already in the last line or would move
7183 	 * beyound the last line and '-' is in 'cpoptions' */
7184 	if (lnum >= curbuf->b_ml.ml_line_count
7185 		|| (lnum + n > curbuf->b_ml.ml_line_count
7186 		    && vim_strchr(p_cpo, CPO_MINUS) != NULL))
7187 	    return FAIL;
7188 	if (lnum + n >= curbuf->b_ml.ml_line_count)
7189 	    lnum = curbuf->b_ml.ml_line_count;
7190 	else
7191 #ifdef FEAT_FOLDING
7192 	if (hasAnyFolding(curwin))
7193 	{
7194 	    linenr_T	last;
7195 
7196 	    /* count each sequence of folded lines as one logical line */
7197 	    while (n--)
7198 	    {
7199 		if (hasFolding(lnum, NULL, &last))
7200 		    lnum = last + 1;
7201 		else
7202 		    ++lnum;
7203 		if (lnum >= curbuf->b_ml.ml_line_count)
7204 		    break;
7205 	    }
7206 	    if (lnum > curbuf->b_ml.ml_line_count)
7207 		lnum = curbuf->b_ml.ml_line_count;
7208 	}
7209 	else
7210 #endif
7211 	    lnum += n;
7212 	curwin->w_cursor.lnum = lnum;
7213     }
7214 
7215     /* try to advance to the column we want to be at */
7216     coladvance(curwin->w_curswant);
7217 
7218     if (upd_topline)
7219 	update_topline();	/* make sure curwin->w_topline is valid */
7220 
7221     return OK;
7222 }
7223 
7224 /*
7225  * Stuff the last inserted text in the read buffer.
7226  * Last_insert actually is a copy of the redo buffer, so we
7227  * first have to remove the command.
7228  */
7229     int
7230 stuff_inserted(c, count, no_esc)
7231     int	    c;		/* Command character to be inserted */
7232     long    count;	/* Repeat this many times */
7233     int	    no_esc;	/* Don't add an ESC at the end */
7234 {
7235     char_u	*esc_ptr;
7236     char_u	*ptr;
7237     char_u	*last_ptr;
7238     char_u	last = NUL;
7239 
7240     ptr = get_last_insert();
7241     if (ptr == NULL)
7242     {
7243 	EMSG(_(e_noinstext));
7244 	return FAIL;
7245     }
7246 
7247     /* may want to stuff the command character, to start Insert mode */
7248     if (c != NUL)
7249 	stuffcharReadbuff(c);
7250     if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
7251 	*esc_ptr = NUL;	    /* remove the ESC */
7252 
7253     /* when the last char is either "0" or "^" it will be quoted if no ESC
7254      * comes after it OR if it will inserted more than once and "ptr"
7255      * starts with ^D.	-- Acevedo
7256      */
7257     last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
7258     if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
7259 	    && (no_esc || (*ptr == Ctrl_D && count > 1)))
7260     {
7261 	last = *last_ptr;
7262 	*last_ptr = NUL;
7263     }
7264 
7265     do
7266     {
7267 	stuffReadbuff(ptr);
7268 	/* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
7269 	if (last)
7270 	    stuffReadbuff((char_u *)(last == '0'
7271 			? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
7272 			: IF_EB("\026^", CTRL_V_STR "^")));
7273     }
7274     while (--count > 0);
7275 
7276     if (last)
7277 	*last_ptr = last;
7278 
7279     if (esc_ptr != NULL)
7280 	*esc_ptr = ESC;	    /* put the ESC back */
7281 
7282     /* may want to stuff a trailing ESC, to get out of Insert mode */
7283     if (!no_esc)
7284 	stuffcharReadbuff(ESC);
7285 
7286     return OK;
7287 }
7288 
7289     char_u *
7290 get_last_insert()
7291 {
7292     if (last_insert == NULL)
7293 	return NULL;
7294     return last_insert + last_insert_skip;
7295 }
7296 
7297 /*
7298  * Get last inserted string, and remove trailing <Esc>.
7299  * Returns pointer to allocated memory (must be freed) or NULL.
7300  */
7301     char_u *
7302 get_last_insert_save()
7303 {
7304     char_u	*s;
7305     int		len;
7306 
7307     if (last_insert == NULL)
7308 	return NULL;
7309     s = vim_strsave(last_insert + last_insert_skip);
7310     if (s != NULL)
7311     {
7312 	len = (int)STRLEN(s);
7313 	if (len > 0 && s[len - 1] == ESC)	/* remove trailing ESC */
7314 	    s[len - 1] = NUL;
7315     }
7316     return s;
7317 }
7318 
7319 /*
7320  * Check the word in front of the cursor for an abbreviation.
7321  * Called when the non-id character "c" has been entered.
7322  * When an abbreviation is recognized it is removed from the text and
7323  * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
7324  */
7325     static int
7326 echeck_abbr(c)
7327     int c;
7328 {
7329     /* Don't check for abbreviation in paste mode, when disabled and just
7330      * after moving around with cursor keys. */
7331     if (p_paste || no_abbr || arrow_used)
7332 	return FALSE;
7333 
7334     return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
7335 		curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
7336 }
7337 
7338 /*
7339  * replace-stack functions
7340  *
7341  * When replacing characters, the replaced characters are remembered for each
7342  * new character.  This is used to re-insert the old text when backspacing.
7343  *
7344  * There is a NUL headed list of characters for each character that is
7345  * currently in the file after the insertion point.  When BS is used, one NUL
7346  * headed list is put back for the deleted character.
7347  *
7348  * For a newline, there are two NUL headed lists.  One contains the characters
7349  * that the NL replaced.  The extra one stores the characters after the cursor
7350  * that were deleted (always white space).
7351  *
7352  * Replace_offset is normally 0, in which case replace_push will add a new
7353  * character at the end of the stack.  If replace_offset is not 0, that many
7354  * characters will be left on the stack above the newly inserted character.
7355  */
7356 
7357 static char_u	*replace_stack = NULL;
7358 static long	replace_stack_nr = 0;	    /* next entry in replace stack */
7359 static long	replace_stack_len = 0;	    /* max. number of entries */
7360 
7361     void
7362 replace_push(c)
7363     int	    c;	    /* character that is replaced (NUL is none) */
7364 {
7365     char_u  *p;
7366 
7367     if (replace_stack_nr < replace_offset)	/* nothing to do */
7368 	return;
7369     if (replace_stack_len <= replace_stack_nr)
7370     {
7371 	replace_stack_len += 50;
7372 	p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
7373 	if (p == NULL)	    /* out of memory */
7374 	{
7375 	    replace_stack_len -= 50;
7376 	    return;
7377 	}
7378 	if (replace_stack != NULL)
7379 	{
7380 	    mch_memmove(p, replace_stack,
7381 				 (size_t)(replace_stack_nr * sizeof(char_u)));
7382 	    vim_free(replace_stack);
7383 	}
7384 	replace_stack = p;
7385     }
7386     p = replace_stack + replace_stack_nr - replace_offset;
7387     if (replace_offset)
7388 	mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
7389     *p = c;
7390     ++replace_stack_nr;
7391 }
7392 
7393 #if defined(FEAT_MBYTE) || defined(PROTO)
7394 /*
7395  * Push a character onto the replace stack.  Handles a multi-byte character in
7396  * reverse byte order, so that the first byte is popped off first.
7397  * Return the number of bytes done (includes composing characters).
7398  */
7399     int
7400 replace_push_mb(p)
7401     char_u *p;
7402 {
7403     int l = (*mb_ptr2len)(p);
7404     int j;
7405 
7406     for (j = l - 1; j >= 0; --j)
7407 	replace_push(p[j]);
7408     return l;
7409 }
7410 #endif
7411 
7412 /*
7413  * Pop one item from the replace stack.
7414  * return -1 if stack empty
7415  * return replaced character or NUL otherwise
7416  */
7417     static int
7418 replace_pop()
7419 {
7420     if (replace_stack_nr == 0)
7421 	return -1;
7422     return (int)replace_stack[--replace_stack_nr];
7423 }
7424 
7425 /*
7426  * Join the top two items on the replace stack.  This removes to "off"'th NUL
7427  * encountered.
7428  */
7429     static void
7430 replace_join(off)
7431     int	    off;	/* offset for which NUL to remove */
7432 {
7433     int	    i;
7434 
7435     for (i = replace_stack_nr; --i >= 0; )
7436 	if (replace_stack[i] == NUL && off-- <= 0)
7437 	{
7438 	    --replace_stack_nr;
7439 	    mch_memmove(replace_stack + i, replace_stack + i + 1,
7440 					      (size_t)(replace_stack_nr - i));
7441 	    return;
7442 	}
7443 }
7444 
7445 /*
7446  * Pop bytes from the replace stack until a NUL is found, and insert them
7447  * before the cursor.  Can only be used in REPLACE or VREPLACE mode.
7448  */
7449     static void
7450 replace_pop_ins()
7451 {
7452     int	    cc;
7453     int	    oldState = State;
7454 
7455     State = NORMAL;			/* don't want REPLACE here */
7456     while ((cc = replace_pop()) > 0)
7457     {
7458 #ifdef FEAT_MBYTE
7459 	mb_replace_pop_ins(cc);
7460 #else
7461 	ins_char(cc);
7462 #endif
7463 	dec_cursor();
7464     }
7465     State = oldState;
7466 }
7467 
7468 #ifdef FEAT_MBYTE
7469 /*
7470  * Insert bytes popped from the replace stack. "cc" is the first byte.  If it
7471  * indicates a multi-byte char, pop the other bytes too.
7472  */
7473     static void
7474 mb_replace_pop_ins(cc)
7475     int		cc;
7476 {
7477     int		n;
7478     char_u	buf[MB_MAXBYTES + 1];
7479     int		i;
7480     int		c;
7481 
7482     if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
7483     {
7484 	buf[0] = cc;
7485 	for (i = 1; i < n; ++i)
7486 	    buf[i] = replace_pop();
7487 	ins_bytes_len(buf, n);
7488     }
7489     else
7490 	ins_char(cc);
7491 
7492     if (enc_utf8)
7493 	/* Handle composing chars. */
7494 	for (;;)
7495 	{
7496 	    c = replace_pop();
7497 	    if (c == -1)	    /* stack empty */
7498 		break;
7499 	    if ((n = MB_BYTE2LEN(c)) == 1)
7500 	    {
7501 		/* Not a multi-byte char, put it back. */
7502 		replace_push(c);
7503 		break;
7504 	    }
7505 	    else
7506 	    {
7507 		buf[0] = c;
7508 		for (i = 1; i < n; ++i)
7509 		    buf[i] = replace_pop();
7510 		if (utf_iscomposing(utf_ptr2char(buf)))
7511 		    ins_bytes_len(buf, n);
7512 		else
7513 		{
7514 		    /* Not a composing char, put it back. */
7515 		    for (i = n - 1; i >= 0; --i)
7516 			replace_push(buf[i]);
7517 		    break;
7518 		}
7519 	    }
7520 	}
7521 }
7522 #endif
7523 
7524 /*
7525  * make the replace stack empty
7526  * (called when exiting replace mode)
7527  */
7528     static void
7529 replace_flush()
7530 {
7531     vim_free(replace_stack);
7532     replace_stack = NULL;
7533     replace_stack_len = 0;
7534     replace_stack_nr = 0;
7535 }
7536 
7537 /*
7538  * Handle doing a BS for one character.
7539  * cc < 0: replace stack empty, just move cursor
7540  * cc == 0: character was inserted, delete it
7541  * cc > 0: character was replaced, put cc (first byte of original char) back
7542  * and check for more characters to be put back
7543  * When "limit_col" is >= 0, don't delete before this column.  Matters when
7544  * using composing characters, use del_char_after_col() instead of del_char().
7545  */
7546     static void
7547 replace_do_bs(limit_col)
7548     int		limit_col;
7549 {
7550     int		cc;
7551 #ifdef FEAT_VREPLACE
7552     int		orig_len = 0;
7553     int		ins_len;
7554     int		orig_vcols = 0;
7555     colnr_T	start_vcol;
7556     char_u	*p;
7557     int		i;
7558     int		vcol;
7559 #endif
7560 
7561     cc = replace_pop();
7562     if (cc > 0)
7563     {
7564 #ifdef FEAT_VREPLACE
7565 	if (State & VREPLACE_FLAG)
7566 	{
7567 	    /* Get the number of screen cells used by the character we are
7568 	     * going to delete. */
7569 	    getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
7570 	    orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
7571 	}
7572 #endif
7573 #ifdef FEAT_MBYTE
7574 	if (has_mbyte)
7575 	{
7576 	    (void)del_char_after_col(limit_col);
7577 # ifdef FEAT_VREPLACE
7578 	    if (State & VREPLACE_FLAG)
7579 		orig_len = (int)STRLEN(ml_get_cursor());
7580 # endif
7581 	    replace_push(cc);
7582 	}
7583 	else
7584 #endif
7585 	{
7586 	    pchar_cursor(cc);
7587 #ifdef FEAT_VREPLACE
7588 	    if (State & VREPLACE_FLAG)
7589 		orig_len = (int)STRLEN(ml_get_cursor()) - 1;
7590 #endif
7591 	}
7592 	replace_pop_ins();
7593 
7594 #ifdef FEAT_VREPLACE
7595 	if (State & VREPLACE_FLAG)
7596 	{
7597 	    /* Get the number of screen cells used by the inserted characters */
7598 	    p = ml_get_cursor();
7599 	    ins_len = (int)STRLEN(p) - orig_len;
7600 	    vcol = start_vcol;
7601 	    for (i = 0; i < ins_len; ++i)
7602 	    {
7603 		vcol += chartabsize(p + i, vcol);
7604 #ifdef FEAT_MBYTE
7605 		i += (*mb_ptr2len)(p) - 1;
7606 #endif
7607 	    }
7608 	    vcol -= start_vcol;
7609 
7610 	    /* Delete spaces that were inserted after the cursor to keep the
7611 	     * text aligned. */
7612 	    curwin->w_cursor.col += ins_len;
7613 	    while (vcol > orig_vcols && gchar_cursor() == ' ')
7614 	    {
7615 		del_char(FALSE);
7616 		++orig_vcols;
7617 	    }
7618 	    curwin->w_cursor.col -= ins_len;
7619 	}
7620 #endif
7621 
7622 	/* mark the buffer as changed and prepare for displaying */
7623 	changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
7624     }
7625     else if (cc == 0)
7626 	(void)del_char_after_col(limit_col);
7627 }
7628 
7629 #ifdef FEAT_CINDENT
7630 /*
7631  * Return TRUE if C-indenting is on.
7632  */
7633     static int
7634 cindent_on()
7635 {
7636     return (!p_paste && (curbuf->b_p_cin
7637 # ifdef FEAT_EVAL
7638 		    || *curbuf->b_p_inde != NUL
7639 # endif
7640 		    ));
7641 }
7642 #endif
7643 
7644 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
7645 /*
7646  * Re-indent the current line, based on the current contents of it and the
7647  * surrounding lines. Fixing the cursor position seems really easy -- I'm very
7648  * confused what all the part that handles Control-T is doing that I'm not.
7649  * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
7650  */
7651 
7652     void
7653 fixthisline(get_the_indent)
7654     int (*get_the_indent) __ARGS((void));
7655 {
7656     change_indent(INDENT_SET, get_the_indent(), FALSE, 0, TRUE);
7657     if (linewhite(curwin->w_cursor.lnum))
7658 	did_ai = TRUE;	    /* delete the indent if the line stays empty */
7659 }
7660 
7661     void
7662 fix_indent()
7663 {
7664     if (p_paste)
7665 	return;
7666 # ifdef FEAT_LISP
7667     if (curbuf->b_p_lisp && curbuf->b_p_ai)
7668 	fixthisline(get_lisp_indent);
7669 # endif
7670 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
7671     else
7672 # endif
7673 # ifdef FEAT_CINDENT
7674 	if (cindent_on())
7675 	    do_c_expr_indent();
7676 # endif
7677 }
7678 
7679 #endif
7680 
7681 #ifdef FEAT_CINDENT
7682 /*
7683  * return TRUE if 'cinkeys' contains the key "keytyped",
7684  * when == '*':	    Only if key is preceded with '*'	(indent before insert)
7685  * when == '!':	    Only if key is prededed with '!'	(don't insert)
7686  * when == ' ':	    Only if key is not preceded with '*'(indent afterwards)
7687  *
7688  * "keytyped" can have a few special values:
7689  * KEY_OPEN_FORW
7690  * KEY_OPEN_BACK
7691  * KEY_COMPLETE	    just finished completion.
7692  *
7693  * If line_is_empty is TRUE accept keys with '0' before them.
7694  */
7695     int
7696 in_cinkeys(keytyped, when, line_is_empty)
7697     int		keytyped;
7698     int		when;
7699     int		line_is_empty;
7700 {
7701     char_u	*look;
7702     int		try_match;
7703     int		try_match_word;
7704     char_u	*p;
7705     char_u	*line;
7706     int		icase;
7707     int		i;
7708 
7709     if (keytyped == NUL)
7710 	/* Can happen with CTRL-Y and CTRL-E on a short line. */
7711 	return FALSE;
7712 
7713 #ifdef FEAT_EVAL
7714     if (*curbuf->b_p_inde != NUL)
7715 	look = curbuf->b_p_indk;	/* 'indentexpr' set: use 'indentkeys' */
7716     else
7717 #endif
7718 	look = curbuf->b_p_cink;	/* 'indentexpr' empty: use 'cinkeys' */
7719     while (*look)
7720     {
7721 	/*
7722 	 * Find out if we want to try a match with this key, depending on
7723 	 * 'when' and a '*' or '!' before the key.
7724 	 */
7725 	switch (when)
7726 	{
7727 	    case '*': try_match = (*look == '*'); break;
7728 	    case '!': try_match = (*look == '!'); break;
7729 	     default: try_match = (*look != '*'); break;
7730 	}
7731 	if (*look == '*' || *look == '!')
7732 	    ++look;
7733 
7734 	/*
7735 	 * If there is a '0', only accept a match if the line is empty.
7736 	 * But may still match when typing last char of a word.
7737 	 */
7738 	if (*look == '0')
7739 	{
7740 	    try_match_word = try_match;
7741 	    if (!line_is_empty)
7742 		try_match = FALSE;
7743 	    ++look;
7744 	}
7745 	else
7746 	    try_match_word = FALSE;
7747 
7748 	/*
7749 	 * does it look like a control character?
7750 	 */
7751 	if (*look == '^'
7752 #ifdef EBCDIC
7753 		&& (Ctrl_chr(look[1]) != 0)
7754 #else
7755 		&& look[1] >= '?' && look[1] <= '_'
7756 #endif
7757 		)
7758 	{
7759 	    if (try_match && keytyped == Ctrl_chr(look[1]))
7760 		return TRUE;
7761 	    look += 2;
7762 	}
7763 	/*
7764 	 * 'o' means "o" command, open forward.
7765 	 * 'O' means "O" command, open backward.
7766 	 */
7767 	else if (*look == 'o')
7768 	{
7769 	    if (try_match && keytyped == KEY_OPEN_FORW)
7770 		return TRUE;
7771 	    ++look;
7772 	}
7773 	else if (*look == 'O')
7774 	{
7775 	    if (try_match && keytyped == KEY_OPEN_BACK)
7776 		return TRUE;
7777 	    ++look;
7778 	}
7779 
7780 	/*
7781 	 * 'e' means to check for "else" at start of line and just before the
7782 	 * cursor.
7783 	 */
7784 	else if (*look == 'e')
7785 	{
7786 	    if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
7787 	    {
7788 		p = ml_get_curline();
7789 		if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
7790 			STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
7791 		    return TRUE;
7792 	    }
7793 	    ++look;
7794 	}
7795 
7796 	/*
7797 	 * ':' only causes an indent if it is at the end of a label or case
7798 	 * statement, or when it was before typing the ':' (to fix
7799 	 * class::method for C++).
7800 	 */
7801 	else if (*look == ':')
7802 	{
7803 	    if (try_match && keytyped == ':')
7804 	    {
7805 		p = ml_get_curline();
7806 		if (cin_iscase(p, FALSE) || cin_isscopedecl(p)
7807 							   || cin_islabel(30))
7808 		    return TRUE;
7809 		/* Need to get the line again after cin_islabel(). */
7810 		p = ml_get_curline();
7811 		if (curwin->w_cursor.col > 2
7812 			&& p[curwin->w_cursor.col - 1] == ':'
7813 			&& p[curwin->w_cursor.col - 2] == ':')
7814 		{
7815 		    p[curwin->w_cursor.col - 1] = ' ';
7816 		    i = (cin_iscase(p, FALSE) || cin_isscopedecl(p)
7817 							  || cin_islabel(30));
7818 		    p = ml_get_curline();
7819 		    p[curwin->w_cursor.col - 1] = ':';
7820 		    if (i)
7821 			return TRUE;
7822 		}
7823 	    }
7824 	    ++look;
7825 	}
7826 
7827 
7828 	/*
7829 	 * Is it a key in <>, maybe?
7830 	 */
7831 	else if (*look == '<')
7832 	{
7833 	    if (try_match)
7834 	    {
7835 		/*
7836 		 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7837 		 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7838 		 * >, *, : and ! keys if they really really want to.
7839 		 */
7840 		if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7841 						       && keytyped == look[1])
7842 		    return TRUE;
7843 
7844 		if (keytyped == get_special_key_code(look + 1))
7845 		    return TRUE;
7846 	    }
7847 	    while (*look && *look != '>')
7848 		look++;
7849 	    while (*look == '>')
7850 		look++;
7851 	}
7852 
7853 	/*
7854 	 * Is it a word: "=word"?
7855 	 */
7856 	else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7857 	{
7858 	    ++look;
7859 	    if (*look == '~')
7860 	    {
7861 		icase = TRUE;
7862 		++look;
7863 	    }
7864 	    else
7865 		icase = FALSE;
7866 	    p = vim_strchr(look, ',');
7867 	    if (p == NULL)
7868 		p = look + STRLEN(look);
7869 	    if ((try_match || try_match_word)
7870 		    && curwin->w_cursor.col >= (colnr_T)(p - look))
7871 	    {
7872 		int		match = FALSE;
7873 
7874 #ifdef FEAT_INS_EXPAND
7875 		if (keytyped == KEY_COMPLETE)
7876 		{
7877 		    char_u	*s;
7878 
7879 		    /* Just completed a word, check if it starts with "look".
7880 		     * search back for the start of a word. */
7881 		    line = ml_get_curline();
7882 # ifdef FEAT_MBYTE
7883 		    if (has_mbyte)
7884 		    {
7885 			char_u	*n;
7886 
7887 			for (s = line + curwin->w_cursor.col; s > line; s = n)
7888 			{
7889 			    n = mb_prevptr(line, s);
7890 			    if (!vim_iswordp(n))
7891 				break;
7892 			}
7893 		    }
7894 		    else
7895 # endif
7896 			for (s = line + curwin->w_cursor.col; s > line; --s)
7897 			    if (!vim_iswordc(s[-1]))
7898 				break;
7899 		    if (s + (p - look) <= line + curwin->w_cursor.col
7900 			    && (icase
7901 				? MB_STRNICMP(s, look, p - look)
7902 				: STRNCMP(s, look, p - look)) == 0)
7903 			match = TRUE;
7904 		}
7905 		else
7906 #endif
7907 		    /* TODO: multi-byte */
7908 		    if (keytyped == (int)p[-1] || (icase && keytyped < 256
7909 			 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7910 		{
7911 		    line = ml_get_cursor();
7912 		    if ((curwin->w_cursor.col == (colnr_T)(p - look)
7913 				|| !vim_iswordc(line[-(p - look) - 1]))
7914 			    && (icase
7915 				? MB_STRNICMP(line - (p - look), look, p - look)
7916 				: STRNCMP(line - (p - look), look, p - look))
7917 									 == 0)
7918 			match = TRUE;
7919 		}
7920 		if (match && try_match_word && !try_match)
7921 		{
7922 		    /* "0=word": Check if there are only blanks before the
7923 		     * word. */
7924 		    line = ml_get_curline();
7925 		    if ((int)(skipwhite(line) - line) !=
7926 				     (int)(curwin->w_cursor.col - (p - look)))
7927 			match = FALSE;
7928 		}
7929 		if (match)
7930 		    return TRUE;
7931 	    }
7932 	    look = p;
7933 	}
7934 
7935 	/*
7936 	 * ok, it's a boring generic character.
7937 	 */
7938 	else
7939 	{
7940 	    if (try_match && *look == keytyped)
7941 		return TRUE;
7942 	    ++look;
7943 	}
7944 
7945 	/*
7946 	 * Skip over ", ".
7947 	 */
7948 	look = skip_to_option_part(look);
7949     }
7950     return FALSE;
7951 }
7952 #endif /* FEAT_CINDENT */
7953 
7954 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7955 /*
7956  * Map Hebrew keyboard when in hkmap mode.
7957  */
7958     int
7959 hkmap(c)
7960     int c;
7961 {
7962     if (p_hkmapp)   /* phonetic mapping, by Ilya Dogolazky */
7963     {
7964 	enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7965 	    KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7966 	    PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7967 	static char_u map[26] =
7968 	    {(char_u)hALEF/*a*/, (char_u)BET  /*b*/, (char_u)hKAF    /*c*/,
7969 	     (char_u)DALET/*d*/, (char_u)-1   /*e*/, (char_u)PEIsofit/*f*/,
7970 	     (char_u)GIMEL/*g*/, (char_u)HEI  /*h*/, (char_u)IUD     /*i*/,
7971 	     (char_u)HET  /*j*/, (char_u)KOF  /*k*/, (char_u)LAMED   /*l*/,
7972 	     (char_u)MEM  /*m*/, (char_u)NUN  /*n*/, (char_u)SAMEH   /*o*/,
7973 	     (char_u)PEI  /*p*/, (char_u)-1   /*q*/, (char_u)RESH    /*r*/,
7974 	     (char_u)ZAIN /*s*/, (char_u)TAV  /*t*/, (char_u)TET     /*u*/,
7975 	     (char_u)VAV  /*v*/, (char_u)hSHIN/*w*/, (char_u)-1      /*x*/,
7976 	     (char_u)AIN  /*y*/, (char_u)ZADI /*z*/};
7977 
7978 	if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7979 	    return (int)(map[CharOrd(c)] - 1 + p_aleph);
7980 							    /* '-1'='sofit' */
7981 	else if (c == 'x')
7982 	    return 'X';
7983 	else if (c == 'q')
7984 	    return '\''; /* {geresh}={'} */
7985 	else if (c == 246)
7986 	    return ' ';  /* \"o --> ' ' for a german keyboard */
7987 	else if (c == 228)
7988 	    return ' ';  /* \"a --> ' '      -- / --	       */
7989 	else if (c == 252)
7990 	    return ' ';  /* \"u --> ' '      -- / --	       */
7991 #ifdef EBCDIC
7992 	else if (islower(c))
7993 #else
7994 	/* NOTE: islower() does not do the right thing for us on Linux so we
7995 	 * do this the same was as 5.7 and previous, so it works correctly on
7996 	 * all systems.  Specifically, the e.g. Delete and Arrow keys are
7997 	 * munged and won't work if e.g. searching for Hebrew text.
7998 	 */
7999 	else if (c >= 'a' && c <= 'z')
8000 #endif
8001 	    return (int)(map[CharOrdLow(c)] + p_aleph);
8002 	else
8003 	    return c;
8004     }
8005     else
8006     {
8007 	switch (c)
8008 	{
8009 	    case '`':	return ';';
8010 	    case '/':	return '.';
8011 	    case '\'':	return ',';
8012 	    case 'q':	return '/';
8013 	    case 'w':	return '\'';
8014 
8015 			/* Hebrew letters - set offset from 'a' */
8016 	    case ',':	c = '{'; break;
8017 	    case '.':	c = 'v'; break;
8018 	    case ';':	c = 't'; break;
8019 	    default: {
8020 			 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
8021 
8022 #ifdef EBCDIC
8023 			 /* see note about islower() above */
8024 			 if (!islower(c))
8025 #else
8026 			 if (c < 'a' || c > 'z')
8027 #endif
8028 			     return c;
8029 			 c = str[CharOrdLow(c)];
8030 			 break;
8031 		     }
8032 	}
8033 
8034 	return (int)(CharOrdLow(c) + p_aleph);
8035     }
8036 }
8037 #endif
8038 
8039     static void
8040 ins_reg()
8041 {
8042     int		need_redraw = FALSE;
8043     int		regname;
8044     int		literally = 0;
8045 #ifdef FEAT_VISUAL
8046     int		vis_active = VIsual_active;
8047 #endif
8048 
8049     /*
8050      * If we are going to wait for a character, show a '"'.
8051      */
8052     pc_status = PC_STATUS_UNSET;
8053     if (redrawing() && !char_avail())
8054     {
8055 	/* may need to redraw when no more chars available now */
8056 	ins_redraw(FALSE);
8057 
8058 	edit_putchar('"', TRUE);
8059 #ifdef FEAT_CMDL_INFO
8060 	add_to_showcmd_c(Ctrl_R);
8061 #endif
8062     }
8063 
8064 #ifdef USE_ON_FLY_SCROLL
8065     dont_scroll = TRUE;		/* disallow scrolling here */
8066 #endif
8067 
8068     /*
8069      * Don't map the register name. This also prevents the mode message to be
8070      * deleted when ESC is hit.
8071      */
8072     ++no_mapping;
8073     regname = plain_vgetc();
8074     LANGMAP_ADJUST(regname, TRUE);
8075     if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
8076     {
8077 	/* Get a third key for literal register insertion */
8078 	literally = regname;
8079 #ifdef FEAT_CMDL_INFO
8080 	add_to_showcmd_c(literally);
8081 #endif
8082 	regname = plain_vgetc();
8083 	LANGMAP_ADJUST(regname, TRUE);
8084     }
8085     --no_mapping;
8086 
8087 #ifdef FEAT_EVAL
8088     /*
8089      * Don't call u_sync() while getting the expression,
8090      * evaluating it or giving an error message for it!
8091      */
8092     ++no_u_sync;
8093     if (regname == '=')
8094     {
8095 # ifdef USE_IM_CONTROL
8096 	int	im_on = im_get_status();
8097 # endif
8098 	regname = get_expr_register();
8099 # ifdef USE_IM_CONTROL
8100 	/* Restore the Input Method. */
8101 	if (im_on)
8102 	    im_set_active(TRUE);
8103 # endif
8104     }
8105     if (regname == NUL || !valid_yank_reg(regname, FALSE))
8106     {
8107 	vim_beep();
8108 	need_redraw = TRUE;	/* remove the '"' */
8109     }
8110     else
8111     {
8112 #endif
8113 	if (literally == Ctrl_O || literally == Ctrl_P)
8114 	{
8115 	    /* Append the command to the redo buffer. */
8116 	    AppendCharToRedobuff(Ctrl_R);
8117 	    AppendCharToRedobuff(literally);
8118 	    AppendCharToRedobuff(regname);
8119 
8120 	    do_put(regname, BACKWARD, 1L,
8121 		 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
8122 	}
8123 	else if (insert_reg(regname, literally) == FAIL)
8124 	{
8125 	    vim_beep();
8126 	    need_redraw = TRUE;	/* remove the '"' */
8127 	}
8128 	else if (stop_insert_mode)
8129 	    /* When the '=' register was used and a function was invoked that
8130 	     * did ":stopinsert" then stuff_empty() returns FALSE but we won't
8131 	     * insert anything, need to remove the '"' */
8132 	    need_redraw = TRUE;
8133 
8134 #ifdef FEAT_EVAL
8135     }
8136     --no_u_sync;
8137 #endif
8138 #ifdef FEAT_CMDL_INFO
8139     clear_showcmd();
8140 #endif
8141 
8142     /* If the inserted register is empty, we need to remove the '"' */
8143     if (need_redraw || stuff_empty())
8144 	edit_unputchar();
8145 
8146 #ifdef FEAT_VISUAL
8147     /* Disallow starting Visual mode here, would get a weird mode. */
8148     if (!vis_active && VIsual_active)
8149 	end_visual_mode();
8150 #endif
8151 }
8152 
8153 /*
8154  * CTRL-G commands in Insert mode.
8155  */
8156     static void
8157 ins_ctrl_g()
8158 {
8159     int		c;
8160 
8161 #ifdef FEAT_INS_EXPAND
8162     /* Right after CTRL-X the cursor will be after the ruler. */
8163     setcursor();
8164 #endif
8165 
8166     /*
8167      * Don't map the second key. This also prevents the mode message to be
8168      * deleted when ESC is hit.
8169      */
8170     ++no_mapping;
8171     c = plain_vgetc();
8172     --no_mapping;
8173     switch (c)
8174     {
8175 	/* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
8176 	case K_UP:
8177 	case Ctrl_K:
8178 	case 'k': ins_up(TRUE);
8179 		  break;
8180 
8181 	/* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
8182 	case K_DOWN:
8183 	case Ctrl_J:
8184 	case 'j': ins_down(TRUE);
8185 		  break;
8186 
8187 	/* CTRL-G u: start new undoable edit */
8188 	case 'u': u_sync(TRUE);
8189 		  ins_need_undo = TRUE;
8190 
8191 		  /* Need to reset Insstart, esp. because a BS that joins
8192 		   * a line to the previous one must save for undo. */
8193 		  Insstart = curwin->w_cursor;
8194 		  break;
8195 
8196 	/* Unknown CTRL-G command, reserved for future expansion. */
8197 	default:  vim_beep();
8198     }
8199 }
8200 
8201 /*
8202  * CTRL-^ in Insert mode.
8203  */
8204     static void
8205 ins_ctrl_hat()
8206 {
8207     if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
8208     {
8209 	/* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
8210 	if (State & LANGMAP)
8211 	{
8212 	    curbuf->b_p_iminsert = B_IMODE_NONE;
8213 	    State &= ~LANGMAP;
8214 	}
8215 	else
8216 	{
8217 	    curbuf->b_p_iminsert = B_IMODE_LMAP;
8218 	    State |= LANGMAP;
8219 #ifdef USE_IM_CONTROL
8220 	    im_set_active(FALSE);
8221 #endif
8222 	}
8223     }
8224 #ifdef USE_IM_CONTROL
8225     else
8226     {
8227 	/* There are no ":lmap" mappings, toggle IM */
8228 	if (im_get_status())
8229 	{
8230 	    curbuf->b_p_iminsert = B_IMODE_NONE;
8231 	    im_set_active(FALSE);
8232 	}
8233 	else
8234 	{
8235 	    curbuf->b_p_iminsert = B_IMODE_IM;
8236 	    State &= ~LANGMAP;
8237 	    im_set_active(TRUE);
8238 	}
8239     }
8240 #endif
8241     set_iminsert_global();
8242     showmode();
8243 #ifdef FEAT_GUI
8244     /* may show different cursor shape or color */
8245     if (gui.in_use)
8246 	gui_update_cursor(TRUE, FALSE);
8247 #endif
8248 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
8249     /* Show/unshow value of 'keymap' in status lines. */
8250     status_redraw_curbuf();
8251 #endif
8252 }
8253 
8254 /*
8255  * Handle ESC in insert mode.
8256  * Returns TRUE when leaving insert mode, FALSE when going to repeat the
8257  * insert.
8258  */
8259     static int
8260 ins_esc(count, cmdchar, nomove)
8261     long	*count;
8262     int		cmdchar;
8263     int		nomove;	    /* don't move cursor */
8264 {
8265     int		temp;
8266     static int	disabled_redraw = FALSE;
8267 
8268 #ifdef FEAT_SPELL
8269     check_spell_redraw();
8270 #endif
8271 #if defined(FEAT_HANGULIN)
8272 # if defined(ESC_CHG_TO_ENG_MODE)
8273     hangul_input_state_set(0);
8274 # endif
8275     if (composing_hangul)
8276     {
8277 	push_raw_key(composing_hangul_buffer, 2);
8278 	composing_hangul = 0;
8279     }
8280 #endif
8281 
8282     temp = curwin->w_cursor.col;
8283     if (disabled_redraw)
8284     {
8285 	--RedrawingDisabled;
8286 	disabled_redraw = FALSE;
8287     }
8288     if (!arrow_used)
8289     {
8290 	/*
8291 	 * Don't append the ESC for "r<CR>" and "grx".
8292 	 * When 'insertmode' is set only CTRL-L stops Insert mode.  Needed for
8293 	 * when "count" is non-zero.
8294 	 */
8295 	if (cmdchar != 'r' && cmdchar != 'v')
8296 	    AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
8297 
8298 	/*
8299 	 * Repeating insert may take a long time.  Check for
8300 	 * interrupt now and then.
8301 	 */
8302 	if (*count > 0)
8303 	{
8304 	    line_breakcheck();
8305 	    if (got_int)
8306 		*count = 0;
8307 	}
8308 
8309 	if (--*count > 0)	/* repeat what was typed */
8310 	{
8311 	    /* Vi repeats the insert without replacing characters. */
8312 	    if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
8313 		State &= ~REPLACE_FLAG;
8314 
8315 	    (void)start_redo_ins();
8316 	    if (cmdchar == 'r' || cmdchar == 'v')
8317 		stuffReadbuff(ESC_STR);	/* no ESC in redo buffer */
8318 	    ++RedrawingDisabled;
8319 	    disabled_redraw = TRUE;
8320 	    return FALSE;	/* repeat the insert */
8321 	}
8322 	stop_insert(&curwin->w_cursor, TRUE);
8323 	undisplay_dollar();
8324     }
8325 
8326     /* When an autoindent was removed, curswant stays after the
8327      * indent */
8328     if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
8329 	curwin->w_set_curswant = TRUE;
8330 
8331     /* Remember the last Insert position in the '^ mark. */
8332     if (!cmdmod.keepjumps)
8333 	curbuf->b_last_insert = curwin->w_cursor;
8334 
8335     /*
8336      * The cursor should end up on the last inserted character.
8337      * Don't do it for CTRL-O, unless past the end of the line.
8338      */
8339     if (!nomove
8340 	    && (curwin->w_cursor.col != 0
8341 #ifdef FEAT_VIRTUALEDIT
8342 		|| curwin->w_cursor.coladd > 0
8343 #endif
8344 	       )
8345 	    && (restart_edit == NUL
8346 		   || (gchar_cursor() == NUL
8347 #ifdef FEAT_VISUAL
8348 		       && !VIsual_active
8349 #endif
8350 		      ))
8351 #ifdef FEAT_RIGHTLEFT
8352 	    && !revins_on
8353 #endif
8354 				      )
8355     {
8356 #ifdef FEAT_VIRTUALEDIT
8357 	if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
8358 	{
8359 	    oneleft();
8360 	    if (restart_edit != NUL)
8361 		++curwin->w_cursor.coladd;
8362 	}
8363 	else
8364 #endif
8365 	{
8366 	    --curwin->w_cursor.col;
8367 #ifdef FEAT_MBYTE
8368 	    /* Correct cursor for multi-byte character. */
8369 	    if (has_mbyte)
8370 		mb_adjust_cursor();
8371 #endif
8372 	}
8373     }
8374 
8375 #ifdef USE_IM_CONTROL
8376     /* Disable IM to allow typing English directly for Normal mode commands.
8377      * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
8378      * well). */
8379     if (!(State & LANGMAP))
8380 	im_save_status(&curbuf->b_p_iminsert);
8381     im_set_active(FALSE);
8382 #endif
8383 
8384     State = NORMAL;
8385     /* need to position cursor again (e.g. when on a TAB ) */
8386     changed_cline_bef_curs();
8387 
8388 #ifdef FEAT_MOUSE
8389     setmouse();
8390 #endif
8391 #ifdef CURSOR_SHAPE
8392     ui_cursor_shape();		/* may show different cursor shape */
8393 #endif
8394 
8395     /*
8396      * When recording or for CTRL-O, need to display the new mode.
8397      * Otherwise remove the mode message.
8398      */
8399     if (Recording || restart_edit != NUL)
8400 	showmode();
8401     else if (p_smd)
8402 	MSG("");
8403 
8404     return TRUE;	    /* exit Insert mode */
8405 }
8406 
8407 #ifdef FEAT_RIGHTLEFT
8408 /*
8409  * Toggle language: hkmap and revins_on.
8410  * Move to end of reverse inserted text.
8411  */
8412     static void
8413 ins_ctrl_()
8414 {
8415     if (revins_on && revins_chars && revins_scol >= 0)
8416     {
8417 	while (gchar_cursor() != NUL && revins_chars--)
8418 	    ++curwin->w_cursor.col;
8419     }
8420     p_ri = !p_ri;
8421     revins_on = (State == INSERT && p_ri);
8422     if (revins_on)
8423     {
8424 	revins_scol = curwin->w_cursor.col;
8425 	revins_legal++;
8426 	revins_chars = 0;
8427 	undisplay_dollar();
8428     }
8429     else
8430 	revins_scol = -1;
8431 #ifdef FEAT_FKMAP
8432     if (p_altkeymap)
8433     {
8434 	/*
8435 	 * to be consistent also for redo command, using '.'
8436 	 * set arrow_used to true and stop it - causing to redo
8437 	 * characters entered in one mode (normal/reverse insert).
8438 	 */
8439 	arrow_used = TRUE;
8440 	(void)stop_arrow();
8441 	p_fkmap = curwin->w_p_rl ^ p_ri;
8442 	if (p_fkmap && p_ri)
8443 	    State = INSERT;
8444     }
8445     else
8446 #endif
8447 	p_hkmap = curwin->w_p_rl ^ p_ri;    /* be consistent! */
8448     showmode();
8449 }
8450 #endif
8451 
8452 #ifdef FEAT_VISUAL
8453 /*
8454  * If 'keymodel' contains "startsel", may start selection.
8455  * Returns TRUE when a CTRL-O and other keys stuffed.
8456  */
8457     static int
8458 ins_start_select(c)
8459     int		c;
8460 {
8461     if (km_startsel)
8462 	switch (c)
8463 	{
8464 	    case K_KHOME:
8465 	    case K_KEND:
8466 	    case K_PAGEUP:
8467 	    case K_KPAGEUP:
8468 	    case K_PAGEDOWN:
8469 	    case K_KPAGEDOWN:
8470 # ifdef MACOS
8471 	    case K_LEFT:
8472 	    case K_RIGHT:
8473 	    case K_UP:
8474 	    case K_DOWN:
8475 	    case K_END:
8476 	    case K_HOME:
8477 # endif
8478 		if (!(mod_mask & MOD_MASK_SHIFT))
8479 		    break;
8480 		/* FALLTHROUGH */
8481 	    case K_S_LEFT:
8482 	    case K_S_RIGHT:
8483 	    case K_S_UP:
8484 	    case K_S_DOWN:
8485 	    case K_S_END:
8486 	    case K_S_HOME:
8487 		/* Start selection right away, the cursor can move with
8488 		 * CTRL-O when beyond the end of the line. */
8489 		start_selection();
8490 
8491 		/* Execute the key in (insert) Select mode. */
8492 		stuffcharReadbuff(Ctrl_O);
8493 		if (mod_mask)
8494 		{
8495 		    char_u	    buf[4];
8496 
8497 		    buf[0] = K_SPECIAL;
8498 		    buf[1] = KS_MODIFIER;
8499 		    buf[2] = mod_mask;
8500 		    buf[3] = NUL;
8501 		    stuffReadbuff(buf);
8502 		}
8503 		stuffcharReadbuff(c);
8504 		return TRUE;
8505 	}
8506     return FALSE;
8507 }
8508 #endif
8509 
8510 /*
8511  * <Insert> key in Insert mode: toggle insert/remplace mode.
8512  */
8513     static void
8514 ins_insert(replaceState)
8515     int	    replaceState;
8516 {
8517 #ifdef FEAT_FKMAP
8518     if (p_fkmap && p_ri)
8519     {
8520 	beep_flush();
8521 	EMSG(farsi_text_3);	/* encoded in Farsi */
8522 	return;
8523     }
8524 #endif
8525 
8526 #ifdef FEAT_AUTOCMD
8527 # ifdef FEAT_EVAL
8528     set_vim_var_string(VV_INSERTMODE,
8529 		   (char_u *)((State & REPLACE_FLAG) ? "i" :
8530 #  ifdef FEAT_VREPLACE
8531 			    replaceState == VREPLACE ? "v" :
8532 #  endif
8533 			    "r"), 1);
8534 # endif
8535     apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
8536 #endif
8537     if (State & REPLACE_FLAG)
8538 	State = INSERT | (State & LANGMAP);
8539     else
8540 	State = replaceState | (State & LANGMAP);
8541     AppendCharToRedobuff(K_INS);
8542     showmode();
8543 #ifdef CURSOR_SHAPE
8544     ui_cursor_shape();		/* may show different cursor shape */
8545 #endif
8546 }
8547 
8548 /*
8549  * Pressed CTRL-O in Insert mode.
8550  */
8551     static void
8552 ins_ctrl_o()
8553 {
8554 #ifdef FEAT_VREPLACE
8555     if (State & VREPLACE_FLAG)
8556 	restart_edit = 'V';
8557     else
8558 #endif
8559 	if (State & REPLACE_FLAG)
8560 	restart_edit = 'R';
8561     else
8562 	restart_edit = 'I';
8563 #ifdef FEAT_VIRTUALEDIT
8564     if (virtual_active())
8565 	ins_at_eol = FALSE;	/* cursor always keeps its column */
8566     else
8567 #endif
8568 	ins_at_eol = (gchar_cursor() == NUL);
8569 }
8570 
8571 /*
8572  * If the cursor is on an indent, ^T/^D insert/delete one
8573  * shiftwidth.	Otherwise ^T/^D behave like a "<<" or ">>".
8574  * Always round the indent to 'shiftwidth', this is compatible
8575  * with vi.  But vi only supports ^T and ^D after an
8576  * autoindent, we support it everywhere.
8577  */
8578     static void
8579 ins_shift(c, lastc)
8580     int	    c;
8581     int	    lastc;
8582 {
8583     if (stop_arrow() == FAIL)
8584 	return;
8585     AppendCharToRedobuff(c);
8586 
8587     /*
8588      * 0^D and ^^D: remove all indent.
8589      */
8590     if (c == Ctrl_D && (lastc == '0' || lastc == '^')
8591 						  && curwin->w_cursor.col > 0)
8592     {
8593 	--curwin->w_cursor.col;
8594 	(void)del_char(FALSE);		/* delete the '^' or '0' */
8595 	/* In Replace mode, restore the characters that '^' or '0' replaced. */
8596 	if (State & REPLACE_FLAG)
8597 	    replace_pop_ins();
8598 	if (lastc == '^')
8599 	    old_indent = get_indent();	/* remember curr. indent */
8600 	change_indent(INDENT_SET, 0, TRUE, 0, TRUE);
8601     }
8602     else
8603 	change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE);
8604 
8605     if (did_ai && *skipwhite(ml_get_curline()) != NUL)
8606 	did_ai = FALSE;
8607 #ifdef FEAT_SMARTINDENT
8608     did_si = FALSE;
8609     can_si = FALSE;
8610     can_si_back = FALSE;
8611 #endif
8612 #ifdef FEAT_CINDENT
8613     can_cindent = FALSE;	/* no cindenting after ^D or ^T */
8614 #endif
8615 }
8616 
8617     static void
8618 ins_del()
8619 {
8620     int	    temp;
8621 
8622     if (stop_arrow() == FAIL)
8623 	return;
8624     if (gchar_cursor() == NUL)		/* delete newline */
8625     {
8626 	temp = curwin->w_cursor.col;
8627 	if (!can_bs(BS_EOL)		/* only if "eol" included */
8628 		|| do_join(2, FALSE, TRUE, FALSE) == FAIL)
8629 	    vim_beep();
8630 	else
8631 	    curwin->w_cursor.col = temp;
8632     }
8633     else if (del_char(FALSE) == FAIL)	/* delete char under cursor */
8634 	vim_beep();
8635     did_ai = FALSE;
8636 #ifdef FEAT_SMARTINDENT
8637     did_si = FALSE;
8638     can_si = FALSE;
8639     can_si_back = FALSE;
8640 #endif
8641     AppendCharToRedobuff(K_DEL);
8642 }
8643 
8644 static void ins_bs_one __ARGS((colnr_T *vcolp));
8645 
8646 /*
8647  * Delete one character for ins_bs().
8648  */
8649     static void
8650 ins_bs_one(vcolp)
8651     colnr_T	*vcolp;
8652 {
8653     dec_cursor();
8654     getvcol(curwin, &curwin->w_cursor, vcolp, NULL, NULL);
8655     if (State & REPLACE_FLAG)
8656     {
8657 	/* Don't delete characters before the insert point when in
8658 	 * Replace mode */
8659 	if (curwin->w_cursor.lnum != Insstart.lnum
8660 		|| curwin->w_cursor.col >= Insstart.col)
8661 	    replace_do_bs(-1);
8662     }
8663     else
8664 	(void)del_char(FALSE);
8665 }
8666 
8667 /*
8668  * Handle Backspace, delete-word and delete-line in Insert mode.
8669  * Return TRUE when backspace was actually used.
8670  */
8671     static int
8672 ins_bs(c, mode, inserted_space_p)
8673     int		c;
8674     int		mode;
8675     int		*inserted_space_p;
8676 {
8677     linenr_T	lnum;
8678     int		cc;
8679     int		temp = 0;	    /* init for GCC */
8680     colnr_T	save_col;
8681     colnr_T	mincol;
8682     int		did_backspace = FALSE;
8683     int		in_indent;
8684     int		oldState;
8685 #ifdef FEAT_MBYTE
8686     int		cpc[MAX_MCO];	    /* composing characters */
8687 #endif
8688 
8689     /*
8690      * can't delete anything in an empty file
8691      * can't backup past first character in buffer
8692      * can't backup past starting point unless 'backspace' > 1
8693      * can backup to a previous line if 'backspace' == 0
8694      */
8695     if (       bufempty()
8696 	    || (
8697 #ifdef FEAT_RIGHTLEFT
8698 		!revins_on &&
8699 #endif
8700 		((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
8701 		    || (!can_bs(BS_START)
8702 			&& (arrow_used
8703 			    || (curwin->w_cursor.lnum == Insstart.lnum
8704 				&& curwin->w_cursor.col <= Insstart.col)))
8705 		    || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
8706 					 && curwin->w_cursor.col <= ai_col)
8707 		    || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
8708     {
8709 	vim_beep();
8710 	return FALSE;
8711     }
8712 
8713     if (stop_arrow() == FAIL)
8714 	return FALSE;
8715     in_indent = inindent(0);
8716 #ifdef FEAT_CINDENT
8717     if (in_indent)
8718 	can_cindent = FALSE;
8719 #endif
8720 #ifdef FEAT_COMMENTS
8721     end_comment_pending = NUL;	/* After BS, don't auto-end comment */
8722 #endif
8723 #ifdef FEAT_RIGHTLEFT
8724     if (revins_on)	    /* put cursor after last inserted char */
8725 	inc_cursor();
8726 #endif
8727 
8728 #ifdef FEAT_VIRTUALEDIT
8729     /* Virtualedit:
8730      *	BACKSPACE_CHAR eats a virtual space
8731      *	BACKSPACE_WORD eats all coladd
8732      *	BACKSPACE_LINE eats all coladd and keeps going
8733      */
8734     if (curwin->w_cursor.coladd > 0)
8735     {
8736 	if (mode == BACKSPACE_CHAR)
8737 	{
8738 	    --curwin->w_cursor.coladd;
8739 	    return TRUE;
8740 	}
8741 	if (mode == BACKSPACE_WORD)
8742 	{
8743 	    curwin->w_cursor.coladd = 0;
8744 	    return TRUE;
8745 	}
8746 	curwin->w_cursor.coladd = 0;
8747     }
8748 #endif
8749 
8750     /*
8751      * delete newline!
8752      */
8753     if (curwin->w_cursor.col == 0)
8754     {
8755 	lnum = Insstart.lnum;
8756 	if (curwin->w_cursor.lnum == Insstart.lnum
8757 #ifdef FEAT_RIGHTLEFT
8758 			|| revins_on
8759 #endif
8760 				    )
8761 	{
8762 	    if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
8763 			       (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
8764 		return FALSE;
8765 	    --Insstart.lnum;
8766 	    Insstart.col = MAXCOL;
8767 	}
8768 	/*
8769 	 * In replace mode:
8770 	 * cc < 0: NL was inserted, delete it
8771 	 * cc >= 0: NL was replaced, put original characters back
8772 	 */
8773 	cc = -1;
8774 	if (State & REPLACE_FLAG)
8775 	    cc = replace_pop();	    /* returns -1 if NL was inserted */
8776 	/*
8777 	 * In replace mode, in the line we started replacing, we only move the
8778 	 * cursor.
8779 	 */
8780 	if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
8781 	{
8782 	    dec_cursor();
8783 	}
8784 	else
8785 	{
8786 #ifdef FEAT_VREPLACE
8787 	    if (!(State & VREPLACE_FLAG)
8788 				   || curwin->w_cursor.lnum > orig_line_count)
8789 #endif
8790 	    {
8791 		temp = gchar_cursor();	/* remember current char */
8792 		--curwin->w_cursor.lnum;
8793 
8794 		/* When "aw" is in 'formatoptions' we must delete the space at
8795 		 * the end of the line, otherwise the line will be broken
8796 		 * again when auto-formatting. */
8797 		if (has_format_option(FO_AUTO)
8798 					   && has_format_option(FO_WHITE_PAR))
8799 		{
8800 		    char_u  *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
8801 									TRUE);
8802 		    int	    len;
8803 
8804 		    len = (int)STRLEN(ptr);
8805 		    if (len > 0 && ptr[len - 1] == ' ')
8806 			ptr[len - 1] = NUL;
8807 		}
8808 
8809 		(void)do_join(2, FALSE, FALSE, FALSE);
8810 		if (temp == NUL && gchar_cursor() != NUL)
8811 		    inc_cursor();
8812 	    }
8813 #ifdef FEAT_VREPLACE
8814 	    else
8815 		dec_cursor();
8816 #endif
8817 
8818 	    /*
8819 	     * In REPLACE mode we have to put back the text that was replaced
8820 	     * by the NL. On the replace stack is first a NUL-terminated
8821 	     * sequence of characters that were deleted and then the
8822 	     * characters that NL replaced.
8823 	     */
8824 	    if (State & REPLACE_FLAG)
8825 	    {
8826 		/*
8827 		 * Do the next ins_char() in NORMAL state, to
8828 		 * prevent ins_char() from replacing characters and
8829 		 * avoiding showmatch().
8830 		 */
8831 		oldState = State;
8832 		State = NORMAL;
8833 		/*
8834 		 * restore characters (blanks) deleted after cursor
8835 		 */
8836 		while (cc > 0)
8837 		{
8838 		    save_col = curwin->w_cursor.col;
8839 #ifdef FEAT_MBYTE
8840 		    mb_replace_pop_ins(cc);
8841 #else
8842 		    ins_char(cc);
8843 #endif
8844 		    curwin->w_cursor.col = save_col;
8845 		    cc = replace_pop();
8846 		}
8847 		/* restore the characters that NL replaced */
8848 		replace_pop_ins();
8849 		State = oldState;
8850 	    }
8851 	}
8852 	did_ai = FALSE;
8853     }
8854     else
8855     {
8856 	/*
8857 	 * Delete character(s) before the cursor.
8858 	 */
8859 #ifdef FEAT_RIGHTLEFT
8860 	if (revins_on)		/* put cursor on last inserted char */
8861 	    dec_cursor();
8862 #endif
8863 	mincol = 0;
8864 						/* keep indent */
8865 	if (mode == BACKSPACE_LINE
8866 		&& (curbuf->b_p_ai
8867 #ifdef FEAT_CINDENT
8868 		    || cindent_on()
8869 #endif
8870 		   )
8871 #ifdef FEAT_RIGHTLEFT
8872 		&& !revins_on
8873 #endif
8874 			    )
8875 	{
8876 	    save_col = curwin->w_cursor.col;
8877 	    beginline(BL_WHITE);
8878 	    if (curwin->w_cursor.col < save_col)
8879 		mincol = curwin->w_cursor.col;
8880 	    curwin->w_cursor.col = save_col;
8881 	}
8882 
8883 	/*
8884 	 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8885 	 */
8886 	if (	   mode == BACKSPACE_CHAR
8887 		&& ((p_sta && in_indent)
8888 		    || (get_sts_value() != 0
8889 			&& curwin->w_cursor.col > 0
8890 			&& (*(ml_get_cursor() - 1) == TAB
8891 			    || (*(ml_get_cursor() - 1) == ' '
8892 				&& (!*inserted_space_p
8893 				    || arrow_used))))))
8894 	{
8895 	    int		ts;
8896 	    colnr_T	vcol;
8897 	    colnr_T	want_vcol;
8898 	    colnr_T	start_vcol;
8899 
8900 	    *inserted_space_p = FALSE;
8901 	    if (p_sta && in_indent)
8902 		ts = (int)get_sw_value();
8903 	    else
8904 		ts = (int)get_sts_value();
8905 	    /* Compute the virtual column where we want to be.  Since
8906 	     * 'showbreak' may get in the way, need to get the last column of
8907 	     * the previous character. */
8908 	    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8909 	    start_vcol = vcol;
8910 	    dec_cursor();
8911 	    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8912 	    inc_cursor();
8913 	    want_vcol = (want_vcol / ts) * ts;
8914 
8915 	    /* delete characters until we are at or before want_vcol */
8916 	    while (vcol > want_vcol
8917 		    && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8918 		ins_bs_one(&vcol);
8919 
8920 	    /* insert extra spaces until we are at want_vcol */
8921 	    while (vcol < want_vcol)
8922 	    {
8923 		/* Remember the first char we inserted */
8924 		if (curwin->w_cursor.lnum == Insstart.lnum
8925 				   && curwin->w_cursor.col < Insstart.col)
8926 		    Insstart.col = curwin->w_cursor.col;
8927 
8928 #ifdef FEAT_VREPLACE
8929 		if (State & VREPLACE_FLAG)
8930 		    ins_char(' ');
8931 		else
8932 #endif
8933 		{
8934 		    ins_str((char_u *)" ");
8935 		    if ((State & REPLACE_FLAG))
8936 			replace_push(NUL);
8937 		}
8938 		getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8939 	    }
8940 
8941 	    /* If we are now back where we started delete one character.  Can
8942 	     * happen when using 'sts' and 'linebreak'. */
8943 	    if (vcol >= start_vcol)
8944 		ins_bs_one(&vcol);
8945 	}
8946 
8947 	/*
8948 	 * Delete upto starting point, start of line or previous word.
8949 	 */
8950 	else do
8951 	{
8952 #ifdef FEAT_RIGHTLEFT
8953 	    if (!revins_on) /* put cursor on char to be deleted */
8954 #endif
8955 		dec_cursor();
8956 
8957 	    /* start of word? */
8958 	    if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8959 	    {
8960 		mode = BACKSPACE_WORD_NOT_SPACE;
8961 		temp = vim_iswordc(gchar_cursor());
8962 	    }
8963 	    /* end of word? */
8964 	    else if (mode == BACKSPACE_WORD_NOT_SPACE
8965 		    && (vim_isspace(cc = gchar_cursor())
8966 			    || vim_iswordc(cc) != temp))
8967 	    {
8968 #ifdef FEAT_RIGHTLEFT
8969 		if (!revins_on)
8970 #endif
8971 		    inc_cursor();
8972 #ifdef FEAT_RIGHTLEFT
8973 		else if (State & REPLACE_FLAG)
8974 		    dec_cursor();
8975 #endif
8976 		break;
8977 	    }
8978 	    if (State & REPLACE_FLAG)
8979 		replace_do_bs(-1);
8980 	    else
8981 	    {
8982 #ifdef FEAT_MBYTE
8983 		if (enc_utf8 && p_deco)
8984 		    (void)utfc_ptr2char(ml_get_cursor(), cpc);
8985 #endif
8986 		(void)del_char(FALSE);
8987 #ifdef FEAT_MBYTE
8988 		/*
8989 		 * If there are combining characters and 'delcombine' is set
8990 		 * move the cursor back.  Don't back up before the base
8991 		 * character.
8992 		 */
8993 		if (enc_utf8 && p_deco && cpc[0] != NUL)
8994 		    inc_cursor();
8995 #endif
8996 #ifdef FEAT_RIGHTLEFT
8997 		if (revins_chars)
8998 		{
8999 		    revins_chars--;
9000 		    revins_legal++;
9001 		}
9002 		if (revins_on && gchar_cursor() == NUL)
9003 		    break;
9004 #endif
9005 	    }
9006 	    /* Just a single backspace?: */
9007 	    if (mode == BACKSPACE_CHAR)
9008 		break;
9009 	} while (
9010 #ifdef FEAT_RIGHTLEFT
9011 		revins_on ||
9012 #endif
9013 		(curwin->w_cursor.col > mincol
9014 		 && (curwin->w_cursor.lnum != Insstart.lnum
9015 		     || curwin->w_cursor.col != Insstart.col)));
9016 	did_backspace = TRUE;
9017     }
9018 #ifdef FEAT_SMARTINDENT
9019     did_si = FALSE;
9020     can_si = FALSE;
9021     can_si_back = FALSE;
9022 #endif
9023     if (curwin->w_cursor.col <= 1)
9024 	did_ai = FALSE;
9025     /*
9026      * It's a little strange to put backspaces into the redo
9027      * buffer, but it makes auto-indent a lot easier to deal
9028      * with.
9029      */
9030     AppendCharToRedobuff(c);
9031 
9032     /* If deleted before the insertion point, adjust it */
9033     if (curwin->w_cursor.lnum == Insstart.lnum
9034 				       && curwin->w_cursor.col < Insstart.col)
9035 	Insstart.col = curwin->w_cursor.col;
9036 
9037     /* vi behaviour: the cursor moves backward but the character that
9038      *		     was there remains visible
9039      * Vim behaviour: the cursor moves backward and the character that
9040      *		      was there is erased from the screen.
9041      * We can emulate the vi behaviour by pretending there is a dollar
9042      * displayed even when there isn't.
9043      *  --pkv Sun Jan 19 01:56:40 EST 2003 */
9044     if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)
9045 	dollar_vcol = curwin->w_virtcol;
9046 
9047 #ifdef FEAT_FOLDING
9048     /* When deleting a char the cursor line must never be in a closed fold.
9049      * E.g., when 'foldmethod' is indent and deleting the first non-white
9050      * char before a Tab. */
9051     if (did_backspace)
9052 	foldOpenCursor();
9053 #endif
9054 
9055     return did_backspace;
9056 }
9057 
9058 #ifdef FEAT_MOUSE
9059     static void
9060 ins_mouse(c)
9061     int	    c;
9062 {
9063     pos_T	tpos;
9064     win_T	*old_curwin = curwin;
9065 
9066 # ifdef FEAT_GUI
9067     /* When GUI is active, also move/paste when 'mouse' is empty */
9068     if (!gui.in_use)
9069 # endif
9070 	if (!mouse_has(MOUSE_INSERT))
9071 	    return;
9072 
9073     undisplay_dollar();
9074     tpos = curwin->w_cursor;
9075     if (do_mouse(NULL, c, BACKWARD, 1L, 0))
9076     {
9077 #ifdef FEAT_WINDOWS
9078 	win_T	*new_curwin = curwin;
9079 
9080 	if (curwin != old_curwin && win_valid(old_curwin))
9081 	{
9082 	    /* Mouse took us to another window.  We need to go back to the
9083 	     * previous one to stop insert there properly. */
9084 	    curwin = old_curwin;
9085 	    curbuf = curwin->w_buffer;
9086 	}
9087 #endif
9088 	start_arrow(curwin == old_curwin ? &tpos : NULL);
9089 #ifdef FEAT_WINDOWS
9090 	if (curwin != new_curwin && win_valid(new_curwin))
9091 	{
9092 	    curwin = new_curwin;
9093 	    curbuf = curwin->w_buffer;
9094 	}
9095 #endif
9096 # ifdef FEAT_CINDENT
9097 	can_cindent = TRUE;
9098 # endif
9099     }
9100 
9101 #ifdef FEAT_WINDOWS
9102     /* redraw status lines (in case another window became active) */
9103     redraw_statuslines();
9104 #endif
9105 }
9106 
9107     static void
9108 ins_mousescroll(dir)
9109     int		dir;
9110 {
9111     pos_T	tpos;
9112 # if defined(FEAT_WINDOWS)
9113     win_T	*old_curwin = curwin;
9114 # endif
9115 # ifdef FEAT_INS_EXPAND
9116     int		did_scroll = FALSE;
9117 # endif
9118 
9119     tpos = curwin->w_cursor;
9120 
9121 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
9122     /* Currently the mouse coordinates are only known in the GUI. */
9123     if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
9124     {
9125 	int row, col;
9126 
9127 	row = mouse_row;
9128 	col = mouse_col;
9129 
9130 	/* find the window at the pointer coordinates */
9131 	curwin = mouse_find_win(&row, &col);
9132 	curbuf = curwin->w_buffer;
9133     }
9134     if (curwin == old_curwin)
9135 # endif
9136 	undisplay_dollar();
9137 
9138 # ifdef FEAT_INS_EXPAND
9139     /* Don't scroll the window in which completion is being done. */
9140     if (!pum_visible()
9141 #  if defined(FEAT_WINDOWS)
9142 	    || curwin != old_curwin
9143 #  endif
9144 	    )
9145 # endif
9146     {
9147 	if (dir == MSCR_DOWN || dir == MSCR_UP)
9148 	{
9149 	    if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
9150 		scroll_redraw(dir,
9151 			(long)(curwin->w_botline - curwin->w_topline));
9152 	    else
9153 		scroll_redraw(dir, 3L);
9154 	}
9155 #ifdef FEAT_GUI
9156 	else
9157 	{
9158 	    int val, step = 6;
9159 
9160 	    if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
9161 		step = W_WIDTH(curwin);
9162 	    val = curwin->w_leftcol + (dir == MSCR_RIGHT ? -step : step);
9163 	    if (val < 0)
9164 		val = 0;
9165 	    gui_do_horiz_scroll(val, TRUE);
9166 	}
9167 #endif
9168 # ifdef FEAT_INS_EXPAND
9169 	did_scroll = TRUE;
9170 # endif
9171     }
9172 
9173 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
9174     curwin->w_redr_status = TRUE;
9175 
9176     curwin = old_curwin;
9177     curbuf = curwin->w_buffer;
9178 # endif
9179 
9180 # ifdef FEAT_INS_EXPAND
9181     /* The popup menu may overlay the window, need to redraw it.
9182      * TODO: Would be more efficient to only redraw the windows that are
9183      * overlapped by the popup menu. */
9184     if (pum_visible() && did_scroll)
9185     {
9186 	redraw_all_later(NOT_VALID);
9187 	ins_compl_show_pum();
9188     }
9189 # endif
9190 
9191     if (!equalpos(curwin->w_cursor, tpos))
9192     {
9193 	start_arrow(&tpos);
9194 # ifdef FEAT_CINDENT
9195 	can_cindent = TRUE;
9196 # endif
9197     }
9198 }
9199 #endif
9200 
9201 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
9202     static void
9203 ins_tabline(c)
9204     int		c;
9205 {
9206     /* We will be leaving the current window, unless closing another tab. */
9207     if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
9208 		|| (current_tab != 0 && current_tab != tabpage_index(curtab)))
9209     {
9210 	undisplay_dollar();
9211 	start_arrow(&curwin->w_cursor);
9212 # ifdef FEAT_CINDENT
9213 	can_cindent = TRUE;
9214 # endif
9215     }
9216 
9217     if (c == K_TABLINE)
9218 	goto_tabpage(current_tab);
9219     else
9220     {
9221 	handle_tabmenu();
9222 	redraw_statuslines();	/* will redraw the tabline when needed */
9223     }
9224 }
9225 #endif
9226 
9227 #if defined(FEAT_GUI) || defined(PROTO)
9228     void
9229 ins_scroll()
9230 {
9231     pos_T	tpos;
9232 
9233     undisplay_dollar();
9234     tpos = curwin->w_cursor;
9235     if (gui_do_scroll())
9236     {
9237 	start_arrow(&tpos);
9238 # ifdef FEAT_CINDENT
9239 	can_cindent = TRUE;
9240 # endif
9241     }
9242 }
9243 
9244     void
9245 ins_horscroll()
9246 {
9247     pos_T	tpos;
9248 
9249     undisplay_dollar();
9250     tpos = curwin->w_cursor;
9251     if (gui_do_horiz_scroll(scrollbar_value, FALSE))
9252     {
9253 	start_arrow(&tpos);
9254 # ifdef FEAT_CINDENT
9255 	can_cindent = TRUE;
9256 # endif
9257     }
9258 }
9259 #endif
9260 
9261     static void
9262 ins_left()
9263 {
9264     pos_T	tpos;
9265 
9266 #ifdef FEAT_FOLDING
9267     if ((fdo_flags & FDO_HOR) && KeyTyped)
9268 	foldOpenCursor();
9269 #endif
9270     undisplay_dollar();
9271     tpos = curwin->w_cursor;
9272     if (oneleft() == OK)
9273     {
9274 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
9275 	/* Only call start_arrow() when not busy with preediting, it will
9276 	 * break undo.  K_LEFT is inserted in im_correct_cursor(). */
9277 	if (!im_is_preediting())
9278 #endif
9279 	    start_arrow(&tpos);
9280 #ifdef FEAT_RIGHTLEFT
9281 	/* If exit reversed string, position is fixed */
9282 	if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
9283 	    revins_legal++;
9284 	revins_chars++;
9285 #endif
9286     }
9287 
9288     /*
9289      * if 'whichwrap' set for cursor in insert mode may go to
9290      * previous line
9291      */
9292     else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
9293     {
9294 	start_arrow(&tpos);
9295 	--(curwin->w_cursor.lnum);
9296 	coladvance((colnr_T)MAXCOL);
9297 	curwin->w_set_curswant = TRUE;	/* so we stay at the end */
9298     }
9299     else
9300 	vim_beep();
9301 }
9302 
9303     static void
9304 ins_home(c)
9305     int		c;
9306 {
9307     pos_T	tpos;
9308 
9309 #ifdef FEAT_FOLDING
9310     if ((fdo_flags & FDO_HOR) && KeyTyped)
9311 	foldOpenCursor();
9312 #endif
9313     undisplay_dollar();
9314     tpos = curwin->w_cursor;
9315     if (c == K_C_HOME)
9316 	curwin->w_cursor.lnum = 1;
9317     curwin->w_cursor.col = 0;
9318 #ifdef FEAT_VIRTUALEDIT
9319     curwin->w_cursor.coladd = 0;
9320 #endif
9321     curwin->w_curswant = 0;
9322     start_arrow(&tpos);
9323 }
9324 
9325     static void
9326 ins_end(c)
9327     int		c;
9328 {
9329     pos_T	tpos;
9330 
9331 #ifdef FEAT_FOLDING
9332     if ((fdo_flags & FDO_HOR) && KeyTyped)
9333 	foldOpenCursor();
9334 #endif
9335     undisplay_dollar();
9336     tpos = curwin->w_cursor;
9337     if (c == K_C_END)
9338 	curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9339     coladvance((colnr_T)MAXCOL);
9340     curwin->w_curswant = MAXCOL;
9341 
9342     start_arrow(&tpos);
9343 }
9344 
9345     static void
9346 ins_s_left()
9347 {
9348 #ifdef FEAT_FOLDING
9349     if ((fdo_flags & FDO_HOR) && KeyTyped)
9350 	foldOpenCursor();
9351 #endif
9352     undisplay_dollar();
9353     if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
9354     {
9355 	start_arrow(&curwin->w_cursor);
9356 	(void)bck_word(1L, FALSE, FALSE);
9357 	curwin->w_set_curswant = TRUE;
9358     }
9359     else
9360 	vim_beep();
9361 }
9362 
9363     static void
9364 ins_right()
9365 {
9366 #ifdef FEAT_FOLDING
9367     if ((fdo_flags & FDO_HOR) && KeyTyped)
9368 	foldOpenCursor();
9369 #endif
9370     undisplay_dollar();
9371     if (gchar_cursor() != NUL
9372 #ifdef FEAT_VIRTUALEDIT
9373 	    || virtual_active()
9374 #endif
9375 	    )
9376     {
9377 	start_arrow(&curwin->w_cursor);
9378 	curwin->w_set_curswant = TRUE;
9379 #ifdef FEAT_VIRTUALEDIT
9380 	if (virtual_active())
9381 	    oneright();
9382 	else
9383 #endif
9384 	{
9385 #ifdef FEAT_MBYTE
9386 	    if (has_mbyte)
9387 		curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
9388 	    else
9389 #endif
9390 		++curwin->w_cursor.col;
9391 	}
9392 
9393 #ifdef FEAT_RIGHTLEFT
9394 	revins_legal++;
9395 	if (revins_chars)
9396 	    revins_chars--;
9397 #endif
9398     }
9399     /* if 'whichwrap' set for cursor in insert mode, may move the
9400      * cursor to the next line */
9401     else if (vim_strchr(p_ww, ']') != NULL
9402 	    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
9403     {
9404 	start_arrow(&curwin->w_cursor);
9405 	curwin->w_set_curswant = TRUE;
9406 	++curwin->w_cursor.lnum;
9407 	curwin->w_cursor.col = 0;
9408     }
9409     else
9410 	vim_beep();
9411 }
9412 
9413     static void
9414 ins_s_right()
9415 {
9416 #ifdef FEAT_FOLDING
9417     if ((fdo_flags & FDO_HOR) && KeyTyped)
9418 	foldOpenCursor();
9419 #endif
9420     undisplay_dollar();
9421     if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
9422 	    || gchar_cursor() != NUL)
9423     {
9424 	start_arrow(&curwin->w_cursor);
9425 	(void)fwd_word(1L, FALSE, 0);
9426 	curwin->w_set_curswant = TRUE;
9427     }
9428     else
9429 	vim_beep();
9430 }
9431 
9432     static void
9433 ins_up(startcol)
9434     int		startcol;	/* when TRUE move to Insstart.col */
9435 {
9436     pos_T	tpos;
9437     linenr_T	old_topline = curwin->w_topline;
9438 #ifdef FEAT_DIFF
9439     int		old_topfill = curwin->w_topfill;
9440 #endif
9441 
9442     undisplay_dollar();
9443     tpos = curwin->w_cursor;
9444     if (cursor_up(1L, TRUE) == OK)
9445     {
9446 	if (startcol)
9447 	    coladvance(getvcol_nolist(&Insstart));
9448 	if (old_topline != curwin->w_topline
9449 #ifdef FEAT_DIFF
9450 		|| old_topfill != curwin->w_topfill
9451 #endif
9452 		)
9453 	    redraw_later(VALID);
9454 	start_arrow(&tpos);
9455 #ifdef FEAT_CINDENT
9456 	can_cindent = TRUE;
9457 #endif
9458     }
9459     else
9460 	vim_beep();
9461 }
9462 
9463     static void
9464 ins_pageup()
9465 {
9466     pos_T	tpos;
9467 
9468     undisplay_dollar();
9469 
9470 #ifdef FEAT_WINDOWS
9471     if (mod_mask & MOD_MASK_CTRL)
9472     {
9473 	/* <C-PageUp>: tab page back */
9474 	if (first_tabpage->tp_next != NULL)
9475 	{
9476 	    start_arrow(&curwin->w_cursor);
9477 	    goto_tabpage(-1);
9478 	}
9479 	return;
9480     }
9481 #endif
9482 
9483     tpos = curwin->w_cursor;
9484     if (onepage(BACKWARD, 1L) == OK)
9485     {
9486 	start_arrow(&tpos);
9487 #ifdef FEAT_CINDENT
9488 	can_cindent = TRUE;
9489 #endif
9490     }
9491     else
9492 	vim_beep();
9493 }
9494 
9495     static void
9496 ins_down(startcol)
9497     int		startcol;	/* when TRUE move to Insstart.col */
9498 {
9499     pos_T	tpos;
9500     linenr_T	old_topline = curwin->w_topline;
9501 #ifdef FEAT_DIFF
9502     int		old_topfill = curwin->w_topfill;
9503 #endif
9504 
9505     undisplay_dollar();
9506     tpos = curwin->w_cursor;
9507     if (cursor_down(1L, TRUE) == OK)
9508     {
9509 	if (startcol)
9510 	    coladvance(getvcol_nolist(&Insstart));
9511 	if (old_topline != curwin->w_topline
9512 #ifdef FEAT_DIFF
9513 		|| old_topfill != curwin->w_topfill
9514 #endif
9515 		)
9516 	    redraw_later(VALID);
9517 	start_arrow(&tpos);
9518 #ifdef FEAT_CINDENT
9519 	can_cindent = TRUE;
9520 #endif
9521     }
9522     else
9523 	vim_beep();
9524 }
9525 
9526     static void
9527 ins_pagedown()
9528 {
9529     pos_T	tpos;
9530 
9531     undisplay_dollar();
9532 
9533 #ifdef FEAT_WINDOWS
9534     if (mod_mask & MOD_MASK_CTRL)
9535     {
9536 	/* <C-PageDown>: tab page forward */
9537 	if (first_tabpage->tp_next != NULL)
9538 	{
9539 	    start_arrow(&curwin->w_cursor);
9540 	    goto_tabpage(0);
9541 	}
9542 	return;
9543     }
9544 #endif
9545 
9546     tpos = curwin->w_cursor;
9547     if (onepage(FORWARD, 1L) == OK)
9548     {
9549 	start_arrow(&tpos);
9550 #ifdef FEAT_CINDENT
9551 	can_cindent = TRUE;
9552 #endif
9553     }
9554     else
9555 	vim_beep();
9556 }
9557 
9558 #ifdef FEAT_DND
9559     static void
9560 ins_drop()
9561 {
9562     do_put('~', BACKWARD, 1L, PUT_CURSEND);
9563 }
9564 #endif
9565 
9566 /*
9567  * Handle TAB in Insert or Replace mode.
9568  * Return TRUE when the TAB needs to be inserted like a normal character.
9569  */
9570     static int
9571 ins_tab()
9572 {
9573     int		ind;
9574     int		i;
9575     int		temp;
9576 
9577     if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
9578 	Insstart_blank_vcol = get_nolist_virtcol();
9579     if (echeck_abbr(TAB + ABBR_OFF))
9580 	return FALSE;
9581 
9582     ind = inindent(0);
9583 #ifdef FEAT_CINDENT
9584     if (ind)
9585 	can_cindent = FALSE;
9586 #endif
9587 
9588     /*
9589      * When nothing special, insert TAB like a normal character
9590      */
9591     if (!curbuf->b_p_et
9592 	    && !(p_sta && ind && curbuf->b_p_ts != get_sw_value())
9593 	    && get_sts_value() == 0)
9594 	return TRUE;
9595 
9596     if (stop_arrow() == FAIL)
9597 	return TRUE;
9598 
9599     did_ai = FALSE;
9600 #ifdef FEAT_SMARTINDENT
9601     did_si = FALSE;
9602     can_si = FALSE;
9603     can_si_back = FALSE;
9604 #endif
9605     AppendToRedobuff((char_u *)"\t");
9606 
9607     if (p_sta && ind)		/* insert tab in indent, use 'shiftwidth' */
9608 	temp = (int)get_sw_value();
9609     else if (curbuf->b_p_sts != 0) /* use 'softtabstop' when set */
9610 	temp = (int)get_sts_value();
9611     else			/* otherwise use 'tabstop' */
9612 	temp = (int)curbuf->b_p_ts;
9613     temp -= get_nolist_virtcol() % temp;
9614 
9615     /*
9616      * Insert the first space with ins_char().	It will delete one char in
9617      * replace mode.  Insert the rest with ins_str(); it will not delete any
9618      * chars.  For VREPLACE mode, we use ins_char() for all characters.
9619      */
9620     ins_char(' ');
9621     while (--temp > 0)
9622     {
9623 #ifdef FEAT_VREPLACE
9624 	if (State & VREPLACE_FLAG)
9625 	    ins_char(' ');
9626 	else
9627 #endif
9628 	{
9629 	    ins_str((char_u *)" ");
9630 	    if (State & REPLACE_FLAG)	    /* no char replaced */
9631 		replace_push(NUL);
9632 	}
9633     }
9634 
9635     /*
9636      * When 'expandtab' not set: Replace spaces by TABs where possible.
9637      */
9638     if (!curbuf->b_p_et && (get_sts_value() || (p_sta && ind)))
9639     {
9640 	char_u		*ptr;
9641 #ifdef FEAT_VREPLACE
9642 	char_u		*saved_line = NULL;	/* init for GCC */
9643 	pos_T		pos;
9644 #endif
9645 	pos_T		fpos;
9646 	pos_T		*cursor;
9647 	colnr_T		want_vcol, vcol;
9648 	int		change_col = -1;
9649 	int		save_list = curwin->w_p_list;
9650 
9651 	/*
9652 	 * Get the current line.  For VREPLACE mode, don't make real changes
9653 	 * yet, just work on a copy of the line.
9654 	 */
9655 #ifdef FEAT_VREPLACE
9656 	if (State & VREPLACE_FLAG)
9657 	{
9658 	    pos = curwin->w_cursor;
9659 	    cursor = &pos;
9660 	    saved_line = vim_strsave(ml_get_curline());
9661 	    if (saved_line == NULL)
9662 		return FALSE;
9663 	    ptr = saved_line + pos.col;
9664 	}
9665 	else
9666 #endif
9667 	{
9668 	    ptr = ml_get_cursor();
9669 	    cursor = &curwin->w_cursor;
9670 	}
9671 
9672 	/* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
9673 	if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9674 	    curwin->w_p_list = FALSE;
9675 
9676 	/* Find first white before the cursor */
9677 	fpos = curwin->w_cursor;
9678 	while (fpos.col > 0 && vim_iswhite(ptr[-1]))
9679 	{
9680 	    --fpos.col;
9681 	    --ptr;
9682 	}
9683 
9684 	/* In Replace mode, don't change characters before the insert point. */
9685 	if ((State & REPLACE_FLAG)
9686 		&& fpos.lnum == Insstart.lnum
9687 		&& fpos.col < Insstart.col)
9688 	{
9689 	    ptr += Insstart.col - fpos.col;
9690 	    fpos.col = Insstart.col;
9691 	}
9692 
9693 	/* compute virtual column numbers of first white and cursor */
9694 	getvcol(curwin, &fpos, &vcol, NULL, NULL);
9695 	getvcol(curwin, cursor, &want_vcol, NULL, NULL);
9696 
9697 	/* Use as many TABs as possible.  Beware of 'showbreak' and
9698 	 * 'linebreak' adding extra virtual columns. */
9699 	while (vim_iswhite(*ptr))
9700 	{
9701 	    i = lbr_chartabsize((char_u *)"\t", vcol);
9702 	    if (vcol + i > want_vcol)
9703 		break;
9704 	    if (*ptr != TAB)
9705 	    {
9706 		*ptr = TAB;
9707 		if (change_col < 0)
9708 		{
9709 		    change_col = fpos.col;  /* Column of first change */
9710 		    /* May have to adjust Insstart */
9711 		    if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
9712 			Insstart.col = fpos.col;
9713 		}
9714 	    }
9715 	    ++fpos.col;
9716 	    ++ptr;
9717 	    vcol += i;
9718 	}
9719 
9720 	if (change_col >= 0)
9721 	{
9722 	    int repl_off = 0;
9723 
9724 	    /* Skip over the spaces we need. */
9725 	    while (vcol < want_vcol && *ptr == ' ')
9726 	    {
9727 		vcol += lbr_chartabsize(ptr, vcol);
9728 		++ptr;
9729 		++repl_off;
9730 	    }
9731 	    if (vcol > want_vcol)
9732 	    {
9733 		/* Must have a char with 'showbreak' just before it. */
9734 		--ptr;
9735 		--repl_off;
9736 	    }
9737 	    fpos.col += repl_off;
9738 
9739 	    /* Delete following spaces. */
9740 	    i = cursor->col - fpos.col;
9741 	    if (i > 0)
9742 	    {
9743 		STRMOVE(ptr, ptr + i);
9744 		/* correct replace stack. */
9745 		if ((State & REPLACE_FLAG)
9746 #ifdef FEAT_VREPLACE
9747 			&& !(State & VREPLACE_FLAG)
9748 #endif
9749 			)
9750 		    for (temp = i; --temp >= 0; )
9751 			replace_join(repl_off);
9752 	    }
9753 #ifdef FEAT_NETBEANS_INTG
9754 	    if (netbeans_active())
9755 	    {
9756 		netbeans_removed(curbuf, fpos.lnum, cursor->col, (long)(i + 1));
9757 		netbeans_inserted(curbuf, fpos.lnum, cursor->col,
9758 							   (char_u *)"\t", 1);
9759 	    }
9760 #endif
9761 	    cursor->col -= i;
9762 
9763 #ifdef FEAT_VREPLACE
9764 	    /*
9765 	     * In VREPLACE mode, we haven't changed anything yet.  Do it now by
9766 	     * backspacing over the changed spacing and then inserting the new
9767 	     * spacing.
9768 	     */
9769 	    if (State & VREPLACE_FLAG)
9770 	    {
9771 		/* Backspace from real cursor to change_col */
9772 		backspace_until_column(change_col);
9773 
9774 		/* Insert each char in saved_line from changed_col to
9775 		 * ptr-cursor */
9776 		ins_bytes_len(saved_line + change_col,
9777 						    cursor->col - change_col);
9778 	    }
9779 #endif
9780 	}
9781 
9782 #ifdef FEAT_VREPLACE
9783 	if (State & VREPLACE_FLAG)
9784 	    vim_free(saved_line);
9785 #endif
9786 	curwin->w_p_list = save_list;
9787     }
9788 
9789     return FALSE;
9790 }
9791 
9792 /*
9793  * Handle CR or NL in insert mode.
9794  * Return TRUE when out of memory or can't undo.
9795  */
9796     static int
9797 ins_eol(c)
9798     int		c;
9799 {
9800     int	    i;
9801 
9802     if (echeck_abbr(c + ABBR_OFF))
9803 	return FALSE;
9804     if (stop_arrow() == FAIL)
9805 	return TRUE;
9806     undisplay_dollar();
9807 
9808     /*
9809      * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
9810      * character under the cursor.  Only push a NUL on the replace stack,
9811      * nothing to put back when the NL is deleted.
9812      */
9813     if ((State & REPLACE_FLAG)
9814 #ifdef FEAT_VREPLACE
9815 	    && !(State & VREPLACE_FLAG)
9816 #endif
9817 	    )
9818 	replace_push(NUL);
9819 
9820     /*
9821      * In VREPLACE mode, a NL replaces the rest of the line, and starts
9822      * replacing the next line, so we push all of the characters left on the
9823      * line onto the replace stack.  This is not done here though, it is done
9824      * in open_line().
9825      */
9826 
9827 #ifdef FEAT_VIRTUALEDIT
9828     /* Put cursor on NUL if on the last char and coladd is 1 (happens after
9829      * CTRL-O). */
9830     if (virtual_active() && curwin->w_cursor.coladd > 0)
9831 	coladvance(getviscol());
9832 #endif
9833 
9834 #ifdef FEAT_RIGHTLEFT
9835 # ifdef FEAT_FKMAP
9836     if (p_altkeymap && p_fkmap)
9837 	fkmap(NL);
9838 # endif
9839     /* NL in reverse insert will always start in the end of
9840      * current line. */
9841     if (revins_on)
9842 	curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9843 #endif
9844 
9845     AppendToRedobuff(NL_STR);
9846     i = open_line(FORWARD,
9847 #ifdef FEAT_COMMENTS
9848 	    has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
9849 #endif
9850 	    0, old_indent);
9851     old_indent = 0;
9852 #ifdef FEAT_CINDENT
9853     can_cindent = TRUE;
9854 #endif
9855 #ifdef FEAT_FOLDING
9856     /* When inserting a line the cursor line must never be in a closed fold. */
9857     foldOpenCursor();
9858 #endif
9859 
9860     return (!i);
9861 }
9862 
9863 #ifdef FEAT_DIGRAPHS
9864 /*
9865  * Handle digraph in insert mode.
9866  * Returns character still to be inserted, or NUL when nothing remaining to be
9867  * done.
9868  */
9869     static int
9870 ins_digraph()
9871 {
9872     int	    c;
9873     int	    cc;
9874     int	    did_putchar = FALSE;
9875 
9876     pc_status = PC_STATUS_UNSET;
9877     if (redrawing() && !char_avail())
9878     {
9879 	/* may need to redraw when no more chars available now */
9880 	ins_redraw(FALSE);
9881 
9882 	edit_putchar('?', TRUE);
9883 	did_putchar = TRUE;
9884 #ifdef FEAT_CMDL_INFO
9885 	add_to_showcmd_c(Ctrl_K);
9886 #endif
9887     }
9888 
9889 #ifdef USE_ON_FLY_SCROLL
9890     dont_scroll = TRUE;		/* disallow scrolling here */
9891 #endif
9892 
9893     /* don't map the digraph chars. This also prevents the
9894      * mode message to be deleted when ESC is hit */
9895     ++no_mapping;
9896     ++allow_keys;
9897     c = plain_vgetc();
9898     --no_mapping;
9899     --allow_keys;
9900     if (did_putchar)
9901 	/* when the line fits in 'columns' the '?' is at the start of the next
9902 	 * line and will not be removed by the redraw */
9903 	edit_unputchar();
9904 
9905     if (IS_SPECIAL(c) || mod_mask)	    /* special key */
9906     {
9907 #ifdef FEAT_CMDL_INFO
9908 	clear_showcmd();
9909 #endif
9910 	insert_special(c, TRUE, FALSE);
9911 	return NUL;
9912     }
9913     if (c != ESC)
9914     {
9915 	did_putchar = FALSE;
9916 	if (redrawing() && !char_avail())
9917 	{
9918 	    /* may need to redraw when no more chars available now */
9919 	    ins_redraw(FALSE);
9920 
9921 	    if (char2cells(c) == 1)
9922 	    {
9923 		ins_redraw(FALSE);
9924 		edit_putchar(c, TRUE);
9925 		did_putchar = TRUE;
9926 	    }
9927 #ifdef FEAT_CMDL_INFO
9928 	    add_to_showcmd_c(c);
9929 #endif
9930 	}
9931 	++no_mapping;
9932 	++allow_keys;
9933 	cc = plain_vgetc();
9934 	--no_mapping;
9935 	--allow_keys;
9936 	if (did_putchar)
9937 	    /* when the line fits in 'columns' the '?' is at the start of the
9938 	     * next line and will not be removed by a redraw */
9939 	    edit_unputchar();
9940 	if (cc != ESC)
9941 	{
9942 	    AppendToRedobuff((char_u *)CTRL_V_STR);
9943 	    c = getdigraph(c, cc, TRUE);
9944 #ifdef FEAT_CMDL_INFO
9945 	    clear_showcmd();
9946 #endif
9947 	    return c;
9948 	}
9949     }
9950 #ifdef FEAT_CMDL_INFO
9951     clear_showcmd();
9952 #endif
9953     return NUL;
9954 }
9955 #endif
9956 
9957 /*
9958  * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9959  * Returns the char to be inserted, or NUL if none found.
9960  */
9961     int
9962 ins_copychar(lnum)
9963     linenr_T	lnum;
9964 {
9965     int	    c;
9966     int	    temp;
9967     char_u  *ptr, *prev_ptr;
9968 
9969     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9970     {
9971 	vim_beep();
9972 	return NUL;
9973     }
9974 
9975     /* try to advance to the cursor column */
9976     temp = 0;
9977     ptr = ml_get(lnum);
9978     prev_ptr = ptr;
9979     validate_virtcol();
9980     while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9981     {
9982 	prev_ptr = ptr;
9983 	temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
9984     }
9985     if ((colnr_T)temp > curwin->w_virtcol)
9986 	ptr = prev_ptr;
9987 
9988 #ifdef FEAT_MBYTE
9989     c = (*mb_ptr2char)(ptr);
9990 #else
9991     c = *ptr;
9992 #endif
9993     if (c == NUL)
9994 	vim_beep();
9995     return c;
9996 }
9997 
9998 /*
9999  * CTRL-Y or CTRL-E typed in Insert mode.
10000  */
10001     static int
10002 ins_ctrl_ey(tc)
10003     int	    tc;
10004 {
10005     int	    c = tc;
10006 
10007 #ifdef FEAT_INS_EXPAND
10008     if (ctrl_x_mode == CTRL_X_SCROLL)
10009     {
10010 	if (c == Ctrl_Y)
10011 	    scrolldown_clamp();
10012 	else
10013 	    scrollup_clamp();
10014 	redraw_later(VALID);
10015     }
10016     else
10017 #endif
10018     {
10019 	c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
10020 	if (c != NUL)
10021 	{
10022 	    long	tw_save;
10023 
10024 	    /* The character must be taken literally, insert like it
10025 	     * was typed after a CTRL-V, and pretend 'textwidth'
10026 	     * wasn't set.  Digits, 'o' and 'x' are special after a
10027 	     * CTRL-V, don't use it for these. */
10028 	    if (c < 256 && !isalnum(c))
10029 		AppendToRedobuff((char_u *)CTRL_V_STR);	/* CTRL-V */
10030 	    tw_save = curbuf->b_p_tw;
10031 	    curbuf->b_p_tw = -1;
10032 	    insert_special(c, TRUE, FALSE);
10033 	    curbuf->b_p_tw = tw_save;
10034 #ifdef FEAT_RIGHTLEFT
10035 	    revins_chars++;
10036 	    revins_legal++;
10037 #endif
10038 	    c = Ctrl_V;	/* pretend CTRL-V is last character */
10039 	    auto_format(FALSE, TRUE);
10040 	}
10041     }
10042     return c;
10043 }
10044 
10045 #ifdef FEAT_SMARTINDENT
10046 /*
10047  * Try to do some very smart auto-indenting.
10048  * Used when inserting a "normal" character.
10049  */
10050     static void
10051 ins_try_si(c)
10052     int	    c;
10053 {
10054     pos_T	*pos, old_pos;
10055     char_u	*ptr;
10056     int		i;
10057     int		temp;
10058 
10059     /*
10060      * do some very smart indenting when entering '{' or '}'
10061      */
10062     if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
10063     {
10064 	/*
10065 	 * for '}' set indent equal to indent of line containing matching '{'
10066 	 */
10067 	if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
10068 	{
10069 	    old_pos = curwin->w_cursor;
10070 	    /*
10071 	     * If the matching '{' has a ')' immediately before it (ignoring
10072 	     * white-space), then line up with the start of the line
10073 	     * containing the matching '(' if there is one.  This handles the
10074 	     * case where an "if (..\n..) {" statement continues over multiple
10075 	     * lines -- webb
10076 	     */
10077 	    ptr = ml_get(pos->lnum);
10078 	    i = pos->col;
10079 	    if (i > 0)		/* skip blanks before '{' */
10080 		while (--i > 0 && vim_iswhite(ptr[i]))
10081 		    ;
10082 	    curwin->w_cursor.lnum = pos->lnum;
10083 	    curwin->w_cursor.col = i;
10084 	    if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
10085 		curwin->w_cursor = *pos;
10086 	    i = get_indent();
10087 	    curwin->w_cursor = old_pos;
10088 #ifdef FEAT_VREPLACE
10089 	    if (State & VREPLACE_FLAG)
10090 		change_indent(INDENT_SET, i, FALSE, NUL, TRUE);
10091 	    else
10092 #endif
10093 		(void)set_indent(i, SIN_CHANGED);
10094 	}
10095 	else if (curwin->w_cursor.col > 0)
10096 	{
10097 	    /*
10098 	     * when inserting '{' after "O" reduce indent, but not
10099 	     * more than indent of previous line
10100 	     */
10101 	    temp = TRUE;
10102 	    if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
10103 	    {
10104 		old_pos = curwin->w_cursor;
10105 		i = get_indent();
10106 		while (curwin->w_cursor.lnum > 1)
10107 		{
10108 		    ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
10109 
10110 		    /* ignore empty lines and lines starting with '#'. */
10111 		    if (*ptr != '#' && *ptr != NUL)
10112 			break;
10113 		}
10114 		if (get_indent() >= i)
10115 		    temp = FALSE;
10116 		curwin->w_cursor = old_pos;
10117 	    }
10118 	    if (temp)
10119 		shift_line(TRUE, FALSE, 1, TRUE);
10120 	}
10121     }
10122 
10123     /*
10124      * set indent of '#' always to 0
10125      */
10126     if (curwin->w_cursor.col > 0 && can_si && c == '#')
10127     {
10128 	/* remember current indent for next line */
10129 	old_indent = get_indent();
10130 	(void)set_indent(0, SIN_CHANGED);
10131     }
10132 
10133     /* Adjust ai_col, the char at this position can be deleted. */
10134     if (ai_col > curwin->w_cursor.col)
10135 	ai_col = curwin->w_cursor.col;
10136 }
10137 #endif
10138 
10139 /*
10140  * Get the value that w_virtcol would have when 'list' is off.
10141  * Unless 'cpo' contains the 'L' flag.
10142  */
10143     static colnr_T
10144 get_nolist_virtcol()
10145 {
10146     if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
10147 	return getvcol_nolist(&curwin->w_cursor);
10148     validate_virtcol();
10149     return curwin->w_virtcol;
10150 }
10151 
10152 #ifdef FEAT_AUTOCMD
10153 /*
10154  * Handle the InsertCharPre autocommand.
10155  * "c" is the character that was typed.
10156  * Return a pointer to allocated memory with the replacement string.
10157  * Return NULL to continue inserting "c".
10158  */
10159     static char_u *
10160 do_insert_char_pre(c)
10161     int c;
10162 {
10163     char_u	*res;
10164     char_u	buf[MB_MAXBYTES + 1];
10165 
10166     /* Return quickly when there is nothing to do. */
10167     if (!has_insertcharpre())
10168 	return NULL;
10169 
10170 #ifdef FEAT_MBYTE
10171     if (has_mbyte)
10172 	buf[(*mb_char2bytes)(c, buf)] = NUL;
10173     else
10174 #endif
10175     {
10176 	buf[0] = c;
10177 	buf[1] = NUL;
10178     }
10179 
10180     /* Lock the text to avoid weird things from happening. */
10181     ++textlock;
10182     set_vim_var_string(VV_CHAR, buf, -1);  /* set v:char */
10183 
10184     res = NULL;
10185     if (apply_autocmds(EVENT_INSERTCHARPRE, NULL, NULL, FALSE, curbuf))
10186     {
10187 	/* Get the value of v:char.  It may be empty or more than one
10188 	 * character.  Only use it when changed, otherwise continue with the
10189 	 * original character to avoid breaking autoindent. */
10190 	if (STRCMP(buf, get_vim_var_str(VV_CHAR)) != 0)
10191 	    res = vim_strsave(get_vim_var_str(VV_CHAR));
10192     }
10193 
10194     set_vim_var_string(VV_CHAR, NULL, -1);  /* clear v:char */
10195     --textlock;
10196 
10197     return res;
10198 }
10199 #endif
10200