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