xref: /vim-8.2.3635/src/edit.c (revision 92d640fa)
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_OCCULT		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_(" Occult 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_OCCULT)
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_OCCULT:
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_OCCULT;
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 'occultfunc', 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_OCCULT 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_OCCULT:
2852 	    num_matches = expand_by_function(type, compl_pattern, &matches);
2853 	    if (num_matches > 0)
2854 		ins_compl_add_matches(num_matches, matches, dir);
2855 	    break;
2856 #endif
2857 
2858 	case CTRL_X_SPELL:
2859 #ifdef FEAT_SYN_HL
2860 	    num_matches = expand_spelling(first_match_pos.lnum,
2861 				 first_match_pos.col, compl_pattern, &matches);
2862 	    if (num_matches > 0)
2863 		ins_compl_add_matches(num_matches, matches, dir);
2864 #endif
2865 	    break;
2866 
2867 	default:	/* normal ^P/^N and ^X^L */
2868 	    /*
2869 	     * If 'infercase' is set, don't use 'smartcase' here
2870 	     */
2871 	    save_p_scs = p_scs;
2872 	    if (ins_buf->b_p_inf)
2873 		p_scs = FALSE;
2874 
2875 	    /*	buffers other than curbuf are scanned from the beginning or the
2876 	     *	end but never from the middle, thus setting nowrapscan in this
2877 	     *	buffers is a good idea, on the other hand, we always set
2878 	     *	wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
2879 	    save_p_ws = p_ws;
2880 	    if (ins_buf != curbuf)
2881 		p_ws = FALSE;
2882 	    else if (*e_cpt == '.')
2883 		p_ws = TRUE;
2884 	    for (;;)
2885 	    {
2886 		int	flags = 0;
2887 
2888 		/* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that has
2889 		 * added a word that was at the beginning of the line */
2890 		if (	ctrl_x_mode == CTRL_X_WHOLE_LINE
2891 			|| (compl_cont_status & CONT_SOL))
2892 		    found_new_match = search_for_exact_line(ins_buf, pos,
2893 							    dir, compl_pattern);
2894 		else
2895 		    found_new_match = searchit(NULL, ins_buf, pos, dir,
2896 				 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
2897 								     RE_LAST);
2898 		if (!compl_started)
2899 		{
2900 		    /* set compl_started even on fail */
2901 		    compl_started = TRUE;
2902 		    first_match_pos = *pos;
2903 		    last_match_pos = *pos;
2904 		}
2905 		else if (first_match_pos.lnum == last_match_pos.lnum
2906 			 && first_match_pos.col == last_match_pos.col)
2907 		    found_new_match = FAIL;
2908 		if (found_new_match == FAIL)
2909 		{
2910 		    if (ins_buf == curbuf)
2911 			found_all = TRUE;
2912 		    break;
2913 		}
2914 
2915 		/* when ADDING, the text before the cursor matches, skip it */
2916 		if (	(compl_cont_status & CONT_ADDING) && ins_buf == curbuf
2917 			&& ini->lnum == pos->lnum
2918 			&& ini->col  == pos->col)
2919 		    continue;
2920 		ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
2921 		if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2922 		{
2923 		    if (compl_cont_status & CONT_ADDING)
2924 		    {
2925 			if (pos->lnum >= ins_buf->b_ml.ml_line_count)
2926 			    continue;
2927 			ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
2928 			if (!p_paste)
2929 			    ptr = skipwhite(ptr);
2930 		    }
2931 		    len = (int)STRLEN(ptr);
2932 		}
2933 		else
2934 		{
2935 		    char_u	*tmp_ptr = ptr;
2936 
2937 		    if (compl_cont_status & CONT_ADDING)
2938 		    {
2939 			tmp_ptr += compl_length;
2940 			/* Skip if already inside a word. */
2941 			if (vim_iswordp(tmp_ptr))
2942 			    continue;
2943 			/* Find start of next word. */
2944 			tmp_ptr = find_word_start(tmp_ptr);
2945 		    }
2946 		    /* Find end of this word. */
2947 		    tmp_ptr = find_word_end(tmp_ptr);
2948 		    len = (int)(tmp_ptr - ptr);
2949 
2950 		    if ((compl_cont_status & CONT_ADDING)
2951 						       && len == compl_length)
2952 		    {
2953 			if (pos->lnum < ins_buf->b_ml.ml_line_count)
2954 			{
2955 			    /* Try next line, if any. the new word will be
2956 			     * "join" as if the normal command "J" was used.
2957 			     * IOSIZE is always greater than
2958 			     * compl_length, so the next STRNCPY always
2959 			     * works -- Acevedo */
2960 			    STRNCPY(IObuff, ptr, len);
2961 			    ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
2962 			    tmp_ptr = ptr = skipwhite(ptr);
2963 			    /* Find start of next word. */
2964 			    tmp_ptr = find_word_start(tmp_ptr);
2965 			    /* Find end of next word. */
2966 			    tmp_ptr = find_word_end(tmp_ptr);
2967 			    if (tmp_ptr > ptr)
2968 			    {
2969 				if (*ptr != ')' && IObuff[len - 1] != TAB)
2970 				{
2971 				    if (IObuff[len - 1] != ' ')
2972 					IObuff[len++] = ' ';
2973 				    /* IObuf =~ "\k.* ", thus len >= 2 */
2974 				    if (p_js
2975 					&& (IObuff[len - 2] == '.'
2976 					    || (vim_strchr(p_cpo, CPO_JOINSP)
2977 								       == NULL
2978 						&& (IObuff[len - 2] == '?'
2979 						 || IObuff[len - 2] == '!'))))
2980 					IObuff[len++] = ' ';
2981 				}
2982 				/* copy as much as posible of the new word */
2983 				if (tmp_ptr - ptr >= IOSIZE - len)
2984 				    tmp_ptr = ptr + IOSIZE - len - 1;
2985 				STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
2986 				len += (int)(tmp_ptr - ptr);
2987 				flags |= CONT_S_IPOS;
2988 			    }
2989 			    IObuff[len] = NUL;
2990 			    ptr = IObuff;
2991 			}
2992 			if (len == compl_length)
2993 			    continue;
2994 		    }
2995 		}
2996 		if (ins_compl_add_infercase(ptr, len,
2997 			    ins_buf == curbuf ?  NULL : ins_buf->b_sfname,
2998 						       dir, flags) != NOTDONE)
2999 		{
3000 		    found_new_match = OK;
3001 		    break;
3002 		}
3003 	    }
3004 	    p_scs = save_p_scs;
3005 	    p_ws = save_p_ws;
3006 	}
3007 	/* check if compl_curr_match has changed, (e.g. other type of
3008 	 * expansion added somenthing) */
3009 	if (compl_curr_match != old_match)
3010 	    found_new_match = OK;
3011 
3012 	/* break the loop for specialized modes (use 'complete' just for the
3013 	 * generic ctrl_x_mode == 0) or when we've found a new match */
3014 	if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
3015 						   || found_new_match != FAIL)
3016 	    break;
3017 
3018 	/* Mark a buffer scanned when it has been scanned completely */
3019 	if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3020 	    ins_buf->b_scanned = TRUE;
3021 
3022 	compl_started = FALSE;
3023     }
3024     compl_started = TRUE;
3025 
3026     if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3027 	    && *e_cpt == NUL)		/* Got to end of 'complete' */
3028 	found_new_match = FAIL;
3029 
3030     i = -1;		/* total of matches, unknown */
3031     if (found_new_match == FAIL
3032 	    || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
3033 	i = ins_compl_make_cyclic();
3034 
3035     /* If several matches were added (FORWARD) or the search failed and has
3036      * just been made cyclic then we have to move compl_curr_match to the next
3037      * or previous entry (if any) -- Acevedo */
3038     compl_curr_match = dir == FORWARD ? old_match->cp_next : old_match->cp_prev;
3039     if (compl_curr_match == NULL)
3040 	compl_curr_match = old_match;
3041     return i;
3042 }
3043 
3044 /* Delete the old text being completed. */
3045     static void
3046 ins_compl_delete()
3047 {
3048     int	    i;
3049 
3050     /*
3051      * In insert mode: Delete the typed part.
3052      * In replace mode: Put the old characters back, if any.
3053      */
3054     i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
3055     backspace_until_column(i);
3056     changed_cline_bef_curs();
3057 }
3058 
3059 /* Insert the new text being completed. */
3060     static void
3061 ins_compl_insert()
3062 {
3063     ins_bytes(compl_shown_match->cp_str + curwin->w_cursor.col - compl_col);
3064 }
3065 
3066 /*
3067  * Fill in the next completion in the current direction.
3068  * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
3069  * get more completions.  If it is FALSE, then we just do nothing when there
3070  * are no more completions in a given direction.  The latter case is used when
3071  * we are still in the middle of finding completions, to allow browsing
3072  * through the ones found so far.
3073  * Return the total number of matches, or -1 if still unknown -- webb.
3074  *
3075  * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
3076  * compl_shown_match here.
3077  *
3078  * Note that this function may be called recursively once only.  First with
3079  * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
3080  * calls this function with "allow_get_expansion" FALSE.
3081  */
3082     static int
3083 ins_compl_next(allow_get_expansion)
3084     int	    allow_get_expansion;
3085 {
3086     int	    num_matches = -1;
3087     int	    i;
3088 
3089     if (allow_get_expansion)
3090     {
3091 	/* Delete old text to be replaced */
3092 	ins_compl_delete();
3093     }
3094     compl_pending = FALSE;
3095     if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
3096 	compl_shown_match = compl_shown_match->cp_next;
3097     else if (compl_shows_dir == BACKWARD && compl_shown_match->cp_prev != NULL)
3098 	compl_shown_match = compl_shown_match->cp_prev;
3099     else
3100     {
3101 	compl_pending = TRUE;
3102 	if (allow_get_expansion)
3103 	{
3104 	    num_matches = ins_compl_get_exp(&compl_startpos,
3105 							  compl_direction);
3106 	    if (compl_pending)
3107 	    {
3108 		if (compl_direction == compl_shows_dir)
3109 		    compl_shown_match = compl_curr_match;
3110 	    }
3111 	}
3112 	else
3113 	    return -1;
3114     }
3115 
3116     /* Insert the text of the new completion */
3117     ins_compl_insert();
3118 
3119     if (!allow_get_expansion)
3120     {
3121 	/* Display the current match. */
3122 	update_screen(0);
3123 
3124 	/* Delete old text to be replaced, since we're still searching and
3125 	 * don't want to match ourselves!  */
3126 	ins_compl_delete();
3127     }
3128 
3129     /*
3130      * Show the file name for the match (if any)
3131      * Truncate the file name to avoid a wait for return.
3132      */
3133     if (compl_shown_match->cp_fname != NULL)
3134     {
3135 	STRCPY(IObuff, "match in file ");
3136 	i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
3137 	if (i <= 0)
3138 	    i = 0;
3139 	else
3140 	    STRCAT(IObuff, "<");
3141 	STRCAT(IObuff, compl_shown_match->cp_fname + i);
3142 	msg(IObuff);
3143 	redraw_cmdline = FALSE;	    /* don't overwrite! */
3144     }
3145 
3146     return num_matches;
3147 }
3148 
3149 /*
3150  * Call this while finding completions, to check whether the user has hit a key
3151  * that should change the currently displayed completion, or exit completion
3152  * mode.  Also, when compl_pending is TRUE, show a completion as soon as
3153  * possible. -- webb
3154  * "frequency" specifies out of how many calls we actually check.
3155  */
3156     void
3157 ins_compl_check_keys(frequency)
3158     int		frequency;
3159 {
3160     static int	count = 0;
3161 
3162     int	    c;
3163 
3164     /* Don't check when reading keys from a script.  That would break the test
3165      * scripts */
3166     if (using_script())
3167 	return;
3168 
3169     /* Only do this at regular intervals */
3170     if (++count < frequency)
3171 	return;
3172     count = 0;
3173 
3174     ++no_mapping;
3175     c = vpeekc_any();
3176     --no_mapping;
3177     if (c != NUL)
3178     {
3179 	if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
3180 	{
3181 	    c = safe_vgetc();	/* Eat the character */
3182 	    if (c == Ctrl_P || c == Ctrl_L)
3183 		compl_shows_dir = BACKWARD;
3184 	    else
3185 		compl_shows_dir = FORWARD;
3186 	    (void)ins_compl_next(FALSE);
3187 	}
3188 	else if (c != Ctrl_R)
3189 	    compl_interrupted = TRUE;
3190     }
3191     if (compl_pending && !got_int)
3192 	(void)ins_compl_next(FALSE);
3193 }
3194 
3195 /*
3196  * Do Insert mode completion.
3197  * Called when character "c" was typed, which has a meaning for completion.
3198  * Returns OK if completion was done, FAIL if something failed (out of mem).
3199  */
3200     static int
3201 ins_complete(c)
3202     int		c;
3203 {
3204     char_u	*line;
3205     int		startcol = 0;	    /* column where searched text starts */
3206     colnr_T	curs_col;	    /* cursor column */
3207     int		n;
3208 
3209     if (c == Ctrl_P || c == Ctrl_L)
3210 	compl_direction = BACKWARD;
3211     else
3212 	compl_direction = FORWARD;
3213     if (!compl_started)
3214     {
3215 	/* First time we hit ^N or ^P (in a row, I mean) */
3216 
3217 	/* Turn off 'sm' so we don't show matches with ^X^L */
3218 	save_sm = p_sm;
3219 	p_sm = FALSE;
3220 
3221 	did_ai = FALSE;
3222 #ifdef FEAT_SMARTINDENT
3223 	did_si = FALSE;
3224 	can_si = FALSE;
3225 	can_si_back = FALSE;
3226 #endif
3227 	if (stop_arrow() == FAIL)
3228 	    return FAIL;
3229 
3230 	line = ml_get(curwin->w_cursor.lnum);
3231 	curs_col = curwin->w_cursor.col;
3232 
3233 	/* if this same ctrl_x_mode has been interrupted use the text from
3234 	 * "compl_startpos" to the cursor as a pattern to add a new word
3235 	 * instead of expand the one before the cursor, in word-wise if
3236 	 * "compl_startpos"
3237 	 * is not in the same line as the cursor then fix it (the line has
3238 	 * been split because it was longer than 'tw').  if SOL is set then
3239 	 * skip the previous pattern, a word at the beginning of the line has
3240 	 * been inserted, we'll look for that  -- Acevedo. */
3241 	if ((compl_cont_status & CONT_INTRPT) && compl_cont_mode == ctrl_x_mode)
3242 	{
3243 	    /*
3244 	     * it is a continued search
3245 	     */
3246 	    compl_cont_status &= ~CONT_INTRPT;	/* remove INTRPT */
3247 	    if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
3248 					|| ctrl_x_mode == CTRL_X_PATH_DEFINES)
3249 	    {
3250 		if (compl_startpos.lnum != curwin->w_cursor.lnum)
3251 		{
3252 		    /* line (probably) wrapped, set compl_startpos to the
3253 		     * first non_blank in the line, if it is not a wordchar
3254 		     * include it to get a better pattern, but then we don't
3255 		     * want the "\\<" prefix, check it bellow */
3256 		    compl_col = (colnr_T)(skipwhite(line) - line);
3257 		    compl_startpos.col = compl_col;
3258 		    compl_startpos.lnum = curwin->w_cursor.lnum;
3259 		    compl_cont_status &= ~CONT_SOL;   /* clear SOL if present */
3260 		}
3261 		else
3262 		{
3263 		    /* S_IPOS was set when we inserted a word that was at the
3264 		     * beginning of the line, which means that we'll go to SOL
3265 		     * mode but first we need to redefine compl_startpos */
3266 		    if (compl_cont_status & CONT_S_IPOS)
3267 		    {
3268 			compl_cont_status |= CONT_SOL;
3269 			compl_startpos.col = (colnr_T)(skipwhite(
3270 						line + compl_length
3271 						+ compl_startpos.col) - line);
3272 		    }
3273 		    compl_col = compl_startpos.col;
3274 		}
3275 		compl_length = curwin->w_cursor.col - (int)compl_col;
3276 		/* IObuff is used to add a "word from the next line" would we
3277 		 * have enough space?  just being paranoic */
3278 #define	MIN_SPACE 75
3279 		if (compl_length > (IOSIZE - MIN_SPACE))
3280 		{
3281 		    compl_cont_status &= ~CONT_SOL;
3282 		    compl_length = (IOSIZE - MIN_SPACE);
3283 		    compl_col = curwin->w_cursor.col - compl_length;
3284 		}
3285 		compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
3286 		if (compl_length < 1)
3287 		    compl_cont_status &= CONT_LOCAL;
3288 	    }
3289 	    else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3290 		compl_cont_status = CONT_ADDING | CONT_N_ADDS;
3291 	    else
3292 		compl_cont_status = 0;
3293 	}
3294 	else
3295 	    compl_cont_status &= CONT_LOCAL;
3296 
3297 	if (!(compl_cont_status & CONT_ADDING))	/* normal expansion */
3298 	{
3299 	    compl_cont_mode = ctrl_x_mode;
3300 	    if (ctrl_x_mode != 0)	/* Remove LOCAL if ctrl_x_mode != 0 */
3301 		compl_cont_status = 0;
3302 	    compl_cont_status |= CONT_N_ADDS;
3303 	    compl_startpos = curwin->w_cursor;
3304 	    startcol = (int)curs_col;
3305 	    compl_col = 0;
3306 	}
3307 
3308 	/* Work out completion pattern and original text -- webb */
3309 	if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
3310 	{
3311 	    if ((compl_cont_status & CONT_SOL)
3312 		    || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3313 	    {
3314 		if (!(compl_cont_status & CONT_ADDING))
3315 		{
3316 		    while (--startcol >= 0 && vim_isIDc(line[startcol]))
3317 			;
3318 		    compl_col += ++startcol;
3319 		    compl_length = curs_col - startcol;
3320 		}
3321 		if (p_ic)
3322 		    compl_pattern = str_foldcase(line + compl_col,
3323 						       compl_length, NULL, 0);
3324 		else
3325 		    compl_pattern = vim_strnsave(line + compl_col,
3326 								compl_length);
3327 		if (compl_pattern == NULL)
3328 		    return FAIL;
3329 	    }
3330 	    else if (compl_cont_status & CONT_ADDING)
3331 	    {
3332 		char_u	    *prefix = (char_u *)"\\<";
3333 
3334 		/* we need 3 extra chars, 1 for the NUL and
3335 		 * 2 >= strlen(prefix)	-- Acevedo */
3336 		compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3337 							   compl_length) + 3);
3338 		if (compl_pattern == NULL)
3339 		    return FAIL;
3340 		if (!vim_iswordp(line + compl_col)
3341 			|| (compl_col > 0
3342 			    && (
3343 #ifdef FEAT_MBYTE
3344 				vim_iswordp(mb_prevptr(line, line + compl_col))
3345 #else
3346 				vim_iswordc(line[compl_col - 1])
3347 #endif
3348 				)))
3349 		    prefix = (char_u *)"";
3350 		STRCPY((char *)compl_pattern, prefix);
3351 		(void)quote_meta(compl_pattern + STRLEN(prefix),
3352 					      line + compl_col, compl_length);
3353 	    }
3354 	    else if (--startcol < 0 ||
3355 #ifdef FEAT_MBYTE
3356 			   !vim_iswordp(mb_prevptr(line, line + startcol + 1))
3357 #else
3358 			   !vim_iswordc(line[startcol])
3359 #endif
3360 		    )
3361 	    {
3362 		/* Match any word of at least two chars */
3363 		compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
3364 		if (compl_pattern == NULL)
3365 		    return FAIL;
3366 		compl_col += curs_col;
3367 		compl_length = 0;
3368 	    }
3369 	    else
3370 	    {
3371 #ifdef FEAT_MBYTE
3372 		/* Search the point of change class of multibyte character
3373 		 * or not a word single byte character backward.  */
3374 		if (has_mbyte)
3375 		{
3376 		    int base_class;
3377 		    int head_off;
3378 
3379 		    startcol -= (*mb_head_off)(line, line + startcol);
3380 		    base_class = mb_get_class(line + startcol);
3381 		    while (--startcol >= 0)
3382 		    {
3383 			head_off = (*mb_head_off)(line, line + startcol);
3384 			if (base_class != mb_get_class(line + startcol
3385 								  - head_off))
3386 			    break;
3387 			startcol -= head_off;
3388 		    }
3389 		}
3390 		else
3391 #endif
3392 		    while (--startcol >= 0 && vim_iswordc(line[startcol]))
3393 			;
3394 		compl_col += ++startcol;
3395 		compl_length = (int)curs_col - startcol;
3396 		if (compl_length == 1)
3397 		{
3398 		    /* Only match word with at least two chars -- webb
3399 		     * there's no need to call quote_meta,
3400 		     * alloc(7) is enough  -- Acevedo
3401 		     */
3402 		    compl_pattern = alloc(7);
3403 		    if (compl_pattern == NULL)
3404 			return FAIL;
3405 		    STRCPY((char *)compl_pattern, "\\<");
3406 		    (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
3407 		    STRCAT((char *)compl_pattern, "\\k");
3408 		}
3409 		else
3410 		{
3411 		    compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3412 							   compl_length) + 3);
3413 		    if (compl_pattern == NULL)
3414 			return FAIL;
3415 		    STRCPY((char *)compl_pattern, "\\<");
3416 		    (void)quote_meta(compl_pattern + 2, line + compl_col,
3417 								compl_length);
3418 		}
3419 	    }
3420 	}
3421 	else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3422 	{
3423 	    compl_col = skipwhite(line) - line;
3424 	    compl_length = (int)curs_col - (int)compl_col;
3425 	    if (compl_length < 0)	/* cursor in indent: empty pattern */
3426 		compl_length = 0;
3427 	    if (p_ic)
3428 		compl_pattern = str_foldcase(line + compl_col, compl_length,
3429 								     NULL, 0);
3430 	    else
3431 		compl_pattern = vim_strnsave(line + compl_col, compl_length);
3432 	    if (compl_pattern == NULL)
3433 		return FAIL;
3434 	}
3435 	else if (ctrl_x_mode == CTRL_X_FILES)
3436 	{
3437 	    while (--startcol >= 0 && vim_isfilec(line[startcol]))
3438 		;
3439 	    compl_col += ++startcol;
3440 	    compl_length = (int)curs_col - startcol;
3441 	    compl_pattern = addstar(line + compl_col, compl_length,
3442 								EXPAND_FILES);
3443 	    if (compl_pattern == NULL)
3444 		return FAIL;
3445 	}
3446 	else if (ctrl_x_mode == CTRL_X_CMDLINE)
3447 	{
3448 	    compl_pattern = vim_strnsave(line, curs_col);
3449 	    if (compl_pattern == NULL)
3450 		return FAIL;
3451 	    set_cmd_context(&compl_xp, compl_pattern,
3452 				     (int)STRLEN(compl_pattern), curs_col);
3453 	    if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
3454 		    || compl_xp.xp_context == EXPAND_NOTHING)
3455 		return FAIL;
3456 	    startcol = (int)(compl_xp.xp_pattern - compl_pattern);
3457 	    compl_col = startcol;
3458 	    compl_length = curs_col - startcol;
3459 	}
3460 	else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OCCULT)
3461 	{
3462 #ifdef FEAT_COMPL_FUNC
3463 	    /*
3464 	     * Call user defined function 'completefunc' with "a:findstart"
3465 	     * set to 1 to obtain the length of text to use for completion.
3466 	     */
3467 	    char_u	*args[2];
3468 	    int		col;
3469 	    char_u	*funcname;
3470 	    pos_T	pos;
3471 
3472 	    /* Call 'completefunc' or 'occultfunc' and get pattern length as a
3473 	     * string */
3474 	    funcname = ctrl_x_mode == CTRL_X_FUNCTION
3475 					  ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3476 	    if (*funcname == NUL)
3477 		return FAIL;
3478 
3479 	    args[0] = (char_u *)"1";
3480 	    args[1] = NULL;
3481 	    pos = curwin->w_cursor;
3482 	    col = call_func_retnr(funcname, 2, args, FALSE);
3483 	    curwin->w_cursor = pos;	/* restore the cursor position */
3484 
3485 	    if (col < 0)
3486 		return FAIL;
3487 	    compl_col = col;
3488 	    if ((colnr_T)compl_col > curs_col)
3489 		compl_col = curs_col;
3490 
3491 	    /* Setup variables for completion.  Need to obtain "line" again,
3492 	     * it may have become invalid. */
3493 	    line = ml_get(curwin->w_cursor.lnum);
3494 	    compl_length = curs_col - compl_col;
3495 	    compl_pattern = vim_strnsave(line + compl_col, compl_length);
3496 	    if (compl_pattern == NULL)
3497 #endif
3498 		return FAIL;
3499 	}
3500 	else if (ctrl_x_mode == CTRL_X_SPELL)
3501 	{
3502 #ifdef FEAT_SYN_HL
3503 	    if (spell_bad_len > 0)
3504 		compl_col = curs_col - spell_bad_len;
3505 	    else
3506 		compl_col = spell_word_start(startcol);
3507 	    if (compl_col >= (colnr_T)startcol)
3508 		return FAIL;
3509 	    compl_length = (int)curs_col - compl_col;
3510 	    compl_pattern = vim_strnsave(line + compl_col, compl_length);
3511 	    if (compl_pattern == NULL)
3512 #endif
3513 		return FAIL;
3514 	}
3515 	else
3516 	{
3517 	    EMSG2(_(e_intern2), "ins_complete()");
3518 	    return FAIL;
3519 	}
3520 
3521 	if (compl_cont_status & CONT_ADDING)
3522 	{
3523 	    edit_submode_pre = (char_u *)_(" Adding");
3524 	    if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3525 	    {
3526 		/* Insert a new line, keep indentation but ignore 'comments' */
3527 #ifdef FEAT_COMMENTS
3528 		char_u *old = curbuf->b_p_com;
3529 
3530 		curbuf->b_p_com = (char_u *)"";
3531 #endif
3532 		compl_startpos.lnum = curwin->w_cursor.lnum;
3533 		compl_startpos.col = compl_col;
3534 		ins_eol('\r');
3535 #ifdef FEAT_COMMENTS
3536 		curbuf->b_p_com = old;
3537 #endif
3538 		compl_length = 0;
3539 		compl_col = curwin->w_cursor.col;
3540 	    }
3541 	}
3542 	else
3543 	{
3544 	    edit_submode_pre = NULL;
3545 	    compl_startpos.col = compl_col;
3546 	}
3547 
3548 	if (compl_cont_status & CONT_LOCAL)
3549 	    edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
3550 	else
3551 	    edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
3552 
3553 	/* Always add completion for the original text.  Note that
3554 	 * "compl_orig_text" itself (not a copy) is added, it will be freed
3555 	 * when the list of matches is freed. */
3556 	compl_orig_text = vim_strnsave(line + compl_col, compl_length);
3557 	if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
3558 					    -1, NULL, 0, ORIGINAL_TEXT) != OK)
3559 	{
3560 	    vim_free(compl_pattern);
3561 	    compl_pattern = NULL;
3562 	    vim_free(compl_orig_text);
3563 	    compl_orig_text = NULL;
3564 	    return FAIL;
3565 	}
3566 
3567 	/* showmode might reset the internal line pointers, so it must
3568 	 * be called before line = ml_get(), or when this address is no
3569 	 * longer needed.  -- Acevedo.
3570 	 */
3571 	edit_submode_extra = (char_u *)_("-- Searching...");
3572 	edit_submode_highl = HLF_COUNT;
3573 	showmode();
3574 	edit_submode_extra = NULL;
3575 	out_flush();
3576     }
3577 
3578     compl_shown_match = compl_curr_match;
3579     compl_shows_dir = compl_direction;
3580 
3581     /*
3582      * Find next match.
3583      */
3584     n = ins_compl_next(TRUE);
3585 
3586     if (n > 1)		/* all matches have been found */
3587 	compl_matches = n;
3588     compl_curr_match = compl_shown_match;
3589     compl_direction = compl_shows_dir;
3590     compl_interrupted = FALSE;
3591 
3592     /* eat the ESC to avoid leaving insert mode */
3593     if (got_int && !global_busy)
3594     {
3595 	(void)vgetc();
3596 	got_int = FALSE;
3597     }
3598 
3599     /* we found no match if the list has only the "compl_orig_text"-entry */
3600     if (compl_first_match == compl_first_match->cp_next)
3601     {
3602 	edit_submode_extra = (compl_cont_status & CONT_ADDING)
3603 			&& compl_length > 1
3604 			     ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
3605 	edit_submode_highl = HLF_E;
3606 	/* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
3607 	 * because we couldn't expand anything at first place, but if we used
3608 	 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
3609 	 * (such as M in M'exico) if not tried already.  -- Acevedo */
3610 	if (	   compl_length > 1
3611 		|| (compl_cont_status & CONT_ADDING)
3612 		|| (ctrl_x_mode != 0
3613 		    && ctrl_x_mode != CTRL_X_PATH_PATTERNS
3614 		    && ctrl_x_mode != CTRL_X_PATH_DEFINES))
3615 	    compl_cont_status &= ~CONT_N_ADDS;
3616     }
3617 
3618     if (compl_curr_match->cp_flags & CONT_S_IPOS)
3619 	compl_cont_status |= CONT_S_IPOS;
3620     else
3621 	compl_cont_status &= ~CONT_S_IPOS;
3622 
3623     if (edit_submode_extra == NULL)
3624     {
3625 	if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
3626 	{
3627 	    edit_submode_extra = (char_u *)_("Back at original");
3628 	    edit_submode_highl = HLF_W;
3629 	}
3630 	else if (compl_cont_status & CONT_S_IPOS)
3631 	{
3632 	    edit_submode_extra = (char_u *)_("Word from other line");
3633 	    edit_submode_highl = HLF_COUNT;
3634 	}
3635 	else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
3636 	{
3637 	    edit_submode_extra = (char_u *)_("The only match");
3638 	    edit_submode_highl = HLF_COUNT;
3639 	}
3640 	else
3641 	{
3642 	    /* Update completion sequence number when needed. */
3643 	    if (compl_curr_match->cp_number == -1)
3644 	    {
3645 		int		number = 0;
3646 		compl_T		*match;
3647 
3648 		if (compl_direction == FORWARD)
3649 		{
3650 		    /* search backwards for the first valid (!= -1) number.
3651 		     * This should normally succeed already at the first loop
3652 		     * cycle, so it's fast! */
3653 		    for (match = compl_curr_match->cp_prev; match != NULL
3654 			    && match != compl_first_match;
3655 						       match = match->cp_prev)
3656 			if (match->cp_number != -1)
3657 			{
3658 			    number = match->cp_number;
3659 			    break;
3660 			}
3661 		    if (match != NULL)
3662 			/* go up and assign all numbers which are not assigned
3663 			 * yet */
3664 			for (match = match->cp_next; match
3665 				&& match->cp_number == -1;
3666 						       match = match->cp_next)
3667 			    match->cp_number = ++number;
3668 		}
3669 		else /* BACKWARD */
3670 		{
3671 		    /* search forwards (upwards) for the first valid (!= -1)
3672 		     * number.  This should normally succeed already at the
3673 		     * first loop cycle, so it's fast! */
3674 		    for (match = compl_curr_match->cp_next; match != NULL
3675 			    && match != compl_first_match;
3676 						       match = match->cp_next)
3677 			if (match->cp_number != -1)
3678 			{
3679 			    number = match->cp_number;
3680 			    break;
3681 			}
3682 		    if (match != NULL)
3683 			/* go down and assign all numbers which are not
3684 			 * assigned yet */
3685 			for (match = match->cp_prev; match
3686 				&& match->cp_number == -1;
3687 						       match = match->cp_prev)
3688 			    match->cp_number = ++number;
3689 		}
3690 	    }
3691 
3692 	    /* The match should always have a sequnce number now, this is just
3693 	     * a safety check. */
3694 	    if (compl_curr_match->cp_number != -1)
3695 	    {
3696 		/* Space for 10 text chars. + 2x10-digit no.s */
3697 		static char_u match_ref[31];
3698 
3699 		if (compl_matches > 0)
3700 		    sprintf((char *)IObuff, _("match %d of %d"),
3701 				compl_curr_match->cp_number, compl_matches);
3702 		else
3703 		    sprintf((char *)IObuff, _("match %d"),
3704 						 compl_curr_match->cp_number);
3705 		vim_strncpy(match_ref, IObuff, 30);
3706 		edit_submode_extra = match_ref;
3707 		edit_submode_highl = HLF_R;
3708 		if (dollar_vcol)
3709 		    curs_columns(FALSE);
3710 	    }
3711 	}
3712     }
3713 
3714     /* Show a message about what (completion) mode we're in. */
3715     showmode();
3716     if (edit_submode_extra != NULL)
3717     {
3718 	if (!p_smd)
3719 	    msg_attr(edit_submode_extra,
3720 		    edit_submode_highl < HLF_COUNT
3721 		    ? hl_attr(edit_submode_highl) : 0);
3722     }
3723     else
3724 	msg_clr_cmdline();	/* necessary for "noshowmode" */
3725 
3726     return OK;
3727 }
3728 
3729 /*
3730  * Looks in the first "len" chars. of "src" for search-metachars.
3731  * If dest is not NULL the chars. are copied there quoting (with
3732  * a backslash) the metachars, and dest would be NUL terminated.
3733  * Returns the length (needed) of dest
3734  */
3735     static int
3736 quote_meta(dest, src, len)
3737     char_u	*dest;
3738     char_u	*src;
3739     int		len;
3740 {
3741     int	m;
3742 
3743     for (m = len; --len >= 0; src++)
3744     {
3745 	switch (*src)
3746 	{
3747 	    case '.':
3748 	    case '*':
3749 	    case '[':
3750 		if (ctrl_x_mode == CTRL_X_DICTIONARY
3751 					   || ctrl_x_mode == CTRL_X_THESAURUS)
3752 		    break;
3753 	    case '~':
3754 		if (!p_magic)	/* quote these only if magic is set */
3755 		    break;
3756 	    case '\\':
3757 		if (ctrl_x_mode == CTRL_X_DICTIONARY
3758 					   || ctrl_x_mode == CTRL_X_THESAURUS)
3759 		    break;
3760 	    case '^':		/* currently it's not needed. */
3761 	    case '$':
3762 		m++;
3763 		if (dest != NULL)
3764 		    *dest++ = '\\';
3765 		break;
3766 	}
3767 	if (dest != NULL)
3768 	    *dest++ = *src;
3769 # ifdef FEAT_MBYTE
3770 	/* Copy remaining bytes of a multibyte character. */
3771 	if (has_mbyte)
3772 	{
3773 	    int i, mb_len;
3774 
3775 	    mb_len = (*mb_ptr2len)(src) - 1;
3776 	    if (mb_len > 0 && len >= mb_len)
3777 		for (i = 0; i < mb_len; ++i)
3778 		{
3779 		    --len;
3780 		    ++src;
3781 		    if (dest != NULL)
3782 			*dest++ = *src;
3783 		}
3784 	}
3785 # endif
3786     }
3787     if (dest != NULL)
3788 	*dest = NUL;
3789 
3790     return m;
3791 }
3792 #endif /* FEAT_INS_EXPAND */
3793 
3794 /*
3795  * Next character is interpreted literally.
3796  * A one, two or three digit decimal number is interpreted as its byte value.
3797  * If one or two digits are entered, the next character is given to vungetc().
3798  * For Unicode a character > 255 may be returned.
3799  */
3800     int
3801 get_literal()
3802 {
3803     int		cc;
3804     int		nc;
3805     int		i;
3806     int		hex = FALSE;
3807     int		octal = FALSE;
3808 #ifdef FEAT_MBYTE
3809     int		unicode = 0;
3810 #endif
3811 
3812     if (got_int)
3813 	return Ctrl_C;
3814 
3815 #ifdef FEAT_GUI
3816     /*
3817      * In GUI there is no point inserting the internal code for a special key.
3818      * It is more useful to insert the string "<KEY>" instead.	This would
3819      * probably be useful in a text window too, but it would not be
3820      * vi-compatible (maybe there should be an option for it?) -- webb
3821      */
3822     if (gui.in_use)
3823 	++allow_keys;
3824 #endif
3825 #ifdef USE_ON_FLY_SCROLL
3826     dont_scroll = TRUE;		/* disallow scrolling here */
3827 #endif
3828     ++no_mapping;		/* don't map the next key hits */
3829     cc = 0;
3830     i = 0;
3831     for (;;)
3832     {
3833 	do
3834 	    nc = safe_vgetc();
3835 	while (nc == K_IGNORE || nc == K_VER_SCROLLBAR
3836 						    || nc == K_HOR_SCROLLBAR);
3837 #ifdef FEAT_CMDL_INFO
3838 	if (!(State & CMDLINE)
3839 # ifdef FEAT_MBYTE
3840 		&& MB_BYTE2LEN_CHECK(nc) == 1
3841 # endif
3842 	   )
3843 	    add_to_showcmd(nc);
3844 #endif
3845 	if (nc == 'x' || nc == 'X')
3846 	    hex = TRUE;
3847 	else if (nc == 'o' || nc == 'O')
3848 	    octal = TRUE;
3849 #ifdef FEAT_MBYTE
3850 	else if (nc == 'u' || nc == 'U')
3851 	    unicode = nc;
3852 #endif
3853 	else
3854 	{
3855 	    if (hex
3856 #ifdef FEAT_MBYTE
3857 		    || unicode != 0
3858 #endif
3859 		    )
3860 	    {
3861 		if (!vim_isxdigit(nc))
3862 		    break;
3863 		cc = cc * 16 + hex2nr(nc);
3864 	    }
3865 	    else if (octal)
3866 	    {
3867 		if (nc < '0' || nc > '7')
3868 		    break;
3869 		cc = cc * 8 + nc - '0';
3870 	    }
3871 	    else
3872 	    {
3873 		if (!VIM_ISDIGIT(nc))
3874 		    break;
3875 		cc = cc * 10 + nc - '0';
3876 	    }
3877 
3878 	    ++i;
3879 	}
3880 
3881 	if (cc > 255
3882 #ifdef FEAT_MBYTE
3883 		&& unicode == 0
3884 #endif
3885 		)
3886 	    cc = 255;		/* limit range to 0-255 */
3887 	nc = 0;
3888 
3889 	if (hex)		/* hex: up to two chars */
3890 	{
3891 	    if (i >= 2)
3892 		break;
3893 	}
3894 #ifdef FEAT_MBYTE
3895 	else if (unicode)	/* Unicode: up to four or eight chars */
3896 	{
3897 	    if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
3898 		break;
3899 	}
3900 #endif
3901 	else if (i >= 3)	/* decimal or octal: up to three chars */
3902 	    break;
3903     }
3904     if (i == 0)	    /* no number entered */
3905     {
3906 	if (nc == K_ZERO)   /* NUL is stored as NL */
3907 	{
3908 	    cc = '\n';
3909 	    nc = 0;
3910 	}
3911 	else
3912 	{
3913 	    cc = nc;
3914 	    nc = 0;
3915 	}
3916     }
3917 
3918     if (cc == 0)	/* NUL is stored as NL */
3919 	cc = '\n';
3920 #ifdef FEAT_MBYTE
3921     if (enc_dbcs && (cc & 0xff) == 0)
3922 	cc = '?';	/* don't accept an illegal DBCS char, the NUL in the
3923 			   second byte will cause trouble! */
3924 #endif
3925 
3926     --no_mapping;
3927 #ifdef FEAT_GUI
3928     if (gui.in_use)
3929 	--allow_keys;
3930 #endif
3931     if (nc)
3932 	vungetc(nc);
3933     got_int = FALSE;	    /* CTRL-C typed after CTRL-V is not an interrupt */
3934     return cc;
3935 }
3936 
3937 /*
3938  * Insert character, taking care of special keys and mod_mask
3939  */
3940     static void
3941 insert_special(c, allow_modmask, ctrlv)
3942     int	    c;
3943     int	    allow_modmask;
3944     int	    ctrlv;	    /* c was typed after CTRL-V */
3945 {
3946     char_u  *p;
3947     int	    len;
3948 
3949     /*
3950      * Special function key, translate into "<Key>". Up to the last '>' is
3951      * inserted with ins_str(), so as not to replace characters in replace
3952      * mode.
3953      * Only use mod_mask for special keys, to avoid things like <S-Space>,
3954      * unless 'allow_modmask' is TRUE.
3955      */
3956 #ifdef MACOS
3957     /* Command-key never produces a normal key */
3958     if (mod_mask & MOD_MASK_CMD)
3959 	allow_modmask = TRUE;
3960 #endif
3961     if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
3962     {
3963 	p = get_special_key_name(c, mod_mask);
3964 	len = (int)STRLEN(p);
3965 	c = p[len - 1];
3966 	if (len > 2)
3967 	{
3968 	    if (stop_arrow() == FAIL)
3969 		return;
3970 	    p[len - 1] = NUL;
3971 	    ins_str(p);
3972 	    AppendToRedobuffLit(p);
3973 	    ctrlv = FALSE;
3974 	}
3975     }
3976     if (stop_arrow() == OK)
3977 	insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
3978 }
3979 
3980 /*
3981  * Special characters in this context are those that need processing other
3982  * than the simple insertion that can be performed here. This includes ESC
3983  * which terminates the insert, and CR/NL which need special processing to
3984  * open up a new line. This routine tries to optimize insertions performed by
3985  * the "redo", "undo" or "put" commands, so it needs to know when it should
3986  * stop and defer processing to the "normal" mechanism.
3987  * '0' and '^' are special, because they can be followed by CTRL-D.
3988  */
3989 #ifdef EBCDIC
3990 # define ISSPECIAL(c)	((c) < ' ' || (c) == '0' || (c) == '^')
3991 #else
3992 # define ISSPECIAL(c)	((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
3993 #endif
3994 
3995 #ifdef FEAT_MBYTE
3996 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
3997 #else
3998 # define WHITECHAR(cc) vim_iswhite(cc)
3999 #endif
4000 
4001     void
4002 insertchar(c, flags, second_indent)
4003     int		c;			/* character to insert or NUL */
4004     int		flags;			/* INSCHAR_FORMAT, etc. */
4005     int		second_indent;		/* indent for second line if >= 0 */
4006 {
4007     int		haveto_redraw = FALSE;
4008     int		textwidth;
4009 #ifdef FEAT_COMMENTS
4010     colnr_T	leader_len;
4011     char_u	*p;
4012     int		no_leader = FALSE;
4013     int		do_comments = (flags & INSCHAR_DO_COM);
4014 #endif
4015     int		fo_white_par;
4016     int		first_line = TRUE;
4017     int		fo_ins_blank;
4018 #ifdef FEAT_MBYTE
4019     int		fo_multibyte;
4020 #endif
4021     int		save_char = NUL;
4022     int		cc;
4023 
4024     textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
4025     fo_ins_blank = has_format_option(FO_INS_BLANK);
4026 #ifdef FEAT_MBYTE
4027     fo_multibyte = has_format_option(FO_MBYTE_BREAK);
4028 #endif
4029     fo_white_par = has_format_option(FO_WHITE_PAR);
4030 
4031     /*
4032      * Try to break the line in two or more pieces when:
4033      * - Always do this if we have been called to do formatting only.
4034      * - Always do this when 'formatoptions' has the 'a' flag and the line
4035      *   ends in white space.
4036      * - Otherwise:
4037      *	 - Don't do this if inserting a blank
4038      *	 - Don't do this if an existing character is being replaced, unless
4039      *	   we're in VREPLACE mode.
4040      *	 - Do this if the cursor is not on the line where insert started
4041      *	 or - 'formatoptions' doesn't have 'l' or the line was not too long
4042      *	       before the insert.
4043      *	    - 'formatoptions' doesn't have 'b' or a blank was inserted at or
4044      *	      before 'textwidth'
4045      */
4046     if (textwidth
4047 	    && ((flags & INSCHAR_FORMAT)
4048 		|| (!vim_iswhite(c)
4049 		    && !((State & REPLACE_FLAG)
4050 #ifdef FEAT_VREPLACE
4051 			&& !(State & VREPLACE_FLAG)
4052 #endif
4053 			&& *ml_get_cursor() != NUL)
4054 		    && (curwin->w_cursor.lnum != Insstart.lnum
4055 			|| ((!has_format_option(FO_INS_LONG)
4056 				|| Insstart_textlen <= (colnr_T)textwidth)
4057 			    && (!fo_ins_blank
4058 				|| Insstart_blank_vcol <= (colnr_T)textwidth
4059 			    ))))))
4060     {
4061 	/*
4062 	 * When 'ai' is off we don't want a space under the cursor to be
4063 	 * deleted.  Replace it with an 'x' temporarily.
4064 	 */
4065 	if (!curbuf->b_p_ai)
4066 	{
4067 	    cc = gchar_cursor();
4068 	    if (vim_iswhite(cc))
4069 	    {
4070 		save_char = cc;
4071 		pchar_cursor('x');
4072 	    }
4073 	}
4074 
4075 	/*
4076 	 * Repeat breaking lines, until the current line is not too long.
4077 	 */
4078 	while (!got_int)
4079 	{
4080 	    int		startcol;		/* Cursor column at entry */
4081 	    int		wantcol;		/* column at textwidth border */
4082 	    int		foundcol;		/* column for start of spaces */
4083 	    int		end_foundcol = 0;	/* column for start of word */
4084 	    colnr_T	len;
4085 	    colnr_T	virtcol;
4086 #ifdef FEAT_VREPLACE
4087 	    int		orig_col = 0;
4088 	    char_u	*saved_text = NULL;
4089 #endif
4090 	    colnr_T	col;
4091 
4092 	    virtcol = get_nolist_virtcol();
4093 	    if (virtcol < (colnr_T)textwidth)
4094 		break;
4095 
4096 #ifdef FEAT_COMMENTS
4097 	    if (no_leader)
4098 		do_comments = FALSE;
4099 	    else if (!(flags & INSCHAR_FORMAT)
4100 					   && has_format_option(FO_WRAP_COMS))
4101 		do_comments = TRUE;
4102 
4103 	    /* Don't break until after the comment leader */
4104 	    if (do_comments)
4105 		leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
4106 	    else
4107 		leader_len = 0;
4108 
4109 	    /* If the line doesn't start with a comment leader, then don't
4110 	     * start one in a following broken line.  Avoids that a %word
4111 	     * moved to the start of the next line causes all following lines
4112 	     * to start with %. */
4113 	    if (leader_len == 0)
4114 		no_leader = TRUE;
4115 #endif
4116 	    if (!(flags & INSCHAR_FORMAT)
4117 #ifdef FEAT_COMMENTS
4118 		    && leader_len == 0
4119 #endif
4120 		    && !has_format_option(FO_WRAP))
4121 
4122 	    {
4123 		textwidth = 0;
4124 		break;
4125 	    }
4126 	    if ((startcol = curwin->w_cursor.col) == 0)
4127 		break;
4128 
4129 	    /* find column of textwidth border */
4130 	    coladvance((colnr_T)textwidth);
4131 	    wantcol = curwin->w_cursor.col;
4132 
4133 	    curwin->w_cursor.col = startcol - 1;
4134 #ifdef FEAT_MBYTE
4135 	    /* Correct cursor for multi-byte character. */
4136 	    if (has_mbyte)
4137 		mb_adjust_cursor();
4138 #endif
4139 	    foundcol = 0;
4140 
4141 	    /*
4142 	     * Find position to break at.
4143 	     * Stop at first entered white when 'formatoptions' has 'v'
4144 	     */
4145 	    while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
4146 			|| curwin->w_cursor.lnum != Insstart.lnum
4147 			|| curwin->w_cursor.col >= Insstart.col)
4148 	    {
4149 		cc = gchar_cursor();
4150 		if (WHITECHAR(cc))
4151 		{
4152 		    /* remember position of blank just before text */
4153 		    end_foundcol = curwin->w_cursor.col;
4154 
4155 		    /* find start of sequence of blanks */
4156 		    while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
4157 		    {
4158 			dec_cursor();
4159 			cc = gchar_cursor();
4160 		    }
4161 		    if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
4162 			break;		/* only spaces in front of text */
4163 #ifdef FEAT_COMMENTS
4164 		    /* Don't break until after the comment leader */
4165 		    if (curwin->w_cursor.col < leader_len)
4166 			break;
4167 #endif
4168 		    if (has_format_option(FO_ONE_LETTER))
4169 		    {
4170 			/* do not break after one-letter words */
4171 			if (curwin->w_cursor.col == 0)
4172 			    break;	/* one-letter word at begin */
4173 
4174 			col = curwin->w_cursor.col;
4175 			dec_cursor();
4176 			cc = gchar_cursor();
4177 
4178 			if (WHITECHAR(cc))
4179 			    continue;	/* one-letter, continue */
4180 			curwin->w_cursor.col = col;
4181 		    }
4182 #ifdef FEAT_MBYTE
4183 		    if (has_mbyte)
4184 			foundcol = curwin->w_cursor.col
4185 					     + (*mb_ptr2len)(ml_get_cursor());
4186 		    else
4187 #endif
4188 			foundcol = curwin->w_cursor.col + 1;
4189 		    if (curwin->w_cursor.col < (colnr_T)wantcol)
4190 			break;
4191 		}
4192 #ifdef FEAT_MBYTE
4193 		else if (cc >= 0x100 && fo_multibyte
4194 				  && curwin->w_cursor.col <= (colnr_T)wantcol)
4195 		{
4196 		    /* Break after or before a multi-byte character. */
4197 		    foundcol = curwin->w_cursor.col;
4198 		    if (curwin->w_cursor.col < (colnr_T)wantcol)
4199 			foundcol += (*mb_char2len)(cc);
4200 		    end_foundcol = foundcol;
4201 		    break;
4202 		}
4203 #endif
4204 		if (curwin->w_cursor.col == 0)
4205 		    break;
4206 		dec_cursor();
4207 	    }
4208 
4209 	    if (foundcol == 0)		/* no spaces, cannot break line */
4210 	    {
4211 		curwin->w_cursor.col = startcol;
4212 		break;
4213 	    }
4214 
4215 	    /* Going to break the line, remove any "$" now. */
4216 	    undisplay_dollar();
4217 
4218 	    /*
4219 	     * Offset between cursor position and line break is used by replace
4220 	     * stack functions.  VREPLACE does not use this, and backspaces
4221 	     * over the text instead.
4222 	     */
4223 #ifdef FEAT_VREPLACE
4224 	    if (State & VREPLACE_FLAG)
4225 		orig_col = startcol;	/* Will start backspacing from here */
4226 	    else
4227 #endif
4228 		replace_offset = startcol - end_foundcol - 1;
4229 
4230 	    /*
4231 	     * adjust startcol for spaces that will be deleted and
4232 	     * characters that will remain on top line
4233 	     */
4234 	    curwin->w_cursor.col = foundcol;
4235 	    while (cc = gchar_cursor(), WHITECHAR(cc))
4236 		inc_cursor();
4237 	    startcol -= curwin->w_cursor.col;
4238 	    if (startcol < 0)
4239 		startcol = 0;
4240 
4241 #ifdef FEAT_VREPLACE
4242 	    if (State & VREPLACE_FLAG)
4243 	    {
4244 		/*
4245 		 * In VREPLACE mode, we will backspace over the text to be
4246 		 * wrapped, so save a copy now to put on the next line.
4247 		 */
4248 		saved_text = vim_strsave(ml_get_cursor());
4249 		curwin->w_cursor.col = orig_col;
4250 		if (saved_text == NULL)
4251 		    break;	/* Can't do it, out of memory */
4252 		saved_text[startcol] = NUL;
4253 
4254 		/* Backspace over characters that will move to the next line */
4255 		if (!fo_white_par)
4256 		    backspace_until_column(foundcol);
4257 	    }
4258 	    else
4259 #endif
4260 	    {
4261 		/* put cursor after pos. to break line */
4262 		if (!fo_white_par)
4263 		    curwin->w_cursor.col = foundcol;
4264 	    }
4265 
4266 	    /*
4267 	     * Split the line just before the margin.
4268 	     * Only insert/delete lines, but don't really redraw the window.
4269 	     */
4270 	    open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
4271 		    + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
4272 #ifdef FEAT_COMMENTS
4273 		    + (do_comments ? OPENLINE_DO_COM : 0)
4274 #endif
4275 		    , old_indent);
4276 	    old_indent = 0;
4277 
4278 	    replace_offset = 0;
4279 	    if (first_line)
4280 	    {
4281 		if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
4282 		    second_indent = get_number_indent(curwin->w_cursor.lnum -1);
4283 		if (second_indent >= 0)
4284 		{
4285 #ifdef FEAT_VREPLACE
4286 		    if (State & VREPLACE_FLAG)
4287 			change_indent(INDENT_SET, second_indent, FALSE, NUL);
4288 		    else
4289 #endif
4290 			(void)set_indent(second_indent, SIN_CHANGED);
4291 		}
4292 		first_line = FALSE;
4293 	    }
4294 
4295 #ifdef FEAT_VREPLACE
4296 	    if (State & VREPLACE_FLAG)
4297 	    {
4298 		/*
4299 		 * In VREPLACE mode we have backspaced over the text to be
4300 		 * moved, now we re-insert it into the new line.
4301 		 */
4302 		ins_bytes(saved_text);
4303 		vim_free(saved_text);
4304 	    }
4305 	    else
4306 #endif
4307 	    {
4308 		/*
4309 		 * Check if cursor is not past the NUL off the line, cindent
4310 		 * may have added or removed indent.
4311 		 */
4312 		curwin->w_cursor.col += startcol;
4313 		len = (colnr_T)STRLEN(ml_get_curline());
4314 		if (curwin->w_cursor.col > len)
4315 		    curwin->w_cursor.col = len;
4316 	    }
4317 
4318 	    haveto_redraw = TRUE;
4319 #ifdef FEAT_CINDENT
4320 	    can_cindent = TRUE;
4321 #endif
4322 	    /* moved the cursor, don't autoindent or cindent now */
4323 	    did_ai = FALSE;
4324 #ifdef FEAT_SMARTINDENT
4325 	    did_si = FALSE;
4326 	    can_si = FALSE;
4327 	    can_si_back = FALSE;
4328 #endif
4329 	    line_breakcheck();
4330 	}
4331 
4332 	if (save_char)			/* put back space after cursor */
4333 	    pchar_cursor(save_char);
4334 
4335 	if (c == NUL)			/* formatting only */
4336 	    return;
4337 	if (haveto_redraw)
4338 	{
4339 	    update_topline();
4340 	    redraw_curbuf_later(VALID);
4341 	}
4342     }
4343     if (c == NUL)	    /* only formatting was wanted */
4344 	return;
4345 
4346 #ifdef FEAT_COMMENTS
4347     /* Check whether this character should end a comment. */
4348     if (did_ai && (int)c == end_comment_pending)
4349     {
4350 	char_u  *line;
4351 	char_u	lead_end[COM_MAX_LEN];	    /* end-comment string */
4352 	int	middle_len, end_len;
4353 	int	i;
4354 
4355 	/*
4356 	 * Need to remove existing (middle) comment leader and insert end
4357 	 * comment leader.  First, check what comment leader we can find.
4358 	 */
4359 	i = get_leader_len(line = ml_get_curline(), &p, FALSE);
4360 	if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL)	/* Just checking */
4361 	{
4362 	    /* Skip middle-comment string */
4363 	    while (*p && p[-1] != ':')	/* find end of middle flags */
4364 		++p;
4365 	    middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
4366 	    /* Don't count trailing white space for middle_len */
4367 	    while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
4368 		--middle_len;
4369 
4370 	    /* Find the end-comment string */
4371 	    while (*p && p[-1] != ':')	/* find end of end flags */
4372 		++p;
4373 	    end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
4374 
4375 	    /* Skip white space before the cursor */
4376 	    i = curwin->w_cursor.col;
4377 	    while (--i >= 0 && vim_iswhite(line[i]))
4378 		;
4379 	    i++;
4380 
4381 	    /* Skip to before the middle leader */
4382 	    i -= middle_len;
4383 
4384 	    /* Check some expected things before we go on */
4385 	    if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
4386 	    {
4387 		/* Backspace over all the stuff we want to replace */
4388 		backspace_until_column(i);
4389 
4390 		/*
4391 		 * Insert the end-comment string, except for the last
4392 		 * character, which will get inserted as normal later.
4393 		 */
4394 		ins_bytes_len(lead_end, end_len - 1);
4395 	    }
4396 	}
4397     }
4398     end_comment_pending = NUL;
4399 #endif
4400 
4401     did_ai = FALSE;
4402 #ifdef FEAT_SMARTINDENT
4403     did_si = FALSE;
4404     can_si = FALSE;
4405     can_si_back = FALSE;
4406 #endif
4407 
4408     /*
4409      * If there's any pending input, grab up to INPUT_BUFLEN at once.
4410      * This speeds up normal text input considerably.
4411      * Don't do this when 'cindent' or 'indentexpr' is set, because we might
4412      * need to re-indent at a ':', or any other character (but not what
4413      * 'paste' is set)..
4414      */
4415 #ifdef USE_ON_FLY_SCROLL
4416     dont_scroll = FALSE;		/* allow scrolling here */
4417 #endif
4418 
4419     if (       !ISSPECIAL(c)
4420 #ifdef FEAT_MBYTE
4421 	    && (!has_mbyte || (*mb_char2len)(c) == 1)
4422 #endif
4423 	    && vpeekc() != NUL
4424 	    && !(State & REPLACE_FLAG)
4425 #ifdef FEAT_CINDENT
4426 	    && !cindent_on()
4427 #endif
4428 #ifdef FEAT_RIGHTLEFT
4429 	    && !p_ri
4430 #endif
4431 	       )
4432     {
4433 #define INPUT_BUFLEN 100
4434 	char_u		buf[INPUT_BUFLEN + 1];
4435 	int		i;
4436 	colnr_T		virtcol = 0;
4437 
4438 	buf[0] = c;
4439 	i = 1;
4440 	if (textwidth)
4441 	    virtcol = get_nolist_virtcol();
4442 	/*
4443 	 * Stop the string when:
4444 	 * - no more chars available
4445 	 * - finding a special character (command key)
4446 	 * - buffer is full
4447 	 * - running into the 'textwidth' boundary
4448 	 * - need to check for abbreviation: A non-word char after a word-char
4449 	 */
4450 	while (	   (c = vpeekc()) != NUL
4451 		&& !ISSPECIAL(c)
4452 #ifdef FEAT_MBYTE
4453 		&& (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
4454 #endif
4455 		&& i < INPUT_BUFLEN
4456 		&& (textwidth == 0
4457 		    || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
4458 		&& !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
4459 	{
4460 #ifdef FEAT_RIGHTLEFT
4461 	    c = vgetc();
4462 	    if (p_hkmap && KeyTyped)
4463 		c = hkmap(c);		    /* Hebrew mode mapping */
4464 # ifdef FEAT_FKMAP
4465 	    if (p_fkmap && KeyTyped)
4466 		c = fkmap(c);		    /* Farsi mode mapping */
4467 # endif
4468 	    buf[i++] = c;
4469 #else
4470 	    buf[i++] = vgetc();
4471 #endif
4472 	}
4473 
4474 #ifdef FEAT_DIGRAPHS
4475 	do_digraph(-1);			/* clear digraphs */
4476 	do_digraph(buf[i-1]);		/* may be the start of a digraph */
4477 #endif
4478 	buf[i] = NUL;
4479 	ins_str(buf);
4480 	if (flags & INSCHAR_CTRLV)
4481 	{
4482 	    redo_literal(*buf);
4483 	    i = 1;
4484 	}
4485 	else
4486 	    i = 0;
4487 	if (buf[i] != NUL)
4488 	    AppendToRedobuffLit(buf + i);
4489     }
4490     else
4491     {
4492 #ifdef FEAT_MBYTE
4493 	if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
4494 	{
4495 	    char_u	buf[MB_MAXBYTES + 1];
4496 
4497 	    (*mb_char2bytes)(c, buf);
4498 	    buf[cc] = NUL;
4499 	    ins_char_bytes(buf, cc);
4500 	    AppendCharToRedobuff(c);
4501 	}
4502 	else
4503 #endif
4504 	{
4505 	    ins_char(c);
4506 	    if (flags & INSCHAR_CTRLV)
4507 		redo_literal(c);
4508 	    else
4509 		AppendCharToRedobuff(c);
4510 	}
4511     }
4512 }
4513 
4514 /*
4515  * Called after inserting or deleting text: When 'formatoptions' includes the
4516  * 'a' flag format from the current line until the end of the paragraph.
4517  * Keep the cursor at the same position relative to the text.
4518  * The caller must have saved the cursor line for undo, following ones will be
4519  * saved here.
4520  */
4521     void
4522 auto_format(trailblank, prev_line)
4523     int		trailblank;	/* when TRUE also format with trailing blank */
4524     int		prev_line;	/* may start in previous line */
4525 {
4526     pos_T	pos;
4527     colnr_T	len;
4528     char_u	*old;
4529     char_u	*new, *pnew;
4530     int		wasatend;
4531     int		cc;
4532 
4533     if (!has_format_option(FO_AUTO))
4534 	return;
4535 
4536     pos = curwin->w_cursor;
4537     old = ml_get_curline();
4538 
4539     /* may remove added space */
4540     check_auto_format(FALSE);
4541 
4542     /* Don't format in Insert mode when the cursor is on a trailing blank, the
4543      * user might insert normal text next.  Also skip formatting when "1" is
4544      * in 'formatoptions' and there is a single character before the cursor.
4545      * Otherwise the line would be broken and when typing another non-white
4546      * next they are not joined back together. */
4547     wasatend = (pos.col == STRLEN(old));
4548     if (*old != NUL && !trailblank && wasatend)
4549     {
4550 	dec_cursor();
4551 	cc = gchar_cursor();
4552 	if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
4553 					  && has_format_option(FO_ONE_LETTER))
4554 	    dec_cursor();
4555 	cc = gchar_cursor();
4556 	if (WHITECHAR(cc))
4557 	{
4558 	    curwin->w_cursor = pos;
4559 	    return;
4560 	}
4561 	curwin->w_cursor = pos;
4562     }
4563 
4564 #ifdef FEAT_COMMENTS
4565     /* With the 'c' flag in 'formatoptions' and 't' missing: only format
4566      * comments. */
4567     if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
4568 				     && get_leader_len(old, NULL, FALSE) == 0)
4569 	return;
4570 #endif
4571 
4572     /*
4573      * May start formatting in a previous line, so that after "x" a word is
4574      * moved to the previous line if it fits there now.  Only when this is not
4575      * the start of a paragraph.
4576      */
4577     if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
4578     {
4579 	--curwin->w_cursor.lnum;
4580 	if (u_save_cursor() == FAIL)
4581 	    return;
4582     }
4583 
4584     /*
4585      * Do the formatting and restore the cursor position.  "saved_cursor" will
4586      * be adjusted for the text formatting.
4587      */
4588     saved_cursor = pos;
4589     format_lines((linenr_T)-1);
4590     curwin->w_cursor = saved_cursor;
4591     saved_cursor.lnum = 0;
4592 
4593     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
4594     {
4595 	/* "cannot happen" */
4596 	curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4597 	coladvance((colnr_T)MAXCOL);
4598     }
4599     else
4600 	check_cursor_col();
4601 
4602     /* Insert mode: If the cursor is now after the end of the line while it
4603      * previously wasn't, the line was broken.  Because of the rule above we
4604      * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
4605      * formatted. */
4606     if (!wasatend && has_format_option(FO_WHITE_PAR))
4607     {
4608 	new = ml_get_curline();
4609 	len = STRLEN(new);
4610 	if (curwin->w_cursor.col == len)
4611 	{
4612 	    pnew = vim_strnsave(new, len + 2);
4613 	    pnew[len] = ' ';
4614 	    pnew[len + 1] = NUL;
4615 	    ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
4616 	    /* remove the space later */
4617 	    did_add_space = TRUE;
4618 	}
4619 	else
4620 	    /* may remove added space */
4621 	    check_auto_format(FALSE);
4622     }
4623 
4624     check_cursor();
4625 }
4626 
4627 /*
4628  * When an extra space was added to continue a paragraph for auto-formatting,
4629  * delete it now.  The space must be under the cursor, just after the insert
4630  * position.
4631  */
4632     static void
4633 check_auto_format(end_insert)
4634     int		end_insert;	    /* TRUE when ending Insert mode */
4635 {
4636     int		c = ' ';
4637     int		cc;
4638 
4639     if (did_add_space)
4640     {
4641 	cc = gchar_cursor();
4642 	if (!WHITECHAR(cc))
4643 	    /* Somehow the space was removed already. */
4644 	    did_add_space = FALSE;
4645 	else
4646 	{
4647 	    if (!end_insert)
4648 	    {
4649 		inc_cursor();
4650 		c = gchar_cursor();
4651 		dec_cursor();
4652 	    }
4653 	    if (c != NUL)
4654 	    {
4655 		/* The space is no longer at the end of the line, delete it. */
4656 		del_char(FALSE);
4657 		did_add_space = FALSE;
4658 	    }
4659 	}
4660     }
4661 }
4662 
4663 /*
4664  * Find out textwidth to be used for formatting:
4665  *	if 'textwidth' option is set, use it
4666  *	else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
4667  *	if invalid value, use 0.
4668  *	Set default to window width (maximum 79) for "gq" operator.
4669  */
4670     int
4671 comp_textwidth(ff)
4672     int		ff;	/* force formatting (for "Q" command) */
4673 {
4674     int		textwidth;
4675 
4676     textwidth = curbuf->b_p_tw;
4677     if (textwidth == 0 && curbuf->b_p_wm)
4678     {
4679 	/* The width is the window width minus 'wrapmargin' minus all the
4680 	 * things that add to the margin. */
4681 	textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
4682 #ifdef FEAT_CMDWIN
4683 	if (cmdwin_type != 0)
4684 	    textwidth -= 1;
4685 #endif
4686 #ifdef FEAT_FOLDING
4687 	textwidth -= curwin->w_p_fdc;
4688 #endif
4689 #ifdef FEAT_SIGNS
4690 	if (curwin->w_buffer->b_signlist != NULL
4691 # ifdef FEAT_NETBEANS_INTG
4692 			    || usingNetbeans
4693 # endif
4694 		    )
4695 	    textwidth -= 1;
4696 #endif
4697 	if (curwin->w_p_nu)
4698 	    textwidth -= 8;
4699     }
4700     if (textwidth < 0)
4701 	textwidth = 0;
4702     if (ff && textwidth == 0)
4703     {
4704 	textwidth = W_WIDTH(curwin) - 1;
4705 	if (textwidth > 79)
4706 	    textwidth = 79;
4707     }
4708     return textwidth;
4709 }
4710 
4711 /*
4712  * Put a character in the redo buffer, for when just after a CTRL-V.
4713  */
4714     static void
4715 redo_literal(c)
4716     int	    c;
4717 {
4718     char_u	buf[10];
4719 
4720     /* Only digits need special treatment.  Translate them into a string of
4721      * three digits. */
4722     if (VIM_ISDIGIT(c))
4723     {
4724 	sprintf((char *)buf, "%03d", c);
4725 	AppendToRedobuff(buf);
4726     }
4727     else
4728 	AppendCharToRedobuff(c);
4729 }
4730 
4731 /*
4732  * start_arrow() is called when an arrow key is used in insert mode.
4733  * For undo/redo it resembles hitting the <ESC> key.
4734  */
4735     static void
4736 start_arrow(end_insert_pos)
4737     pos_T    *end_insert_pos;
4738 {
4739     if (!arrow_used)	    /* something has been inserted */
4740     {
4741 	AppendToRedobuff(ESC_STR);
4742 	stop_insert(end_insert_pos, FALSE);
4743 	arrow_used = TRUE;	/* this means we stopped the current insert */
4744     }
4745 #ifdef FEAT_SYN_HL
4746     check_spell_redraw();
4747 #endif
4748 }
4749 
4750 #ifdef FEAT_SYN_HL
4751 /*
4752  * If we skipped highlighting word at cursor, do it now.
4753  * It may be skipped again, thus reset spell_redraw_lnum first.
4754  */
4755     static void
4756 check_spell_redraw()
4757 {
4758     if (spell_redraw_lnum != 0)
4759     {
4760 	linenr_T	lnum = spell_redraw_lnum;
4761 
4762 	spell_redraw_lnum = 0;
4763 	redrawWinline(lnum, FALSE);
4764     }
4765 }
4766 
4767 /*
4768  * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
4769  * spelled word, if there is one.
4770  */
4771     static void
4772 spell_back_to_badword()
4773 {
4774     pos_T	tpos = curwin->w_cursor;
4775 
4776     spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
4777     if (curwin->w_cursor.col != tpos.col)
4778 	start_arrow(&tpos);
4779 }
4780 #endif
4781 
4782 /*
4783  * stop_arrow() is called before a change is made in insert mode.
4784  * If an arrow key has been used, start a new insertion.
4785  * Returns FAIL if undo is impossible, shouldn't insert then.
4786  */
4787     int
4788 stop_arrow()
4789 {
4790     if (arrow_used)
4791     {
4792 	if (u_save_cursor() == OK)
4793 	{
4794 	    arrow_used = FALSE;
4795 	    ins_need_undo = FALSE;
4796 	}
4797 	Insstart = curwin->w_cursor;	/* new insertion starts here */
4798 	Insstart_textlen = linetabsize(ml_get_curline());
4799 	ai_col = 0;
4800 #ifdef FEAT_VREPLACE
4801 	if (State & VREPLACE_FLAG)
4802 	{
4803 	    orig_line_count = curbuf->b_ml.ml_line_count;
4804 	    vr_lines_changed = 1;
4805 	}
4806 #endif
4807 	ResetRedobuff();
4808 	AppendToRedobuff((char_u *)"1i");   /* pretend we start an insertion */
4809     }
4810     else if (ins_need_undo)
4811     {
4812 	if (u_save_cursor() == OK)
4813 	    ins_need_undo = FALSE;
4814     }
4815 
4816 #ifdef FEAT_FOLDING
4817     /* Always open fold at the cursor line when inserting something. */
4818     foldOpenCursor();
4819 #endif
4820 
4821     return (arrow_used || ins_need_undo ? FAIL : OK);
4822 }
4823 
4824 /*
4825  * do a few things to stop inserting
4826  */
4827     static void
4828 stop_insert(end_insert_pos, esc)
4829     pos_T    *end_insert_pos;	/* where insert ended */
4830     int	    esc;		/* called by ins_esc() */
4831 {
4832     int	    cc;
4833 
4834     stop_redo_ins();
4835     replace_flush();		/* abandon replace stack */
4836 
4837     /*
4838      * save the inserted text for later redo with ^@
4839      */
4840     vim_free(last_insert);
4841     last_insert = get_inserted();
4842     last_insert_skip = new_insert_skip;
4843 
4844     if (!arrow_used)
4845     {
4846 	/* Auto-format now.  It may seem strange to do this when stopping an
4847 	 * insertion (or moving the cursor), but it's required when appending
4848 	 * a line and having it end in a space.  But only do it when something
4849 	 * was actually inserted, otherwise undo won't work. */
4850 	if (!ins_need_undo && has_format_option(FO_AUTO))
4851 	{
4852 	    pos_T   tpos = curwin->w_cursor;
4853 
4854 	    /* When the cursor is at the end of the line after a space the
4855 	     * formatting will move it to the following word.  Avoid that by
4856 	     * moving the cursor onto the space. */
4857 	    cc = 'x';
4858 	    if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
4859 	    {
4860 		dec_cursor();
4861 		cc = gchar_cursor();
4862 		if (!vim_iswhite(cc))
4863 		    curwin->w_cursor = tpos;
4864 	    }
4865 
4866 	    auto_format(TRUE, FALSE);
4867 
4868 	    if (vim_iswhite(cc))
4869 	    {
4870 		if (gchar_cursor() != NUL)
4871 		    inc_cursor();
4872 #ifdef FEAT_VIRTUALEDIT
4873 		/* If the cursor is still at the same character, also keep
4874 		 * the "coladd". */
4875 		if (gchar_cursor() == NUL
4876 			&& curwin->w_cursor.lnum == tpos.lnum
4877 			&& curwin->w_cursor.col == tpos.col)
4878 		    curwin->w_cursor.coladd = tpos.coladd;
4879 #endif
4880 	    }
4881 	}
4882 
4883 	/* If a space was inserted for auto-formatting, remove it now. */
4884 	check_auto_format(TRUE);
4885 
4886 	/* If we just did an auto-indent, remove the white space from the end
4887 	 * of the line, and put the cursor back.
4888 	 * Do this when ESC was used or moving the cursor up/down. */
4889 	if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
4890 			   && curwin->w_cursor.lnum != end_insert_pos->lnum)))
4891 	{
4892 	    pos_T	tpos = curwin->w_cursor;
4893 
4894 	    curwin->w_cursor = *end_insert_pos;
4895 	    if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
4896 		--curwin->w_cursor.col;
4897 	    while (cc = gchar_cursor(), vim_iswhite(cc))
4898 		(void)del_char(TRUE);
4899 	    if (curwin->w_cursor.lnum != tpos.lnum)
4900 		curwin->w_cursor = tpos;
4901 	    else if (cc != NUL)
4902 		++curwin->w_cursor.col;	/* put cursor back on the NUL */
4903 
4904 #ifdef FEAT_VISUAL
4905 	    /* <C-S-Right> may have started Visual mode, adjust the position for
4906 	     * deleted characters. */
4907 	    if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
4908 	    {
4909 		cc = STRLEN(ml_get_curline());
4910 		if (VIsual.col > (colnr_T)cc)
4911 		{
4912 		    VIsual.col = cc;
4913 # ifdef FEAT_VIRTUALEDIT
4914 		    VIsual.coladd = 0;
4915 # endif
4916 		}
4917 	    }
4918 #endif
4919 	}
4920     }
4921     did_ai = FALSE;
4922 #ifdef FEAT_SMARTINDENT
4923     did_si = FALSE;
4924     can_si = FALSE;
4925     can_si_back = FALSE;
4926 #endif
4927 
4928     /* set '[ and '] to the inserted text */
4929     curbuf->b_op_start = Insstart;
4930     curbuf->b_op_end = *end_insert_pos;
4931 }
4932 
4933 /*
4934  * Set the last inserted text to a single character.
4935  * Used for the replace command.
4936  */
4937     void
4938 set_last_insert(c)
4939     int		c;
4940 {
4941     char_u	*s;
4942 
4943     vim_free(last_insert);
4944 #ifdef FEAT_MBYTE
4945     last_insert = alloc(MB_MAXBYTES * 3 + 5);
4946 #else
4947     last_insert = alloc(6);
4948 #endif
4949     if (last_insert != NULL)
4950     {
4951 	s = last_insert;
4952 	/* Use the CTRL-V only when entering a special char */
4953 	if (c < ' ' || c == DEL)
4954 	    *s++ = Ctrl_V;
4955 	s = add_char2buf(c, s);
4956 	*s++ = ESC;
4957 	*s++ = NUL;
4958 	last_insert_skip = 0;
4959     }
4960 }
4961 
4962 #if defined(EXITFREE) || defined(PROTO)
4963     void
4964 free_last_insert()
4965 {
4966     vim_free(last_insert);
4967     last_insert = NULL;
4968 }
4969 #endif
4970 
4971 /*
4972  * Add character "c" to buffer "s".  Escape the special meaning of K_SPECIAL
4973  * and CSI.  Handle multi-byte characters.
4974  * Returns a pointer to after the added bytes.
4975  */
4976     char_u *
4977 add_char2buf(c, s)
4978     int		c;
4979     char_u	*s;
4980 {
4981 #ifdef FEAT_MBYTE
4982     char_u	temp[MB_MAXBYTES];
4983     int		i;
4984     int		len;
4985 
4986     len = (*mb_char2bytes)(c, temp);
4987     for (i = 0; i < len; ++i)
4988     {
4989 	c = temp[i];
4990 #endif
4991 	/* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
4992 	if (c == K_SPECIAL)
4993 	{
4994 	    *s++ = K_SPECIAL;
4995 	    *s++ = KS_SPECIAL;
4996 	    *s++ = KE_FILLER;
4997 	}
4998 #ifdef FEAT_GUI
4999 	else if (c == CSI)
5000 	{
5001 	    *s++ = CSI;
5002 	    *s++ = KS_EXTRA;
5003 	    *s++ = (int)KE_CSI;
5004 	}
5005 #endif
5006 	else
5007 	    *s++ = c;
5008 #ifdef FEAT_MBYTE
5009     }
5010 #endif
5011     return s;
5012 }
5013 
5014 /*
5015  * move cursor to start of line
5016  * if flags & BL_WHITE	move to first non-white
5017  * if flags & BL_SOL	move to first non-white if startofline is set,
5018  *			    otherwise keep "curswant" column
5019  * if flags & BL_FIX	don't leave the cursor on a NUL.
5020  */
5021     void
5022 beginline(flags)
5023     int		flags;
5024 {
5025     if ((flags & BL_SOL) && !p_sol)
5026 	coladvance(curwin->w_curswant);
5027     else
5028     {
5029 	curwin->w_cursor.col = 0;
5030 #ifdef FEAT_VIRTUALEDIT
5031 	curwin->w_cursor.coladd = 0;
5032 #endif
5033 
5034 	if (flags & (BL_WHITE | BL_SOL))
5035 	{
5036 	    char_u  *ptr;
5037 
5038 	    for (ptr = ml_get_curline(); vim_iswhite(*ptr)
5039 			       && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
5040 		++curwin->w_cursor.col;
5041 	}
5042 	curwin->w_set_curswant = TRUE;
5043     }
5044 }
5045 
5046 /*
5047  * oneright oneleft cursor_down cursor_up
5048  *
5049  * Move one char {right,left,down,up}.
5050  * Doesn't move onto the NUL past the end of the line.
5051  * Return OK when successful, FAIL when we hit a line of file boundary.
5052  */
5053 
5054     int
5055 oneright()
5056 {
5057     char_u	*ptr;
5058 #ifdef FEAT_MBYTE
5059     int		l;
5060 #endif
5061 
5062 #ifdef FEAT_VIRTUALEDIT
5063     if (virtual_active())
5064     {
5065 	pos_T	prevpos = curwin->w_cursor;
5066 
5067 	/* Adjust for multi-wide char (excluding TAB) */
5068 	ptr = ml_get_cursor();
5069 	coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
5070 #ifdef FEAT_MBYTE
5071 			    (*mb_ptr2char)(ptr)
5072 #else
5073 			    *ptr
5074 #endif
5075 			    ))
5076 		    ? ptr2cells(ptr) : 1));
5077 	curwin->w_set_curswant = TRUE;
5078 	/* Return OK if the cursor moved, FAIL otherwise (at window edge). */
5079 	return (prevpos.col != curwin->w_cursor.col
5080 		    || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
5081     }
5082 #endif
5083 
5084     ptr = ml_get_cursor();
5085 #ifdef FEAT_MBYTE
5086     if (has_mbyte && (l = (*mb_ptr2len)(ptr)) > 1)
5087     {
5088 	/* The character under the cursor is a multi-byte character, move
5089 	 * several bytes right, but don't end up on the NUL. */
5090 	if (ptr[l] == NUL)
5091 	    return FAIL;
5092 	curwin->w_cursor.col += l;
5093     }
5094     else
5095 #endif
5096     {
5097 	if (*ptr++ == NUL || *ptr == NUL)
5098 	    return FAIL;
5099 	++curwin->w_cursor.col;
5100     }
5101 
5102     curwin->w_set_curswant = TRUE;
5103     return OK;
5104 }
5105 
5106     int
5107 oneleft()
5108 {
5109 #ifdef FEAT_VIRTUALEDIT
5110     if (virtual_active())
5111     {
5112 	int width;
5113 	int v = getviscol();
5114 
5115 	if (v == 0)
5116 	    return FAIL;
5117 
5118 # ifdef FEAT_LINEBREAK
5119 	/* We might get stuck on 'showbreak', skip over it. */
5120 	width = 1;
5121 	for (;;)
5122 	{
5123 	    coladvance(v - width);
5124 	    /* getviscol() is slow, skip it when 'showbreak' is empty and
5125 	     * there are no multi-byte characters */
5126 	    if ((*p_sbr == NUL
5127 #  ifdef FEAT_MBYTE
5128 			&& !has_mbyte
5129 #  endif
5130 			) || getviscol() < v)
5131 		break;
5132 	    ++width;
5133 	}
5134 # else
5135 	coladvance(v - 1);
5136 # endif
5137 
5138 	if (curwin->w_cursor.coladd == 1)
5139 	{
5140 	    char_u *ptr;
5141 
5142 	    /* Adjust for multi-wide char (not a TAB) */
5143 	    ptr = ml_get_cursor();
5144 	    if (*ptr != TAB && vim_isprintc(
5145 #  ifdef FEAT_MBYTE
5146 			    (*mb_ptr2char)(ptr)
5147 #  else
5148 			    *ptr
5149 #  endif
5150 			    ) && ptr2cells(ptr) > 1)
5151 		curwin->w_cursor.coladd = 0;
5152 	}
5153 
5154 	curwin->w_set_curswant = TRUE;
5155 	return OK;
5156     }
5157 #endif
5158 
5159     if (curwin->w_cursor.col == 0)
5160 	return FAIL;
5161 
5162     curwin->w_set_curswant = TRUE;
5163     --curwin->w_cursor.col;
5164 
5165 #ifdef FEAT_MBYTE
5166     /* if the character on the left of the current cursor is a multi-byte
5167      * character, move to its first byte */
5168     if (has_mbyte)
5169 	mb_adjust_cursor();
5170 #endif
5171     return OK;
5172 }
5173 
5174     int
5175 cursor_up(n, upd_topline)
5176     long	n;
5177     int		upd_topline;	    /* When TRUE: update topline */
5178 {
5179     linenr_T	lnum;
5180 
5181     if (n > 0)
5182     {
5183 	lnum = curwin->w_cursor.lnum;
5184 	/* This fails if the cursor is already in the first line or the count
5185 	 * is larger than the line number and '-' is in 'cpoptions' */
5186 	if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
5187 	    return FAIL;
5188 	if (n >= lnum)
5189 	    lnum = 1;
5190 	else
5191 #ifdef FEAT_FOLDING
5192 	    if (hasAnyFolding(curwin))
5193 	{
5194 	    /*
5195 	     * Count each sequence of folded lines as one logical line.
5196 	     */
5197 	    /* go to the the start of the current fold */
5198 	    (void)hasFolding(lnum, &lnum, NULL);
5199 
5200 	    while (n--)
5201 	    {
5202 		/* move up one line */
5203 		--lnum;
5204 		if (lnum <= 1)
5205 		    break;
5206 		/* If we entered a fold, move to the beginning, unless in
5207 		 * Insert mode or when 'foldopen' contains "all": it will open
5208 		 * in a moment. */
5209 		if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
5210 		    (void)hasFolding(lnum, &lnum, NULL);
5211 	    }
5212 	    if (lnum < 1)
5213 		lnum = 1;
5214 	}
5215 	else
5216 #endif
5217 	    lnum -= n;
5218 	curwin->w_cursor.lnum = lnum;
5219     }
5220 
5221     /* try to advance to the column we want to be at */
5222     coladvance(curwin->w_curswant);
5223 
5224     if (upd_topline)
5225 	update_topline();	/* make sure curwin->w_topline is valid */
5226 
5227     return OK;
5228 }
5229 
5230 /*
5231  * Cursor down a number of logical lines.
5232  */
5233     int
5234 cursor_down(n, upd_topline)
5235     long	n;
5236     int		upd_topline;	    /* When TRUE: update topline */
5237 {
5238     linenr_T	lnum;
5239 
5240     if (n > 0)
5241     {
5242 	lnum = curwin->w_cursor.lnum;
5243 #ifdef FEAT_FOLDING
5244 	/* Move to last line of fold, will fail if it's the end-of-file. */
5245 	(void)hasFolding(lnum, NULL, &lnum);
5246 #endif
5247 	/* This fails if the cursor is already in the last line or would move
5248 	 * beyound the last line and '-' is in 'cpoptions' */
5249 	if (lnum >= curbuf->b_ml.ml_line_count
5250 		|| (lnum + n > curbuf->b_ml.ml_line_count
5251 		    && vim_strchr(p_cpo, CPO_MINUS) != NULL))
5252 	    return FAIL;
5253 	if (lnum + n >= curbuf->b_ml.ml_line_count)
5254 	    lnum = curbuf->b_ml.ml_line_count;
5255 	else
5256 #ifdef FEAT_FOLDING
5257 	if (hasAnyFolding(curwin))
5258 	{
5259 	    linenr_T	last;
5260 
5261 	    /* count each sequence of folded lines as one logical line */
5262 	    while (n--)
5263 	    {
5264 		if (hasFolding(lnum, NULL, &last))
5265 		    lnum = last + 1;
5266 		else
5267 		    ++lnum;
5268 		if (lnum >= curbuf->b_ml.ml_line_count)
5269 		    break;
5270 	    }
5271 	    if (lnum > curbuf->b_ml.ml_line_count)
5272 		lnum = curbuf->b_ml.ml_line_count;
5273 	}
5274 	else
5275 #endif
5276 	    lnum += n;
5277 	curwin->w_cursor.lnum = lnum;
5278     }
5279 
5280     /* try to advance to the column we want to be at */
5281     coladvance(curwin->w_curswant);
5282 
5283     if (upd_topline)
5284 	update_topline();	/* make sure curwin->w_topline is valid */
5285 
5286     return OK;
5287 }
5288 
5289 /*
5290  * Stuff the last inserted text in the read buffer.
5291  * Last_insert actually is a copy of the redo buffer, so we
5292  * first have to remove the command.
5293  */
5294     int
5295 stuff_inserted(c, count, no_esc)
5296     int	    c;		/* Command character to be inserted */
5297     long    count;	/* Repeat this many times */
5298     int	    no_esc;	/* Don't add an ESC at the end */
5299 {
5300     char_u	*esc_ptr;
5301     char_u	*ptr;
5302     char_u	*last_ptr;
5303     char_u	last = NUL;
5304 
5305     ptr = get_last_insert();
5306     if (ptr == NULL)
5307     {
5308 	EMSG(_(e_noinstext));
5309 	return FAIL;
5310     }
5311 
5312     /* may want to stuff the command character, to start Insert mode */
5313     if (c != NUL)
5314 	stuffcharReadbuff(c);
5315     if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
5316 	*esc_ptr = NUL;	    /* remove the ESC */
5317 
5318     /* when the last char is either "0" or "^" it will be quoted if no ESC
5319      * comes after it OR if it will inserted more than once and "ptr"
5320      * starts with ^D.	-- Acevedo
5321      */
5322     last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
5323     if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
5324 	    && (no_esc || (*ptr == Ctrl_D && count > 1)))
5325     {
5326 	last = *last_ptr;
5327 	*last_ptr = NUL;
5328     }
5329 
5330     do
5331     {
5332 	stuffReadbuff(ptr);
5333 	/* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
5334 	if (last)
5335 	    stuffReadbuff((char_u *)(last == '0'
5336 			? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
5337 			: IF_EB("\026^", CTRL_V_STR "^")));
5338     }
5339     while (--count > 0);
5340 
5341     if (last)
5342 	*last_ptr = last;
5343 
5344     if (esc_ptr != NULL)
5345 	*esc_ptr = ESC;	    /* put the ESC back */
5346 
5347     /* may want to stuff a trailing ESC, to get out of Insert mode */
5348     if (!no_esc)
5349 	stuffcharReadbuff(ESC);
5350 
5351     return OK;
5352 }
5353 
5354     char_u *
5355 get_last_insert()
5356 {
5357     if (last_insert == NULL)
5358 	return NULL;
5359     return last_insert + last_insert_skip;
5360 }
5361 
5362 /*
5363  * Get last inserted string, and remove trailing <Esc>.
5364  * Returns pointer to allocated memory (must be freed) or NULL.
5365  */
5366     char_u *
5367 get_last_insert_save()
5368 {
5369     char_u	*s;
5370     int		len;
5371 
5372     if (last_insert == NULL)
5373 	return NULL;
5374     s = vim_strsave(last_insert + last_insert_skip);
5375     if (s != NULL)
5376     {
5377 	len = (int)STRLEN(s);
5378 	if (len > 0 && s[len - 1] == ESC)	/* remove trailing ESC */
5379 	    s[len - 1] = NUL;
5380     }
5381     return s;
5382 }
5383 
5384 /*
5385  * Check the word in front of the cursor for an abbreviation.
5386  * Called when the non-id character "c" has been entered.
5387  * When an abbreviation is recognized it is removed from the text and
5388  * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
5389  */
5390     static int
5391 echeck_abbr(c)
5392     int c;
5393 {
5394     /* Don't check for abbreviation in paste mode, when disabled and just
5395      * after moving around with cursor keys. */
5396     if (p_paste || no_abbr || arrow_used)
5397 	return FALSE;
5398 
5399     return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
5400 		curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
5401 }
5402 
5403 /*
5404  * replace-stack functions
5405  *
5406  * When replacing characters, the replaced characters are remembered for each
5407  * new character.  This is used to re-insert the old text when backspacing.
5408  *
5409  * There is a NUL headed list of characters for each character that is
5410  * currently in the file after the insertion point.  When BS is used, one NUL
5411  * headed list is put back for the deleted character.
5412  *
5413  * For a newline, there are two NUL headed lists.  One contains the characters
5414  * that the NL replaced.  The extra one stores the characters after the cursor
5415  * that were deleted (always white space).
5416  *
5417  * Replace_offset is normally 0, in which case replace_push will add a new
5418  * character at the end of the stack.  If replace_offset is not 0, that many
5419  * characters will be left on the stack above the newly inserted character.
5420  */
5421 
5422 static char_u	*replace_stack = NULL;
5423 static long	replace_stack_nr = 0;	    /* next entry in replace stack */
5424 static long	replace_stack_len = 0;	    /* max. number of entries */
5425 
5426     void
5427 replace_push(c)
5428     int	    c;	    /* character that is replaced (NUL is none) */
5429 {
5430     char_u  *p;
5431 
5432     if (replace_stack_nr < replace_offset)	/* nothing to do */
5433 	return;
5434     if (replace_stack_len <= replace_stack_nr)
5435     {
5436 	replace_stack_len += 50;
5437 	p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
5438 	if (p == NULL)	    /* out of memory */
5439 	{
5440 	    replace_stack_len -= 50;
5441 	    return;
5442 	}
5443 	if (replace_stack != NULL)
5444 	{
5445 	    mch_memmove(p, replace_stack,
5446 				 (size_t)(replace_stack_nr * sizeof(char_u)));
5447 	    vim_free(replace_stack);
5448 	}
5449 	replace_stack = p;
5450     }
5451     p = replace_stack + replace_stack_nr - replace_offset;
5452     if (replace_offset)
5453 	mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
5454     *p = c;
5455     ++replace_stack_nr;
5456 }
5457 
5458 /*
5459  * call replace_push(c) with replace_offset set to the first NUL.
5460  */
5461     static void
5462 replace_push_off(c)
5463     int	    c;
5464 {
5465     char_u	*p;
5466 
5467     p = replace_stack + replace_stack_nr;
5468     for (replace_offset = 1; replace_offset < replace_stack_nr;
5469 							     ++replace_offset)
5470 	if (*--p == NUL)
5471 	    break;
5472     replace_push(c);
5473     replace_offset = 0;
5474 }
5475 
5476 /*
5477  * Pop one item from the replace stack.
5478  * return -1 if stack empty
5479  * return replaced character or NUL otherwise
5480  */
5481     static int
5482 replace_pop()
5483 {
5484     if (replace_stack_nr == 0)
5485 	return -1;
5486     return (int)replace_stack[--replace_stack_nr];
5487 }
5488 
5489 /*
5490  * Join the top two items on the replace stack.  This removes to "off"'th NUL
5491  * encountered.
5492  */
5493     static void
5494 replace_join(off)
5495     int	    off;	/* offset for which NUL to remove */
5496 {
5497     int	    i;
5498 
5499     for (i = replace_stack_nr; --i >= 0; )
5500 	if (replace_stack[i] == NUL && off-- <= 0)
5501 	{
5502 	    --replace_stack_nr;
5503 	    mch_memmove(replace_stack + i, replace_stack + i + 1,
5504 					      (size_t)(replace_stack_nr - i));
5505 	    return;
5506 	}
5507 }
5508 
5509 /*
5510  * Pop bytes from the replace stack until a NUL is found, and insert them
5511  * before the cursor.  Can only be used in REPLACE or VREPLACE mode.
5512  */
5513     static void
5514 replace_pop_ins()
5515 {
5516     int	    cc;
5517     int	    oldState = State;
5518 
5519     State = NORMAL;			/* don't want REPLACE here */
5520     while ((cc = replace_pop()) > 0)
5521     {
5522 #ifdef FEAT_MBYTE
5523 	mb_replace_pop_ins(cc);
5524 #else
5525 	ins_char(cc);
5526 #endif
5527 	dec_cursor();
5528     }
5529     State = oldState;
5530 }
5531 
5532 #ifdef FEAT_MBYTE
5533 /*
5534  * Insert bytes popped from the replace stack. "cc" is the first byte.  If it
5535  * indicates a multi-byte char, pop the other bytes too.
5536  */
5537     static void
5538 mb_replace_pop_ins(cc)
5539     int		cc;
5540 {
5541     int		n;
5542     char_u	buf[MB_MAXBYTES];
5543     int		i;
5544     int		c;
5545 
5546     if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
5547     {
5548 	buf[0] = cc;
5549 	for (i = 1; i < n; ++i)
5550 	    buf[i] = replace_pop();
5551 	ins_bytes_len(buf, n);
5552     }
5553     else
5554 	ins_char(cc);
5555 
5556     if (enc_utf8)
5557 	/* Handle composing chars. */
5558 	for (;;)
5559 	{
5560 	    c = replace_pop();
5561 	    if (c == -1)	    /* stack empty */
5562 		break;
5563 	    if ((n = MB_BYTE2LEN(c)) == 1)
5564 	    {
5565 		/* Not a multi-byte char, put it back. */
5566 		replace_push(c);
5567 		break;
5568 	    }
5569 	    else
5570 	    {
5571 		buf[0] = c;
5572 		for (i = 1; i < n; ++i)
5573 		    buf[i] = replace_pop();
5574 		if (utf_iscomposing(utf_ptr2char(buf)))
5575 		    ins_bytes_len(buf, n);
5576 		else
5577 		{
5578 		    /* Not a composing char, put it back. */
5579 		    for (i = n - 1; i >= 0; --i)
5580 			replace_push(buf[i]);
5581 		    break;
5582 		}
5583 	    }
5584 	}
5585 }
5586 #endif
5587 
5588 /*
5589  * make the replace stack empty
5590  * (called when exiting replace mode)
5591  */
5592     static void
5593 replace_flush()
5594 {
5595     vim_free(replace_stack);
5596     replace_stack = NULL;
5597     replace_stack_len = 0;
5598     replace_stack_nr = 0;
5599 }
5600 
5601 /*
5602  * Handle doing a BS for one character.
5603  * cc < 0: replace stack empty, just move cursor
5604  * cc == 0: character was inserted, delete it
5605  * cc > 0: character was replaced, put cc (first byte of original char) back
5606  * and check for more characters to be put back
5607  */
5608     static void
5609 replace_do_bs()
5610 {
5611     int		cc;
5612 #ifdef FEAT_VREPLACE
5613     int		orig_len = 0;
5614     int		ins_len;
5615     int		orig_vcols = 0;
5616     colnr_T	start_vcol;
5617     char_u	*p;
5618     int		i;
5619     int		vcol;
5620 #endif
5621 
5622     cc = replace_pop();
5623     if (cc > 0)
5624     {
5625 #ifdef FEAT_VREPLACE
5626 	if (State & VREPLACE_FLAG)
5627 	{
5628 	    /* Get the number of screen cells used by the character we are
5629 	     * going to delete. */
5630 	    getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
5631 	    orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
5632 	}
5633 #endif
5634 #ifdef FEAT_MBYTE
5635 	if (has_mbyte)
5636 	{
5637 	    del_char(FALSE);
5638 # ifdef FEAT_VREPLACE
5639 	    if (State & VREPLACE_FLAG)
5640 		orig_len = STRLEN(ml_get_cursor());
5641 # endif
5642 	    replace_push(cc);
5643 	}
5644 	else
5645 #endif
5646 	{
5647 	    pchar_cursor(cc);
5648 #ifdef FEAT_VREPLACE
5649 	    if (State & VREPLACE_FLAG)
5650 		orig_len = STRLEN(ml_get_cursor()) - 1;
5651 #endif
5652 	}
5653 	replace_pop_ins();
5654 
5655 #ifdef FEAT_VREPLACE
5656 	if (State & VREPLACE_FLAG)
5657 	{
5658 	    /* Get the number of screen cells used by the inserted characters */
5659 	    p = ml_get_cursor();
5660 	    ins_len = STRLEN(p) - orig_len;
5661 	    vcol = start_vcol;
5662 	    for (i = 0; i < ins_len; ++i)
5663 	    {
5664 		vcol += chartabsize(p + i, vcol);
5665 #ifdef FEAT_MBYTE
5666 		i += (*mb_ptr2len)(p) - 1;
5667 #endif
5668 	    }
5669 	    vcol -= start_vcol;
5670 
5671 	    /* Delete spaces that were inserted after the cursor to keep the
5672 	     * text aligned. */
5673 	    curwin->w_cursor.col += ins_len;
5674 	    while (vcol > orig_vcols && gchar_cursor() == ' ')
5675 	    {
5676 		del_char(FALSE);
5677 		++orig_vcols;
5678 	    }
5679 	    curwin->w_cursor.col -= ins_len;
5680 	}
5681 #endif
5682 
5683 	/* mark the buffer as changed and prepare for displaying */
5684 	changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
5685     }
5686     else if (cc == 0)
5687 	(void)del_char(FALSE);
5688 }
5689 
5690 #ifdef FEAT_CINDENT
5691 /*
5692  * Return TRUE if C-indenting is on.
5693  */
5694     static int
5695 cindent_on()
5696 {
5697     return (!p_paste && (curbuf->b_p_cin
5698 # ifdef FEAT_EVAL
5699 		    || *curbuf->b_p_inde != NUL
5700 # endif
5701 		    ));
5702 }
5703 #endif
5704 
5705 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
5706 /*
5707  * Re-indent the current line, based on the current contents of it and the
5708  * surrounding lines. Fixing the cursor position seems really easy -- I'm very
5709  * confused what all the part that handles Control-T is doing that I'm not.
5710  * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
5711  */
5712 
5713     void
5714 fixthisline(get_the_indent)
5715     int (*get_the_indent) __ARGS((void));
5716 {
5717     change_indent(INDENT_SET, get_the_indent(), FALSE, 0);
5718     if (linewhite(curwin->w_cursor.lnum))
5719 	did_ai = TRUE;	    /* delete the indent if the line stays empty */
5720 }
5721 
5722     void
5723 fix_indent()
5724 {
5725     if (p_paste)
5726 	return;
5727 # ifdef FEAT_LISP
5728     if (curbuf->b_p_lisp && curbuf->b_p_ai)
5729 	fixthisline(get_lisp_indent);
5730 # endif
5731 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
5732     else
5733 # endif
5734 # ifdef FEAT_CINDENT
5735 	if (cindent_on())
5736 	    do_c_expr_indent();
5737 # endif
5738 }
5739 
5740 #endif
5741 
5742 #ifdef FEAT_CINDENT
5743 /*
5744  * return TRUE if 'cinkeys' contains the key "keytyped",
5745  * when == '*':	    Only if key is preceded with '*'	(indent before insert)
5746  * when == '!':	    Only if key is prededed with '!'	(don't insert)
5747  * when == ' ':	    Only if key is not preceded with '*'(indent afterwards)
5748  *
5749  * "keytyped" can have a few special values:
5750  * KEY_OPEN_FORW
5751  * KEY_OPEN_BACK
5752  * KEY_COMPLETE	    just finished completion.
5753  *
5754  * If line_is_empty is TRUE accept keys with '0' before them.
5755  */
5756     int
5757 in_cinkeys(keytyped, when, line_is_empty)
5758     int		keytyped;
5759     int		when;
5760     int		line_is_empty;
5761 {
5762     char_u	*look;
5763     int		try_match;
5764     int		try_match_word;
5765     char_u	*p;
5766     char_u	*line;
5767     int		icase;
5768     int		i;
5769 
5770 #ifdef FEAT_EVAL
5771     if (*curbuf->b_p_inde != NUL)
5772 	look = curbuf->b_p_indk;	/* 'indentexpr' set: use 'indentkeys' */
5773     else
5774 #endif
5775 	look = curbuf->b_p_cink;	/* 'indentexpr' empty: use 'cinkeys' */
5776     while (*look)
5777     {
5778 	/*
5779 	 * Find out if we want to try a match with this key, depending on
5780 	 * 'when' and a '*' or '!' before the key.
5781 	 */
5782 	switch (when)
5783 	{
5784 	    case '*': try_match = (*look == '*'); break;
5785 	    case '!': try_match = (*look == '!'); break;
5786 	     default: try_match = (*look != '*'); break;
5787 	}
5788 	if (*look == '*' || *look == '!')
5789 	    ++look;
5790 
5791 	/*
5792 	 * If there is a '0', only accept a match if the line is empty.
5793 	 * But may still match when typing last char of a word.
5794 	 */
5795 	if (*look == '0')
5796 	{
5797 	    try_match_word = try_match;
5798 	    if (!line_is_empty)
5799 		try_match = FALSE;
5800 	    ++look;
5801 	}
5802 	else
5803 	    try_match_word = FALSE;
5804 
5805 	/*
5806 	 * does it look like a control character?
5807 	 */
5808 	if (*look == '^'
5809 #ifdef EBCDIC
5810 		&& (Ctrl_chr(look[1]) != 0)
5811 #else
5812 		&& look[1] >= '?' && look[1] <= '_'
5813 #endif
5814 		)
5815 	{
5816 	    if (try_match && keytyped == Ctrl_chr(look[1]))
5817 		return TRUE;
5818 	    look += 2;
5819 	}
5820 	/*
5821 	 * 'o' means "o" command, open forward.
5822 	 * 'O' means "O" command, open backward.
5823 	 */
5824 	else if (*look == 'o')
5825 	{
5826 	    if (try_match && keytyped == KEY_OPEN_FORW)
5827 		return TRUE;
5828 	    ++look;
5829 	}
5830 	else if (*look == 'O')
5831 	{
5832 	    if (try_match && keytyped == KEY_OPEN_BACK)
5833 		return TRUE;
5834 	    ++look;
5835 	}
5836 
5837 	/*
5838 	 * 'e' means to check for "else" at start of line and just before the
5839 	 * cursor.
5840 	 */
5841 	else if (*look == 'e')
5842 	{
5843 	    if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
5844 	    {
5845 		p = ml_get_curline();
5846 		if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
5847 			STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
5848 		    return TRUE;
5849 	    }
5850 	    ++look;
5851 	}
5852 
5853 	/*
5854 	 * ':' only causes an indent if it is at the end of a label or case
5855 	 * statement, or when it was before typing the ':' (to fix
5856 	 * class::method for C++).
5857 	 */
5858 	else if (*look == ':')
5859 	{
5860 	    if (try_match && keytyped == ':')
5861 	    {
5862 		p = ml_get_curline();
5863 		if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
5864 		    return TRUE;
5865 		if (curwin->w_cursor.col > 2
5866 			&& p[curwin->w_cursor.col - 1] == ':'
5867 			&& p[curwin->w_cursor.col - 2] == ':')
5868 		{
5869 		    p[curwin->w_cursor.col - 1] = ' ';
5870 		    i = (cin_iscase(p) || cin_isscopedecl(p)
5871 							  || cin_islabel(30));
5872 		    p = ml_get_curline();
5873 		    p[curwin->w_cursor.col - 1] = ':';
5874 		    if (i)
5875 			return TRUE;
5876 		}
5877 	    }
5878 	    ++look;
5879 	}
5880 
5881 
5882 	/*
5883 	 * Is it a key in <>, maybe?
5884 	 */
5885 	else if (*look == '<')
5886 	{
5887 	    if (try_match)
5888 	    {
5889 		/*
5890 		 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
5891 		 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
5892 		 * >, *, : and ! keys if they really really want to.
5893 		 */
5894 		if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
5895 						       && keytyped == look[1])
5896 		    return TRUE;
5897 
5898 		if (keytyped == get_special_key_code(look + 1))
5899 		    return TRUE;
5900 	    }
5901 	    while (*look && *look != '>')
5902 		look++;
5903 	    while (*look == '>')
5904 		look++;
5905 	}
5906 
5907 	/*
5908 	 * Is it a word: "=word"?
5909 	 */
5910 	else if (*look == '=' && look[1] != ',' && look[1] != NUL)
5911 	{
5912 	    ++look;
5913 	    if (*look == '~')
5914 	    {
5915 		icase = TRUE;
5916 		++look;
5917 	    }
5918 	    else
5919 		icase = FALSE;
5920 	    p = vim_strchr(look, ',');
5921 	    if (p == NULL)
5922 		p = look + STRLEN(look);
5923 	    if ((try_match || try_match_word)
5924 		    && curwin->w_cursor.col >= (colnr_T)(p - look))
5925 	    {
5926 		int		match = FALSE;
5927 
5928 #ifdef FEAT_INS_EXPAND
5929 		if (keytyped == KEY_COMPLETE)
5930 		{
5931 		    char_u	*s;
5932 
5933 		    /* Just completed a word, check if it starts with "look".
5934 		     * search back for the start of a word. */
5935 		    line = ml_get_curline();
5936 # ifdef FEAT_MBYTE
5937 		    if (has_mbyte)
5938 		    {
5939 			char_u	*n;
5940 
5941 			for (s = line + curwin->w_cursor.col; s > line; s = n)
5942 			{
5943 			    n = mb_prevptr(line, s);
5944 			    if (!vim_iswordp(n))
5945 				break;
5946 			}
5947 		    }
5948 		    else
5949 # endif
5950 			for (s = line + curwin->w_cursor.col; s > line; --s)
5951 			    if (!vim_iswordc(s[-1]))
5952 				break;
5953 		    if (s + (p - look) <= line + curwin->w_cursor.col
5954 			    && (icase
5955 				? MB_STRNICMP(s, look, p - look)
5956 				: STRNCMP(s, look, p - look)) == 0)
5957 			match = TRUE;
5958 		}
5959 		else
5960 #endif
5961 		    /* TODO: multi-byte */
5962 		    if (keytyped == (int)p[-1] || (icase && keytyped < 256
5963 			 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
5964 		{
5965 		    line = ml_get_cursor();
5966 		    if ((curwin->w_cursor.col == (colnr_T)(p - look)
5967 				|| !vim_iswordc(line[-(p - look) - 1]))
5968 			    && (icase
5969 				? MB_STRNICMP(line - (p - look), look, p - look)
5970 				: STRNCMP(line - (p - look), look, p - look))
5971 									 == 0)
5972 			match = TRUE;
5973 		}
5974 		if (match && try_match_word && !try_match)
5975 		{
5976 		    /* "0=word": Check if there are only blanks before the
5977 		     * word. */
5978 		    line = ml_get_curline();
5979 		    if ((int)(skipwhite(line) - line) !=
5980 				     (int)(curwin->w_cursor.col - (p - look)))
5981 			match = FALSE;
5982 		}
5983 		if (match)
5984 		    return TRUE;
5985 	    }
5986 	    look = p;
5987 	}
5988 
5989 	/*
5990 	 * ok, it's a boring generic character.
5991 	 */
5992 	else
5993 	{
5994 	    if (try_match && *look == keytyped)
5995 		return TRUE;
5996 	    ++look;
5997 	}
5998 
5999 	/*
6000 	 * Skip over ", ".
6001 	 */
6002 	look = skip_to_option_part(look);
6003     }
6004     return FALSE;
6005 }
6006 #endif /* FEAT_CINDENT */
6007 
6008 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
6009 /*
6010  * Map Hebrew keyboard when in hkmap mode.
6011  */
6012     int
6013 hkmap(c)
6014     int c;
6015 {
6016     if (p_hkmapp)   /* phonetic mapping, by Ilya Dogolazky */
6017     {
6018 	enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
6019 	    KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
6020 	    PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
6021 	static char_u map[26] =
6022 	    {(char_u)hALEF/*a*/, (char_u)BET  /*b*/, (char_u)hKAF    /*c*/,
6023 	     (char_u)DALET/*d*/, (char_u)-1   /*e*/, (char_u)PEIsofit/*f*/,
6024 	     (char_u)GIMEL/*g*/, (char_u)HEI  /*h*/, (char_u)IUD     /*i*/,
6025 	     (char_u)HET  /*j*/, (char_u)KOF  /*k*/, (char_u)LAMED   /*l*/,
6026 	     (char_u)MEM  /*m*/, (char_u)NUN  /*n*/, (char_u)SAMEH   /*o*/,
6027 	     (char_u)PEI  /*p*/, (char_u)-1   /*q*/, (char_u)RESH    /*r*/,
6028 	     (char_u)ZAIN /*s*/, (char_u)TAV  /*t*/, (char_u)TET     /*u*/,
6029 	     (char_u)VAV  /*v*/, (char_u)hSHIN/*w*/, (char_u)-1      /*x*/,
6030 	     (char_u)AIN  /*y*/, (char_u)ZADI /*z*/};
6031 
6032 	if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
6033 	    return (int)(map[CharOrd(c)] - 1 + p_aleph);
6034 							    /* '-1'='sofit' */
6035 	else if (c == 'x')
6036 	    return 'X';
6037 	else if (c == 'q')
6038 	    return '\''; /* {geresh}={'} */
6039 	else if (c == 246)
6040 	    return ' ';  /* \"o --> ' ' for a german keyboard */
6041 	else if (c == 228)
6042 	    return ' ';  /* \"a --> ' '      -- / --	       */
6043 	else if (c == 252)
6044 	    return ' ';  /* \"u --> ' '      -- / --	       */
6045 #ifdef EBCDIC
6046 	else if (islower(c))
6047 #else
6048 	/* NOTE: islower() does not do the right thing for us on Linux so we
6049 	 * do this the same was as 5.7 and previous, so it works correctly on
6050 	 * all systems.  Specifically, the e.g. Delete and Arrow keys are
6051 	 * munged and won't work if e.g. searching for Hebrew text.
6052 	 */
6053 	else if (c >= 'a' && c <= 'z')
6054 #endif
6055 	    return (int)(map[CharOrdLow(c)] + p_aleph);
6056 	else
6057 	    return c;
6058     }
6059     else
6060     {
6061 	switch (c)
6062 	{
6063 	    case '`':	return ';';
6064 	    case '/':	return '.';
6065 	    case '\'':	return ',';
6066 	    case 'q':	return '/';
6067 	    case 'w':	return '\'';
6068 
6069 			/* Hebrew letters - set offset from 'a' */
6070 	    case ',':	c = '{'; break;
6071 	    case '.':	c = 'v'; break;
6072 	    case ';':	c = 't'; break;
6073 	    default: {
6074 			 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
6075 
6076 #ifdef EBCDIC
6077 			 /* see note about islower() above */
6078 			 if (!islower(c))
6079 #else
6080 			 if (c < 'a' || c > 'z')
6081 #endif
6082 			     return c;
6083 			 c = str[CharOrdLow(c)];
6084 			 break;
6085 		     }
6086 	}
6087 
6088 	return (int)(CharOrdLow(c) + p_aleph);
6089     }
6090 }
6091 #endif
6092 
6093     static void
6094 ins_reg()
6095 {
6096     int		need_redraw = FALSE;
6097     int		regname;
6098     int		literally = 0;
6099 
6100     /*
6101      * If we are going to wait for a character, show a '"'.
6102      */
6103     pc_status = PC_STATUS_UNSET;
6104     if (redrawing() && !char_avail())
6105     {
6106 	/* may need to redraw when no more chars available now */
6107 	ins_redraw();
6108 
6109 	edit_putchar('"', TRUE);
6110 #ifdef FEAT_CMDL_INFO
6111 	add_to_showcmd_c(Ctrl_R);
6112 #endif
6113     }
6114 
6115 #ifdef USE_ON_FLY_SCROLL
6116     dont_scroll = TRUE;		/* disallow scrolling here */
6117 #endif
6118 
6119     /*
6120      * Don't map the register name. This also prevents the mode message to be
6121      * deleted when ESC is hit.
6122      */
6123     ++no_mapping;
6124     regname = safe_vgetc();
6125 #ifdef FEAT_LANGMAP
6126     LANGMAP_ADJUST(regname, TRUE);
6127 #endif
6128     if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
6129     {
6130 	/* Get a third key for literal register insertion */
6131 	literally = regname;
6132 #ifdef FEAT_CMDL_INFO
6133 	add_to_showcmd_c(literally);
6134 #endif
6135 	regname = safe_vgetc();
6136 #ifdef FEAT_LANGMAP
6137 	LANGMAP_ADJUST(regname, TRUE);
6138 #endif
6139     }
6140     --no_mapping;
6141 
6142 #ifdef FEAT_EVAL
6143     /*
6144      * Don't call u_sync() while getting the expression,
6145      * evaluating it or giving an error message for it!
6146      */
6147     ++no_u_sync;
6148     if (regname == '=')
6149     {
6150 # ifdef USE_IM_CONTROL
6151 	int	im_on = im_get_status();
6152 # endif
6153 	regname = get_expr_register();
6154 # ifdef USE_IM_CONTROL
6155 	/* Restore the Input Method. */
6156 	if (im_on)
6157 	    im_set_active(TRUE);
6158 # endif
6159     }
6160     if (regname == NUL || !valid_yank_reg(regname, FALSE))
6161     {
6162 	vim_beep();
6163 	need_redraw = TRUE;	/* remove the '"' */
6164     }
6165     else
6166     {
6167 #endif
6168 	if (literally == Ctrl_O || literally == Ctrl_P)
6169 	{
6170 	    /* Append the command to the redo buffer. */
6171 	    AppendCharToRedobuff(Ctrl_R);
6172 	    AppendCharToRedobuff(literally);
6173 	    AppendCharToRedobuff(regname);
6174 
6175 	    do_put(regname, BACKWARD, 1L,
6176 		 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
6177 	}
6178 	else if (insert_reg(regname, literally) == FAIL)
6179 	{
6180 	    vim_beep();
6181 	    need_redraw = TRUE;	/* remove the '"' */
6182 	}
6183 	else if (stop_insert_mode)
6184 	    /* When the '=' register was used and a function was invoked that
6185 	     * did ":stopinsert" then stuff_empty() returns FALSE but we won't
6186 	     * insert anything, need to remove the '"' */
6187 	    need_redraw = TRUE;
6188 
6189 #ifdef FEAT_EVAL
6190     }
6191     --no_u_sync;
6192 #endif
6193 #ifdef FEAT_CMDL_INFO
6194     clear_showcmd();
6195 #endif
6196 
6197     /* If the inserted register is empty, we need to remove the '"' */
6198     if (need_redraw || stuff_empty())
6199 	edit_unputchar();
6200 }
6201 
6202 /*
6203  * CTRL-G commands in Insert mode.
6204  */
6205     static void
6206 ins_ctrl_g()
6207 {
6208     int		c;
6209 
6210 #ifdef FEAT_INS_EXPAND
6211     /* Right after CTRL-X the cursor will be after the ruler. */
6212     setcursor();
6213 #endif
6214 
6215     /*
6216      * Don't map the second key. This also prevents the mode message to be
6217      * deleted when ESC is hit.
6218      */
6219     ++no_mapping;
6220     c = safe_vgetc();
6221     --no_mapping;
6222     switch (c)
6223     {
6224 	/* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
6225 	case K_UP:
6226 	case Ctrl_K:
6227 	case 'k': ins_up(TRUE);
6228 		  break;
6229 
6230 	/* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
6231 	case K_DOWN:
6232 	case Ctrl_J:
6233 	case 'j': ins_down(TRUE);
6234 		  break;
6235 
6236 	/* CTRL-G u: start new undoable edit */
6237 	case 'u': u_sync();
6238 		  ins_need_undo = TRUE;
6239 		  break;
6240 
6241 	/* Unknown CTRL-G command, reserved for future expansion. */
6242 	default:  vim_beep();
6243     }
6244 }
6245 
6246 /*
6247  * CTRL-^ in Insert mode.
6248  */
6249     static void
6250 ins_ctrl_hat()
6251 {
6252     if (map_to_exists_mode((char_u *)"", LANGMAP))
6253     {
6254 	/* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
6255 	if (State & LANGMAP)
6256 	{
6257 	    curbuf->b_p_iminsert = B_IMODE_NONE;
6258 	    State &= ~LANGMAP;
6259 	}
6260 	else
6261 	{
6262 	    curbuf->b_p_iminsert = B_IMODE_LMAP;
6263 	    State |= LANGMAP;
6264 #ifdef USE_IM_CONTROL
6265 	    im_set_active(FALSE);
6266 #endif
6267 	}
6268     }
6269 #ifdef USE_IM_CONTROL
6270     else
6271     {
6272 	/* There are no ":lmap" mappings, toggle IM */
6273 	if (im_get_status())
6274 	{
6275 	    curbuf->b_p_iminsert = B_IMODE_NONE;
6276 	    im_set_active(FALSE);
6277 	}
6278 	else
6279 	{
6280 	    curbuf->b_p_iminsert = B_IMODE_IM;
6281 	    State &= ~LANGMAP;
6282 	    im_set_active(TRUE);
6283 	}
6284     }
6285 #endif
6286     set_iminsert_global();
6287     showmode();
6288 #ifdef FEAT_GUI
6289     /* may show different cursor shape or color */
6290     if (gui.in_use)
6291 	gui_update_cursor(TRUE, FALSE);
6292 #endif
6293 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
6294     /* Show/unshow value of 'keymap' in status lines. */
6295     status_redraw_curbuf();
6296 #endif
6297 }
6298 
6299 /*
6300  * Handle ESC in insert mode.
6301  * Returns TRUE when leaving insert mode, FALSE when going to repeat the
6302  * insert.
6303  */
6304     static int
6305 ins_esc(count, cmdchar, nomove)
6306     long	*count;
6307     int		cmdchar;
6308     int		nomove;	    /* don't move cursor */
6309 {
6310     int		temp;
6311     static int	disabled_redraw = FALSE;
6312 
6313 #ifdef FEAT_SYN_HL
6314     check_spell_redraw();
6315 #endif
6316 #if defined(FEAT_HANGULIN)
6317 # if defined(ESC_CHG_TO_ENG_MODE)
6318     hangul_input_state_set(0);
6319 # endif
6320     if (composing_hangul)
6321     {
6322 	push_raw_key(composing_hangul_buffer, 2);
6323 	composing_hangul = 0;
6324     }
6325 #endif
6326 #if defined(FEAT_MBYTE) && defined(MACOS_CLASSIC)
6327     previous_script = GetScriptManagerVariable(smKeyScript);
6328     KeyScript(smKeyRoman); /* or smKeySysScript */
6329 #endif
6330 
6331     temp = curwin->w_cursor.col;
6332     if (disabled_redraw)
6333     {
6334 	--RedrawingDisabled;
6335 	disabled_redraw = FALSE;
6336     }
6337     if (!arrow_used)
6338     {
6339 	/*
6340 	 * Don't append the ESC for "r<CR>" and "grx".
6341 	 * When 'insertmode' is set only CTRL-L stops Insert mode.  Needed for
6342 	 * when "count" is non-zero.
6343 	 */
6344 	if (cmdchar != 'r' && cmdchar != 'v')
6345 	    AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
6346 
6347 	/*
6348 	 * Repeating insert may take a long time.  Check for
6349 	 * interrupt now and then.
6350 	 */
6351 	if (*count > 0)
6352 	{
6353 	    line_breakcheck();
6354 	    if (got_int)
6355 		*count = 0;
6356 	}
6357 
6358 	if (--*count > 0)	/* repeat what was typed */
6359 	{
6360 	    /* Vi repeats the insert without replacing characters. */
6361 	    if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
6362 		State &= ~REPLACE_FLAG;
6363 
6364 	    (void)start_redo_ins();
6365 	    if (cmdchar == 'r' || cmdchar == 'v')
6366 		stuffReadbuff(ESC_STR);	/* no ESC in redo buffer */
6367 	    ++RedrawingDisabled;
6368 	    disabled_redraw = TRUE;
6369 	    return FALSE;	/* repeat the insert */
6370 	}
6371 	stop_insert(&curwin->w_cursor, TRUE);
6372 	undisplay_dollar();
6373     }
6374 
6375     /* When an autoindent was removed, curswant stays after the
6376      * indent */
6377     if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
6378 	curwin->w_set_curswant = TRUE;
6379 
6380     /* Remember the last Insert position in the '^ mark. */
6381     if (!cmdmod.keepjumps)
6382 	curbuf->b_last_insert = curwin->w_cursor;
6383 
6384     /*
6385      * The cursor should end up on the last inserted character.
6386      * Don't do it for CTRL-O, unless past the end of the line.
6387      */
6388     if (!nomove
6389 	    && (curwin->w_cursor.col != 0
6390 #ifdef FEAT_VIRTUALEDIT
6391 		|| curwin->w_cursor.coladd > 0
6392 #endif
6393 	       )
6394 	    && (restart_edit == NUL
6395 		   || (gchar_cursor() == NUL
6396 #ifdef FEAT_VISUAL
6397 		       && !VIsual_active
6398 #endif
6399 		      ))
6400 #ifdef FEAT_RIGHTLEFT
6401 	    && !revins_on
6402 #endif
6403 				      )
6404     {
6405 #ifdef FEAT_VIRTUALEDIT
6406 	if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
6407 	{
6408 	    oneleft();
6409 	    if (restart_edit != NUL)
6410 		++curwin->w_cursor.coladd;
6411 	}
6412 	else
6413 #endif
6414 	{
6415 	    --curwin->w_cursor.col;
6416 #ifdef FEAT_MBYTE
6417 	    /* Correct cursor for multi-byte character. */
6418 	    if (has_mbyte)
6419 		mb_adjust_cursor();
6420 #endif
6421 	}
6422     }
6423 
6424 #ifdef USE_IM_CONTROL
6425     /* Disable IM to allow typing English directly for Normal mode commands.
6426      * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
6427      * well). */
6428     if (!(State & LANGMAP))
6429 	im_save_status(&curbuf->b_p_iminsert);
6430     im_set_active(FALSE);
6431 #endif
6432 
6433     State = NORMAL;
6434     /* need to position cursor again (e.g. when on a TAB ) */
6435     changed_cline_bef_curs();
6436 
6437 #ifdef FEAT_MOUSE
6438     setmouse();
6439 #endif
6440 #ifdef CURSOR_SHAPE
6441     ui_cursor_shape();		/* may show different cursor shape */
6442 #endif
6443 
6444     /*
6445      * When recording or for CTRL-O, need to display the new mode.
6446      * Otherwise remove the mode message.
6447      */
6448     if (Recording || restart_edit != NUL)
6449 	showmode();
6450     else if (p_smd)
6451 	MSG("");
6452 
6453     return TRUE;	    /* exit Insert mode */
6454 }
6455 
6456 #ifdef FEAT_RIGHTLEFT
6457 /*
6458  * Toggle language: hkmap and revins_on.
6459  * Move to end of reverse inserted text.
6460  */
6461     static void
6462 ins_ctrl_()
6463 {
6464     if (revins_on && revins_chars && revins_scol >= 0)
6465     {
6466 	while (gchar_cursor() != NUL && revins_chars--)
6467 	    ++curwin->w_cursor.col;
6468     }
6469     p_ri = !p_ri;
6470     revins_on = (State == INSERT && p_ri);
6471     if (revins_on)
6472     {
6473 	revins_scol = curwin->w_cursor.col;
6474 	revins_legal++;
6475 	revins_chars = 0;
6476 	undisplay_dollar();
6477     }
6478     else
6479 	revins_scol = -1;
6480 #ifdef FEAT_FKMAP
6481     if (p_altkeymap)
6482     {
6483 	/*
6484 	 * to be consistent also for redo command, using '.'
6485 	 * set arrow_used to true and stop it - causing to redo
6486 	 * characters entered in one mode (normal/reverse insert).
6487 	 */
6488 	arrow_used = TRUE;
6489 	(void)stop_arrow();
6490 	p_fkmap = curwin->w_p_rl ^ p_ri;
6491 	if (p_fkmap && p_ri)
6492 	    State = INSERT;
6493     }
6494     else
6495 #endif
6496 	p_hkmap = curwin->w_p_rl ^ p_ri;    /* be consistent! */
6497     showmode();
6498 }
6499 #endif
6500 
6501 #ifdef FEAT_VISUAL
6502 /*
6503  * If 'keymodel' contains "startsel", may start selection.
6504  * Returns TRUE when a CTRL-O and other keys stuffed.
6505  */
6506     static int
6507 ins_start_select(c)
6508     int		c;
6509 {
6510     if (km_startsel)
6511 	switch (c)
6512 	{
6513 	    case K_KHOME:
6514 	    case K_KEND:
6515 	    case K_PAGEUP:
6516 	    case K_KPAGEUP:
6517 	    case K_PAGEDOWN:
6518 	    case K_KPAGEDOWN:
6519 # ifdef MACOS
6520 	    case K_LEFT:
6521 	    case K_RIGHT:
6522 	    case K_UP:
6523 	    case K_DOWN:
6524 	    case K_END:
6525 	    case K_HOME:
6526 # endif
6527 		if (!(mod_mask & MOD_MASK_SHIFT))
6528 		    break;
6529 		/* FALLTHROUGH */
6530 	    case K_S_LEFT:
6531 	    case K_S_RIGHT:
6532 	    case K_S_UP:
6533 	    case K_S_DOWN:
6534 	    case K_S_END:
6535 	    case K_S_HOME:
6536 		/* Start selection right away, the cursor can move with
6537 		 * CTRL-O when beyond the end of the line. */
6538 		start_selection();
6539 
6540 		/* Execute the key in (insert) Select mode. */
6541 		stuffcharReadbuff(Ctrl_O);
6542 		if (mod_mask)
6543 		{
6544 		    char_u	    buf[4];
6545 
6546 		    buf[0] = K_SPECIAL;
6547 		    buf[1] = KS_MODIFIER;
6548 		    buf[2] = mod_mask;
6549 		    buf[3] = NUL;
6550 		    stuffReadbuff(buf);
6551 		}
6552 		stuffcharReadbuff(c);
6553 		return TRUE;
6554 	}
6555     return FALSE;
6556 }
6557 #endif
6558 
6559 /*
6560  * <Insert> key in Insert mode: toggle insert/remplace mode.
6561  */
6562     static void
6563 ins_insert(replaceState)
6564     int	    replaceState;
6565 {
6566 #ifdef FEAT_FKMAP
6567     if (p_fkmap && p_ri)
6568     {
6569 	beep_flush();
6570 	EMSG(farsi_text_3);	/* encoded in Farsi */
6571 	return;
6572     }
6573 #endif
6574 
6575 #ifdef FEAT_AUTOCMD
6576     set_vim_var_string(VV_INSERTMODE,
6577 		   (char_u *)((State & REPLACE_FLAG) ? "i" :
6578 			    replaceState == VREPLACE ? "v" : "r"), 1);
6579     apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
6580 #endif
6581     if (State & REPLACE_FLAG)
6582 	State = INSERT | (State & LANGMAP);
6583     else
6584 	State = replaceState | (State & LANGMAP);
6585     AppendCharToRedobuff(K_INS);
6586     showmode();
6587 #ifdef CURSOR_SHAPE
6588     ui_cursor_shape();		/* may show different cursor shape */
6589 #endif
6590 }
6591 
6592 /*
6593  * Pressed CTRL-O in Insert mode.
6594  */
6595     static void
6596 ins_ctrl_o()
6597 {
6598 #ifdef FEAT_VREPLACE
6599     if (State & VREPLACE_FLAG)
6600 	restart_edit = 'V';
6601     else
6602 #endif
6603 	if (State & REPLACE_FLAG)
6604 	restart_edit = 'R';
6605     else
6606 	restart_edit = 'I';
6607 #ifdef FEAT_VIRTUALEDIT
6608     if (virtual_active())
6609 	ins_at_eol = FALSE;	/* cursor always keeps its column */
6610     else
6611 #endif
6612 	ins_at_eol = (gchar_cursor() == NUL);
6613 }
6614 
6615 /*
6616  * If the cursor is on an indent, ^T/^D insert/delete one
6617  * shiftwidth.	Otherwise ^T/^D behave like a "<<" or ">>".
6618  * Always round the indent to 'shiftwith', this is compatible
6619  * with vi.  But vi only supports ^T and ^D after an
6620  * autoindent, we support it everywhere.
6621  */
6622     static void
6623 ins_shift(c, lastc)
6624     int	    c;
6625     int	    lastc;
6626 {
6627     if (stop_arrow() == FAIL)
6628 	return;
6629     AppendCharToRedobuff(c);
6630 
6631     /*
6632      * 0^D and ^^D: remove all indent.
6633      */
6634     if ((lastc == '0' || lastc == '^') && curwin->w_cursor.col)
6635     {
6636 	--curwin->w_cursor.col;
6637 	(void)del_char(FALSE);		/* delete the '^' or '0' */
6638 	/* In Replace mode, restore the characters that '^' or '0' replaced. */
6639 	if (State & REPLACE_FLAG)
6640 	    replace_pop_ins();
6641 	if (lastc == '^')
6642 	    old_indent = get_indent();	/* remember curr. indent */
6643 	change_indent(INDENT_SET, 0, TRUE, 0);
6644     }
6645     else
6646 	change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0);
6647 
6648     if (did_ai && *skipwhite(ml_get_curline()) != NUL)
6649 	did_ai = FALSE;
6650 #ifdef FEAT_SMARTINDENT
6651     did_si = FALSE;
6652     can_si = FALSE;
6653     can_si_back = FALSE;
6654 #endif
6655 #ifdef FEAT_CINDENT
6656     can_cindent = FALSE;	/* no cindenting after ^D or ^T */
6657 #endif
6658 }
6659 
6660     static void
6661 ins_del()
6662 {
6663     int	    temp;
6664 
6665     if (stop_arrow() == FAIL)
6666 	return;
6667     if (gchar_cursor() == NUL)		/* delete newline */
6668     {
6669 	temp = curwin->w_cursor.col;
6670 	if (!can_bs(BS_EOL)		/* only if "eol" included */
6671 		|| u_save((linenr_T)(curwin->w_cursor.lnum - 1),
6672 		    (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
6673 		|| do_join(FALSE) == FAIL)
6674 	    vim_beep();
6675 	else
6676 	    curwin->w_cursor.col = temp;
6677     }
6678     else if (del_char(FALSE) == FAIL)	/* delete char under cursor */
6679 	vim_beep();
6680     did_ai = FALSE;
6681 #ifdef FEAT_SMARTINDENT
6682     did_si = FALSE;
6683     can_si = FALSE;
6684     can_si_back = FALSE;
6685 #endif
6686     AppendCharToRedobuff(K_DEL);
6687 }
6688 
6689 /*
6690  * Handle Backspace, delete-word and delete-line in Insert mode.
6691  * Return TRUE when backspace was actually used.
6692  */
6693     static int
6694 ins_bs(c, mode, inserted_space_p)
6695     int		c;
6696     int		mode;
6697     int		*inserted_space_p;
6698 {
6699     linenr_T	lnum;
6700     int		cc;
6701     int		temp = 0;	    /* init for GCC */
6702     colnr_T	mincol;
6703     int		did_backspace = FALSE;
6704     int		in_indent;
6705     int		oldState;
6706 #ifdef FEAT_MBYTE
6707     int		p1, p2;
6708 #endif
6709 
6710     /*
6711      * can't delete anything in an empty file
6712      * can't backup past first character in buffer
6713      * can't backup past starting point unless 'backspace' > 1
6714      * can backup to a previous line if 'backspace' == 0
6715      */
6716     if (       bufempty()
6717 	    || (
6718 #ifdef FEAT_RIGHTLEFT
6719 		!revins_on &&
6720 #endif
6721 		((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
6722 		    || (!can_bs(BS_START)
6723 			&& (arrow_used
6724 			    || (curwin->w_cursor.lnum == Insstart.lnum
6725 				&& curwin->w_cursor.col <= Insstart.col)))
6726 		    || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
6727 					 && curwin->w_cursor.col <= ai_col)
6728 		    || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
6729     {
6730 	vim_beep();
6731 	return FALSE;
6732     }
6733 
6734     if (stop_arrow() == FAIL)
6735 	return FALSE;
6736     in_indent = inindent(0);
6737 #ifdef FEAT_CINDENT
6738     if (in_indent)
6739 	can_cindent = FALSE;
6740 #endif
6741 #ifdef FEAT_COMMENTS
6742     end_comment_pending = NUL;	/* After BS, don't auto-end comment */
6743 #endif
6744 #ifdef FEAT_RIGHTLEFT
6745     if (revins_on)	    /* put cursor after last inserted char */
6746 	inc_cursor();
6747 #endif
6748 
6749 #ifdef FEAT_VIRTUALEDIT
6750     /* Virtualedit:
6751      *	BACKSPACE_CHAR eats a virtual space
6752      *	BACKSPACE_WORD eats all coladd
6753      *	BACKSPACE_LINE eats all coladd and keeps going
6754      */
6755     if (curwin->w_cursor.coladd > 0)
6756     {
6757 	if (mode == BACKSPACE_CHAR)
6758 	{
6759 	    --curwin->w_cursor.coladd;
6760 	    return TRUE;
6761 	}
6762 	if (mode == BACKSPACE_WORD)
6763 	{
6764 	    curwin->w_cursor.coladd = 0;
6765 	    return TRUE;
6766 	}
6767 	curwin->w_cursor.coladd = 0;
6768     }
6769 #endif
6770 
6771     /*
6772      * delete newline!
6773      */
6774     if (curwin->w_cursor.col == 0)
6775     {
6776 	lnum = Insstart.lnum;
6777 	if (curwin->w_cursor.lnum == Insstart.lnum
6778 #ifdef FEAT_RIGHTLEFT
6779 			|| revins_on
6780 #endif
6781 				    )
6782 	{
6783 	    if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
6784 			       (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
6785 		return FALSE;
6786 	    --Insstart.lnum;
6787 	    Insstart.col = MAXCOL;
6788 	}
6789 	/*
6790 	 * In replace mode:
6791 	 * cc < 0: NL was inserted, delete it
6792 	 * cc >= 0: NL was replaced, put original characters back
6793 	 */
6794 	cc = -1;
6795 	if (State & REPLACE_FLAG)
6796 	    cc = replace_pop();	    /* returns -1 if NL was inserted */
6797 	/*
6798 	 * In replace mode, in the line we started replacing, we only move the
6799 	 * cursor.
6800 	 */
6801 	if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
6802 	{
6803 	    dec_cursor();
6804 	}
6805 	else
6806 	{
6807 #ifdef FEAT_VREPLACE
6808 	    if (!(State & VREPLACE_FLAG)
6809 				   || curwin->w_cursor.lnum > orig_line_count)
6810 #endif
6811 	    {
6812 		temp = gchar_cursor();	/* remember current char */
6813 		--curwin->w_cursor.lnum;
6814 
6815 		/* When "aw" is in 'formatoptions' we must delete the space at
6816 		 * the end of the line, otherwise the line will be broken
6817 		 * again when auto-formatting. */
6818 		if (has_format_option(FO_AUTO)
6819 					   && has_format_option(FO_WHITE_PAR))
6820 		{
6821 		    char_u  *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
6822 									TRUE);
6823 		    int	    len;
6824 
6825 		    len = STRLEN(ptr);
6826 		    if (len > 0 && ptr[len - 1] == ' ')
6827 			ptr[len - 1] = NUL;
6828 		}
6829 
6830 		(void)do_join(FALSE);
6831 		if (temp == NUL && gchar_cursor() != NUL)
6832 		    inc_cursor();
6833 	    }
6834 #ifdef FEAT_VREPLACE
6835 	    else
6836 		dec_cursor();
6837 #endif
6838 
6839 	    /*
6840 	     * In REPLACE mode we have to put back the text that was replaced
6841 	     * by the NL. On the replace stack is first a NUL-terminated
6842 	     * sequence of characters that were deleted and then the
6843 	     * characters that NL replaced.
6844 	     */
6845 	    if (State & REPLACE_FLAG)
6846 	    {
6847 		/*
6848 		 * Do the next ins_char() in NORMAL state, to
6849 		 * prevent ins_char() from replacing characters and
6850 		 * avoiding showmatch().
6851 		 */
6852 		oldState = State;
6853 		State = NORMAL;
6854 		/*
6855 		 * restore characters (blanks) deleted after cursor
6856 		 */
6857 		while (cc > 0)
6858 		{
6859 		    temp = curwin->w_cursor.col;
6860 #ifdef FEAT_MBYTE
6861 		    mb_replace_pop_ins(cc);
6862 #else
6863 		    ins_char(cc);
6864 #endif
6865 		    curwin->w_cursor.col = temp;
6866 		    cc = replace_pop();
6867 		}
6868 		/* restore the characters that NL replaced */
6869 		replace_pop_ins();
6870 		State = oldState;
6871 	    }
6872 	}
6873 	did_ai = FALSE;
6874     }
6875     else
6876     {
6877 	/*
6878 	 * Delete character(s) before the cursor.
6879 	 */
6880 #ifdef FEAT_RIGHTLEFT
6881 	if (revins_on)		/* put cursor on last inserted char */
6882 	    dec_cursor();
6883 #endif
6884 	mincol = 0;
6885 						/* keep indent */
6886 	if (mode == BACKSPACE_LINE && curbuf->b_p_ai
6887 #ifdef FEAT_RIGHTLEFT
6888 		&& !revins_on
6889 #endif
6890 			    )
6891 	{
6892 	    temp = curwin->w_cursor.col;
6893 	    beginline(BL_WHITE);
6894 	    if (curwin->w_cursor.col < (colnr_T)temp)
6895 		mincol = curwin->w_cursor.col;
6896 	    curwin->w_cursor.col = temp;
6897 	}
6898 
6899 	/*
6900 	 * Handle deleting one 'shiftwidth' or 'softtabstop'.
6901 	 */
6902 	if (	   mode == BACKSPACE_CHAR
6903 		&& ((p_sta && in_indent)
6904 		    || (curbuf->b_p_sts
6905 			&& (*(ml_get_cursor() - 1) == TAB
6906 			    || (*(ml_get_cursor() - 1) == ' '
6907 				&& (!*inserted_space_p
6908 				    || arrow_used))))))
6909 	{
6910 	    int		ts;
6911 	    colnr_T	vcol;
6912 	    colnr_T	want_vcol;
6913 	    int		extra = 0;
6914 
6915 	    *inserted_space_p = FALSE;
6916 	    if (p_sta)
6917 		ts = curbuf->b_p_sw;
6918 	    else
6919 		ts = curbuf->b_p_sts;
6920 	    /* Compute the virtual column where we want to be.  Since
6921 	     * 'showbreak' may get in the way, need to get the last column of
6922 	     * the previous character. */
6923 	    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6924 	    dec_cursor();
6925 	    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
6926 	    inc_cursor();
6927 	    want_vcol = (want_vcol / ts) * ts;
6928 
6929 	    /* delete characters until we are at or before want_vcol */
6930 	    while (vcol > want_vcol
6931 		    && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
6932 	    {
6933 		dec_cursor();
6934 		getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6935 		if (State & REPLACE_FLAG)
6936 		{
6937 		    /* Don't delete characters before the insert point when in
6938 		     * Replace mode */
6939 		    if (curwin->w_cursor.lnum != Insstart.lnum
6940 			    || curwin->w_cursor.col >= Insstart.col)
6941 		    {
6942 #if 0	/* what was this for?  It causes problems when sw != ts. */
6943 			if (State == REPLACE && (int)vcol < want_vcol)
6944 			{
6945 			    (void)del_char(FALSE);
6946 			    extra = 2;	/* don't pop too much */
6947 			}
6948 			else
6949 #endif
6950 			    replace_do_bs();
6951 		    }
6952 		}
6953 		else
6954 		    (void)del_char(FALSE);
6955 	    }
6956 
6957 	    /* insert extra spaces until we are at want_vcol */
6958 	    while (vcol < want_vcol)
6959 	    {
6960 		/* Remember the first char we inserted */
6961 		if (curwin->w_cursor.lnum == Insstart.lnum
6962 				   && curwin->w_cursor.col < Insstart.col)
6963 		    Insstart.col = curwin->w_cursor.col;
6964 
6965 #ifdef FEAT_VREPLACE
6966 		if (State & VREPLACE_FLAG)
6967 		    ins_char(' ');
6968 		else
6969 #endif
6970 		{
6971 		    ins_str((char_u *)" ");
6972 		    if ((State & REPLACE_FLAG) && extra <= 1)
6973 		    {
6974 			if (extra)
6975 			    replace_push_off(NUL);
6976 			else
6977 			    replace_push(NUL);
6978 		    }
6979 		    if (extra == 2)
6980 			extra = 1;
6981 		}
6982 		getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6983 	    }
6984 	}
6985 
6986 	/*
6987 	 * Delete upto starting point, start of line or previous word.
6988 	 */
6989 	else do
6990 	{
6991 #ifdef FEAT_RIGHTLEFT
6992 	    if (!revins_on) /* put cursor on char to be deleted */
6993 #endif
6994 		dec_cursor();
6995 
6996 	    /* start of word? */
6997 	    if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
6998 	    {
6999 		mode = BACKSPACE_WORD_NOT_SPACE;
7000 		temp = vim_iswordc(gchar_cursor());
7001 	    }
7002 	    /* end of word? */
7003 	    else if (mode == BACKSPACE_WORD_NOT_SPACE
7004 		    && (vim_isspace(cc = gchar_cursor())
7005 			    || vim_iswordc(cc) != temp))
7006 	    {
7007 #ifdef FEAT_RIGHTLEFT
7008 		if (!revins_on)
7009 #endif
7010 		    inc_cursor();
7011 #ifdef FEAT_RIGHTLEFT
7012 		else if (State & REPLACE_FLAG)
7013 		    dec_cursor();
7014 #endif
7015 		break;
7016 	    }
7017 	    if (State & REPLACE_FLAG)
7018 		replace_do_bs();
7019 	    else
7020 	    {
7021 #ifdef FEAT_MBYTE
7022 		if (enc_utf8 && p_deco)
7023 		    (void)utfc_ptr2char(ml_get_cursor(), &p1, &p2);
7024 #endif
7025 		(void)del_char(FALSE);
7026 #ifdef FEAT_MBYTE
7027 		/*
7028 		 * If p1 or p2 is non-zero, there are combining characters we
7029 		 * need to take account of.  Don't back up before the base
7030 		 * character.
7031 		 */
7032 		if (enc_utf8 && p_deco && (p1 != NUL || p2 != NUL))
7033 		    inc_cursor();
7034 #endif
7035 #ifdef FEAT_RIGHTLEFT
7036 		if (revins_chars)
7037 		{
7038 		    revins_chars--;
7039 		    revins_legal++;
7040 		}
7041 		if (revins_on && gchar_cursor() == NUL)
7042 		    break;
7043 #endif
7044 	    }
7045 	    /* Just a single backspace?: */
7046 	    if (mode == BACKSPACE_CHAR)
7047 		break;
7048 	} while (
7049 #ifdef FEAT_RIGHTLEFT
7050 		revins_on ||
7051 #endif
7052 		(curwin->w_cursor.col > mincol
7053 		 && (curwin->w_cursor.lnum != Insstart.lnum
7054 		     || curwin->w_cursor.col != Insstart.col)));
7055 	did_backspace = TRUE;
7056     }
7057 #ifdef FEAT_SMARTINDENT
7058     did_si = FALSE;
7059     can_si = FALSE;
7060     can_si_back = FALSE;
7061 #endif
7062     if (curwin->w_cursor.col <= 1)
7063 	did_ai = FALSE;
7064     /*
7065      * It's a little strange to put backspaces into the redo
7066      * buffer, but it makes auto-indent a lot easier to deal
7067      * with.
7068      */
7069     AppendCharToRedobuff(c);
7070 
7071     /* If deleted before the insertion point, adjust it */
7072     if (curwin->w_cursor.lnum == Insstart.lnum
7073 				       && curwin->w_cursor.col < Insstart.col)
7074 	Insstart.col = curwin->w_cursor.col;
7075 
7076     /* vi behaviour: the cursor moves backward but the character that
7077      *		     was there remains visible
7078      * Vim behaviour: the cursor moves backward and the character that
7079      *		      was there is erased from the screen.
7080      * We can emulate the vi behaviour by pretending there is a dollar
7081      * displayed even when there isn't.
7082      *  --pkv Sun Jan 19 01:56:40 EST 2003 */
7083     if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
7084 	dollar_vcol = curwin->w_virtcol;
7085 
7086     return did_backspace;
7087 }
7088 
7089 #ifdef FEAT_MOUSE
7090     static void
7091 ins_mouse(c)
7092     int	    c;
7093 {
7094     pos_T	tpos;
7095 
7096 # ifdef FEAT_GUI
7097     /* When GUI is active, also move/paste when 'mouse' is empty */
7098     if (!gui.in_use)
7099 # endif
7100 	if (!mouse_has(MOUSE_INSERT))
7101 	    return;
7102 
7103     undisplay_dollar();
7104     tpos = curwin->w_cursor;
7105     if (do_mouse(NULL, c, BACKWARD, 1L, 0))
7106     {
7107 	start_arrow(&tpos);
7108 # ifdef FEAT_CINDENT
7109 	can_cindent = TRUE;
7110 # endif
7111     }
7112 
7113 #ifdef FEAT_WINDOWS
7114     /* redraw status lines (in case another window became active) */
7115     redraw_statuslines();
7116 #endif
7117 }
7118 
7119     static void
7120 ins_mousescroll(up)
7121     int		up;
7122 {
7123     pos_T	tpos;
7124 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7125     win_T	*old_curwin;
7126 # endif
7127 
7128     tpos = curwin->w_cursor;
7129 
7130 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7131     old_curwin = curwin;
7132 
7133     /* Currently the mouse coordinates are only known in the GUI. */
7134     if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
7135     {
7136 	int row, col;
7137 
7138 	row = mouse_row;
7139 	col = mouse_col;
7140 
7141 	/* find the window at the pointer coordinates */
7142 	curwin = mouse_find_win(&row, &col);
7143 	curbuf = curwin->w_buffer;
7144     }
7145     if (curwin == old_curwin)
7146 # endif
7147 	undisplay_dollar();
7148 
7149     if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
7150 	scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
7151     else
7152 	scroll_redraw(up, 3L);
7153 
7154 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7155     curwin->w_redr_status = TRUE;
7156 
7157     curwin = old_curwin;
7158     curbuf = curwin->w_buffer;
7159 # endif
7160 
7161     if (!equalpos(curwin->w_cursor, tpos))
7162     {
7163 	start_arrow(&tpos);
7164 # ifdef FEAT_CINDENT
7165 	can_cindent = TRUE;
7166 # endif
7167     }
7168 }
7169 #endif
7170 
7171 #ifdef FEAT_GUI
7172     void
7173 ins_scroll()
7174 {
7175     pos_T	tpos;
7176 
7177     undisplay_dollar();
7178     tpos = curwin->w_cursor;
7179     if (gui_do_scroll())
7180     {
7181 	start_arrow(&tpos);
7182 # ifdef FEAT_CINDENT
7183 	can_cindent = TRUE;
7184 # endif
7185     }
7186 }
7187 
7188     void
7189 ins_horscroll()
7190 {
7191     pos_T	tpos;
7192 
7193     undisplay_dollar();
7194     tpos = curwin->w_cursor;
7195     if (gui_do_horiz_scroll())
7196     {
7197 	start_arrow(&tpos);
7198 # ifdef FEAT_CINDENT
7199 	can_cindent = TRUE;
7200 # endif
7201     }
7202 }
7203 #endif
7204 
7205     static void
7206 ins_left()
7207 {
7208     pos_T	tpos;
7209 
7210 #ifdef FEAT_FOLDING
7211     if ((fdo_flags & FDO_HOR) && KeyTyped)
7212 	foldOpenCursor();
7213 #endif
7214     undisplay_dollar();
7215     tpos = curwin->w_cursor;
7216     if (oneleft() == OK)
7217     {
7218 	start_arrow(&tpos);
7219 #ifdef FEAT_RIGHTLEFT
7220 	/* If exit reversed string, position is fixed */
7221 	if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
7222 	    revins_legal++;
7223 	revins_chars++;
7224 #endif
7225     }
7226 
7227     /*
7228      * if 'whichwrap' set for cursor in insert mode may go to
7229      * previous line
7230      */
7231     else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
7232     {
7233 	start_arrow(&tpos);
7234 	--(curwin->w_cursor.lnum);
7235 	coladvance((colnr_T)MAXCOL);
7236 	curwin->w_set_curswant = TRUE;	/* so we stay at the end */
7237     }
7238     else
7239 	vim_beep();
7240 }
7241 
7242     static void
7243 ins_home(c)
7244     int		c;
7245 {
7246     pos_T	tpos;
7247 
7248 #ifdef FEAT_FOLDING
7249     if ((fdo_flags & FDO_HOR) && KeyTyped)
7250 	foldOpenCursor();
7251 #endif
7252     undisplay_dollar();
7253     tpos = curwin->w_cursor;
7254     if (c == K_C_HOME)
7255 	curwin->w_cursor.lnum = 1;
7256     curwin->w_cursor.col = 0;
7257 #ifdef FEAT_VIRTUALEDIT
7258     curwin->w_cursor.coladd = 0;
7259 #endif
7260     curwin->w_curswant = 0;
7261     start_arrow(&tpos);
7262 }
7263 
7264     static void
7265 ins_end(c)
7266     int		c;
7267 {
7268     pos_T	tpos;
7269 
7270 #ifdef FEAT_FOLDING
7271     if ((fdo_flags & FDO_HOR) && KeyTyped)
7272 	foldOpenCursor();
7273 #endif
7274     undisplay_dollar();
7275     tpos = curwin->w_cursor;
7276     if (c == K_C_END)
7277 	curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7278     coladvance((colnr_T)MAXCOL);
7279     curwin->w_curswant = MAXCOL;
7280 
7281     start_arrow(&tpos);
7282 }
7283 
7284     static void
7285 ins_s_left()
7286 {
7287 #ifdef FEAT_FOLDING
7288     if ((fdo_flags & FDO_HOR) && KeyTyped)
7289 	foldOpenCursor();
7290 #endif
7291     undisplay_dollar();
7292     if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
7293     {
7294 	start_arrow(&curwin->w_cursor);
7295 	(void)bck_word(1L, FALSE, FALSE);
7296 	curwin->w_set_curswant = TRUE;
7297     }
7298     else
7299 	vim_beep();
7300 }
7301 
7302     static void
7303 ins_right()
7304 {
7305 #ifdef FEAT_FOLDING
7306     if ((fdo_flags & FDO_HOR) && KeyTyped)
7307 	foldOpenCursor();
7308 #endif
7309     undisplay_dollar();
7310     if (gchar_cursor() != NUL || virtual_active()
7311 	    )
7312     {
7313 	start_arrow(&curwin->w_cursor);
7314 	curwin->w_set_curswant = TRUE;
7315 #ifdef FEAT_VIRTUALEDIT
7316 	if (virtual_active())
7317 	    oneright();
7318 	else
7319 #endif
7320 	{
7321 #ifdef FEAT_MBYTE
7322 	    if (has_mbyte)
7323 		curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
7324 	    else
7325 #endif
7326 		++curwin->w_cursor.col;
7327 	}
7328 
7329 #ifdef FEAT_RIGHTLEFT
7330 	revins_legal++;
7331 	if (revins_chars)
7332 	    revins_chars--;
7333 #endif
7334     }
7335     /* if 'whichwrap' set for cursor in insert mode, may move the
7336      * cursor to the next line */
7337     else if (vim_strchr(p_ww, ']') != NULL
7338 	    && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
7339     {
7340 	start_arrow(&curwin->w_cursor);
7341 	curwin->w_set_curswant = TRUE;
7342 	++curwin->w_cursor.lnum;
7343 	curwin->w_cursor.col = 0;
7344     }
7345     else
7346 	vim_beep();
7347 }
7348 
7349     static void
7350 ins_s_right()
7351 {
7352 #ifdef FEAT_FOLDING
7353     if ((fdo_flags & FDO_HOR) && KeyTyped)
7354 	foldOpenCursor();
7355 #endif
7356     undisplay_dollar();
7357     if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
7358 	    || gchar_cursor() != NUL)
7359     {
7360 	start_arrow(&curwin->w_cursor);
7361 	(void)fwd_word(1L, FALSE, 0);
7362 	curwin->w_set_curswant = TRUE;
7363     }
7364     else
7365 	vim_beep();
7366 }
7367 
7368     static void
7369 ins_up(startcol)
7370     int		startcol;	/* when TRUE move to Insstart.col */
7371 {
7372     pos_T	tpos;
7373     linenr_T	old_topline = curwin->w_topline;
7374 #ifdef FEAT_DIFF
7375     int		old_topfill = curwin->w_topfill;
7376 #endif
7377 
7378     undisplay_dollar();
7379     tpos = curwin->w_cursor;
7380     if (cursor_up(1L, TRUE) == OK)
7381     {
7382 	if (startcol)
7383 	    coladvance(getvcol_nolist(&Insstart));
7384 	if (old_topline != curwin->w_topline
7385 #ifdef FEAT_DIFF
7386 		|| old_topfill != curwin->w_topfill
7387 #endif
7388 		)
7389 	    redraw_later(VALID);
7390 	start_arrow(&tpos);
7391 #ifdef FEAT_CINDENT
7392 	can_cindent = TRUE;
7393 #endif
7394     }
7395     else
7396 	vim_beep();
7397 }
7398 
7399     static void
7400 ins_pageup()
7401 {
7402     pos_T	tpos;
7403 
7404     undisplay_dollar();
7405     tpos = curwin->w_cursor;
7406     if (onepage(BACKWARD, 1L) == OK)
7407     {
7408 	start_arrow(&tpos);
7409 #ifdef FEAT_CINDENT
7410 	can_cindent = TRUE;
7411 #endif
7412     }
7413     else
7414 	vim_beep();
7415 }
7416 
7417     static void
7418 ins_down(startcol)
7419     int		startcol;	/* when TRUE move to Insstart.col */
7420 {
7421     pos_T	tpos;
7422     linenr_T	old_topline = curwin->w_topline;
7423 #ifdef FEAT_DIFF
7424     int		old_topfill = curwin->w_topfill;
7425 #endif
7426 
7427     undisplay_dollar();
7428     tpos = curwin->w_cursor;
7429     if (cursor_down(1L, TRUE) == OK)
7430     {
7431 	if (startcol)
7432 	    coladvance(getvcol_nolist(&Insstart));
7433 	if (old_topline != curwin->w_topline
7434 #ifdef FEAT_DIFF
7435 		|| old_topfill != curwin->w_topfill
7436 #endif
7437 		)
7438 	    redraw_later(VALID);
7439 	start_arrow(&tpos);
7440 #ifdef FEAT_CINDENT
7441 	can_cindent = TRUE;
7442 #endif
7443     }
7444     else
7445 	vim_beep();
7446 }
7447 
7448     static void
7449 ins_pagedown()
7450 {
7451     pos_T	tpos;
7452 
7453     undisplay_dollar();
7454     tpos = curwin->w_cursor;
7455     if (onepage(FORWARD, 1L) == OK)
7456     {
7457 	start_arrow(&tpos);
7458 #ifdef FEAT_CINDENT
7459 	can_cindent = TRUE;
7460 #endif
7461     }
7462     else
7463 	vim_beep();
7464 }
7465 
7466 #ifdef FEAT_DND
7467     static void
7468 ins_drop()
7469 {
7470     do_put('~', BACKWARD, 1L, PUT_CURSEND);
7471 }
7472 #endif
7473 
7474 /*
7475  * Handle TAB in Insert or Replace mode.
7476  * Return TRUE when the TAB needs to be inserted like a normal character.
7477  */
7478     static int
7479 ins_tab()
7480 {
7481     int		ind;
7482     int		i;
7483     int		temp;
7484 
7485     if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
7486 	Insstart_blank_vcol = get_nolist_virtcol();
7487     if (echeck_abbr(TAB + ABBR_OFF))
7488 	return FALSE;
7489 
7490     ind = inindent(0);
7491 #ifdef FEAT_CINDENT
7492     if (ind)
7493 	can_cindent = FALSE;
7494 #endif
7495 
7496     /*
7497      * When nothing special, insert TAB like a normal character
7498      */
7499     if (!curbuf->b_p_et
7500 	    && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
7501 	    && curbuf->b_p_sts == 0)
7502 	return TRUE;
7503 
7504     if (stop_arrow() == FAIL)
7505 	return TRUE;
7506 
7507     did_ai = FALSE;
7508 #ifdef FEAT_SMARTINDENT
7509     did_si = FALSE;
7510     can_si = FALSE;
7511     can_si_back = FALSE;
7512 #endif
7513     AppendToRedobuff((char_u *)"\t");
7514 
7515     if (p_sta && ind)		/* insert tab in indent, use 'shiftwidth' */
7516 	temp = (int)curbuf->b_p_sw;
7517     else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
7518 	temp = (int)curbuf->b_p_sts;
7519     else			/* otherwise use 'tabstop' */
7520 	temp = (int)curbuf->b_p_ts;
7521     temp -= get_nolist_virtcol() % temp;
7522 
7523     /*
7524      * Insert the first space with ins_char().	It will delete one char in
7525      * replace mode.  Insert the rest with ins_str(); it will not delete any
7526      * chars.  For VREPLACE mode, we use ins_char() for all characters.
7527      */
7528     ins_char(' ');
7529     while (--temp > 0)
7530     {
7531 #ifdef FEAT_VREPLACE
7532 	if (State & VREPLACE_FLAG)
7533 	    ins_char(' ');
7534 	else
7535 #endif
7536 	{
7537 	    ins_str((char_u *)" ");
7538 	    if (State & REPLACE_FLAG)	    /* no char replaced */
7539 		replace_push(NUL);
7540 	}
7541     }
7542 
7543     /*
7544      * When 'expandtab' not set: Replace spaces by TABs where possible.
7545      */
7546     if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
7547     {
7548 	char_u		*ptr;
7549 #ifdef FEAT_VREPLACE
7550 	char_u		*saved_line = NULL;	/* init for GCC */
7551 	pos_T		pos;
7552 #endif
7553 	pos_T		fpos;
7554 	pos_T		*cursor;
7555 	colnr_T		want_vcol, vcol;
7556 	int		change_col = -1;
7557 	int		save_list = curwin->w_p_list;
7558 
7559 	/*
7560 	 * Get the current line.  For VREPLACE mode, don't make real changes
7561 	 * yet, just work on a copy of the line.
7562 	 */
7563 #ifdef FEAT_VREPLACE
7564 	if (State & VREPLACE_FLAG)
7565 	{
7566 	    pos = curwin->w_cursor;
7567 	    cursor = &pos;
7568 	    saved_line = vim_strsave(ml_get_curline());
7569 	    if (saved_line == NULL)
7570 		return FALSE;
7571 	    ptr = saved_line + pos.col;
7572 	}
7573 	else
7574 #endif
7575 	{
7576 	    ptr = ml_get_cursor();
7577 	    cursor = &curwin->w_cursor;
7578 	}
7579 
7580 	/* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
7581 	if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
7582 	    curwin->w_p_list = FALSE;
7583 
7584 	/* Find first white before the cursor */
7585 	fpos = curwin->w_cursor;
7586 	while (fpos.col > 0 && vim_iswhite(ptr[-1]))
7587 	{
7588 	    --fpos.col;
7589 	    --ptr;
7590 	}
7591 
7592 	/* In Replace mode, don't change characters before the insert point. */
7593 	if ((State & REPLACE_FLAG)
7594 		&& fpos.lnum == Insstart.lnum
7595 		&& fpos.col < Insstart.col)
7596 	{
7597 	    ptr += Insstart.col - fpos.col;
7598 	    fpos.col = Insstart.col;
7599 	}
7600 
7601 	/* compute virtual column numbers of first white and cursor */
7602 	getvcol(curwin, &fpos, &vcol, NULL, NULL);
7603 	getvcol(curwin, cursor, &want_vcol, NULL, NULL);
7604 
7605 	/* Use as many TABs as possible.  Beware of 'showbreak' and
7606 	 * 'linebreak' adding extra virtual columns. */
7607 	while (vim_iswhite(*ptr))
7608 	{
7609 	    i = lbr_chartabsize((char_u *)"\t", vcol);
7610 	    if (vcol + i > want_vcol)
7611 		break;
7612 	    if (*ptr != TAB)
7613 	    {
7614 		*ptr = TAB;
7615 		if (change_col < 0)
7616 		{
7617 		    change_col = fpos.col;  /* Column of first change */
7618 		    /* May have to adjust Insstart */
7619 		    if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
7620 			Insstart.col = fpos.col;
7621 		}
7622 	    }
7623 	    ++fpos.col;
7624 	    ++ptr;
7625 	    vcol += i;
7626 	}
7627 
7628 	if (change_col >= 0)
7629 	{
7630 	    int repl_off = 0;
7631 
7632 	    /* Skip over the spaces we need. */
7633 	    while (vcol < want_vcol && *ptr == ' ')
7634 	    {
7635 		vcol += lbr_chartabsize(ptr, vcol);
7636 		++ptr;
7637 		++repl_off;
7638 	    }
7639 	    if (vcol > want_vcol)
7640 	    {
7641 		/* Must have a char with 'showbreak' just before it. */
7642 		--ptr;
7643 		--repl_off;
7644 	    }
7645 	    fpos.col += repl_off;
7646 
7647 	    /* Delete following spaces. */
7648 	    i = cursor->col - fpos.col;
7649 	    if (i > 0)
7650 	    {
7651 		mch_memmove(ptr, ptr + i, STRLEN(ptr + i) + 1);
7652 		/* correct replace stack. */
7653 		if ((State & REPLACE_FLAG)
7654 #ifdef FEAT_VREPLACE
7655 			&& !(State & VREPLACE_FLAG)
7656 #endif
7657 			)
7658 		    for (temp = i; --temp >= 0; )
7659 			replace_join(repl_off);
7660 	    }
7661 #ifdef FEAT_NETBEANS_INTG
7662 	    if (usingNetbeans)
7663 	    {
7664 		netbeans_removed(curbuf, fpos.lnum, cursor->col,
7665 							       (long)(i + 1));
7666 		netbeans_inserted(curbuf, fpos.lnum, cursor->col,
7667 							   (char_u *)"\t", 1);
7668 	    }
7669 #endif
7670 	    cursor->col -= i;
7671 
7672 #ifdef FEAT_VREPLACE
7673 	    /*
7674 	     * In VREPLACE mode, we haven't changed anything yet.  Do it now by
7675 	     * backspacing over the changed spacing and then inserting the new
7676 	     * spacing.
7677 	     */
7678 	    if (State & VREPLACE_FLAG)
7679 	    {
7680 		/* Backspace from real cursor to change_col */
7681 		backspace_until_column(change_col);
7682 
7683 		/* Insert each char in saved_line from changed_col to
7684 		 * ptr-cursor */
7685 		ins_bytes_len(saved_line + change_col,
7686 						    cursor->col - change_col);
7687 	    }
7688 #endif
7689 	}
7690 
7691 #ifdef FEAT_VREPLACE
7692 	if (State & VREPLACE_FLAG)
7693 	    vim_free(saved_line);
7694 #endif
7695 	curwin->w_p_list = save_list;
7696     }
7697 
7698     return FALSE;
7699 }
7700 
7701 /*
7702  * Handle CR or NL in insert mode.
7703  * Return TRUE when out of memory or can't undo.
7704  */
7705     static int
7706 ins_eol(c)
7707     int		c;
7708 {
7709     int	    i;
7710 
7711     if (echeck_abbr(c + ABBR_OFF))
7712 	return FALSE;
7713     if (stop_arrow() == FAIL)
7714 	return TRUE;
7715     undisplay_dollar();
7716 
7717     /*
7718      * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
7719      * character under the cursor.  Only push a NUL on the replace stack,
7720      * nothing to put back when the NL is deleted.
7721      */
7722     if ((State & REPLACE_FLAG)
7723 #ifdef FEAT_VREPLACE
7724 	    && !(State & VREPLACE_FLAG)
7725 #endif
7726 	    )
7727 	replace_push(NUL);
7728 
7729     /*
7730      * In VREPLACE mode, a NL replaces the rest of the line, and starts
7731      * replacing the next line, so we push all of the characters left on the
7732      * line onto the replace stack.  This is not done here though, it is done
7733      * in open_line().
7734      */
7735 
7736 #ifdef FEAT_RIGHTLEFT
7737 # ifdef FEAT_FKMAP
7738     if (p_altkeymap && p_fkmap)
7739 	fkmap(NL);
7740 # endif
7741     /* NL in reverse insert will always start in the end of
7742      * current line. */
7743     if (revins_on)
7744 	curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
7745 #endif
7746 
7747     AppendToRedobuff(NL_STR);
7748     i = open_line(FORWARD,
7749 #ifdef FEAT_COMMENTS
7750 	    has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
7751 #endif
7752 	    0, old_indent);
7753     old_indent = 0;
7754 #ifdef FEAT_CINDENT
7755     can_cindent = TRUE;
7756 #endif
7757 
7758     return (!i);
7759 }
7760 
7761 #ifdef FEAT_DIGRAPHS
7762 /*
7763  * Handle digraph in insert mode.
7764  * Returns character still to be inserted, or NUL when nothing remaining to be
7765  * done.
7766  */
7767     static int
7768 ins_digraph()
7769 {
7770     int	    c;
7771     int	    cc;
7772 
7773     pc_status = PC_STATUS_UNSET;
7774     if (redrawing() && !char_avail())
7775     {
7776 	/* may need to redraw when no more chars available now */
7777 	ins_redraw();
7778 
7779 	edit_putchar('?', TRUE);
7780 #ifdef FEAT_CMDL_INFO
7781 	add_to_showcmd_c(Ctrl_K);
7782 #endif
7783     }
7784 
7785 #ifdef USE_ON_FLY_SCROLL
7786     dont_scroll = TRUE;		/* disallow scrolling here */
7787 #endif
7788 
7789     /* don't map the digraph chars. This also prevents the
7790      * mode message to be deleted when ESC is hit */
7791     ++no_mapping;
7792     ++allow_keys;
7793     c = safe_vgetc();
7794     --no_mapping;
7795     --allow_keys;
7796     if (IS_SPECIAL(c) || mod_mask)	    /* special key */
7797     {
7798 #ifdef FEAT_CMDL_INFO
7799 	clear_showcmd();
7800 #endif
7801 	insert_special(c, TRUE, FALSE);
7802 	return NUL;
7803     }
7804     if (c != ESC)
7805     {
7806 	if (redrawing() && !char_avail())
7807 	{
7808 	    /* may need to redraw when no more chars available now */
7809 	    ins_redraw();
7810 
7811 	    if (char2cells(c) == 1)
7812 	    {
7813 		/* first remove the '?', otherwise it's restored when typing
7814 		 * an ESC next */
7815 		edit_unputchar();
7816 		ins_redraw();
7817 		edit_putchar(c, TRUE);
7818 	    }
7819 #ifdef FEAT_CMDL_INFO
7820 	    add_to_showcmd_c(c);
7821 #endif
7822 	}
7823 	++no_mapping;
7824 	++allow_keys;
7825 	cc = safe_vgetc();
7826 	--no_mapping;
7827 	--allow_keys;
7828 	if (cc != ESC)
7829 	{
7830 	    AppendToRedobuff((char_u *)CTRL_V_STR);
7831 	    c = getdigraph(c, cc, TRUE);
7832 #ifdef FEAT_CMDL_INFO
7833 	    clear_showcmd();
7834 #endif
7835 	    return c;
7836 	}
7837     }
7838     edit_unputchar();
7839 #ifdef FEAT_CMDL_INFO
7840     clear_showcmd();
7841 #endif
7842     return NUL;
7843 }
7844 #endif
7845 
7846 /*
7847  * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
7848  * Returns the char to be inserted, or NUL if none found.
7849  */
7850     static int
7851 ins_copychar(lnum)
7852     linenr_T	lnum;
7853 {
7854     int	    c;
7855     int	    temp;
7856     char_u  *ptr, *prev_ptr;
7857 
7858     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
7859     {
7860 	vim_beep();
7861 	return NUL;
7862     }
7863 
7864     /* try to advance to the cursor column */
7865     temp = 0;
7866     ptr = ml_get(lnum);
7867     prev_ptr = ptr;
7868     validate_virtcol();
7869     while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
7870     {
7871 	prev_ptr = ptr;
7872 	temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
7873     }
7874     if ((colnr_T)temp > curwin->w_virtcol)
7875 	ptr = prev_ptr;
7876 
7877 #ifdef FEAT_MBYTE
7878     c = (*mb_ptr2char)(ptr);
7879 #else
7880     c = *ptr;
7881 #endif
7882     if (c == NUL)
7883 	vim_beep();
7884     return c;
7885 }
7886 
7887 /*
7888  * CTRL-Y or CTRL-E typed in Insert mode.
7889  */
7890     static int
7891 ins_ctrl_ey(tc)
7892     int	    tc;
7893 {
7894     int	    c = tc;
7895 
7896 #ifdef FEAT_INS_EXPAND
7897     if (ctrl_x_mode == CTRL_X_SCROLL)
7898     {
7899 	if (c == Ctrl_Y)
7900 	    scrolldown_clamp();
7901 	else
7902 	    scrollup_clamp();
7903 	redraw_later(VALID);
7904     }
7905     else
7906 #endif
7907     {
7908 	c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
7909 	if (c != NUL)
7910 	{
7911 	    long	tw_save;
7912 
7913 	    /* The character must be taken literally, insert like it
7914 	     * was typed after a CTRL-V, and pretend 'textwidth'
7915 	     * wasn't set.  Digits, 'o' and 'x' are special after a
7916 	     * CTRL-V, don't use it for these. */
7917 	    if (c < 256 && !isalnum(c))
7918 		AppendToRedobuff((char_u *)CTRL_V_STR);	/* CTRL-V */
7919 	    tw_save = curbuf->b_p_tw;
7920 	    curbuf->b_p_tw = -1;
7921 	    insert_special(c, TRUE, FALSE);
7922 	    curbuf->b_p_tw = tw_save;
7923 #ifdef FEAT_RIGHTLEFT
7924 	    revins_chars++;
7925 	    revins_legal++;
7926 #endif
7927 	    c = Ctrl_V;	/* pretend CTRL-V is last character */
7928 	    auto_format(FALSE, TRUE);
7929 	}
7930     }
7931     return c;
7932 }
7933 
7934 #ifdef FEAT_SMARTINDENT
7935 /*
7936  * Try to do some very smart auto-indenting.
7937  * Used when inserting a "normal" character.
7938  */
7939     static void
7940 ins_try_si(c)
7941     int	    c;
7942 {
7943     pos_T	*pos, old_pos;
7944     char_u	*ptr;
7945     int		i;
7946     int		temp;
7947 
7948     /*
7949      * do some very smart indenting when entering '{' or '}'
7950      */
7951     if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
7952     {
7953 	/*
7954 	 * for '}' set indent equal to indent of line containing matching '{'
7955 	 */
7956 	if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
7957 	{
7958 	    old_pos = curwin->w_cursor;
7959 	    /*
7960 	     * If the matching '{' has a ')' immediately before it (ignoring
7961 	     * white-space), then line up with the start of the line
7962 	     * containing the matching '(' if there is one.  This handles the
7963 	     * case where an "if (..\n..) {" statement continues over multiple
7964 	     * lines -- webb
7965 	     */
7966 	    ptr = ml_get(pos->lnum);
7967 	    i = pos->col;
7968 	    if (i > 0)		/* skip blanks before '{' */
7969 		while (--i > 0 && vim_iswhite(ptr[i]))
7970 		    ;
7971 	    curwin->w_cursor.lnum = pos->lnum;
7972 	    curwin->w_cursor.col = i;
7973 	    if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
7974 		curwin->w_cursor = *pos;
7975 	    i = get_indent();
7976 	    curwin->w_cursor = old_pos;
7977 #ifdef FEAT_VREPLACE
7978 	    if (State & VREPLACE_FLAG)
7979 		change_indent(INDENT_SET, i, FALSE, NUL);
7980 	    else
7981 #endif
7982 		(void)set_indent(i, SIN_CHANGED);
7983 	}
7984 	else if (curwin->w_cursor.col > 0)
7985 	{
7986 	    /*
7987 	     * when inserting '{' after "O" reduce indent, but not
7988 	     * more than indent of previous line
7989 	     */
7990 	    temp = TRUE;
7991 	    if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
7992 	    {
7993 		old_pos = curwin->w_cursor;
7994 		i = get_indent();
7995 		while (curwin->w_cursor.lnum > 1)
7996 		{
7997 		    ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
7998 
7999 		    /* ignore empty lines and lines starting with '#'. */
8000 		    if (*ptr != '#' && *ptr != NUL)
8001 			break;
8002 		}
8003 		if (get_indent() >= i)
8004 		    temp = FALSE;
8005 		curwin->w_cursor = old_pos;
8006 	    }
8007 	    if (temp)
8008 		shift_line(TRUE, FALSE, 1);
8009 	}
8010     }
8011 
8012     /*
8013      * set indent of '#' always to 0
8014      */
8015     if (curwin->w_cursor.col > 0 && can_si && c == '#')
8016     {
8017 	/* remember current indent for next line */
8018 	old_indent = get_indent();
8019 	(void)set_indent(0, SIN_CHANGED);
8020     }
8021 
8022     /* Adjust ai_col, the char at this position can be deleted. */
8023     if (ai_col > curwin->w_cursor.col)
8024 	ai_col = curwin->w_cursor.col;
8025 }
8026 #endif
8027 
8028 /*
8029  * Get the value that w_virtcol would have when 'list' is off.
8030  * Unless 'cpo' contains the 'L' flag.
8031  */
8032     static colnr_T
8033 get_nolist_virtcol()
8034 {
8035     if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
8036 	return getvcol_nolist(&curwin->w_cursor);
8037     validate_virtcol();
8038     return curwin->w_virtcol;
8039 }
8040