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