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