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