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