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