Add fork support
[MacVim.git] / src / edit.c
blobc16dadddefe3230e71f20107d8bdc3f7edd69447
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * edit.c: functions for Insert mode
14 #include "vim.h"
16 #ifdef FEAT_INS_EXPAND
18 * definitions used for CTRL-X submode
20 #define CTRL_X_WANT_IDENT 0x100
22 #define CTRL_X_NOT_DEFINED_YET 1
23 #define CTRL_X_SCROLL 2
24 #define CTRL_X_WHOLE_LINE 3
25 #define CTRL_X_FILES 4
26 #define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
27 #define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
28 #define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
29 #define CTRL_X_FINISHED 8
30 #define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
31 #define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
32 #define CTRL_X_CMDLINE 11
33 #define CTRL_X_FUNCTION 12
34 #define CTRL_X_OMNI 13
35 #define CTRL_X_SPELL 14
36 #define CTRL_X_LOCAL_MSG 15 /* only used in "ctrl_x_msgs" */
38 #define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
40 static char *ctrl_x_msgs[] =
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^Ps^U^V^Y)"),
44 NULL,
45 N_(" Whole line completion (^L^N^P)"),
46 N_(" File name completion (^F^N^P)"),
47 N_(" Tag completion (^]^N^P)"),
48 N_(" Path pattern completion (^N^P)"),
49 N_(" Definition completion (^D^N^P)"),
50 NULL,
51 N_(" Dictionary completion (^K^N^P)"),
52 N_(" Thesaurus completion (^T^N^P)"),
53 N_(" Command-line completion (^V^N^P)"),
54 N_(" User defined completion (^U^N^P)"),
55 N_(" Omni completion (^O^N^P)"),
56 N_(" Spelling suggestion (s^N^P)"),
57 N_(" Keyword Local completion (^N^P)"),
60 static char_u e_hitend[] = N_("Hit end of paragraph");
63 * Structure used to store one match for insert completion.
65 typedef struct compl_S compl_T;
66 struct compl_S
68 compl_T *cp_next;
69 compl_T *cp_prev;
70 char_u *cp_str; /* matched text */
71 char cp_icase; /* TRUE or FALSE: ignore case */
72 char_u *(cp_text[CPT_COUNT]); /* text for the menu */
73 char_u *cp_fname; /* file containing the match, allocated when
74 * cp_flags has FREE_FNAME */
75 int cp_flags; /* ORIGINAL_TEXT, CONT_S_IPOS or FREE_FNAME */
76 int cp_number; /* sequence number */
79 #define ORIGINAL_TEXT (1) /* the original text when the expansion begun */
80 #define FREE_FNAME (2)
83 * All the current matches are stored in a list.
84 * "compl_first_match" points to the start of the list.
85 * "compl_curr_match" points to the currently selected entry.
86 * "compl_shown_match" is different from compl_curr_match during
87 * ins_compl_get_exp().
89 static compl_T *compl_first_match = NULL;
90 static compl_T *compl_curr_match = NULL;
91 static compl_T *compl_shown_match = NULL;
93 /* After using a cursor key <Enter> selects a match in the popup menu,
94 * otherwise it inserts a line break. */
95 static int compl_enter_selects = FALSE;
97 /* When "compl_leader" is not NULL only matches that start with this string
98 * are used. */
99 static char_u *compl_leader = NULL;
101 static int compl_get_longest = FALSE; /* put longest common string
102 in compl_leader */
104 static int compl_used_match; /* Selected one of the matches. When
105 FALSE the match was edited or using
106 the longest common string. */
108 static int compl_was_interrupted = FALSE; /* didn't finish finding
109 completions. */
111 static int compl_restarting = FALSE; /* don't insert match */
113 /* When the first completion is done "compl_started" is set. When it's
114 * FALSE the word to be completed must be located. */
115 static int compl_started = FALSE;
117 static int compl_matches = 0;
118 static char_u *compl_pattern = NULL;
119 static int compl_direction = FORWARD;
120 static int compl_shows_dir = FORWARD;
121 static int compl_pending = 0; /* > 1 for postponed CTRL-N */
122 static pos_T compl_startpos;
123 static colnr_T compl_col = 0; /* column where the text starts
124 * that is being completed */
125 static char_u *compl_orig_text = NULL; /* text as it was before
126 * completion started */
127 static int compl_cont_mode = 0;
128 static expand_T compl_xp;
130 static void ins_ctrl_x __ARGS((void));
131 static int has_compl_option __ARGS((int dict_opt));
132 static int ins_compl_accept_char __ARGS((int c));
133 static int ins_compl_add __ARGS((char_u *str, int len, int icase, char_u *fname, char_u **cptext, int cdir, int flags, int adup));
134 static int ins_compl_equal __ARGS((compl_T *match, char_u *str, int len));
135 static void ins_compl_longest_match __ARGS((compl_T *match));
136 static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int icase));
137 static int ins_compl_make_cyclic __ARGS((void));
138 static void ins_compl_upd_pum __ARGS((void));
139 static void ins_compl_del_pum __ARGS((void));
140 static int pum_wanted __ARGS((void));
141 static int pum_enough_matches __ARGS((void));
142 static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int flags, int thesaurus));
143 static void ins_compl_files __ARGS((int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir));
144 static char_u *find_line_end __ARGS((char_u *ptr));
145 static void ins_compl_free __ARGS((void));
146 static void ins_compl_clear __ARGS((void));
147 static int ins_compl_bs __ARGS((void));
148 static void ins_compl_new_leader __ARGS((void));
149 static void ins_compl_addleader __ARGS((int c));
150 static void ins_compl_restart __ARGS((void));
151 static void ins_compl_set_original_text __ARGS((char_u *str));
152 static void ins_compl_addfrommatch __ARGS((void));
153 static int ins_compl_prep __ARGS((int c));
154 static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag));
155 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
156 static void ins_compl_add_list __ARGS((list_T *list));
157 #endif
158 static int ins_compl_get_exp __ARGS((pos_T *ini));
159 static void ins_compl_delete __ARGS((void));
160 static void ins_compl_insert __ARGS((void));
161 static int ins_compl_next __ARGS((int allow_get_expansion, int count, int insert_match));
162 static int ins_compl_key2dir __ARGS((int c));
163 static int ins_compl_pum_key __ARGS((int c));
164 static int ins_compl_key2count __ARGS((int c));
165 static int ins_compl_use_match __ARGS((int c));
166 static int ins_complete __ARGS((int c));
167 static int quote_meta __ARGS((char_u *dest, char_u *str, int len));
168 #endif /* FEAT_INS_EXPAND */
170 #define BACKSPACE_CHAR 1
171 #define BACKSPACE_WORD 2
172 #define BACKSPACE_WORD_NOT_SPACE 3
173 #define BACKSPACE_LINE 4
175 static void ins_redraw __ARGS((int ready));
176 static void ins_ctrl_v __ARGS((void));
177 static void undisplay_dollar __ARGS((void));
178 static void insert_special __ARGS((int, int, int));
179 static void internal_format __ARGS((int textwidth, int second_indent, int flags, int format_only));
180 static void check_auto_format __ARGS((int));
181 static void redo_literal __ARGS((int c));
182 static void start_arrow __ARGS((pos_T *end_insert_pos));
183 #ifdef FEAT_SPELL
184 static void check_spell_redraw __ARGS((void));
185 static void spell_back_to_badword __ARGS((void));
186 static int spell_bad_len = 0; /* length of located bad word */
187 #endif
188 static void stop_insert __ARGS((pos_T *end_insert_pos, int esc));
189 static int echeck_abbr __ARGS((int));
190 #if 0
191 static void replace_push_off __ARGS((int c));
192 #endif
193 static int replace_pop __ARGS((void));
194 static void replace_join __ARGS((int off));
195 static void replace_pop_ins __ARGS((void));
196 #ifdef FEAT_MBYTE
197 static void mb_replace_pop_ins __ARGS((int cc));
198 #endif
199 static void replace_flush __ARGS((void));
200 static void replace_do_bs __ARGS((void));
201 #ifdef FEAT_CINDENT
202 static int cindent_on __ARGS((void));
203 #endif
204 static void ins_reg __ARGS((void));
205 static void ins_ctrl_g __ARGS((void));
206 static void ins_ctrl_hat __ARGS((void));
207 static int ins_esc __ARGS((long *count, int cmdchar, int nomove));
208 #ifdef FEAT_RIGHTLEFT
209 static void ins_ctrl_ __ARGS((void));
210 #endif
211 #ifdef FEAT_VISUAL
212 static int ins_start_select __ARGS((int c));
213 #endif
214 static void ins_insert __ARGS((int replaceState));
215 static void ins_ctrl_o __ARGS((void));
216 static void ins_shift __ARGS((int c, int lastc));
217 static void ins_del __ARGS((void));
218 static int ins_bs __ARGS((int c, int mode, int *inserted_space_p));
219 #ifdef FEAT_MOUSE
220 static void ins_mouse __ARGS((int c));
221 static void ins_mousescroll __ARGS((int up));
222 #endif
223 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
224 static void ins_tabline __ARGS((int c));
225 #endif
226 static void ins_left __ARGS((void));
227 static void ins_home __ARGS((int c));
228 static void ins_end __ARGS((int c));
229 static void ins_s_left __ARGS((void));
230 static void ins_right __ARGS((void));
231 static void ins_s_right __ARGS((void));
232 static void ins_up __ARGS((int startcol));
233 static void ins_pageup __ARGS((void));
234 static void ins_down __ARGS((int startcol));
235 static void ins_pagedown __ARGS((void));
236 #ifdef FEAT_DND
237 static void ins_drop __ARGS((void));
238 #endif
239 static int ins_tab __ARGS((void));
240 static int ins_eol __ARGS((int c));
241 #ifdef FEAT_DIGRAPHS
242 static int ins_digraph __ARGS((void));
243 #endif
244 static int ins_copychar __ARGS((linenr_T lnum));
245 static int ins_ctrl_ey __ARGS((int tc));
246 #ifdef FEAT_SMARTINDENT
247 static void ins_try_si __ARGS((int c));
248 #endif
249 static colnr_T get_nolist_virtcol __ARGS((void));
251 static colnr_T Insstart_textlen; /* length of line when insert started */
252 static colnr_T Insstart_blank_vcol; /* vcol for first inserted blank */
254 static char_u *last_insert = NULL; /* the text of the previous insert,
255 K_SPECIAL and CSI are escaped */
256 static int last_insert_skip; /* nr of chars in front of previous insert */
257 static int new_insert_skip; /* nr of chars in front of current insert */
258 static int did_restart_edit; /* "restart_edit" when calling edit() */
260 #ifdef FEAT_CINDENT
261 static int can_cindent; /* may do cindenting on this line */
262 #endif
264 static int old_indent = 0; /* for ^^D command in insert mode */
266 #ifdef FEAT_RIGHTLEFT
267 static int revins_on; /* reverse insert mode on */
268 static int revins_chars; /* how much to skip after edit */
269 static int revins_legal; /* was the last char 'legal'? */
270 static int revins_scol; /* start column of revins session */
271 #endif
273 static int ins_need_undo; /* call u_save() before inserting a
274 char. Set when edit() is called.
275 after that arrow_used is used. */
277 static int did_add_space = FALSE; /* auto_format() added an extra space
278 under the cursor */
281 * edit(): Start inserting text.
283 * "cmdchar" can be:
284 * 'i' normal insert command
285 * 'a' normal append command
286 * 'R' replace command
287 * 'r' "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo,
288 * but still only one <CR> is inserted. The <Esc> is not used for redo.
289 * 'g' "gI" command.
290 * 'V' "gR" command for Virtual Replace mode.
291 * 'v' "gr" command for single character Virtual Replace mode.
293 * This function is not called recursively. For CTRL-O commands, it returns
294 * and lets the caller handle the Normal-mode command.
296 * Return TRUE if a CTRL-O command caused the return (insert mode pending).
299 edit(cmdchar, startln, count)
300 int cmdchar;
301 int startln; /* if set, insert at start of line */
302 long count;
304 int c = 0;
305 char_u *ptr;
306 int lastc;
307 colnr_T mincol;
308 static linenr_T o_lnum = 0;
309 int i;
310 int did_backspace = TRUE; /* previous char was backspace */
311 #ifdef FEAT_CINDENT
312 int line_is_white = FALSE; /* line is empty before insert */
313 #endif
314 linenr_T old_topline = 0; /* topline before insertion */
315 #ifdef FEAT_DIFF
316 int old_topfill = -1;
317 #endif
318 int inserted_space = FALSE; /* just inserted a space */
319 int replaceState = REPLACE;
320 int nomove = FALSE; /* don't move cursor on return */
322 /* Remember whether editing was restarted after CTRL-O. */
323 did_restart_edit = restart_edit;
325 /* sleep before redrawing, needed for "CTRL-O :" that results in an
326 * error message */
327 check_for_delay(TRUE);
329 #ifdef HAVE_SANDBOX
330 /* Don't allow inserting in the sandbox. */
331 if (sandbox != 0)
333 EMSG(_(e_sandbox));
334 return FALSE;
336 #endif
337 /* Don't allow changes in the buffer while editing the cmdline. The
338 * caller of getcmdline() may get confused. */
339 if (textlock != 0)
341 EMSG(_(e_secure));
342 return FALSE;
345 #ifdef FEAT_INS_EXPAND
346 /* Don't allow recursive insert mode when busy with completion. */
347 if (compl_started || pum_visible())
349 EMSG(_(e_secure));
350 return FALSE;
352 ins_compl_clear(); /* clear stuff for CTRL-X mode */
353 #endif
355 #ifdef FEAT_AUTOCMD
357 * Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx".
359 if (cmdchar != 'r' && cmdchar != 'v')
361 # ifdef FEAT_EVAL
362 if (cmdchar == 'R')
363 ptr = (char_u *)"r";
364 else if (cmdchar == 'V')
365 ptr = (char_u *)"v";
366 else
367 ptr = (char_u *)"i";
368 set_vim_var_string(VV_INSERTMODE, ptr, 1);
369 # endif
370 apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf);
372 #endif
374 #ifdef FEAT_MOUSE
376 * When doing a paste with the middle mouse button, Insstart is set to
377 * where the paste started.
379 if (where_paste_started.lnum != 0)
380 Insstart = where_paste_started;
381 else
382 #endif
384 Insstart = curwin->w_cursor;
385 if (startln)
386 Insstart.col = 0;
388 Insstart_textlen = linetabsize(ml_get_curline());
389 Insstart_blank_vcol = MAXCOL;
390 if (!did_ai)
391 ai_col = 0;
393 if (cmdchar != NUL && restart_edit == 0)
395 ResetRedobuff();
396 AppendNumberToRedobuff(count);
397 #ifdef FEAT_VREPLACE
398 if (cmdchar == 'V' || cmdchar == 'v')
400 /* "gR" or "gr" command */
401 AppendCharToRedobuff('g');
402 AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R');
404 else
405 #endif
407 AppendCharToRedobuff(cmdchar);
408 if (cmdchar == 'g') /* "gI" command */
409 AppendCharToRedobuff('I');
410 else if (cmdchar == 'r') /* "r<CR>" command */
411 count = 1; /* insert only one <CR> */
415 if (cmdchar == 'R')
417 #ifdef FEAT_FKMAP
418 if (p_fkmap && p_ri)
420 beep_flush();
421 EMSG(farsi_text_3); /* encoded in Farsi */
422 State = INSERT;
424 else
425 #endif
426 State = REPLACE;
428 #ifdef FEAT_VREPLACE
429 else if (cmdchar == 'V' || cmdchar == 'v')
431 State = VREPLACE;
432 replaceState = VREPLACE;
433 orig_line_count = curbuf->b_ml.ml_line_count;
434 vr_lines_changed = 1;
436 #endif
437 else
438 State = INSERT;
440 stop_insert_mode = FALSE;
443 * Need to recompute the cursor position, it might move when the cursor is
444 * on a TAB or special character.
446 curs_columns(TRUE);
449 * Enable langmap or IME, indicated by 'iminsert'.
450 * Note that IME may enabled/disabled without us noticing here, thus the
451 * 'iminsert' value may not reflect what is actually used. It is updated
452 * when hitting <Esc>.
454 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
455 State |= LANGMAP;
456 #ifdef USE_IM_CONTROL
457 im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
458 #endif
460 #ifdef FEAT_MOUSE
461 setmouse();
462 #endif
463 #ifdef FEAT_CMDL_INFO
464 clear_showcmd();
465 #endif
466 #ifdef FEAT_RIGHTLEFT
467 /* there is no reverse replace mode */
468 revins_on = (State == INSERT && p_ri);
469 if (revins_on)
470 undisplay_dollar();
471 revins_chars = 0;
472 revins_legal = 0;
473 revins_scol = -1;
474 #endif
477 * Handle restarting Insert mode.
478 * Don't do this for "CTRL-O ." (repeat an insert): we get here with
479 * restart_edit non-zero, and something in the stuff buffer.
481 if (restart_edit != 0 && stuff_empty())
483 #ifdef FEAT_MOUSE
485 * After a paste we consider text typed to be part of the insert for
486 * the pasted text. You can backspace over the pasted text too.
488 if (where_paste_started.lnum)
489 arrow_used = FALSE;
490 else
491 #endif
492 arrow_used = TRUE;
493 restart_edit = 0;
496 * If the cursor was after the end-of-line before the CTRL-O and it is
497 * now at the end-of-line, put it after the end-of-line (this is not
498 * correct in very rare cases).
499 * Also do this if curswant is greater than the current virtual
500 * column. Eg after "^O$" or "^O80|".
502 validate_virtcol();
503 update_curswant();
504 if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
505 || curwin->w_curswant > curwin->w_virtcol)
506 && *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL)
508 if (ptr[1] == NUL)
509 ++curwin->w_cursor.col;
510 #ifdef FEAT_MBYTE
511 else if (has_mbyte)
513 i = (*mb_ptr2len)(ptr);
514 if (ptr[i] == NUL)
515 curwin->w_cursor.col += i;
517 #endif
519 ins_at_eol = FALSE;
521 else
522 arrow_used = FALSE;
524 /* we are in insert mode now, don't need to start it anymore */
525 need_start_insertmode = FALSE;
527 /* Need to save the line for undo before inserting the first char. */
528 ins_need_undo = TRUE;
530 #ifdef FEAT_MOUSE
531 where_paste_started.lnum = 0;
532 #endif
533 #ifdef FEAT_CINDENT
534 can_cindent = TRUE;
535 #endif
536 #ifdef FEAT_FOLDING
537 /* The cursor line is not in a closed fold, unless 'insertmode' is set or
538 * restarting. */
539 if (!p_im && did_restart_edit == 0)
540 foldOpenCursor();
541 #endif
544 * If 'showmode' is set, show the current (insert/replace/..) mode.
545 * A warning message for changing a readonly file is given here, before
546 * actually changing anything. It's put after the mode, if any.
548 i = 0;
549 if (p_smd && msg_silent == 0)
550 i = showmode();
552 if (!p_im && did_restart_edit == 0)
553 change_warning(i + 1);
555 #ifdef CURSOR_SHAPE
556 ui_cursor_shape(); /* may show different cursor shape */
557 #endif
558 #ifdef FEAT_DIGRAPHS
559 do_digraph(-1); /* clear digraphs */
560 #endif
563 * Get the current length of the redo buffer, those characters have to be
564 * skipped if we want to get to the inserted characters.
566 ptr = get_inserted();
567 if (ptr == NULL)
568 new_insert_skip = 0;
569 else
571 new_insert_skip = (int)STRLEN(ptr);
572 vim_free(ptr);
575 old_indent = 0;
578 * Main loop in Insert mode: repeat until Insert mode is left.
580 for (;;)
582 #ifdef FEAT_RIGHTLEFT
583 if (!revins_legal)
584 revins_scol = -1; /* reset on illegal motions */
585 else
586 revins_legal = 0;
587 #endif
588 if (arrow_used) /* don't repeat insert when arrow key used */
589 count = 0;
591 if (stop_insert_mode)
593 /* ":stopinsert" used or 'insertmode' reset */
594 count = 0;
595 goto doESCkey;
598 /* set curwin->w_curswant for next K_DOWN or K_UP */
599 if (!arrow_used)
600 curwin->w_set_curswant = TRUE;
602 /* If there is no typeahead may check for timestamps (e.g., for when a
603 * menu invoked a shell command). */
604 if (stuff_empty())
606 did_check_timestamps = FALSE;
607 if (need_check_timestamps)
608 check_timestamps(FALSE);
612 * When emsg() was called msg_scroll will have been set.
614 msg_scroll = FALSE;
616 #ifdef FEAT_GUI
617 /* When 'mousefocus' is set a mouse movement may have taken us to
618 * another window. "need_mouse_correct" may then be set because of an
619 * autocommand. */
620 if (need_mouse_correct)
621 gui_mouse_correct();
622 #endif
624 #ifdef FEAT_FOLDING
625 /* Open fold at the cursor line, according to 'foldopen'. */
626 if (fdo_flags & FDO_INSERT)
627 foldOpenCursor();
628 /* Close folds where the cursor isn't, according to 'foldclose' */
629 if (!char_avail())
630 foldCheckClose();
631 #endif
634 * If we inserted a character at the last position of the last line in
635 * the window, scroll the window one line up. This avoids an extra
636 * redraw.
637 * This is detected when the cursor column is smaller after inserting
638 * something.
639 * Don't do this when the topline changed already, it has
640 * already been adjusted (by insertchar() calling open_line())).
642 if (curbuf->b_mod_set
643 && curwin->w_p_wrap
644 && !did_backspace
645 && curwin->w_topline == old_topline
646 #ifdef FEAT_DIFF
647 && curwin->w_topfill == old_topfill
648 #endif
651 mincol = curwin->w_wcol;
652 validate_cursor_col();
654 if ((int)curwin->w_wcol < (int)mincol - curbuf->b_p_ts
655 && curwin->w_wrow == W_WINROW(curwin)
656 + curwin->w_height - 1 - p_so
657 && (curwin->w_cursor.lnum != curwin->w_topline
658 #ifdef FEAT_DIFF
659 || curwin->w_topfill > 0
660 #endif
663 #ifdef FEAT_DIFF
664 if (curwin->w_topfill > 0)
665 --curwin->w_topfill;
666 else
667 #endif
668 #ifdef FEAT_FOLDING
669 if (hasFolding(curwin->w_topline, NULL, &old_topline))
670 set_topline(curwin, old_topline + 1);
671 else
672 #endif
673 set_topline(curwin, curwin->w_topline + 1);
677 /* May need to adjust w_topline to show the cursor. */
678 update_topline();
680 did_backspace = FALSE;
682 validate_cursor(); /* may set must_redraw */
685 * Redraw the display when no characters are waiting.
686 * Also shows mode, ruler and positions cursor.
688 ins_redraw(TRUE);
690 #ifdef FEAT_SCROLLBIND
691 if (curwin->w_p_scb)
692 do_check_scrollbind(TRUE);
693 #endif
695 update_curswant();
696 old_topline = curwin->w_topline;
697 #ifdef FEAT_DIFF
698 old_topfill = curwin->w_topfill;
699 #endif
701 #ifdef USE_ON_FLY_SCROLL
702 dont_scroll = FALSE; /* allow scrolling here */
703 #endif
706 * Get a character for Insert mode.
708 lastc = c; /* remember previous char for CTRL-D */
709 c = safe_vgetc();
711 #ifdef FEAT_AUTOCMD
712 /* Don't want K_CURSORHOLD for the second key, e.g., after CTRL-V. */
713 did_cursorhold = TRUE;
714 #endif
716 #ifdef FEAT_RIGHTLEFT
717 if (p_hkmap && KeyTyped)
718 c = hkmap(c); /* Hebrew mode mapping */
719 #endif
720 #ifdef FEAT_FKMAP
721 if (p_fkmap && KeyTyped)
722 c = fkmap(c); /* Farsi mode mapping */
723 #endif
725 #ifdef FEAT_INS_EXPAND
727 * Special handling of keys while the popup menu is visible or wanted
728 * and the cursor is still in the completed word. Only when there is
729 * a match, skip this when no matches were found.
731 if (compl_started
732 && pum_wanted()
733 && curwin->w_cursor.col >= compl_col
734 && (compl_shown_match == NULL
735 || compl_shown_match != compl_shown_match->cp_next))
737 /* BS: Delete one character from "compl_leader". */
738 if ((c == K_BS || c == Ctrl_H)
739 && curwin->w_cursor.col > compl_col
740 && (c = ins_compl_bs()) == NUL)
741 continue;
743 /* When no match was selected or it was edited. */
744 if (!compl_used_match)
746 /* CTRL-L: Add one character from the current match to
747 * "compl_leader". Except when at the original match and
748 * there is nothing to add, CTRL-L works like CTRL-P then. */
749 if (c == Ctrl_L
750 && (ctrl_x_mode != CTRL_X_WHOLE_LINE
751 || STRLEN(compl_shown_match->cp_str)
752 > curwin->w_cursor.col - compl_col))
754 ins_compl_addfrommatch();
755 continue;
758 /* A non-white character that fits in with the current
759 * completion: Add to "compl_leader". */
760 if (ins_compl_accept_char(c))
762 ins_compl_addleader(c);
763 continue;
766 /* Pressing CTRL-Y selects the current match. When
767 * compl_enter_selects is set the Enter key does the same. */
768 if (c == Ctrl_Y || (compl_enter_selects
769 && (c == CAR || c == K_KENTER || c == NL)))
771 ins_compl_delete();
772 ins_compl_insert();
777 /* Prepare for or stop CTRL-X mode. This doesn't do completion, but
778 * it does fix up the text when finishing completion. */
779 compl_get_longest = FALSE;
780 if (c != K_IGNORE && ins_compl_prep(c))
781 continue;
782 #endif
784 /* CTRL-\ CTRL-N goes to Normal mode,
785 * CTRL-\ CTRL-G goes to mode selected with 'insertmode',
786 * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor. */
787 if (c == Ctrl_BSL)
789 /* may need to redraw when no more chars available now */
790 ins_redraw(FALSE);
791 ++no_mapping;
792 ++allow_keys;
793 c = plain_vgetc();
794 --no_mapping;
795 --allow_keys;
796 if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O)
798 /* it's something else */
799 vungetc(c);
800 c = Ctrl_BSL;
802 else if (c == Ctrl_G && p_im)
803 continue;
804 else
806 if (c == Ctrl_O)
808 ins_ctrl_o();
809 ins_at_eol = FALSE; /* cursor keeps its column */
810 nomove = TRUE;
812 count = 0;
813 goto doESCkey;
817 #ifdef FEAT_DIGRAPHS
818 c = do_digraph(c);
819 #endif
821 #ifdef FEAT_INS_EXPAND
822 if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
823 goto docomplete;
824 #endif
825 if (c == Ctrl_V || c == Ctrl_Q)
827 ins_ctrl_v();
828 c = Ctrl_V; /* pretend CTRL-V is last typed character */
829 continue;
832 #ifdef FEAT_CINDENT
833 if (cindent_on()
834 # ifdef FEAT_INS_EXPAND
835 && ctrl_x_mode == 0
836 # endif
839 /* A key name preceded by a bang means this key is not to be
840 * inserted. Skip ahead to the re-indenting below.
841 * A key name preceded by a star means that indenting has to be
842 * done before inserting the key. */
843 line_is_white = inindent(0);
844 if (in_cinkeys(c, '!', line_is_white))
845 goto force_cindent;
846 if (can_cindent && in_cinkeys(c, '*', line_is_white)
847 && stop_arrow() == OK)
848 do_c_expr_indent();
850 #endif
852 #ifdef FEAT_RIGHTLEFT
853 if (curwin->w_p_rl)
854 switch (c)
856 case K_LEFT: c = K_RIGHT; break;
857 case K_S_LEFT: c = K_S_RIGHT; break;
858 case K_C_LEFT: c = K_C_RIGHT; break;
859 case K_RIGHT: c = K_LEFT; break;
860 case K_S_RIGHT: c = K_S_LEFT; break;
861 case K_C_RIGHT: c = K_C_LEFT; break;
863 #endif
865 #ifdef FEAT_VISUAL
867 * If 'keymodel' contains "startsel", may start selection. If it
868 * does, a CTRL-O and c will be stuffed, we need to get these
869 * characters.
871 if (ins_start_select(c))
872 continue;
873 #endif
876 * The big switch to handle a character in insert mode.
878 switch (c)
880 case ESC: /* End input mode */
881 if (echeck_abbr(ESC + ABBR_OFF))
882 break;
883 /*FALLTHROUGH*/
885 case Ctrl_C: /* End input mode */
886 #ifdef FEAT_CMDWIN
887 if (c == Ctrl_C && cmdwin_type != 0)
889 /* Close the cmdline window. */
890 cmdwin_result = K_IGNORE;
891 got_int = FALSE; /* don't stop executing autocommands et al. */
892 nomove = TRUE;
893 goto doESCkey;
895 #endif
897 #ifdef UNIX
898 do_intr:
899 #endif
900 /* when 'insertmode' set, and not halfway a mapping, don't leave
901 * Insert mode */
902 if (goto_im())
904 if (got_int)
906 (void)vgetc(); /* flush all buffers */
907 got_int = FALSE;
909 else
910 vim_beep();
911 break;
913 doESCkey:
915 * This is the ONLY return from edit()!
917 /* Always update o_lnum, so that a "CTRL-O ." that adds a line
918 * still puts the cursor back after the inserted text. */
919 if (ins_at_eol && gchar_cursor() == NUL)
920 o_lnum = curwin->w_cursor.lnum;
922 if (ins_esc(&count, cmdchar, nomove))
924 #ifdef FEAT_AUTOCMD
925 if (cmdchar != 'r' && cmdchar != 'v')
926 apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
927 FALSE, curbuf);
928 did_cursorhold = FALSE;
929 #endif
930 return (c == Ctrl_O);
932 continue;
934 case Ctrl_Z: /* suspend when 'insertmode' set */
935 if (!p_im)
936 goto normalchar; /* insert CTRL-Z as normal char */
937 stuffReadbuff((char_u *)":st\r");
938 c = Ctrl_O;
939 /*FALLTHROUGH*/
941 case Ctrl_O: /* execute one command */
942 #ifdef FEAT_COMPL_FUNC
943 if (ctrl_x_mode == CTRL_X_OMNI)
944 goto docomplete;
945 #endif
946 if (echeck_abbr(Ctrl_O + ABBR_OFF))
947 break;
948 ins_ctrl_o();
950 #ifdef FEAT_VIRTUALEDIT
951 /* don't move the cursor left when 'virtualedit' has "onemore". */
952 if (ve_flags & VE_ONEMORE)
954 ins_at_eol = FALSE;
955 nomove = TRUE;
957 #endif
958 count = 0;
959 goto doESCkey;
961 case K_INS: /* toggle insert/replace mode */
962 case K_KINS:
963 ins_insert(replaceState);
964 break;
966 case K_SELECT: /* end of Select mode mapping - ignore */
967 break;
969 #ifdef FEAT_SNIFF
970 case K_SNIFF: /* Sniff command received */
971 stuffcharReadbuff(K_SNIFF);
972 goto doESCkey;
973 #endif
975 case K_HELP: /* Help key works like <ESC> <Help> */
976 case K_F1:
977 case K_XF1:
978 stuffcharReadbuff(K_HELP);
979 if (p_im)
980 need_start_insertmode = TRUE;
981 goto doESCkey;
983 #ifdef FEAT_NETBEANS_INTG
984 case K_F21: /* NetBeans command */
985 ++no_mapping; /* don't map the next key hits */
986 i = plain_vgetc();
987 --no_mapping;
988 netbeans_keycommand(i);
989 break;
990 #endif
992 case K_ZERO: /* Insert the previously inserted text. */
993 case NUL:
994 case Ctrl_A:
995 /* For ^@ the trailing ESC will end the insert, unless there is an
996 * error. */
997 if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
998 && c != Ctrl_A && !p_im)
999 goto doESCkey; /* quit insert mode */
1000 inserted_space = FALSE;
1001 break;
1003 case Ctrl_R: /* insert the contents of a register */
1004 ins_reg();
1005 auto_format(FALSE, TRUE);
1006 inserted_space = FALSE;
1007 break;
1009 case Ctrl_G: /* commands starting with CTRL-G */
1010 ins_ctrl_g();
1011 break;
1013 case Ctrl_HAT: /* switch input mode and/or langmap */
1014 ins_ctrl_hat();
1015 break;
1017 #ifdef FEAT_RIGHTLEFT
1018 case Ctrl__: /* switch between languages */
1019 if (!p_ari)
1020 goto normalchar;
1021 ins_ctrl_();
1022 break;
1023 #endif
1025 case Ctrl_D: /* Make indent one shiftwidth smaller. */
1026 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1027 if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
1028 goto docomplete;
1029 #endif
1030 /* FALLTHROUGH */
1032 case Ctrl_T: /* Make indent one shiftwidth greater. */
1033 # ifdef FEAT_INS_EXPAND
1034 if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
1036 if (has_compl_option(FALSE))
1037 goto docomplete;
1038 break;
1040 # endif
1041 ins_shift(c, lastc);
1042 auto_format(FALSE, TRUE);
1043 inserted_space = FALSE;
1044 break;
1046 case K_DEL: /* delete character under the cursor */
1047 case K_KDEL:
1048 ins_del();
1049 auto_format(FALSE, TRUE);
1050 break;
1052 case K_BS: /* delete character before the cursor */
1053 case Ctrl_H:
1054 did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1055 auto_format(FALSE, TRUE);
1056 break;
1058 case Ctrl_W: /* delete word before the cursor */
1059 did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1060 auto_format(FALSE, TRUE);
1061 break;
1063 case Ctrl_U: /* delete all inserted text in current line */
1064 # ifdef FEAT_COMPL_FUNC
1065 /* CTRL-X CTRL-U completes with 'completefunc'. */
1066 if (ctrl_x_mode == CTRL_X_FUNCTION)
1067 goto docomplete;
1068 # endif
1069 did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1070 auto_format(FALSE, TRUE);
1071 inserted_space = FALSE;
1072 break;
1074 #ifdef FEAT_MOUSE
1075 case K_LEFTMOUSE: /* mouse keys */
1076 case K_LEFTMOUSE_NM:
1077 case K_LEFTDRAG:
1078 case K_LEFTRELEASE:
1079 case K_LEFTRELEASE_NM:
1080 case K_MIDDLEMOUSE:
1081 case K_MIDDLEDRAG:
1082 case K_MIDDLERELEASE:
1083 case K_RIGHTMOUSE:
1084 case K_RIGHTDRAG:
1085 case K_RIGHTRELEASE:
1086 case K_X1MOUSE:
1087 case K_X1DRAG:
1088 case K_X1RELEASE:
1089 case K_X2MOUSE:
1090 case K_X2DRAG:
1091 case K_X2RELEASE:
1092 ins_mouse(c);
1093 break;
1095 case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */
1096 ins_mousescroll(FALSE);
1097 break;
1099 case K_MOUSEUP: /* Default action for scroll wheel down: scroll down */
1100 ins_mousescroll(TRUE);
1101 break;
1102 #endif
1103 #ifdef FEAT_GUI_TABLINE
1104 case K_TABLINE:
1105 case K_TABMENU:
1106 ins_tabline(c);
1107 break;
1108 #endif
1110 case K_IGNORE: /* Something mapped to nothing */
1111 break;
1113 #ifdef FEAT_AUTOCMD
1114 case K_CURSORHOLD: /* Didn't type something for a while. */
1115 apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf);
1116 did_cursorhold = TRUE;
1117 break;
1118 #endif
1120 #ifdef FEAT_GUI_W32
1121 /* On Win32 ignore <M-F4>, we get it when closing the window was
1122 * cancelled. */
1123 case K_F4:
1124 if (mod_mask != MOD_MASK_ALT)
1125 goto normalchar;
1126 break;
1127 #endif
1129 #ifdef FEAT_GUI
1130 case K_VER_SCROLLBAR:
1131 ins_scroll();
1132 break;
1134 case K_HOR_SCROLLBAR:
1135 ins_horscroll();
1136 break;
1137 #endif
1139 case K_HOME: /* <Home> */
1140 case K_KHOME:
1141 case K_S_HOME:
1142 case K_C_HOME:
1143 ins_home(c);
1144 break;
1146 case K_END: /* <End> */
1147 case K_KEND:
1148 case K_S_END:
1149 case K_C_END:
1150 ins_end(c);
1151 break;
1153 case K_LEFT: /* <Left> */
1154 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1155 ins_s_left();
1156 else
1157 ins_left();
1158 break;
1160 case K_S_LEFT: /* <S-Left> */
1161 case K_C_LEFT:
1162 ins_s_left();
1163 break;
1165 case K_RIGHT: /* <Right> */
1166 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1167 ins_s_right();
1168 else
1169 ins_right();
1170 break;
1172 case K_S_RIGHT: /* <S-Right> */
1173 case K_C_RIGHT:
1174 ins_s_right();
1175 break;
1177 case K_UP: /* <Up> */
1178 #ifdef FEAT_INS_EXPAND
1179 if (pum_visible())
1180 goto docomplete;
1181 #endif
1182 if (mod_mask & MOD_MASK_SHIFT)
1183 ins_pageup();
1184 else
1185 ins_up(FALSE);
1186 break;
1188 case K_S_UP: /* <S-Up> */
1189 case K_PAGEUP:
1190 case K_KPAGEUP:
1191 #ifdef FEAT_INS_EXPAND
1192 if (pum_visible())
1193 goto docomplete;
1194 #endif
1195 ins_pageup();
1196 break;
1198 case K_DOWN: /* <Down> */
1199 #ifdef FEAT_INS_EXPAND
1200 if (pum_visible())
1201 goto docomplete;
1202 #endif
1203 if (mod_mask & MOD_MASK_SHIFT)
1204 ins_pagedown();
1205 else
1206 ins_down(FALSE);
1207 break;
1209 case K_S_DOWN: /* <S-Down> */
1210 case K_PAGEDOWN:
1211 case K_KPAGEDOWN:
1212 #ifdef FEAT_INS_EXPAND
1213 if (pum_visible())
1214 goto docomplete;
1215 #endif
1216 ins_pagedown();
1217 break;
1219 #ifdef FEAT_DND
1220 case K_DROP: /* drag-n-drop event */
1221 ins_drop();
1222 break;
1223 #endif
1225 case K_S_TAB: /* When not mapped, use like a normal TAB */
1226 c = TAB;
1227 /* FALLTHROUGH */
1229 case TAB: /* TAB or Complete patterns along path */
1230 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1231 if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1232 goto docomplete;
1233 #endif
1234 inserted_space = FALSE;
1235 if (ins_tab())
1236 goto normalchar; /* insert TAB as a normal char */
1237 auto_format(FALSE, TRUE);
1238 break;
1240 case K_KENTER: /* <Enter> */
1241 c = CAR;
1242 /* FALLTHROUGH */
1243 case CAR:
1244 case NL:
1245 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1246 /* In a quickfix window a <CR> jumps to the error under the
1247 * cursor. */
1248 if (bt_quickfix(curbuf) && c == CAR)
1250 if (curwin->w_llist_ref == NULL) /* quickfix window */
1251 do_cmdline_cmd((char_u *)".cc");
1252 else /* location list window */
1253 do_cmdline_cmd((char_u *)".ll");
1254 break;
1256 #endif
1257 #ifdef FEAT_CMDWIN
1258 if (cmdwin_type != 0)
1260 /* Execute the command in the cmdline window. */
1261 cmdwin_result = CAR;
1262 goto doESCkey;
1264 #endif
1265 if (ins_eol(c) && !p_im)
1266 goto doESCkey; /* out of memory */
1267 auto_format(FALSE, FALSE);
1268 inserted_space = FALSE;
1269 break;
1271 #if defined(FEAT_DIGRAPHS) || defined (FEAT_INS_EXPAND)
1272 case Ctrl_K: /* digraph or keyword completion */
1273 # ifdef FEAT_INS_EXPAND
1274 if (ctrl_x_mode == CTRL_X_DICTIONARY)
1276 if (has_compl_option(TRUE))
1277 goto docomplete;
1278 break;
1280 # endif
1281 # ifdef FEAT_DIGRAPHS
1282 c = ins_digraph();
1283 if (c == NUL)
1284 break;
1285 # endif
1286 goto normalchar;
1287 #endif
1289 #ifdef FEAT_INS_EXPAND
1290 case Ctrl_X: /* Enter CTRL-X mode */
1291 ins_ctrl_x();
1292 break;
1294 case Ctrl_RSB: /* Tag name completion after ^X */
1295 if (ctrl_x_mode != CTRL_X_TAGS)
1296 goto normalchar;
1297 goto docomplete;
1299 case Ctrl_F: /* File name completion after ^X */
1300 if (ctrl_x_mode != CTRL_X_FILES)
1301 goto normalchar;
1302 goto docomplete;
1304 case 's': /* Spelling completion after ^X */
1305 case Ctrl_S:
1306 if (ctrl_x_mode != CTRL_X_SPELL)
1307 goto normalchar;
1308 goto docomplete;
1309 #endif
1311 case Ctrl_L: /* Whole line completion after ^X */
1312 #ifdef FEAT_INS_EXPAND
1313 if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1314 #endif
1316 /* CTRL-L with 'insertmode' set: Leave Insert mode */
1317 if (p_im)
1319 if (echeck_abbr(Ctrl_L + ABBR_OFF))
1320 break;
1321 goto doESCkey;
1323 goto normalchar;
1325 #ifdef FEAT_INS_EXPAND
1326 /* FALLTHROUGH */
1328 case Ctrl_P: /* Do previous/next pattern completion */
1329 case Ctrl_N:
1330 /* if 'complete' is empty then plain ^P is no longer special,
1331 * but it is under other ^X modes */
1332 if (*curbuf->b_p_cpt == NUL
1333 && ctrl_x_mode != 0
1334 && !(compl_cont_status & CONT_LOCAL))
1335 goto normalchar;
1337 docomplete:
1338 if (ins_complete(c) == FAIL)
1339 compl_cont_status = 0;
1340 break;
1341 #endif /* FEAT_INS_EXPAND */
1343 case Ctrl_Y: /* copy from previous line or scroll down */
1344 case Ctrl_E: /* copy from next line or scroll up */
1345 c = ins_ctrl_ey(c);
1346 break;
1348 default:
1349 #ifdef UNIX
1350 if (c == intr_char) /* special interrupt char */
1351 goto do_intr;
1352 #endif
1355 * Insert a nomal character.
1357 normalchar:
1358 #ifdef FEAT_SMARTINDENT
1359 /* Try to perform smart-indenting. */
1360 ins_try_si(c);
1361 #endif
1363 if (c == ' ')
1365 inserted_space = TRUE;
1366 #ifdef FEAT_CINDENT
1367 if (inindent(0))
1368 can_cindent = FALSE;
1369 #endif
1370 if (Insstart_blank_vcol == MAXCOL
1371 && curwin->w_cursor.lnum == Insstart.lnum)
1372 Insstart_blank_vcol = get_nolist_virtcol();
1375 if (vim_iswordc(c) || !echeck_abbr(
1376 #ifdef FEAT_MBYTE
1377 /* Add ABBR_OFF for characters above 0x100, this is
1378 * what check_abbr() expects. */
1379 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1380 #endif
1383 insert_special(c, FALSE, FALSE);
1384 #ifdef FEAT_RIGHTLEFT
1385 revins_legal++;
1386 revins_chars++;
1387 #endif
1390 auto_format(FALSE, TRUE);
1392 #ifdef FEAT_FOLDING
1393 /* When inserting a character the cursor line must never be in a
1394 * closed fold. */
1395 foldOpenCursor();
1396 #endif
1397 break;
1398 } /* end of switch (c) */
1400 #ifdef FEAT_AUTOCMD
1401 /* If typed something may trigger CursorHoldI again. */
1402 if (c != K_CURSORHOLD)
1403 did_cursorhold = FALSE;
1404 #endif
1406 /* If the cursor was moved we didn't just insert a space */
1407 if (arrow_used)
1408 inserted_space = FALSE;
1410 #ifdef FEAT_CINDENT
1411 if (can_cindent && cindent_on()
1412 # ifdef FEAT_INS_EXPAND
1413 && ctrl_x_mode == 0
1414 # endif
1417 force_cindent:
1419 * Indent now if a key was typed that is in 'cinkeys'.
1421 if (in_cinkeys(c, ' ', line_is_white))
1423 if (stop_arrow() == OK)
1424 /* re-indent the current line */
1425 do_c_expr_indent();
1428 #endif /* FEAT_CINDENT */
1430 } /* for (;;) */
1431 /* NOTREACHED */
1435 * Redraw for Insert mode.
1436 * This is postponed until getting the next character to make '$' in the 'cpo'
1437 * option work correctly.
1438 * Only redraw when there are no characters available. This speeds up
1439 * inserting sequences of characters (e.g., for CTRL-R).
1441 /*ARGSUSED*/
1442 static void
1443 ins_redraw(ready)
1444 int ready; /* not busy with something */
1446 if (!char_avail())
1448 #ifdef FEAT_AUTOCMD
1449 /* Trigger CursorMoved if the cursor moved. Not when the popup menu is
1450 * visible, the command might delete it. */
1451 if (ready && has_cursormovedI()
1452 && !equalpos(last_cursormoved, curwin->w_cursor)
1453 # ifdef FEAT_INS_EXPAND
1454 && !pum_visible()
1455 # endif
1458 apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf);
1459 last_cursormoved = curwin->w_cursor;
1461 #endif
1462 if (must_redraw)
1463 update_screen(0);
1464 else if (clear_cmdline || redraw_cmdline)
1465 showmode(); /* clear cmdline and show mode */
1466 showruler(FALSE);
1467 setcursor();
1468 emsg_on_display = FALSE; /* may remove error message now */
1473 * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1475 static void
1476 ins_ctrl_v()
1478 int c;
1480 /* may need to redraw when no more chars available now */
1481 ins_redraw(FALSE);
1483 if (redrawing() && !char_avail())
1484 edit_putchar('^', TRUE);
1485 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1487 #ifdef FEAT_CMDL_INFO
1488 add_to_showcmd_c(Ctrl_V);
1489 #endif
1491 c = get_literal();
1492 #ifdef FEAT_CMDL_INFO
1493 clear_showcmd();
1494 #endif
1495 insert_special(c, FALSE, TRUE);
1496 #ifdef FEAT_RIGHTLEFT
1497 revins_chars++;
1498 revins_legal++;
1499 #endif
1503 * Put a character directly onto the screen. It's not stored in a buffer.
1504 * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1506 static int pc_status;
1507 #define PC_STATUS_UNSET 0 /* pc_bytes was not set */
1508 #define PC_STATUS_RIGHT 1 /* right halve of double-wide char */
1509 #define PC_STATUS_LEFT 2 /* left halve of double-wide char */
1510 #define PC_STATUS_SET 3 /* pc_bytes was filled */
1511 #ifdef FEAT_MBYTE
1512 static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1513 #else
1514 static char_u pc_bytes[2]; /* saved bytes */
1515 #endif
1516 static int pc_attr;
1517 static int pc_row;
1518 static int pc_col;
1520 void
1521 edit_putchar(c, highlight)
1522 int c;
1523 int highlight;
1525 int attr;
1527 if (ScreenLines != NULL)
1529 update_topline(); /* just in case w_topline isn't valid */
1530 validate_cursor();
1531 if (highlight)
1532 attr = hl_attr(HLF_8);
1533 else
1534 attr = 0;
1535 pc_row = W_WINROW(curwin) + curwin->w_wrow;
1536 pc_col = W_WINCOL(curwin);
1537 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1538 pc_status = PC_STATUS_UNSET;
1539 #endif
1540 #ifdef FEAT_RIGHTLEFT
1541 if (curwin->w_p_rl)
1543 pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1544 # ifdef FEAT_MBYTE
1545 if (has_mbyte)
1547 int fix_col = mb_fix_col(pc_col, pc_row);
1549 if (fix_col != pc_col)
1551 screen_putchar(' ', pc_row, fix_col, attr);
1552 --curwin->w_wcol;
1553 pc_status = PC_STATUS_RIGHT;
1556 # endif
1558 else
1559 #endif
1561 pc_col += curwin->w_wcol;
1562 #ifdef FEAT_MBYTE
1563 if (mb_lefthalve(pc_row, pc_col))
1564 pc_status = PC_STATUS_LEFT;
1565 #endif
1568 /* save the character to be able to put it back */
1569 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1570 if (pc_status == PC_STATUS_UNSET)
1571 #endif
1573 screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1574 pc_status = PC_STATUS_SET;
1576 screen_putchar(c, pc_row, pc_col, attr);
1581 * Undo the previous edit_putchar().
1583 void
1584 edit_unputchar()
1586 if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1588 #if defined(FEAT_MBYTE)
1589 if (pc_status == PC_STATUS_RIGHT)
1590 ++curwin->w_wcol;
1591 if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1592 redrawWinline(curwin->w_cursor.lnum, FALSE);
1593 else
1594 #endif
1595 screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1600 * Called when p_dollar is set: display a '$' at the end of the changed text
1601 * Only works when cursor is in the line that changes.
1603 void
1604 display_dollar(col)
1605 colnr_T col;
1607 colnr_T save_col;
1609 if (!redrawing())
1610 return;
1612 cursor_off();
1613 save_col = curwin->w_cursor.col;
1614 curwin->w_cursor.col = col;
1615 #ifdef FEAT_MBYTE
1616 if (has_mbyte)
1618 char_u *p;
1620 /* If on the last byte of a multi-byte move to the first byte. */
1621 p = ml_get_curline();
1622 curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1624 #endif
1625 curs_columns(FALSE); /* recompute w_wrow and w_wcol */
1626 if (curwin->w_wcol < W_WIDTH(curwin))
1628 edit_putchar('$', FALSE);
1629 dollar_vcol = curwin->w_virtcol;
1631 curwin->w_cursor.col = save_col;
1635 * Call this function before moving the cursor from the normal insert position
1636 * in insert mode.
1638 static void
1639 undisplay_dollar()
1641 if (dollar_vcol)
1643 dollar_vcol = 0;
1644 redrawWinline(curwin->w_cursor.lnum, FALSE);
1649 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1650 * Keep the cursor on the same character.
1651 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1652 * type == INDENT_DEC decrease indent (for CTRL-D)
1653 * type == INDENT_SET set indent to "amount"
1654 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1656 void
1657 change_indent(type, amount, round, replaced)
1658 int type;
1659 int amount;
1660 int round;
1661 int replaced; /* replaced character, put on replace stack */
1663 int vcol;
1664 int last_vcol;
1665 int insstart_less; /* reduction for Insstart.col */
1666 int new_cursor_col;
1667 int i;
1668 char_u *ptr;
1669 int save_p_list;
1670 int start_col;
1671 colnr_T vc;
1672 #ifdef FEAT_VREPLACE
1673 colnr_T orig_col = 0; /* init for GCC */
1674 char_u *new_line, *orig_line = NULL; /* init for GCC */
1676 /* VREPLACE mode needs to know what the line was like before changing */
1677 if (State & VREPLACE_FLAG)
1679 orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */
1680 orig_col = curwin->w_cursor.col;
1682 #endif
1684 /* for the following tricks we don't want list mode */
1685 save_p_list = curwin->w_p_list;
1686 curwin->w_p_list = FALSE;
1687 vc = getvcol_nolist(&curwin->w_cursor);
1688 vcol = vc;
1691 * For Replace mode we need to fix the replace stack later, which is only
1692 * possible when the cursor is in the indent. Remember the number of
1693 * characters before the cursor if it's possible.
1695 start_col = curwin->w_cursor.col;
1697 /* determine offset from first non-blank */
1698 new_cursor_col = curwin->w_cursor.col;
1699 beginline(BL_WHITE);
1700 new_cursor_col -= curwin->w_cursor.col;
1702 insstart_less = curwin->w_cursor.col;
1705 * If the cursor is in the indent, compute how many screen columns the
1706 * cursor is to the left of the first non-blank.
1708 if (new_cursor_col < 0)
1709 vcol = get_indent() - vcol;
1711 if (new_cursor_col > 0) /* can't fix replace stack */
1712 start_col = -1;
1715 * Set the new indent. The cursor will be put on the first non-blank.
1717 if (type == INDENT_SET)
1718 (void)set_indent(amount, SIN_CHANGED);
1719 else
1721 #ifdef FEAT_VREPLACE
1722 int save_State = State;
1724 /* Avoid being called recursively. */
1725 if (State & VREPLACE_FLAG)
1726 State = INSERT;
1727 #endif
1728 shift_line(type == INDENT_DEC, round, 1);
1729 #ifdef FEAT_VREPLACE
1730 State = save_State;
1731 #endif
1733 insstart_less -= curwin->w_cursor.col;
1736 * Try to put cursor on same character.
1737 * If the cursor is at or after the first non-blank in the line,
1738 * compute the cursor column relative to the column of the first
1739 * non-blank character.
1740 * If we are not in insert mode, leave the cursor on the first non-blank.
1741 * If the cursor is before the first non-blank, position it relative
1742 * to the first non-blank, counted in screen columns.
1744 if (new_cursor_col >= 0)
1747 * When changing the indent while the cursor is touching it, reset
1748 * Insstart_col to 0.
1750 if (new_cursor_col == 0)
1751 insstart_less = MAXCOL;
1752 new_cursor_col += curwin->w_cursor.col;
1754 else if (!(State & INSERT))
1755 new_cursor_col = curwin->w_cursor.col;
1756 else
1759 * Compute the screen column where the cursor should be.
1761 vcol = get_indent() - vcol;
1762 curwin->w_virtcol = (vcol < 0) ? 0 : vcol;
1765 * Advance the cursor until we reach the right screen column.
1767 vcol = last_vcol = 0;
1768 new_cursor_col = -1;
1769 ptr = ml_get_curline();
1770 while (vcol <= (int)curwin->w_virtcol)
1772 last_vcol = vcol;
1773 #ifdef FEAT_MBYTE
1774 if (has_mbyte && new_cursor_col >= 0)
1775 new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1776 else
1777 #endif
1778 ++new_cursor_col;
1779 vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol);
1781 vcol = last_vcol;
1784 * May need to insert spaces to be able to position the cursor on
1785 * the right screen column.
1787 if (vcol != (int)curwin->w_virtcol)
1789 curwin->w_cursor.col = new_cursor_col;
1790 i = (int)curwin->w_virtcol - vcol;
1791 ptr = alloc(i + 1);
1792 if (ptr != NULL)
1794 new_cursor_col += i;
1795 ptr[i] = NUL;
1796 while (--i >= 0)
1797 ptr[i] = ' ';
1798 ins_str(ptr);
1799 vim_free(ptr);
1804 * When changing the indent while the cursor is in it, reset
1805 * Insstart_col to 0.
1807 insstart_less = MAXCOL;
1810 curwin->w_p_list = save_p_list;
1812 if (new_cursor_col <= 0)
1813 curwin->w_cursor.col = 0;
1814 else
1815 curwin->w_cursor.col = new_cursor_col;
1816 curwin->w_set_curswant = TRUE;
1817 changed_cline_bef_curs();
1820 * May have to adjust the start of the insert.
1822 if (State & INSERT)
1824 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1826 if ((int)Insstart.col <= insstart_less)
1827 Insstart.col = 0;
1828 else
1829 Insstart.col -= insstart_less;
1831 if ((int)ai_col <= insstart_less)
1832 ai_col = 0;
1833 else
1834 ai_col -= insstart_less;
1838 * For REPLACE mode, may have to fix the replace stack, if it's possible.
1839 * If the number of characters before the cursor decreased, need to pop a
1840 * few characters from the replace stack.
1841 * If the number of characters before the cursor increased, need to push a
1842 * few NULs onto the replace stack.
1844 if (REPLACE_NORMAL(State) && start_col >= 0)
1846 while (start_col > (int)curwin->w_cursor.col)
1848 replace_join(0); /* remove a NUL from the replace stack */
1849 --start_col;
1851 while (start_col < (int)curwin->w_cursor.col || replaced)
1853 replace_push(NUL);
1854 if (replaced)
1856 replace_push(replaced);
1857 replaced = NUL;
1859 ++start_col;
1863 #ifdef FEAT_VREPLACE
1865 * For VREPLACE mode, we also have to fix the replace stack. In this case
1866 * it is always possible because we backspace over the whole line and then
1867 * put it back again the way we wanted it.
1869 if (State & VREPLACE_FLAG)
1871 /* If orig_line didn't allocate, just return. At least we did the job,
1872 * even if you can't backspace. */
1873 if (orig_line == NULL)
1874 return;
1876 /* Save new line */
1877 new_line = vim_strsave(ml_get_curline());
1878 if (new_line == NULL)
1879 return;
1881 /* We only put back the new line up to the cursor */
1882 new_line[curwin->w_cursor.col] = NUL;
1884 /* Put back original line */
1885 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1886 curwin->w_cursor.col = orig_col;
1888 /* Backspace from cursor to start of line */
1889 backspace_until_column(0);
1891 /* Insert new stuff into line again */
1892 ins_bytes(new_line);
1894 vim_free(new_line);
1896 #endif
1900 * Truncate the space at the end of a line. This is to be used only in an
1901 * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE
1902 * modes.
1904 void
1905 truncate_spaces(line)
1906 char_u *line;
1908 int i;
1910 /* find start of trailing white space */
1911 for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
1913 if (State & REPLACE_FLAG)
1914 replace_join(0); /* remove a NUL from the replace stack */
1916 line[i + 1] = NUL;
1919 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1920 || defined(FEAT_COMMENTS) || defined(PROTO)
1922 * Backspace the cursor until the given column. Handles REPLACE and VREPLACE
1923 * modes correctly. May also be used when not in insert mode at all.
1925 void
1926 backspace_until_column(col)
1927 int col;
1929 while ((int)curwin->w_cursor.col > col)
1931 curwin->w_cursor.col--;
1932 if (State & REPLACE_FLAG)
1933 replace_do_bs();
1934 else
1935 (void)del_char(FALSE);
1938 #endif
1940 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1942 * CTRL-X pressed in Insert mode.
1944 static void
1945 ins_ctrl_x()
1947 /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
1948 * CTRL-V works like CTRL-N */
1949 if (ctrl_x_mode != CTRL_X_CMDLINE)
1951 /* if the next ^X<> won't ADD nothing, then reset
1952 * compl_cont_status */
1953 if (compl_cont_status & CONT_N_ADDS)
1954 compl_cont_status |= CONT_INTRPT;
1955 else
1956 compl_cont_status = 0;
1957 /* We're not sure which CTRL-X mode it will be yet */
1958 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
1959 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
1960 edit_submode_pre = NULL;
1961 showmode();
1966 * Return TRUE if the 'dict' or 'tsr' option can be used.
1968 static int
1969 has_compl_option(dict_opt)
1970 int dict_opt;
1972 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
1973 # ifdef FEAT_SPELL
1974 && !curwin->w_p_spell
1975 # endif
1977 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
1979 ctrl_x_mode = 0;
1980 edit_submode = NULL;
1981 msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty")
1982 : (char_u *)_("'thesaurus' option is empty"),
1983 hl_attr(HLF_E));
1984 if (emsg_silent == 0)
1986 vim_beep();
1987 setcursor();
1988 out_flush();
1989 ui_delay(2000L, FALSE);
1991 return FALSE;
1993 return TRUE;
1997 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
1998 * This depends on the current mode.
2001 vim_is_ctrl_x_key(c)
2002 int c;
2004 /* Always allow ^R - let it's results then be checked */
2005 if (c == Ctrl_R)
2006 return TRUE;
2008 /* Accept <PageUp> and <PageDown> if the popup menu is visible. */
2009 if (ins_compl_pum_key(c))
2010 return TRUE;
2012 switch (ctrl_x_mode)
2014 case 0: /* Not in any CTRL-X mode */
2015 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
2016 case CTRL_X_NOT_DEFINED_YET:
2017 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
2018 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
2019 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
2020 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
2021 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
2022 || c == Ctrl_S || c == 's');
2023 case CTRL_X_SCROLL:
2024 return (c == Ctrl_Y || c == Ctrl_E);
2025 case CTRL_X_WHOLE_LINE:
2026 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
2027 case CTRL_X_FILES:
2028 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
2029 case CTRL_X_DICTIONARY:
2030 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
2031 case CTRL_X_THESAURUS:
2032 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
2033 case CTRL_X_TAGS:
2034 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
2035 #ifdef FEAT_FIND_ID
2036 case CTRL_X_PATH_PATTERNS:
2037 return (c == Ctrl_P || c == Ctrl_N);
2038 case CTRL_X_PATH_DEFINES:
2039 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
2040 #endif
2041 case CTRL_X_CMDLINE:
2042 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
2043 || c == Ctrl_X);
2044 #ifdef FEAT_COMPL_FUNC
2045 case CTRL_X_FUNCTION:
2046 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
2047 case CTRL_X_OMNI:
2048 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
2049 #endif
2050 case CTRL_X_SPELL:
2051 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
2053 EMSG(_(e_internal));
2054 return FALSE;
2058 * Return TRUE when character "c" is part of the item currently being
2059 * completed. Used to decide whether to abandon complete mode when the menu
2060 * is visible.
2062 static int
2063 ins_compl_accept_char(c)
2064 int c;
2066 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
2067 /* When expanding an identifier only accept identifier chars. */
2068 return vim_isIDc(c);
2070 switch (ctrl_x_mode)
2072 case CTRL_X_FILES:
2073 /* When expanding file name only accept file name chars. But not
2074 * path separators, so that "proto/<Tab>" expands files in
2075 * "proto", not "proto/" as a whole */
2076 return vim_isfilec(c) && !vim_ispathsep(c);
2078 case CTRL_X_CMDLINE:
2079 case CTRL_X_OMNI:
2080 /* Command line and Omni completion can work with just about any
2081 * printable character, but do stop at white space. */
2082 return vim_isprintc(c) && !vim_iswhite(c);
2084 case CTRL_X_WHOLE_LINE:
2085 /* For while line completion a space can be part of the line. */
2086 return vim_isprintc(c);
2088 return vim_iswordc(c);
2092 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
2093 * case of the originally typed text is used, and the case of the completed
2094 * text is inferred, ie this tries to work out what case you probably wanted
2095 * the rest of the word to be in -- webb
2098 ins_compl_add_infercase(str, len, icase, fname, dir, flags)
2099 char_u *str;
2100 int len;
2101 int icase;
2102 char_u *fname;
2103 int dir;
2104 int flags;
2106 char_u *p;
2107 int i, c;
2108 int actual_len; /* Take multi-byte characters */
2109 int actual_compl_length; /* into account. */
2110 int *wca; /* Wide character array. */
2111 int has_lower = FALSE;
2112 int was_letter = FALSE;
2114 if (p_ic && curbuf->b_p_inf && len > 0)
2116 /* Infer case of completed part. */
2118 /* Find actual length of completion. */
2119 #ifdef FEAT_MBYTE
2120 if (has_mbyte)
2122 p = str;
2123 actual_len = 0;
2124 while (*p != NUL)
2126 mb_ptr_adv(p);
2127 ++actual_len;
2130 else
2131 #endif
2132 actual_len = len;
2134 /* Find actual length of original text. */
2135 #ifdef FEAT_MBYTE
2136 if (has_mbyte)
2138 p = compl_orig_text;
2139 actual_compl_length = 0;
2140 while (*p != NUL)
2142 mb_ptr_adv(p);
2143 ++actual_compl_length;
2146 else
2147 #endif
2148 actual_compl_length = compl_length;
2150 /* Allocate wide character array for the completion and fill it. */
2151 wca = (int *)alloc(actual_len * sizeof(int));
2152 if (wca != NULL)
2154 p = str;
2155 for (i = 0; i < actual_len; ++i)
2156 #ifdef FEAT_MBYTE
2157 if (has_mbyte)
2158 wca[i] = mb_ptr2char_adv(&p);
2159 else
2160 #endif
2161 wca[i] = *(p++);
2163 /* Rule 1: Were any chars converted to lower? */
2164 p = compl_orig_text;
2165 for (i = 0; i < actual_compl_length; ++i)
2167 #ifdef FEAT_MBYTE
2168 if (has_mbyte)
2169 c = mb_ptr2char_adv(&p);
2170 else
2171 #endif
2172 c = *(p++);
2173 if (MB_ISLOWER(c))
2175 has_lower = TRUE;
2176 if (MB_ISUPPER(wca[i]))
2178 /* Rule 1 is satisfied. */
2179 for (i = actual_compl_length; i < actual_len; ++i)
2180 wca[i] = MB_TOLOWER(wca[i]);
2181 break;
2187 * Rule 2: No lower case, 2nd consecutive letter converted to
2188 * upper case.
2190 if (!has_lower)
2192 p = compl_orig_text;
2193 for (i = 0; i < actual_compl_length; ++i)
2195 #ifdef FEAT_MBYTE
2196 if (has_mbyte)
2197 c = mb_ptr2char_adv(&p);
2198 else
2199 #endif
2200 c = *(p++);
2201 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
2203 /* Rule 2 is satisfied. */
2204 for (i = actual_compl_length; i < actual_len; ++i)
2205 wca[i] = MB_TOUPPER(wca[i]);
2206 break;
2208 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
2212 /* Copy the original case of the part we typed. */
2213 p = compl_orig_text;
2214 for (i = 0; i < actual_compl_length; ++i)
2216 #ifdef FEAT_MBYTE
2217 if (has_mbyte)
2218 c = mb_ptr2char_adv(&p);
2219 else
2220 #endif
2221 c = *(p++);
2222 if (MB_ISLOWER(c))
2223 wca[i] = MB_TOLOWER(wca[i]);
2224 else if (MB_ISUPPER(c))
2225 wca[i] = MB_TOUPPER(wca[i]);
2229 * Generate encoding specific output from wide character array.
2230 * Multi-byte characters can occupy up to five bytes more than
2231 * ASCII characters, and we also need one byte for NUL, so stay
2232 * six bytes away from the edge of IObuff.
2234 p = IObuff;
2235 i = 0;
2236 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
2237 #ifdef FEAT_MBYTE
2238 if (has_mbyte)
2239 p += mb_char2bytes(wca[i++], p);
2240 else
2241 #endif
2242 *(p++) = wca[i++];
2243 *p = NUL;
2245 vim_free(wca);
2248 return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2249 flags, FALSE);
2251 return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2255 * Add a match to the list of matches.
2256 * If the given string is already in the list of completions, then return
2257 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2258 * maybe because alloc() returns NULL, then FAIL is returned.
2260 static int
2261 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup)
2262 char_u *str;
2263 int len;
2264 int icase;
2265 char_u *fname;
2266 char_u **cptext; /* extra text for popup menu or NULL */
2267 int cdir;
2268 int flags;
2269 int adup; /* accept duplicate match */
2271 compl_T *match;
2272 int dir = (cdir == 0 ? compl_direction : cdir);
2274 ui_breakcheck();
2275 if (got_int)
2276 return FAIL;
2277 if (len < 0)
2278 len = (int)STRLEN(str);
2281 * If the same match is already present, don't add it.
2283 if (compl_first_match != NULL && !adup)
2285 match = compl_first_match;
2288 if ( !(match->cp_flags & ORIGINAL_TEXT)
2289 && STRNCMP(match->cp_str, str, len) == 0
2290 && match->cp_str[len] == NUL)
2291 return NOTDONE;
2292 match = match->cp_next;
2293 } while (match != NULL && match != compl_first_match);
2296 /* Remove any popup menu before changing the list of matches. */
2297 ins_compl_del_pum();
2300 * Allocate a new match structure.
2301 * Copy the values to the new match structure.
2303 match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2304 if (match == NULL)
2305 return FAIL;
2306 match->cp_number = -1;
2307 if (flags & ORIGINAL_TEXT)
2308 match->cp_number = 0;
2309 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2311 vim_free(match);
2312 return FAIL;
2314 match->cp_icase = icase;
2316 /* match-fname is:
2317 * - compl_curr_match->cp_fname if it is a string equal to fname.
2318 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2319 * - NULL otherwise. --Acevedo */
2320 if (fname != NULL
2321 && compl_curr_match != NULL
2322 && compl_curr_match->cp_fname != NULL
2323 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2324 match->cp_fname = compl_curr_match->cp_fname;
2325 else if (fname != NULL)
2327 match->cp_fname = vim_strsave(fname);
2328 flags |= FREE_FNAME;
2330 else
2331 match->cp_fname = NULL;
2332 match->cp_flags = flags;
2334 if (cptext != NULL)
2336 int i;
2338 for (i = 0; i < CPT_COUNT; ++i)
2339 if (cptext[i] != NULL && *cptext[i] != NUL)
2340 match->cp_text[i] = vim_strsave(cptext[i]);
2344 * Link the new match structure in the list of matches.
2346 if (compl_first_match == NULL)
2347 match->cp_next = match->cp_prev = NULL;
2348 else if (dir == FORWARD)
2350 match->cp_next = compl_curr_match->cp_next;
2351 match->cp_prev = compl_curr_match;
2353 else /* BACKWARD */
2355 match->cp_next = compl_curr_match;
2356 match->cp_prev = compl_curr_match->cp_prev;
2358 if (match->cp_next)
2359 match->cp_next->cp_prev = match;
2360 if (match->cp_prev)
2361 match->cp_prev->cp_next = match;
2362 else /* if there's nothing before, it is the first match */
2363 compl_first_match = match;
2364 compl_curr_match = match;
2367 * Find the longest common string if still doing that.
2369 if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2370 ins_compl_longest_match(match);
2372 return OK;
2376 * Return TRUE if "str[len]" matches with match->cp_str, considering
2377 * match->cp_icase.
2379 static int
2380 ins_compl_equal(match, str, len)
2381 compl_T *match;
2382 char_u *str;
2383 int len;
2385 if (match->cp_icase)
2386 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2387 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2391 * Reduce the longest common string for match "match".
2393 static void
2394 ins_compl_longest_match(match)
2395 compl_T *match;
2397 char_u *p, *s;
2398 int c1, c2;
2399 int had_match;
2401 if (compl_leader == NULL)
2403 /* First match, use it as a whole. */
2404 compl_leader = vim_strsave(match->cp_str);
2405 if (compl_leader != NULL)
2407 had_match = (curwin->w_cursor.col > compl_col);
2408 ins_compl_delete();
2409 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
2410 ins_redraw(FALSE);
2412 /* When the match isn't there (to avoid matching itself) remove it
2413 * again after redrawing. */
2414 if (!had_match)
2415 ins_compl_delete();
2416 compl_used_match = FALSE;
2419 else
2421 /* Reduce the text if this match differs from compl_leader. */
2422 p = compl_leader;
2423 s = match->cp_str;
2424 while (*p != NUL)
2426 #ifdef FEAT_MBYTE
2427 if (has_mbyte)
2429 c1 = mb_ptr2char(p);
2430 c2 = mb_ptr2char(s);
2432 else
2433 #endif
2435 c1 = *p;
2436 c2 = *s;
2438 if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2439 : (c1 != c2))
2440 break;
2441 #ifdef FEAT_MBYTE
2442 if (has_mbyte)
2444 mb_ptr_adv(p);
2445 mb_ptr_adv(s);
2447 else
2448 #endif
2450 ++p;
2451 ++s;
2455 if (*p != NUL)
2457 /* Leader was shortened, need to change the inserted text. */
2458 *p = NUL;
2459 had_match = (curwin->w_cursor.col > compl_col);
2460 ins_compl_delete();
2461 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
2462 ins_redraw(FALSE);
2464 /* When the match isn't there (to avoid matching itself) remove it
2465 * again after redrawing. */
2466 if (!had_match)
2467 ins_compl_delete();
2470 compl_used_match = FALSE;
2475 * Add an array of matches to the list of matches.
2476 * Frees matches[].
2478 static void
2479 ins_compl_add_matches(num_matches, matches, icase)
2480 int num_matches;
2481 char_u **matches;
2482 int icase;
2484 int i;
2485 int add_r = OK;
2486 int dir = compl_direction;
2488 for (i = 0; i < num_matches && add_r != FAIL; i++)
2489 if ((add_r = ins_compl_add(matches[i], -1, icase,
2490 NULL, NULL, dir, 0, FALSE)) == OK)
2491 /* if dir was BACKWARD then honor it just once */
2492 dir = FORWARD;
2493 FreeWild(num_matches, matches);
2496 /* Make the completion list cyclic.
2497 * Return the number of matches (excluding the original).
2499 static int
2500 ins_compl_make_cyclic()
2502 compl_T *match;
2503 int count = 0;
2505 if (compl_first_match != NULL)
2508 * Find the end of the list.
2510 match = compl_first_match;
2511 /* there's always an entry for the compl_orig_text, it doesn't count. */
2512 while (match->cp_next != NULL && match->cp_next != compl_first_match)
2514 match = match->cp_next;
2515 ++count;
2517 match->cp_next = compl_first_match;
2518 compl_first_match->cp_prev = match;
2520 return count;
2524 * Start completion for the complete() function.
2525 * "startcol" is where the matched text starts (1 is first column).
2526 * "list" is the list of matches.
2528 void
2529 set_completion(startcol, list)
2530 int startcol;
2531 list_T *list;
2533 /* If already doing completions stop it. */
2534 if (ctrl_x_mode != 0)
2535 ins_compl_prep(' ');
2536 ins_compl_clear();
2538 if (stop_arrow() == FAIL)
2539 return;
2541 if (startcol > (int)curwin->w_cursor.col)
2542 startcol = curwin->w_cursor.col;
2543 compl_col = startcol;
2544 compl_length = curwin->w_cursor.col - startcol;
2545 /* compl_pattern doesn't need to be set */
2546 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2547 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2548 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2549 return;
2551 /* Handle like dictionary completion. */
2552 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2554 ins_compl_add_list(list);
2555 compl_matches = ins_compl_make_cyclic();
2556 compl_started = TRUE;
2557 compl_used_match = TRUE;
2558 compl_cont_status = 0;
2560 compl_curr_match = compl_first_match;
2561 ins_complete(Ctrl_N);
2562 out_flush();
2566 /* "compl_match_array" points the currently displayed list of entries in the
2567 * popup menu. It is NULL when there is no popup menu. */
2568 static pumitem_T *compl_match_array = NULL;
2569 static int compl_match_arraysize;
2572 * Update the screen and when there is any scrolling remove the popup menu.
2574 static void
2575 ins_compl_upd_pum()
2577 int h;
2579 if (compl_match_array != NULL)
2581 h = curwin->w_cline_height;
2582 update_screen(0);
2583 if (h != curwin->w_cline_height)
2584 ins_compl_del_pum();
2589 * Remove any popup menu.
2591 static void
2592 ins_compl_del_pum()
2594 if (compl_match_array != NULL)
2596 pum_undisplay();
2597 vim_free(compl_match_array);
2598 compl_match_array = NULL;
2603 * Return TRUE if the popup menu should be displayed.
2605 static int
2606 pum_wanted()
2608 /* 'completeopt' must contain "menu" or "menuone" */
2609 if (vim_strchr(p_cot, 'm') == NULL)
2610 return FALSE;
2612 /* The display looks bad on a B&W display. */
2613 if (t_colors < 8
2614 #ifdef FEAT_GUI
2615 && !gui.in_use
2616 #endif
2618 return FALSE;
2619 return TRUE;
2623 * Return TRUE if there are two or more matches to be shown in the popup menu.
2624 * One if 'completopt' contains "menuone".
2626 static int
2627 pum_enough_matches()
2629 compl_T *compl;
2630 int i;
2632 /* Don't display the popup menu if there are no matches or there is only
2633 * one (ignoring the original text). */
2634 compl = compl_first_match;
2635 i = 0;
2638 if (compl == NULL
2639 || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2640 break;
2641 compl = compl->cp_next;
2642 } while (compl != compl_first_match);
2644 if (strstr((char *)p_cot, "menuone") != NULL)
2645 return (i >= 1);
2646 return (i >= 2);
2650 * Show the popup menu for the list of matches.
2651 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2653 void
2654 ins_compl_show_pum()
2656 compl_T *compl;
2657 compl_T *shown_compl = NULL;
2658 int did_find_shown_match = FALSE;
2659 int shown_match_ok = FALSE;
2660 int i;
2661 int cur = -1;
2662 colnr_T col;
2663 int lead_len = 0;
2665 if (!pum_wanted() || !pum_enough_matches())
2666 return;
2668 #if defined(FEAT_EVAL)
2669 /* Dirty hard-coded hack: remove any matchparen highlighting. */
2670 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2671 #endif
2673 /* Update the screen before drawing the popup menu over it. */
2674 update_screen(0);
2676 if (compl_match_array == NULL)
2678 /* Need to build the popup menu list. */
2679 compl_match_arraysize = 0;
2680 compl = compl_first_match;
2681 if (compl_leader != NULL)
2682 lead_len = (int)STRLEN(compl_leader);
2685 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2686 && (compl_leader == NULL
2687 || ins_compl_equal(compl, compl_leader, lead_len)))
2688 ++compl_match_arraysize;
2689 compl = compl->cp_next;
2690 } while (compl != NULL && compl != compl_first_match);
2691 if (compl_match_arraysize == 0)
2692 return;
2693 compl_match_array = (pumitem_T *)alloc_clear(
2694 (unsigned)(sizeof(pumitem_T)
2695 * compl_match_arraysize));
2696 if (compl_match_array != NULL)
2698 /* If the current match is the original text don't find the first
2699 * match after it, don't highlight anything. */
2700 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2701 shown_match_ok = TRUE;
2703 i = 0;
2704 compl = compl_first_match;
2707 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2708 && (compl_leader == NULL
2709 || ins_compl_equal(compl, compl_leader, lead_len)))
2711 if (!shown_match_ok)
2713 if (compl == compl_shown_match || did_find_shown_match)
2715 /* This item is the shown match or this is the
2716 * first displayed item after the shown match. */
2717 compl_shown_match = compl;
2718 did_find_shown_match = TRUE;
2719 shown_match_ok = TRUE;
2721 else
2722 /* Remember this displayed match for when the
2723 * shown match is just below it. */
2724 shown_compl = compl;
2725 cur = i;
2728 if (compl->cp_text[CPT_ABBR] != NULL)
2729 compl_match_array[i].pum_text =
2730 compl->cp_text[CPT_ABBR];
2731 else
2732 compl_match_array[i].pum_text = compl->cp_str;
2733 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2734 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2735 if (compl->cp_text[CPT_MENU] != NULL)
2736 compl_match_array[i++].pum_extra =
2737 compl->cp_text[CPT_MENU];
2738 else
2739 compl_match_array[i++].pum_extra = compl->cp_fname;
2742 if (compl == compl_shown_match)
2744 did_find_shown_match = TRUE;
2746 /* When the original text is the shown match don't set
2747 * compl_shown_match. */
2748 if (compl->cp_flags & ORIGINAL_TEXT)
2749 shown_match_ok = TRUE;
2751 if (!shown_match_ok && shown_compl != NULL)
2753 /* The shown match isn't displayed, set it to the
2754 * previously displayed match. */
2755 compl_shown_match = shown_compl;
2756 shown_match_ok = TRUE;
2759 compl = compl->cp_next;
2760 } while (compl != NULL && compl != compl_first_match);
2762 if (!shown_match_ok) /* no displayed match at all */
2763 cur = -1;
2766 else
2768 /* popup menu already exists, only need to find the current item.*/
2769 for (i = 0; i < compl_match_arraysize; ++i)
2770 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2771 || compl_match_array[i].pum_text
2772 == compl_shown_match->cp_text[CPT_ABBR])
2774 cur = i;
2775 break;
2779 if (compl_match_array != NULL)
2781 /* Compute the screen column of the start of the completed text.
2782 * Use the cursor to get all wrapping and other settings right. */
2783 col = curwin->w_cursor.col;
2784 curwin->w_cursor.col = compl_col;
2785 pum_display(compl_match_array, compl_match_arraysize, cur);
2786 curwin->w_cursor.col = col;
2790 #define DICT_FIRST (1) /* use just first element in "dict" */
2791 #define DICT_EXACT (2) /* "dict" is the exact name of a file */
2794 * Add any identifiers that match the given pattern in the list of dictionary
2795 * files "dict_start" to the list of completions.
2797 static void
2798 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2799 char_u *dict_start;
2800 char_u *pat;
2801 int flags; /* DICT_FIRST and/or DICT_EXACT */
2802 int thesaurus; /* Thesaurus completion */
2804 char_u *dict = dict_start;
2805 char_u *ptr;
2806 char_u *buf;
2807 regmatch_T regmatch;
2808 char_u **files;
2809 int count;
2810 int i;
2811 int save_p_scs;
2812 int dir = compl_direction;
2814 if (*dict == NUL)
2816 #ifdef FEAT_SPELL
2817 /* When 'dictionary' is empty and spell checking is enabled use
2818 * "spell". */
2819 if (!thesaurus && curwin->w_p_spell)
2820 dict = (char_u *)"spell";
2821 else
2822 #endif
2823 return;
2826 buf = alloc(LSIZE);
2827 if (buf == NULL)
2828 return;
2829 regmatch.regprog = NULL; /* so that we can goto theend */
2831 /* If 'infercase' is set, don't use 'smartcase' here */
2832 save_p_scs = p_scs;
2833 if (curbuf->b_p_inf)
2834 p_scs = FALSE;
2836 /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
2837 * to only match at the start of a line. Otherwise just match the
2838 * pattern. Also need to double backslashes. */
2839 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2841 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
2843 if (pat_esc == NULL)
2844 goto theend;
2845 i = (int)STRLEN(pat_esc) + 10;
2846 ptr = alloc(i);
2847 if (ptr == NULL)
2849 vim_free(pat_esc);
2850 goto theend;
2852 vim_snprintf((char *)ptr, i, "^\\s*\\zs\\V%s", pat_esc);
2853 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
2854 vim_free(pat_esc);
2855 vim_free(ptr);
2857 else
2859 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2860 if (regmatch.regprog == NULL)
2861 goto theend;
2864 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2865 regmatch.rm_ic = ignorecase(pat);
2866 while (*dict != NUL && !got_int && !compl_interrupted)
2868 /* copy one dictionary file name into buf */
2869 if (flags == DICT_EXACT)
2871 count = 1;
2872 files = &dict;
2874 else
2876 /* Expand wildcards in the dictionary name, but do not allow
2877 * backticks (for security, the 'dict' option may have been set in
2878 * a modeline). */
2879 copy_option_part(&dict, buf, LSIZE, ",");
2880 # ifdef FEAT_SPELL
2881 if (!thesaurus && STRCMP(buf, "spell") == 0)
2882 count = -1;
2883 else
2884 # endif
2885 if (vim_strchr(buf, '`') != NULL
2886 || expand_wildcards(1, &buf, &count, &files,
2887 EW_FILE|EW_SILENT) != OK)
2888 count = 0;
2891 # ifdef FEAT_SPELL
2892 if (count == -1)
2894 /* Complete from active spelling. Skip "\<" in the pattern, we
2895 * don't use it as a RE. */
2896 if (pat[0] == '\\' && pat[1] == '<')
2897 ptr = pat + 2;
2898 else
2899 ptr = pat;
2900 spell_dump_compl(curbuf, ptr, regmatch.rm_ic, &dir, 0);
2902 else
2903 # endif
2904 if (count > 0) /* avoid warning for using "files" uninit */
2906 ins_compl_files(count, files, thesaurus, flags,
2907 &regmatch, buf, &dir);
2908 if (flags != DICT_EXACT)
2909 FreeWild(count, files);
2911 if (flags != 0)
2912 break;
2915 theend:
2916 p_scs = save_p_scs;
2917 vim_free(regmatch.regprog);
2918 vim_free(buf);
2921 static void
2922 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
2923 int count;
2924 char_u **files;
2925 int thesaurus;
2926 int flags;
2927 regmatch_T *regmatch;
2928 char_u *buf;
2929 int *dir;
2931 char_u *ptr;
2932 int i;
2933 FILE *fp;
2934 int add_r;
2936 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
2938 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
2939 if (flags != DICT_EXACT)
2941 vim_snprintf((char *)IObuff, IOSIZE,
2942 _("Scanning dictionary: %s"), (char *)files[i]);
2943 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
2946 if (fp != NULL)
2949 * Read dictionary file line by line.
2950 * Check each line for a match.
2952 while (!got_int && !compl_interrupted
2953 && !vim_fgets(buf, LSIZE, fp))
2955 ptr = buf;
2956 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
2958 ptr = regmatch->startp[0];
2959 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2960 ptr = find_line_end(ptr);
2961 else
2962 ptr = find_word_end(ptr);
2963 add_r = ins_compl_add_infercase(regmatch->startp[0],
2964 (int)(ptr - regmatch->startp[0]),
2965 p_ic, files[i], *dir, 0);
2966 if (thesaurus)
2968 char_u *wstart;
2971 * Add the other matches on the line
2973 ptr = buf;
2974 while (!got_int)
2976 /* Find start of the next word. Skip white
2977 * space and punctuation. */
2978 ptr = find_word_start(ptr);
2979 if (*ptr == NUL || *ptr == NL)
2980 break;
2981 wstart = ptr;
2983 /* Find end of the word. */
2984 #ifdef FEAT_MBYTE
2985 if (has_mbyte)
2986 /* Japanese words may have characters in
2987 * different classes, only separate words
2988 * with single-byte non-word characters. */
2989 while (*ptr != NUL)
2991 int l = (*mb_ptr2len)(ptr);
2993 if (l < 2 && !vim_iswordc(*ptr))
2994 break;
2995 ptr += l;
2997 else
2998 #endif
2999 ptr = find_word_end(ptr);
3001 /* Add the word. Skip the regexp match. */
3002 if (wstart != regmatch->startp[0])
3003 add_r = ins_compl_add_infercase(wstart,
3004 (int)(ptr - wstart),
3005 p_ic, files[i], *dir, 0);
3008 if (add_r == OK)
3009 /* if dir was BACKWARD then honor it just once */
3010 *dir = FORWARD;
3011 else if (add_r == FAIL)
3012 break;
3013 /* avoid expensive call to vim_regexec() when at end
3014 * of line */
3015 if (*ptr == '\n' || got_int)
3016 break;
3018 line_breakcheck();
3019 ins_compl_check_keys(50);
3021 fclose(fp);
3027 * Find the start of the next word.
3028 * Returns a pointer to the first char of the word. Also stops at a NUL.
3030 char_u *
3031 find_word_start(ptr)
3032 char_u *ptr;
3034 #ifdef FEAT_MBYTE
3035 if (has_mbyte)
3036 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
3037 ptr += (*mb_ptr2len)(ptr);
3038 else
3039 #endif
3040 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
3041 ++ptr;
3042 return ptr;
3046 * Find the end of the word. Assumes it starts inside a word.
3047 * Returns a pointer to just after the word.
3049 char_u *
3050 find_word_end(ptr)
3051 char_u *ptr;
3053 #ifdef FEAT_MBYTE
3054 int start_class;
3056 if (has_mbyte)
3058 start_class = mb_get_class(ptr);
3059 if (start_class > 1)
3060 while (*ptr != NUL)
3062 ptr += (*mb_ptr2len)(ptr);
3063 if (mb_get_class(ptr) != start_class)
3064 break;
3067 else
3068 #endif
3069 while (vim_iswordc(*ptr))
3070 ++ptr;
3071 return ptr;
3075 * Find the end of the line, omitting CR and NL at the end.
3076 * Returns a pointer to just after the line.
3078 static char_u *
3079 find_line_end(ptr)
3080 char_u *ptr;
3082 char_u *s;
3084 s = ptr + STRLEN(ptr);
3085 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
3086 --s;
3087 return s;
3091 * Free the list of completions
3093 static void
3094 ins_compl_free()
3096 compl_T *match;
3097 int i;
3099 vim_free(compl_pattern);
3100 compl_pattern = NULL;
3101 vim_free(compl_leader);
3102 compl_leader = NULL;
3104 if (compl_first_match == NULL)
3105 return;
3107 ins_compl_del_pum();
3108 pum_clear();
3110 compl_curr_match = compl_first_match;
3113 match = compl_curr_match;
3114 compl_curr_match = compl_curr_match->cp_next;
3115 vim_free(match->cp_str);
3116 /* several entries may use the same fname, free it just once. */
3117 if (match->cp_flags & FREE_FNAME)
3118 vim_free(match->cp_fname);
3119 for (i = 0; i < CPT_COUNT; ++i)
3120 vim_free(match->cp_text[i]);
3121 vim_free(match);
3122 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
3123 compl_first_match = compl_curr_match = NULL;
3126 static void
3127 ins_compl_clear()
3129 compl_cont_status = 0;
3130 compl_started = FALSE;
3131 compl_matches = 0;
3132 vim_free(compl_pattern);
3133 compl_pattern = NULL;
3134 vim_free(compl_leader);
3135 compl_leader = NULL;
3136 edit_submode_extra = NULL;
3137 vim_free(compl_orig_text);
3138 compl_orig_text = NULL;
3139 compl_enter_selects = FALSE;
3143 * Return TRUE when Insert completion is active.
3146 ins_compl_active()
3148 return compl_started;
3152 * Delete one character before the cursor and show the subset of the matches
3153 * that match the word that is now before the cursor.
3154 * Returns the character to be used, NUL if the work is done and another char
3155 * to be got from the user.
3157 static int
3158 ins_compl_bs()
3160 char_u *line;
3161 char_u *p;
3163 line = ml_get_curline();
3164 p = line + curwin->w_cursor.col;
3165 mb_ptr_back(line, p);
3167 /* Stop completion when the whole word was deleted. For Omni completion
3168 * allow the word to be deleted, we won't match everything. */
3169 if ((int)(p - line) - (int)compl_col < 0
3170 || ((int)(p - line) - (int)compl_col == 0
3171 && (ctrl_x_mode & CTRL_X_OMNI) == 0))
3172 return K_BS;
3174 /* Deleted more than what was used to find matches or didn't finish
3175 * finding all matches: need to look for matches all over again. */
3176 if (curwin->w_cursor.col <= compl_col + compl_length
3177 || compl_was_interrupted)
3178 ins_compl_restart();
3180 vim_free(compl_leader);
3181 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3182 if (compl_leader != NULL)
3184 ins_compl_new_leader();
3185 return NUL;
3187 return K_BS;
3191 * Called after changing "compl_leader".
3192 * Show the popup menu with a different set of matches.
3193 * May also search for matches again if the previous search was interrupted.
3195 static void
3196 ins_compl_new_leader()
3198 ins_compl_del_pum();
3199 ins_compl_delete();
3200 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
3201 compl_used_match = FALSE;
3203 if (compl_started)
3204 ins_compl_set_original_text(compl_leader);
3205 else
3207 #ifdef FEAT_SPELL
3208 spell_bad_len = 0; /* need to redetect bad word */
3209 #endif
3211 * Matches were cleared, need to search for them now. First display
3212 * the changed text before the cursor. Set "compl_restarting" to
3213 * avoid that the first match is inserted.
3215 update_screen(0);
3216 #ifdef FEAT_GUI
3217 if (gui.in_use)
3219 /* Show the cursor after the match, not after the redrawn text. */
3220 setcursor();
3221 out_flush();
3222 gui_update_cursor(FALSE, FALSE);
3224 #endif
3225 compl_restarting = TRUE;
3226 if (ins_complete(Ctrl_N) == FAIL)
3227 compl_cont_status = 0;
3228 compl_restarting = FALSE;
3231 #if 0 /* disabled, made CTRL-L, BS and typing char jump to original text. */
3232 if (!compl_used_match)
3234 /* Go to the original text, since none of the matches is inserted. */
3235 if (compl_first_match->cp_prev != NULL
3236 && (compl_first_match->cp_prev->cp_flags & ORIGINAL_TEXT))
3237 compl_shown_match = compl_first_match->cp_prev;
3238 else
3239 compl_shown_match = compl_first_match;
3240 compl_curr_match = compl_shown_match;
3241 compl_shows_dir = compl_direction;
3243 #endif
3244 compl_enter_selects = !compl_used_match;
3246 /* Show the popup menu with a different set of matches. */
3247 ins_compl_show_pum();
3249 /* Don't let Enter select the original text when there is no popup menu. */
3250 if (compl_match_array == NULL)
3251 compl_enter_selects = FALSE;
3255 * Append one character to the match leader. May reduce the number of
3256 * matches.
3258 static void
3259 ins_compl_addleader(c)
3260 int c;
3262 #ifdef FEAT_MBYTE
3263 int cc;
3265 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3267 char_u buf[MB_MAXBYTES + 1];
3269 (*mb_char2bytes)(c, buf);
3270 buf[cc] = NUL;
3271 ins_char_bytes(buf, cc);
3273 else
3274 #endif
3275 ins_char(c);
3277 /* If we didn't complete finding matches we must search again. */
3278 if (compl_was_interrupted)
3279 ins_compl_restart();
3281 vim_free(compl_leader);
3282 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3283 curwin->w_cursor.col - compl_col);
3284 if (compl_leader != NULL)
3285 ins_compl_new_leader();
3289 * Setup for finding completions again without leaving CTRL-X mode. Used when
3290 * BS or a key was typed while still searching for matches.
3292 static void
3293 ins_compl_restart()
3295 ins_compl_free();
3296 compl_started = FALSE;
3297 compl_matches = 0;
3298 compl_cont_status = 0;
3299 compl_cont_mode = 0;
3303 * Set the first match, the original text.
3305 static void
3306 ins_compl_set_original_text(str)
3307 char_u *str;
3309 char_u *p;
3311 /* Replace the original text entry. */
3312 if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */
3314 p = vim_strsave(str);
3315 if (p != NULL)
3317 vim_free(compl_first_match->cp_str);
3318 compl_first_match->cp_str = p;
3324 * Append one character to the match leader. May reduce the number of
3325 * matches.
3327 static void
3328 ins_compl_addfrommatch()
3330 char_u *p;
3331 int len = curwin->w_cursor.col - compl_col;
3332 int c;
3333 compl_T *cp;
3335 p = compl_shown_match->cp_str;
3336 if ((int)STRLEN(p) <= len) /* the match is too short */
3338 /* When still at the original match use the first entry that matches
3339 * the leader. */
3340 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
3342 p = NULL;
3343 for (cp = compl_shown_match->cp_next; cp != NULL
3344 && cp != compl_first_match; cp = cp->cp_next)
3346 if (compl_leader == NULL
3347 || ins_compl_equal(cp, compl_leader,
3348 (int)STRLEN(compl_leader)))
3350 p = cp->cp_str;
3351 break;
3354 if (p == NULL || (int)STRLEN(p) <= len)
3355 return;
3357 else
3358 return;
3360 p += len;
3361 #ifdef FEAT_MBYTE
3362 c = mb_ptr2char(p);
3363 #else
3364 c = *p;
3365 #endif
3366 ins_compl_addleader(c);
3370 * Prepare for Insert mode completion, or stop it.
3371 * Called just after typing a character in Insert mode.
3372 * Returns TRUE when the character is not to be inserted;
3374 static int
3375 ins_compl_prep(c)
3376 int c;
3378 char_u *ptr;
3379 int want_cindent;
3380 int retval = FALSE;
3382 /* Forget any previous 'special' messages if this is actually
3383 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3385 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3386 edit_submode_extra = NULL;
3388 /* Ignore end of Select mode mapping and mouse scroll buttons. */
3389 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP)
3390 return retval;
3392 /* Set "compl_get_longest" when finding the first matches. */
3393 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3394 || (ctrl_x_mode == 0 && !compl_started))
3396 compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3397 compl_used_match = TRUE;
3400 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3403 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3404 * it will be yet. Now we decide.
3406 switch (c)
3408 case Ctrl_E:
3409 case Ctrl_Y:
3410 ctrl_x_mode = CTRL_X_SCROLL;
3411 if (!(State & REPLACE_FLAG))
3412 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3413 else
3414 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3415 edit_submode_pre = NULL;
3416 showmode();
3417 break;
3418 case Ctrl_L:
3419 ctrl_x_mode = CTRL_X_WHOLE_LINE;
3420 break;
3421 case Ctrl_F:
3422 ctrl_x_mode = CTRL_X_FILES;
3423 break;
3424 case Ctrl_K:
3425 ctrl_x_mode = CTRL_X_DICTIONARY;
3426 break;
3427 case Ctrl_R:
3428 /* Simply allow ^R to happen without affecting ^X mode */
3429 break;
3430 case Ctrl_T:
3431 ctrl_x_mode = CTRL_X_THESAURUS;
3432 break;
3433 #ifdef FEAT_COMPL_FUNC
3434 case Ctrl_U:
3435 ctrl_x_mode = CTRL_X_FUNCTION;
3436 break;
3437 case Ctrl_O:
3438 ctrl_x_mode = CTRL_X_OMNI;
3439 break;
3440 #endif
3441 case 's':
3442 case Ctrl_S:
3443 ctrl_x_mode = CTRL_X_SPELL;
3444 #ifdef FEAT_SPELL
3445 ++emsg_off; /* Avoid getting the E756 error twice. */
3446 spell_back_to_badword();
3447 --emsg_off;
3448 #endif
3449 break;
3450 case Ctrl_RSB:
3451 ctrl_x_mode = CTRL_X_TAGS;
3452 break;
3453 #ifdef FEAT_FIND_ID
3454 case Ctrl_I:
3455 case K_S_TAB:
3456 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3457 break;
3458 case Ctrl_D:
3459 ctrl_x_mode = CTRL_X_PATH_DEFINES;
3460 break;
3461 #endif
3462 case Ctrl_V:
3463 case Ctrl_Q:
3464 ctrl_x_mode = CTRL_X_CMDLINE;
3465 break;
3466 case Ctrl_P:
3467 case Ctrl_N:
3468 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
3469 * just started ^X mode, or there were enough ^X's to cancel
3470 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3471 * do normal expansion when interrupting a different mode (say
3472 * ^X^F^X^P or ^P^X^X^P, see below)
3473 * nothing changes if interrupting mode 0, (eg, the flag
3474 * doesn't change when going to ADDING mode -- Acevedo */
3475 if (!(compl_cont_status & CONT_INTRPT))
3476 compl_cont_status |= CONT_LOCAL;
3477 else if (compl_cont_mode != 0)
3478 compl_cont_status &= ~CONT_LOCAL;
3479 /* FALLTHROUGH */
3480 default:
3481 /* If we have typed at least 2 ^X's... for modes != 0, we set
3482 * compl_cont_status = 0 (eg, as if we had just started ^X
3483 * mode).
3484 * For mode 0, we set "compl_cont_mode" to an impossible
3485 * value, in both cases ^X^X can be used to restart the same
3486 * mode (avoiding ADDING mode).
3487 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3488 * 'complete' and local ^P expansions respectively.
3489 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3490 * mode -- Acevedo */
3491 if (c == Ctrl_X)
3493 if (compl_cont_mode != 0)
3494 compl_cont_status = 0;
3495 else
3496 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3498 ctrl_x_mode = 0;
3499 edit_submode = NULL;
3500 showmode();
3501 break;
3504 else if (ctrl_x_mode != 0)
3506 /* We're already in CTRL-X mode, do we stay in it? */
3507 if (!vim_is_ctrl_x_key(c))
3509 if (ctrl_x_mode == CTRL_X_SCROLL)
3510 ctrl_x_mode = 0;
3511 else
3512 ctrl_x_mode = CTRL_X_FINISHED;
3513 edit_submode = NULL;
3515 showmode();
3518 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3520 /* Show error message from attempted keyword completion (probably
3521 * 'Pattern not found') until another key is hit, then go back to
3522 * showing what mode we are in. */
3523 showmode();
3524 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3525 && !ins_compl_pum_key(c))
3526 || ctrl_x_mode == CTRL_X_FINISHED)
3528 /* Get here when we have finished typing a sequence of ^N and
3529 * ^P or other completion characters in CTRL-X mode. Free up
3530 * memory that was used, and make sure we can redo the insert. */
3531 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3533 char_u *p;
3534 int temp = 0;
3537 * If any of the original typed text has been changed, eg when
3538 * ignorecase is set, we must add back-spaces to the redo
3539 * buffer. We add as few as necessary to delete just the part
3540 * of the original text that has changed.
3541 * When using the longest match, edited the match or used
3542 * CTRL-E then don't use the current match.
3544 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3545 ptr = compl_curr_match->cp_str;
3546 else if (compl_leader != NULL)
3547 ptr = compl_leader;
3548 else
3549 ptr = compl_orig_text;
3550 if (compl_orig_text != NULL)
3552 p = compl_orig_text;
3553 for (temp = 0; p[temp] != NUL && p[temp] == ptr[temp];
3554 ++temp)
3556 #ifdef FEAT_MBYTE
3557 if (temp > 0)
3558 temp -= (*mb_head_off)(compl_orig_text, p + temp);
3559 #endif
3560 for (p += temp; *p != NUL; mb_ptr_adv(p))
3561 AppendCharToRedobuff(K_BS);
3563 if (ptr != NULL)
3564 AppendToRedobuffLit(ptr + temp, -1);
3567 #ifdef FEAT_CINDENT
3568 want_cindent = (can_cindent && cindent_on());
3569 #endif
3571 * When completing whole lines: fix indent for 'cindent'.
3572 * Otherwise, break line if it's too long.
3574 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3576 #ifdef FEAT_CINDENT
3577 /* re-indent the current line */
3578 if (want_cindent)
3580 do_c_expr_indent();
3581 want_cindent = FALSE; /* don't do it again */
3583 #endif
3585 else
3587 int prev_col = curwin->w_cursor.col;
3589 /* put the cursor on the last char, for 'tw' formatting */
3590 if (prev_col > 0)
3591 dec_cursor();
3592 if (stop_arrow() == OK)
3593 insertchar(NUL, 0, -1);
3594 if (prev_col > 0
3595 && ml_get_curline()[curwin->w_cursor.col] != NUL)
3596 inc_cursor();
3599 auto_format(FALSE, TRUE);
3601 /* If the popup menu is displayed pressing CTRL-Y means accepting
3602 * the selection without inserting anything. When
3603 * compl_enter_selects is set the Enter key does the same. */
3604 if ((c == Ctrl_Y || (compl_enter_selects
3605 && (c == CAR || c == K_KENTER || c == NL)))
3606 && pum_visible())
3607 retval = TRUE;
3609 /* CTRL-E means completion is Ended, go back to the typed text. */
3610 if (c == Ctrl_E)
3612 ins_compl_delete();
3613 if (compl_leader != NULL)
3614 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
3615 else if (compl_first_match != NULL)
3616 ins_bytes(compl_orig_text
3617 + curwin->w_cursor.col - compl_col);
3618 retval = TRUE;
3621 ins_compl_free();
3622 compl_started = FALSE;
3623 compl_matches = 0;
3624 msg_clr_cmdline(); /* necessary for "noshowmode" */
3625 ctrl_x_mode = 0;
3626 compl_enter_selects = FALSE;
3627 if (edit_submode != NULL)
3629 edit_submode = NULL;
3630 showmode();
3633 #ifdef FEAT_CINDENT
3635 * Indent now if a key was typed that is in 'cinkeys'.
3637 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3638 do_c_expr_indent();
3639 #endif
3643 /* reset continue_* if we left expansion-mode, if we stay they'll be
3644 * (re)set properly in ins_complete() */
3645 if (!vim_is_ctrl_x_key(c))
3647 compl_cont_status = 0;
3648 compl_cont_mode = 0;
3651 return retval;
3655 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3656 * (depending on flag) starting from buf and looking for a non-scanned
3657 * buffer (other than curbuf). curbuf is special, if it is called with
3658 * buf=curbuf then it has to be the first call for a given flag/expansion.
3660 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3662 static buf_T *
3663 ins_compl_next_buf(buf, flag)
3664 buf_T *buf;
3665 int flag;
3667 #ifdef FEAT_WINDOWS
3668 static win_T *wp;
3669 #endif
3671 if (flag == 'w') /* just windows */
3673 #ifdef FEAT_WINDOWS
3674 if (buf == curbuf) /* first call for this flag/expansion */
3675 wp = curwin;
3676 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3677 && wp->w_buffer->b_scanned)
3679 buf = wp->w_buffer;
3680 #else
3681 buf = curbuf;
3682 #endif
3684 else
3685 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3686 * (unlisted buffers)
3687 * When completing whole lines skip unloaded buffers. */
3688 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3689 && ((flag == 'U'
3690 ? buf->b_p_bl
3691 : (!buf->b_p_bl
3692 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3693 || buf->b_scanned))
3695 return buf;
3698 #ifdef FEAT_COMPL_FUNC
3699 static void expand_by_function __ARGS((int type, char_u *base));
3702 * Execute user defined complete function 'completefunc' or 'omnifunc', and
3703 * get matches in "matches".
3705 static void
3706 expand_by_function(type, base)
3707 int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3708 char_u *base;
3710 list_T *matchlist;
3711 char_u *args[2];
3712 char_u *funcname;
3713 pos_T pos;
3715 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3716 if (*funcname == NUL)
3717 return;
3719 /* Call 'completefunc' to obtain the list of matches. */
3720 args[0] = (char_u *)"0";
3721 args[1] = base;
3723 pos = curwin->w_cursor;
3724 matchlist = call_func_retlist(funcname, 2, args, FALSE);
3725 curwin->w_cursor = pos; /* restore the cursor position */
3726 if (matchlist == NULL)
3727 return;
3729 ins_compl_add_list(matchlist);
3730 list_unref(matchlist);
3732 #endif /* FEAT_COMPL_FUNC */
3734 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
3736 * Add completions from a list.
3738 static void
3739 ins_compl_add_list(list)
3740 list_T *list;
3742 listitem_T *li;
3743 int dir = compl_direction;
3745 /* Go through the List with matches and add each of them. */
3746 for (li = list->lv_first; li != NULL; li = li->li_next)
3748 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
3749 /* if dir was BACKWARD then honor it just once */
3750 dir = FORWARD;
3751 else if (did_emsg)
3752 break;
3757 * Add a match to the list of matches from a typeval_T.
3758 * If the given string is already in the list of completions, then return
3759 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3760 * maybe because alloc() returns NULL, then FAIL is returned.
3763 ins_compl_add_tv(tv, dir)
3764 typval_T *tv;
3765 int dir;
3767 char_u *word;
3768 int icase = FALSE;
3769 int adup = FALSE;
3770 char_u *(cptext[CPT_COUNT]);
3772 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3774 word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
3775 cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
3776 (char_u *)"abbr", FALSE);
3777 cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
3778 (char_u *)"menu", FALSE);
3779 cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
3780 (char_u *)"kind", FALSE);
3781 cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
3782 (char_u *)"info", FALSE);
3783 if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
3784 icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
3785 if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
3786 adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
3788 else
3790 word = get_tv_string_chk(tv);
3791 vim_memset(cptext, 0, sizeof(cptext));
3793 if (word == NULL || *word == NUL)
3794 return FAIL;
3795 return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup);
3797 #endif
3800 * Get the next expansion(s), using "compl_pattern".
3801 * The search starts at position "ini" in curbuf and in the direction
3802 * compl_direction.
3803 * When "compl_started" is FALSE start at that position, otherwise continue
3804 * where we stopped searching before.
3805 * This may return before finding all the matches.
3806 * Return the total number of matches or -1 if still unknown -- Acevedo
3808 static int
3809 ins_compl_get_exp(ini)
3810 pos_T *ini;
3812 static pos_T first_match_pos;
3813 static pos_T last_match_pos;
3814 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
3815 static int found_all = FALSE; /* Found all matches of a
3816 certain type. */
3817 static buf_T *ins_buf = NULL; /* buffer being scanned */
3819 pos_T *pos;
3820 char_u **matches;
3821 int save_p_scs;
3822 int save_p_ws;
3823 int save_p_ic;
3824 int i;
3825 int num_matches;
3826 int len;
3827 int found_new_match;
3828 int type = ctrl_x_mode;
3829 char_u *ptr;
3830 char_u *dict = NULL;
3831 int dict_f = 0;
3832 compl_T *old_match;
3834 if (!compl_started)
3836 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
3837 ins_buf->b_scanned = 0;
3838 found_all = FALSE;
3839 ins_buf = curbuf;
3840 e_cpt = (compl_cont_status & CONT_LOCAL)
3841 ? (char_u *)"." : curbuf->b_p_cpt;
3842 last_match_pos = first_match_pos = *ini;
3845 old_match = compl_curr_match; /* remember the last current match */
3846 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3847 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
3848 for (;;)
3850 found_new_match = FAIL;
3852 /* For ^N/^P pick a new entry from e_cpt if compl_started is off,
3853 * or if found_all says this entry is done. For ^X^L only use the
3854 * entries from 'complete' that look in loaded buffers. */
3855 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3856 && (!compl_started || found_all))
3858 found_all = FALSE;
3859 while (*e_cpt == ',' || *e_cpt == ' ')
3860 e_cpt++;
3861 if (*e_cpt == '.' && !curbuf->b_scanned)
3863 ins_buf = curbuf;
3864 first_match_pos = *ini;
3865 /* So that ^N can match word immediately after cursor */
3866 if (ctrl_x_mode == 0)
3867 dec(&first_match_pos);
3868 last_match_pos = first_match_pos;
3869 type = 0;
3871 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3872 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
3874 /* Scan a buffer, but not the current one. */
3875 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
3877 compl_started = TRUE;
3878 first_match_pos.col = last_match_pos.col = 0;
3879 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
3880 last_match_pos.lnum = 0;
3881 type = 0;
3883 else /* unloaded buffer, scan like dictionary */
3885 found_all = TRUE;
3886 if (ins_buf->b_fname == NULL)
3887 continue;
3888 type = CTRL_X_DICTIONARY;
3889 dict = ins_buf->b_fname;
3890 dict_f = DICT_EXACT;
3892 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3893 ins_buf->b_fname == NULL
3894 ? buf_spname(ins_buf)
3895 : ins_buf->b_sfname == NULL
3896 ? (char *)ins_buf->b_fname
3897 : (char *)ins_buf->b_sfname);
3898 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3900 else if (*e_cpt == NUL)
3901 break;
3902 else
3904 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3905 type = -1;
3906 else if (*e_cpt == 'k' || *e_cpt == 's')
3908 if (*e_cpt == 'k')
3909 type = CTRL_X_DICTIONARY;
3910 else
3911 type = CTRL_X_THESAURUS;
3912 if (*++e_cpt != ',' && *e_cpt != NUL)
3914 dict = e_cpt;
3915 dict_f = DICT_FIRST;
3918 #ifdef FEAT_FIND_ID
3919 else if (*e_cpt == 'i')
3920 type = CTRL_X_PATH_PATTERNS;
3921 else if (*e_cpt == 'd')
3922 type = CTRL_X_PATH_DEFINES;
3923 #endif
3924 else if (*e_cpt == ']' || *e_cpt == 't')
3926 type = CTRL_X_TAGS;
3927 sprintf((char*)IObuff, _("Scanning tags."));
3928 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3930 else
3931 type = -1;
3933 /* in any case e_cpt is advanced to the next entry */
3934 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
3936 found_all = TRUE;
3937 if (type == -1)
3938 continue;
3942 switch (type)
3944 case -1:
3945 break;
3946 #ifdef FEAT_FIND_ID
3947 case CTRL_X_PATH_PATTERNS:
3948 case CTRL_X_PATH_DEFINES:
3949 find_pattern_in_path(compl_pattern, compl_direction,
3950 (int)STRLEN(compl_pattern), FALSE, FALSE,
3951 (type == CTRL_X_PATH_DEFINES
3952 && !(compl_cont_status & CONT_SOL))
3953 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
3954 (linenr_T)1, (linenr_T)MAXLNUM);
3955 break;
3956 #endif
3958 case CTRL_X_DICTIONARY:
3959 case CTRL_X_THESAURUS:
3960 ins_compl_dictionaries(
3961 dict != NULL ? dict
3962 : (type == CTRL_X_THESAURUS
3963 ? (*curbuf->b_p_tsr == NUL
3964 ? p_tsr
3965 : curbuf->b_p_tsr)
3966 : (*curbuf->b_p_dict == NUL
3967 ? p_dict
3968 : curbuf->b_p_dict)),
3969 compl_pattern,
3970 dict != NULL ? dict_f
3971 : 0, type == CTRL_X_THESAURUS);
3972 dict = NULL;
3973 break;
3975 case CTRL_X_TAGS:
3976 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
3977 save_p_ic = p_ic;
3978 p_ic = ignorecase(compl_pattern);
3980 /* Find up to TAG_MANY matches. Avoids that an enourmous number
3981 * of matches is found when compl_pattern is empty */
3982 if (find_tags(compl_pattern, &num_matches, &matches,
3983 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
3984 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
3985 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3987 ins_compl_add_matches(num_matches, matches, p_ic);
3989 p_ic = save_p_ic;
3990 break;
3992 case CTRL_X_FILES:
3993 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3994 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
3997 /* May change home directory back to "~". */
3998 tilde_replace(compl_pattern, num_matches, matches);
3999 ins_compl_add_matches(num_matches, matches,
4000 #ifdef CASE_INSENSITIVE_FILENAME
4001 TRUE
4002 #else
4003 FALSE
4004 #endif
4007 break;
4009 case CTRL_X_CMDLINE:
4010 if (expand_cmdline(&compl_xp, compl_pattern,
4011 (int)STRLEN(compl_pattern),
4012 &num_matches, &matches) == EXPAND_OK)
4013 ins_compl_add_matches(num_matches, matches, FALSE);
4014 break;
4016 #ifdef FEAT_COMPL_FUNC
4017 case CTRL_X_FUNCTION:
4018 case CTRL_X_OMNI:
4019 expand_by_function(type, compl_pattern);
4020 break;
4021 #endif
4023 case CTRL_X_SPELL:
4024 #ifdef FEAT_SPELL
4025 num_matches = expand_spelling(first_match_pos.lnum,
4026 first_match_pos.col, compl_pattern, &matches);
4027 if (num_matches > 0)
4028 ins_compl_add_matches(num_matches, matches, p_ic);
4029 #endif
4030 break;
4032 default: /* normal ^P/^N and ^X^L */
4034 * If 'infercase' is set, don't use 'smartcase' here
4036 save_p_scs = p_scs;
4037 if (ins_buf->b_p_inf)
4038 p_scs = FALSE;
4040 /* buffers other than curbuf are scanned from the beginning or the
4041 * end but never from the middle, thus setting nowrapscan in this
4042 * buffers is a good idea, on the other hand, we always set
4043 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
4044 save_p_ws = p_ws;
4045 if (ins_buf != curbuf)
4046 p_ws = FALSE;
4047 else if (*e_cpt == '.')
4048 p_ws = TRUE;
4049 for (;;)
4051 int flags = 0;
4053 ++msg_silent; /* Don't want messages for wrapscan. */
4055 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
4056 * has added a word that was at the beginning of the line */
4057 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
4058 || (compl_cont_status & CONT_SOL))
4059 found_new_match = search_for_exact_line(ins_buf, pos,
4060 compl_direction, compl_pattern);
4061 else
4062 found_new_match = searchit(NULL, ins_buf, pos,
4063 compl_direction,
4064 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
4065 RE_LAST, (linenr_T)0);
4066 --msg_silent;
4067 if (!compl_started)
4069 /* set "compl_started" even on fail */
4070 compl_started = TRUE;
4071 first_match_pos = *pos;
4072 last_match_pos = *pos;
4074 else if (first_match_pos.lnum == last_match_pos.lnum
4075 && first_match_pos.col == last_match_pos.col)
4076 found_new_match = FAIL;
4077 if (found_new_match == FAIL)
4079 if (ins_buf == curbuf)
4080 found_all = TRUE;
4081 break;
4084 /* when ADDING, the text before the cursor matches, skip it */
4085 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
4086 && ini->lnum == pos->lnum
4087 && ini->col == pos->col)
4088 continue;
4089 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
4090 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4092 if (compl_cont_status & CONT_ADDING)
4094 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
4095 continue;
4096 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4097 if (!p_paste)
4098 ptr = skipwhite(ptr);
4100 len = (int)STRLEN(ptr);
4102 else
4104 char_u *tmp_ptr = ptr;
4106 if (compl_cont_status & CONT_ADDING)
4108 tmp_ptr += compl_length;
4109 /* Skip if already inside a word. */
4110 if (vim_iswordp(tmp_ptr))
4111 continue;
4112 /* Find start of next word. */
4113 tmp_ptr = find_word_start(tmp_ptr);
4115 /* Find end of this word. */
4116 tmp_ptr = find_word_end(tmp_ptr);
4117 len = (int)(tmp_ptr - ptr);
4119 if ((compl_cont_status & CONT_ADDING)
4120 && len == compl_length)
4122 if (pos->lnum < ins_buf->b_ml.ml_line_count)
4124 /* Try next line, if any. the new word will be
4125 * "join" as if the normal command "J" was used.
4126 * IOSIZE is always greater than
4127 * compl_length, so the next STRNCPY always
4128 * works -- Acevedo */
4129 STRNCPY(IObuff, ptr, len);
4130 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4131 tmp_ptr = ptr = skipwhite(ptr);
4132 /* Find start of next word. */
4133 tmp_ptr = find_word_start(tmp_ptr);
4134 /* Find end of next word. */
4135 tmp_ptr = find_word_end(tmp_ptr);
4136 if (tmp_ptr > ptr)
4138 if (*ptr != ')' && IObuff[len - 1] != TAB)
4140 if (IObuff[len - 1] != ' ')
4141 IObuff[len++] = ' ';
4142 /* IObuf =~ "\k.* ", thus len >= 2 */
4143 if (p_js
4144 && (IObuff[len - 2] == '.'
4145 || (vim_strchr(p_cpo, CPO_JOINSP)
4146 == NULL
4147 && (IObuff[len - 2] == '?'
4148 || IObuff[len - 2] == '!'))))
4149 IObuff[len++] = ' ';
4151 /* copy as much as posible of the new word */
4152 if (tmp_ptr - ptr >= IOSIZE - len)
4153 tmp_ptr = ptr + IOSIZE - len - 1;
4154 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4155 len += (int)(tmp_ptr - ptr);
4156 flags |= CONT_S_IPOS;
4158 IObuff[len] = NUL;
4159 ptr = IObuff;
4161 if (len == compl_length)
4162 continue;
4165 if (ins_compl_add_infercase(ptr, len, p_ic,
4166 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
4167 0, flags) != NOTDONE)
4169 found_new_match = OK;
4170 break;
4173 p_scs = save_p_scs;
4174 p_ws = save_p_ws;
4177 /* check if compl_curr_match has changed, (e.g. other type of
4178 * expansion added somenthing) */
4179 if (type != 0 && compl_curr_match != old_match)
4180 found_new_match = OK;
4182 /* break the loop for specialized modes (use 'complete' just for the
4183 * generic ctrl_x_mode == 0) or when we've found a new match */
4184 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4185 || found_new_match != FAIL)
4187 if (got_int)
4188 break;
4189 /* Fill the popup menu as soon as possible. */
4190 if (type != -1)
4191 ins_compl_check_keys(0);
4193 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4194 || compl_interrupted)
4195 break;
4196 compl_started = TRUE;
4198 else
4200 /* Mark a buffer scanned when it has been scanned completely */
4201 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
4202 ins_buf->b_scanned = TRUE;
4204 compl_started = FALSE;
4207 compl_started = TRUE;
4209 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4210 && *e_cpt == NUL) /* Got to end of 'complete' */
4211 found_new_match = FAIL;
4213 i = -1; /* total of matches, unknown */
4214 if (found_new_match == FAIL
4215 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
4216 i = ins_compl_make_cyclic();
4218 /* If several matches were added (FORWARD) or the search failed and has
4219 * just been made cyclic then we have to move compl_curr_match to the next
4220 * or previous entry (if any) -- Acevedo */
4221 compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
4222 : old_match->cp_prev;
4223 if (compl_curr_match == NULL)
4224 compl_curr_match = old_match;
4225 return i;
4228 /* Delete the old text being completed. */
4229 static void
4230 ins_compl_delete()
4232 int i;
4235 * In insert mode: Delete the typed part.
4236 * In replace mode: Put the old characters back, if any.
4238 i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
4239 backspace_until_column(i);
4240 changed_cline_bef_curs();
4243 /* Insert the new text being completed. */
4244 static void
4245 ins_compl_insert()
4247 ins_bytes(compl_shown_match->cp_str + curwin->w_cursor.col - compl_col);
4248 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4249 compl_used_match = FALSE;
4250 else
4251 compl_used_match = TRUE;
4255 * Fill in the next completion in the current direction.
4256 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4257 * get more completions. If it is FALSE, then we just do nothing when there
4258 * are no more completions in a given direction. The latter case is used when
4259 * we are still in the middle of finding completions, to allow browsing
4260 * through the ones found so far.
4261 * Return the total number of matches, or -1 if still unknown -- webb.
4263 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4264 * compl_shown_match here.
4266 * Note that this function may be called recursively once only. First with
4267 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4268 * calls this function with "allow_get_expansion" FALSE.
4270 static int
4271 ins_compl_next(allow_get_expansion, count, insert_match)
4272 int allow_get_expansion;
4273 int count; /* repeat completion this many times; should
4274 be at least 1 */
4275 int insert_match; /* Insert the newly selected match */
4277 int num_matches = -1;
4278 int i;
4279 int todo = count;
4280 compl_T *found_compl = NULL;
4281 int found_end = FALSE;
4282 int advance;
4284 if (compl_leader != NULL
4285 && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4287 /* Set "compl_shown_match" to the actually shown match, it may differ
4288 * when "compl_leader" is used to omit some of the matches. */
4289 while (!ins_compl_equal(compl_shown_match,
4290 compl_leader, (int)STRLEN(compl_leader))
4291 && compl_shown_match->cp_next != NULL
4292 && compl_shown_match->cp_next != compl_first_match)
4293 compl_shown_match = compl_shown_match->cp_next;
4295 /* If we didn't find it searching forward, and compl_shows_dir is
4296 * backward, find the last match. */
4297 if (compl_shows_dir == BACKWARD
4298 && !ins_compl_equal(compl_shown_match,
4299 compl_leader, (int)STRLEN(compl_leader))
4300 && (compl_shown_match->cp_next == NULL
4301 || compl_shown_match->cp_next == compl_first_match))
4303 while (!ins_compl_equal(compl_shown_match,
4304 compl_leader, (int)STRLEN(compl_leader))
4305 && compl_shown_match->cp_prev != NULL
4306 && compl_shown_match->cp_prev != compl_first_match)
4307 compl_shown_match = compl_shown_match->cp_prev;
4311 if (allow_get_expansion && insert_match
4312 && (!(compl_get_longest || compl_restarting) || compl_used_match))
4313 /* Delete old text to be replaced */
4314 ins_compl_delete();
4316 /* When finding the longest common text we stick at the original text,
4317 * don't let CTRL-N or CTRL-P move to the first match. */
4318 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4320 /* When restarting the search don't insert the first match either. */
4321 if (compl_restarting)
4323 advance = FALSE;
4324 compl_restarting = FALSE;
4327 /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4328 * around. */
4329 while (--todo >= 0)
4331 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4333 compl_shown_match = compl_shown_match->cp_next;
4334 found_end = (compl_first_match != NULL
4335 && (compl_shown_match->cp_next == compl_first_match
4336 || compl_shown_match == compl_first_match));
4338 else if (compl_shows_dir == BACKWARD
4339 && compl_shown_match->cp_prev != NULL)
4341 found_end = (compl_shown_match == compl_first_match);
4342 compl_shown_match = compl_shown_match->cp_prev;
4343 found_end |= (compl_shown_match == compl_first_match);
4345 else
4347 if (!allow_get_expansion)
4349 if (advance)
4351 if (compl_shows_dir == BACKWARD)
4352 compl_pending -= todo + 1;
4353 else
4354 compl_pending += todo + 1;
4356 return -1;
4359 if (advance)
4361 if (compl_shows_dir == BACKWARD)
4362 --compl_pending;
4363 else
4364 ++compl_pending;
4367 /* Find matches. */
4368 num_matches = ins_compl_get_exp(&compl_startpos);
4370 /* handle any pending completions */
4371 while (compl_pending != 0 && compl_direction == compl_shows_dir
4372 && advance)
4374 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4376 compl_shown_match = compl_shown_match->cp_next;
4377 --compl_pending;
4379 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4381 compl_shown_match = compl_shown_match->cp_prev;
4382 ++compl_pending;
4384 else
4385 break;
4387 found_end = FALSE;
4389 if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4390 && compl_leader != NULL
4391 && !ins_compl_equal(compl_shown_match,
4392 compl_leader, (int)STRLEN(compl_leader)))
4393 ++todo;
4394 else
4395 /* Remember a matching item. */
4396 found_compl = compl_shown_match;
4398 /* Stop at the end of the list when we found a usable match. */
4399 if (found_end)
4401 if (found_compl != NULL)
4403 compl_shown_match = found_compl;
4404 break;
4406 todo = 1; /* use first usable match after wrapping around */
4410 /* Insert the text of the new completion, or the compl_leader. */
4411 if (insert_match)
4413 if (!compl_get_longest || compl_used_match)
4414 ins_compl_insert();
4415 else
4416 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
4418 else
4419 compl_used_match = FALSE;
4421 if (!allow_get_expansion)
4423 /* may undisplay the popup menu first */
4424 ins_compl_upd_pum();
4426 /* redraw to show the user what was inserted */
4427 update_screen(0);
4429 /* display the updated popup menu */
4430 ins_compl_show_pum();
4431 #ifdef FEAT_GUI
4432 if (gui.in_use)
4434 /* Show the cursor after the match, not after the redrawn text. */
4435 setcursor();
4436 out_flush();
4437 gui_update_cursor(FALSE, FALSE);
4439 #endif
4441 /* Delete old text to be replaced, since we're still searching and
4442 * don't want to match ourselves! */
4443 ins_compl_delete();
4446 /* Enter will select a match when the match wasn't inserted and the popup
4447 * menu is visible. */
4448 compl_enter_selects = !insert_match && compl_match_array != NULL;
4451 * Show the file name for the match (if any)
4452 * Truncate the file name to avoid a wait for return.
4454 if (compl_shown_match->cp_fname != NULL)
4456 STRCPY(IObuff, "match in file ");
4457 i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4458 if (i <= 0)
4459 i = 0;
4460 else
4461 STRCAT(IObuff, "<");
4462 STRCAT(IObuff, compl_shown_match->cp_fname + i);
4463 msg(IObuff);
4464 redraw_cmdline = FALSE; /* don't overwrite! */
4467 return num_matches;
4471 * Call this while finding completions, to check whether the user has hit a key
4472 * that should change the currently displayed completion, or exit completion
4473 * mode. Also, when compl_pending is not zero, show a completion as soon as
4474 * possible. -- webb
4475 * "frequency" specifies out of how many calls we actually check.
4477 void
4478 ins_compl_check_keys(frequency)
4479 int frequency;
4481 static int count = 0;
4483 int c;
4485 /* Don't check when reading keys from a script. That would break the test
4486 * scripts */
4487 if (using_script())
4488 return;
4490 /* Only do this at regular intervals */
4491 if (++count < frequency)
4492 return;
4493 count = 0;
4495 /* Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4496 * can't do its work correctly. */
4497 c = vpeekc_any();
4498 if (c != NUL)
4500 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4502 c = safe_vgetc(); /* Eat the character */
4503 compl_shows_dir = ins_compl_key2dir(c);
4504 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4505 c != K_UP && c != K_DOWN);
4507 else
4509 /* Need to get the character to have KeyTyped set. We'll put it
4510 * back with vungetc() below. */
4511 c = safe_vgetc();
4513 /* Don't interrupt completion when the character wasn't typed,
4514 * e.g., when doing @q to replay keys. */
4515 if (c != Ctrl_R && KeyTyped)
4516 compl_interrupted = TRUE;
4518 vungetc(c);
4521 if (compl_pending != 0 && !got_int)
4523 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4525 compl_pending = 0;
4526 (void)ins_compl_next(FALSE, todo, TRUE);
4531 * Decide the direction of Insert mode complete from the key typed.
4532 * Returns BACKWARD or FORWARD.
4534 static int
4535 ins_compl_key2dir(c)
4536 int c;
4538 if (c == Ctrl_P || c == Ctrl_L
4539 || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4540 || c == K_S_UP || c == K_UP)))
4541 return BACKWARD;
4542 return FORWARD;
4546 * Return TRUE for keys that are used for completion only when the popup menu
4547 * is visible.
4549 static int
4550 ins_compl_pum_key(c)
4551 int c;
4553 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4554 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4555 || c == K_UP || c == K_DOWN);
4559 * Decide the number of completions to move forward.
4560 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4562 static int
4563 ins_compl_key2count(c)
4564 int c;
4566 int h;
4568 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4570 h = pum_get_height();
4571 if (h > 3)
4572 h -= 2; /* keep some context */
4573 return h;
4575 return 1;
4579 * Return TRUE if completion with "c" should insert the match, FALSE if only
4580 * to change the currently selected completion.
4582 static int
4583 ins_compl_use_match(c)
4584 int c;
4586 switch (c)
4588 case K_UP:
4589 case K_DOWN:
4590 case K_PAGEDOWN:
4591 case K_KPAGEDOWN:
4592 case K_S_DOWN:
4593 case K_PAGEUP:
4594 case K_KPAGEUP:
4595 case K_S_UP:
4596 return FALSE;
4598 return TRUE;
4602 * Do Insert mode completion.
4603 * Called when character "c" was typed, which has a meaning for completion.
4604 * Returns OK if completion was done, FAIL if something failed (out of mem).
4606 static int
4607 ins_complete(c)
4608 int c;
4610 char_u *line;
4611 int startcol = 0; /* column where searched text starts */
4612 colnr_T curs_col; /* cursor column */
4613 int n;
4615 compl_direction = ins_compl_key2dir(c);
4616 if (!compl_started)
4618 /* First time we hit ^N or ^P (in a row, I mean) */
4620 did_ai = FALSE;
4621 #ifdef FEAT_SMARTINDENT
4622 did_si = FALSE;
4623 can_si = FALSE;
4624 can_si_back = FALSE;
4625 #endif
4626 if (stop_arrow() == FAIL)
4627 return FAIL;
4629 line = ml_get(curwin->w_cursor.lnum);
4630 curs_col = curwin->w_cursor.col;
4631 compl_pending = 0;
4633 /* If this same ctrl_x_mode has been interrupted use the text from
4634 * "compl_startpos" to the cursor as a pattern to add a new word
4635 * instead of expand the one before the cursor, in word-wise if
4636 * "compl_startpos" is not in the same line as the cursor then fix it
4637 * (the line has been split because it was longer than 'tw'). if SOL
4638 * is set then skip the previous pattern, a word at the beginning of
4639 * the line has been inserted, we'll look for that -- Acevedo. */
4640 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4641 && compl_cont_mode == ctrl_x_mode)
4644 * it is a continued search
4646 compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */
4647 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4648 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4650 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4652 /* line (probably) wrapped, set compl_startpos to the
4653 * first non_blank in the line, if it is not a wordchar
4654 * include it to get a better pattern, but then we don't
4655 * want the "\\<" prefix, check it bellow */
4656 compl_col = (colnr_T)(skipwhite(line) - line);
4657 compl_startpos.col = compl_col;
4658 compl_startpos.lnum = curwin->w_cursor.lnum;
4659 compl_cont_status &= ~CONT_SOL; /* clear SOL if present */
4661 else
4663 /* S_IPOS was set when we inserted a word that was at the
4664 * beginning of the line, which means that we'll go to SOL
4665 * mode but first we need to redefine compl_startpos */
4666 if (compl_cont_status & CONT_S_IPOS)
4668 compl_cont_status |= CONT_SOL;
4669 compl_startpos.col = (colnr_T)(skipwhite(
4670 line + compl_length
4671 + compl_startpos.col) - line);
4673 compl_col = compl_startpos.col;
4675 compl_length = curwin->w_cursor.col - (int)compl_col;
4676 /* IObuff is used to add a "word from the next line" would we
4677 * have enough space? just being paranoic */
4678 #define MIN_SPACE 75
4679 if (compl_length > (IOSIZE - MIN_SPACE))
4681 compl_cont_status &= ~CONT_SOL;
4682 compl_length = (IOSIZE - MIN_SPACE);
4683 compl_col = curwin->w_cursor.col - compl_length;
4685 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4686 if (compl_length < 1)
4687 compl_cont_status &= CONT_LOCAL;
4689 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4690 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4691 else
4692 compl_cont_status = 0;
4694 else
4695 compl_cont_status &= CONT_LOCAL;
4697 if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */
4699 compl_cont_mode = ctrl_x_mode;
4700 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
4701 compl_cont_status = 0;
4702 compl_cont_status |= CONT_N_ADDS;
4703 compl_startpos = curwin->w_cursor;
4704 startcol = (int)curs_col;
4705 compl_col = 0;
4708 /* Work out completion pattern and original text -- webb */
4709 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
4711 if ((compl_cont_status & CONT_SOL)
4712 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4714 if (!(compl_cont_status & CONT_ADDING))
4716 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4718 compl_col += ++startcol;
4719 compl_length = curs_col - startcol;
4721 if (p_ic)
4722 compl_pattern = str_foldcase(line + compl_col,
4723 compl_length, NULL, 0);
4724 else
4725 compl_pattern = vim_strnsave(line + compl_col,
4726 compl_length);
4727 if (compl_pattern == NULL)
4728 return FAIL;
4730 else if (compl_cont_status & CONT_ADDING)
4732 char_u *prefix = (char_u *)"\\<";
4734 /* we need 3 extra chars, 1 for the NUL and
4735 * 2 >= strlen(prefix) -- Acevedo */
4736 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4737 compl_length) + 3);
4738 if (compl_pattern == NULL)
4739 return FAIL;
4740 if (!vim_iswordp(line + compl_col)
4741 || (compl_col > 0
4742 && (
4743 #ifdef FEAT_MBYTE
4744 vim_iswordp(mb_prevptr(line, line + compl_col))
4745 #else
4746 vim_iswordc(line[compl_col - 1])
4747 #endif
4749 prefix = (char_u *)"";
4750 STRCPY((char *)compl_pattern, prefix);
4751 (void)quote_meta(compl_pattern + STRLEN(prefix),
4752 line + compl_col, compl_length);
4754 else if (--startcol < 0 ||
4755 #ifdef FEAT_MBYTE
4756 !vim_iswordp(mb_prevptr(line, line + startcol + 1))
4757 #else
4758 !vim_iswordc(line[startcol])
4759 #endif
4762 /* Match any word of at least two chars */
4763 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4764 if (compl_pattern == NULL)
4765 return FAIL;
4766 compl_col += curs_col;
4767 compl_length = 0;
4769 else
4771 #ifdef FEAT_MBYTE
4772 /* Search the point of change class of multibyte character
4773 * or not a word single byte character backward. */
4774 if (has_mbyte)
4776 int base_class;
4777 int head_off;
4779 startcol -= (*mb_head_off)(line, line + startcol);
4780 base_class = mb_get_class(line + startcol);
4781 while (--startcol >= 0)
4783 head_off = (*mb_head_off)(line, line + startcol);
4784 if (base_class != mb_get_class(line + startcol
4785 - head_off))
4786 break;
4787 startcol -= head_off;
4790 else
4791 #endif
4792 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4794 compl_col += ++startcol;
4795 compl_length = (int)curs_col - startcol;
4796 if (compl_length == 1)
4798 /* Only match word with at least two chars -- webb
4799 * there's no need to call quote_meta,
4800 * alloc(7) is enough -- Acevedo
4802 compl_pattern = alloc(7);
4803 if (compl_pattern == NULL)
4804 return FAIL;
4805 STRCPY((char *)compl_pattern, "\\<");
4806 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4807 STRCAT((char *)compl_pattern, "\\k");
4809 else
4811 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4812 compl_length) + 3);
4813 if (compl_pattern == NULL)
4814 return FAIL;
4815 STRCPY((char *)compl_pattern, "\\<");
4816 (void)quote_meta(compl_pattern + 2, line + compl_col,
4817 compl_length);
4821 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4823 compl_col = (colnr_T)(skipwhite(line) - line);
4824 compl_length = (int)curs_col - (int)compl_col;
4825 if (compl_length < 0) /* cursor in indent: empty pattern */
4826 compl_length = 0;
4827 if (p_ic)
4828 compl_pattern = str_foldcase(line + compl_col, compl_length,
4829 NULL, 0);
4830 else
4831 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4832 if (compl_pattern == NULL)
4833 return FAIL;
4835 else if (ctrl_x_mode == CTRL_X_FILES)
4837 while (--startcol >= 0 && vim_isfilec(line[startcol]))
4839 compl_col += ++startcol;
4840 compl_length = (int)curs_col - startcol;
4841 compl_pattern = addstar(line + compl_col, compl_length,
4842 EXPAND_FILES);
4843 if (compl_pattern == NULL)
4844 return FAIL;
4846 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4848 compl_pattern = vim_strnsave(line, curs_col);
4849 if (compl_pattern == NULL)
4850 return FAIL;
4851 set_cmd_context(&compl_xp, compl_pattern,
4852 (int)STRLEN(compl_pattern), curs_col);
4853 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4854 || compl_xp.xp_context == EXPAND_NOTHING)
4855 /* No completion possible, use an empty pattern to get a
4856 * "pattern not found" message. */
4857 compl_col = curs_col;
4858 else
4859 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4860 compl_length = curs_col - compl_col;
4862 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
4864 #ifdef FEAT_COMPL_FUNC
4866 * Call user defined function 'completefunc' with "a:findstart"
4867 * set to 1 to obtain the length of text to use for completion.
4869 char_u *args[2];
4870 int col;
4871 char_u *funcname;
4872 pos_T pos;
4874 /* Call 'completefunc' or 'omnifunc' and get pattern length as a
4875 * string */
4876 funcname = ctrl_x_mode == CTRL_X_FUNCTION
4877 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
4878 if (*funcname == NUL)
4880 EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4881 ? "completefunc" : "omnifunc");
4882 return FAIL;
4885 args[0] = (char_u *)"1";
4886 args[1] = NULL;
4887 pos = curwin->w_cursor;
4888 col = call_func_retnr(funcname, 2, args, FALSE);
4889 curwin->w_cursor = pos; /* restore the cursor position */
4891 if (col < 0)
4892 col = curs_col;
4893 compl_col = col;
4894 if ((colnr_T)compl_col > curs_col)
4895 compl_col = curs_col;
4897 /* Setup variables for completion. Need to obtain "line" again,
4898 * it may have become invalid. */
4899 line = ml_get(curwin->w_cursor.lnum);
4900 compl_length = curs_col - compl_col;
4901 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4902 if (compl_pattern == NULL)
4903 #endif
4904 return FAIL;
4906 else if (ctrl_x_mode == CTRL_X_SPELL)
4908 #ifdef FEAT_SPELL
4909 if (spell_bad_len > 0)
4910 compl_col = curs_col - spell_bad_len;
4911 else
4912 compl_col = spell_word_start(startcol);
4913 if (compl_col >= (colnr_T)startcol)
4915 compl_length = 0;
4916 compl_col = curs_col;
4918 else
4920 spell_expand_check_cap(compl_col);
4921 compl_length = (int)curs_col - compl_col;
4923 /* Need to obtain "line" again, it may have become invalid. */
4924 line = ml_get(curwin->w_cursor.lnum);
4925 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4926 if (compl_pattern == NULL)
4927 #endif
4928 return FAIL;
4930 else
4932 EMSG2(_(e_intern2), "ins_complete()");
4933 return FAIL;
4936 if (compl_cont_status & CONT_ADDING)
4938 edit_submode_pre = (char_u *)_(" Adding");
4939 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4941 /* Insert a new line, keep indentation but ignore 'comments' */
4942 #ifdef FEAT_COMMENTS
4943 char_u *old = curbuf->b_p_com;
4945 curbuf->b_p_com = (char_u *)"";
4946 #endif
4947 compl_startpos.lnum = curwin->w_cursor.lnum;
4948 compl_startpos.col = compl_col;
4949 ins_eol('\r');
4950 #ifdef FEAT_COMMENTS
4951 curbuf->b_p_com = old;
4952 #endif
4953 compl_length = 0;
4954 compl_col = curwin->w_cursor.col;
4957 else
4959 edit_submode_pre = NULL;
4960 compl_startpos.col = compl_col;
4963 if (compl_cont_status & CONT_LOCAL)
4964 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
4965 else
4966 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
4968 /* Always add completion for the original text. */
4969 vim_free(compl_orig_text);
4970 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
4971 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
4972 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
4974 vim_free(compl_pattern);
4975 compl_pattern = NULL;
4976 vim_free(compl_orig_text);
4977 compl_orig_text = NULL;
4978 return FAIL;
4981 /* showmode might reset the internal line pointers, so it must
4982 * be called before line = ml_get(), or when this address is no
4983 * longer needed. -- Acevedo.
4985 edit_submode_extra = (char_u *)_("-- Searching...");
4986 edit_submode_highl = HLF_COUNT;
4987 showmode();
4988 edit_submode_extra = NULL;
4989 out_flush();
4992 compl_shown_match = compl_curr_match;
4993 compl_shows_dir = compl_direction;
4996 * Find next match (and following matches).
4998 n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
5000 /* may undisplay the popup menu */
5001 ins_compl_upd_pum();
5003 if (n > 1) /* all matches have been found */
5004 compl_matches = n;
5005 compl_curr_match = compl_shown_match;
5006 compl_direction = compl_shows_dir;
5008 /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5009 * mode. */
5010 if (got_int && !global_busy)
5012 (void)vgetc();
5013 got_int = FALSE;
5016 /* we found no match if the list has only the "compl_orig_text"-entry */
5017 if (compl_first_match == compl_first_match->cp_next)
5019 edit_submode_extra = (compl_cont_status & CONT_ADDING)
5020 && compl_length > 1
5021 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
5022 edit_submode_highl = HLF_E;
5023 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5024 * because we couldn't expand anything at first place, but if we used
5025 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5026 * (such as M in M'exico) if not tried already. -- Acevedo */
5027 if ( compl_length > 1
5028 || (compl_cont_status & CONT_ADDING)
5029 || (ctrl_x_mode != 0
5030 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
5031 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
5032 compl_cont_status &= ~CONT_N_ADDS;
5035 if (compl_curr_match->cp_flags & CONT_S_IPOS)
5036 compl_cont_status |= CONT_S_IPOS;
5037 else
5038 compl_cont_status &= ~CONT_S_IPOS;
5040 if (edit_submode_extra == NULL)
5042 if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
5044 edit_submode_extra = (char_u *)_("Back at original");
5045 edit_submode_highl = HLF_W;
5047 else if (compl_cont_status & CONT_S_IPOS)
5049 edit_submode_extra = (char_u *)_("Word from other line");
5050 edit_submode_highl = HLF_COUNT;
5052 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5054 edit_submode_extra = (char_u *)_("The only match");
5055 edit_submode_highl = HLF_COUNT;
5057 else
5059 /* Update completion sequence number when needed. */
5060 if (compl_curr_match->cp_number == -1)
5062 int number = 0;
5063 compl_T *match;
5065 if (compl_direction == FORWARD)
5067 /* search backwards for the first valid (!= -1) number.
5068 * This should normally succeed already at the first loop
5069 * cycle, so it's fast! */
5070 for (match = compl_curr_match->cp_prev; match != NULL
5071 && match != compl_first_match;
5072 match = match->cp_prev)
5073 if (match->cp_number != -1)
5075 number = match->cp_number;
5076 break;
5078 if (match != NULL)
5079 /* go up and assign all numbers which are not assigned
5080 * yet */
5081 for (match = match->cp_next;
5082 match != NULL && match->cp_number == -1;
5083 match = match->cp_next)
5084 match->cp_number = ++number;
5086 else /* BACKWARD */
5088 /* search forwards (upwards) for the first valid (!= -1)
5089 * number. This should normally succeed already at the
5090 * first loop cycle, so it's fast! */
5091 for (match = compl_curr_match->cp_next; match != NULL
5092 && match != compl_first_match;
5093 match = match->cp_next)
5094 if (match->cp_number != -1)
5096 number = match->cp_number;
5097 break;
5099 if (match != NULL)
5100 /* go down and assign all numbers which are not
5101 * assigned yet */
5102 for (match = match->cp_prev; match
5103 && match->cp_number == -1;
5104 match = match->cp_prev)
5105 match->cp_number = ++number;
5109 /* The match should always have a sequence number now, this is
5110 * just a safety check. */
5111 if (compl_curr_match->cp_number != -1)
5113 /* Space for 10 text chars. + 2x10-digit no.s = 31.
5114 * Translations may need more than twice that. */
5115 static char_u match_ref[81];
5117 if (compl_matches > 0)
5118 vim_snprintf((char *)match_ref, sizeof(match_ref),
5119 _("match %d of %d"),
5120 compl_curr_match->cp_number, compl_matches);
5121 else
5122 vim_snprintf((char *)match_ref, sizeof(match_ref),
5123 _("match %d"),
5124 compl_curr_match->cp_number);
5125 edit_submode_extra = match_ref;
5126 edit_submode_highl = HLF_R;
5127 if (dollar_vcol)
5128 curs_columns(FALSE);
5133 /* Show a message about what (completion) mode we're in. */
5134 showmode();
5135 if (edit_submode_extra != NULL)
5137 if (!p_smd)
5138 msg_attr(edit_submode_extra,
5139 edit_submode_highl < HLF_COUNT
5140 ? hl_attr(edit_submode_highl) : 0);
5142 else
5143 msg_clr_cmdline(); /* necessary for "noshowmode" */
5145 /* Show the popup menu, unless we got interrupted. */
5146 if (!compl_interrupted)
5148 /* RedrawingDisabled may be set when invoked through complete(). */
5149 n = RedrawingDisabled;
5150 RedrawingDisabled = 0;
5151 ins_compl_show_pum();
5152 setcursor();
5153 RedrawingDisabled = n;
5155 compl_was_interrupted = compl_interrupted;
5156 compl_interrupted = FALSE;
5158 return OK;
5162 * Looks in the first "len" chars. of "src" for search-metachars.
5163 * If dest is not NULL the chars. are copied there quoting (with
5164 * a backslash) the metachars, and dest would be NUL terminated.
5165 * Returns the length (needed) of dest
5167 static int
5168 quote_meta(dest, src, len)
5169 char_u *dest;
5170 char_u *src;
5171 int len;
5173 int m;
5175 for (m = len; --len >= 0; src++)
5177 switch (*src)
5179 case '.':
5180 case '*':
5181 case '[':
5182 if (ctrl_x_mode == CTRL_X_DICTIONARY
5183 || ctrl_x_mode == CTRL_X_THESAURUS)
5184 break;
5185 case '~':
5186 if (!p_magic) /* quote these only if magic is set */
5187 break;
5188 case '\\':
5189 if (ctrl_x_mode == CTRL_X_DICTIONARY
5190 || ctrl_x_mode == CTRL_X_THESAURUS)
5191 break;
5192 case '^': /* currently it's not needed. */
5193 case '$':
5194 m++;
5195 if (dest != NULL)
5196 *dest++ = '\\';
5197 break;
5199 if (dest != NULL)
5200 *dest++ = *src;
5201 # ifdef FEAT_MBYTE
5202 /* Copy remaining bytes of a multibyte character. */
5203 if (has_mbyte)
5205 int i, mb_len;
5207 mb_len = (*mb_ptr2len)(src) - 1;
5208 if (mb_len > 0 && len >= mb_len)
5209 for (i = 0; i < mb_len; ++i)
5211 --len;
5212 ++src;
5213 if (dest != NULL)
5214 *dest++ = *src;
5217 # endif
5219 if (dest != NULL)
5220 *dest = NUL;
5222 return m;
5224 #endif /* FEAT_INS_EXPAND */
5227 * Next character is interpreted literally.
5228 * A one, two or three digit decimal number is interpreted as its byte value.
5229 * If one or two digits are entered, the next character is given to vungetc().
5230 * For Unicode a character > 255 may be returned.
5233 get_literal()
5235 int cc;
5236 int nc;
5237 int i;
5238 int hex = FALSE;
5239 int octal = FALSE;
5240 #ifdef FEAT_MBYTE
5241 int unicode = 0;
5242 #endif
5244 if (got_int)
5245 return Ctrl_C;
5247 #ifdef FEAT_GUI
5249 * In GUI there is no point inserting the internal code for a special key.
5250 * It is more useful to insert the string "<KEY>" instead. This would
5251 * probably be useful in a text window too, but it would not be
5252 * vi-compatible (maybe there should be an option for it?) -- webb
5254 if (gui.in_use)
5255 ++allow_keys;
5256 #endif
5257 #ifdef USE_ON_FLY_SCROLL
5258 dont_scroll = TRUE; /* disallow scrolling here */
5259 #endif
5260 ++no_mapping; /* don't map the next key hits */
5261 cc = 0;
5262 i = 0;
5263 for (;;)
5265 nc = plain_vgetc();
5266 #ifdef FEAT_CMDL_INFO
5267 if (!(State & CMDLINE)
5268 # ifdef FEAT_MBYTE
5269 && MB_BYTE2LEN_CHECK(nc) == 1
5270 # endif
5272 add_to_showcmd(nc);
5273 #endif
5274 if (nc == 'x' || nc == 'X')
5275 hex = TRUE;
5276 else if (nc == 'o' || nc == 'O')
5277 octal = TRUE;
5278 #ifdef FEAT_MBYTE
5279 else if (nc == 'u' || nc == 'U')
5280 unicode = nc;
5281 #endif
5282 else
5284 if (hex
5285 #ifdef FEAT_MBYTE
5286 || unicode != 0
5287 #endif
5290 if (!vim_isxdigit(nc))
5291 break;
5292 cc = cc * 16 + hex2nr(nc);
5294 else if (octal)
5296 if (nc < '0' || nc > '7')
5297 break;
5298 cc = cc * 8 + nc - '0';
5300 else
5302 if (!VIM_ISDIGIT(nc))
5303 break;
5304 cc = cc * 10 + nc - '0';
5307 ++i;
5310 if (cc > 255
5311 #ifdef FEAT_MBYTE
5312 && unicode == 0
5313 #endif
5315 cc = 255; /* limit range to 0-255 */
5316 nc = 0;
5318 if (hex) /* hex: up to two chars */
5320 if (i >= 2)
5321 break;
5323 #ifdef FEAT_MBYTE
5324 else if (unicode) /* Unicode: up to four or eight chars */
5326 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
5327 break;
5329 #endif
5330 else if (i >= 3) /* decimal or octal: up to three chars */
5331 break;
5333 if (i == 0) /* no number entered */
5335 if (nc == K_ZERO) /* NUL is stored as NL */
5337 cc = '\n';
5338 nc = 0;
5340 else
5342 cc = nc;
5343 nc = 0;
5347 if (cc == 0) /* NUL is stored as NL */
5348 cc = '\n';
5349 #ifdef FEAT_MBYTE
5350 if (enc_dbcs && (cc & 0xff) == 0)
5351 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
5352 second byte will cause trouble! */
5353 #endif
5355 --no_mapping;
5356 #ifdef FEAT_GUI
5357 if (gui.in_use)
5358 --allow_keys;
5359 #endif
5360 if (nc)
5361 vungetc(nc);
5362 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
5363 return cc;
5367 * Insert character, taking care of special keys and mod_mask
5369 static void
5370 insert_special(c, allow_modmask, ctrlv)
5371 int c;
5372 int allow_modmask;
5373 int ctrlv; /* c was typed after CTRL-V */
5375 char_u *p;
5376 int len;
5379 * Special function key, translate into "<Key>". Up to the last '>' is
5380 * inserted with ins_str(), so as not to replace characters in replace
5381 * mode.
5382 * Only use mod_mask for special keys, to avoid things like <S-Space>,
5383 * unless 'allow_modmask' is TRUE.
5385 #ifdef MACOS
5386 /* Command-key never produces a normal key */
5387 if (mod_mask & MOD_MASK_CMD)
5388 allow_modmask = TRUE;
5389 #endif
5390 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5392 p = get_special_key_name(c, mod_mask);
5393 len = (int)STRLEN(p);
5394 c = p[len - 1];
5395 if (len > 2)
5397 if (stop_arrow() == FAIL)
5398 return;
5399 p[len - 1] = NUL;
5400 ins_str(p);
5401 AppendToRedobuffLit(p, -1);
5402 ctrlv = FALSE;
5405 if (stop_arrow() == OK)
5406 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5410 * Special characters in this context are those that need processing other
5411 * than the simple insertion that can be performed here. This includes ESC
5412 * which terminates the insert, and CR/NL which need special processing to
5413 * open up a new line. This routine tries to optimize insertions performed by
5414 * the "redo", "undo" or "put" commands, so it needs to know when it should
5415 * stop and defer processing to the "normal" mechanism.
5416 * '0' and '^' are special, because they can be followed by CTRL-D.
5418 #ifdef EBCDIC
5419 # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
5420 #else
5421 # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5422 #endif
5424 #ifdef FEAT_MBYTE
5425 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5426 #else
5427 # define WHITECHAR(cc) vim_iswhite(cc)
5428 #endif
5430 void
5431 insertchar(c, flags, second_indent)
5432 int c; /* character to insert or NUL */
5433 int flags; /* INSCHAR_FORMAT, etc. */
5434 int second_indent; /* indent for second line if >= 0 */
5436 int textwidth;
5437 #ifdef FEAT_COMMENTS
5438 char_u *p;
5439 #endif
5440 int fo_ins_blank;
5442 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5443 fo_ins_blank = has_format_option(FO_INS_BLANK);
5446 * Try to break the line in two or more pieces when:
5447 * - Always do this if we have been called to do formatting only.
5448 * - Always do this when 'formatoptions' has the 'a' flag and the line
5449 * ends in white space.
5450 * - Otherwise:
5451 * - Don't do this if inserting a blank
5452 * - Don't do this if an existing character is being replaced, unless
5453 * we're in VREPLACE mode.
5454 * - Do this if the cursor is not on the line where insert started
5455 * or - 'formatoptions' doesn't have 'l' or the line was not too long
5456 * before the insert.
5457 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5458 * before 'textwidth'
5460 if (textwidth > 0
5461 && ((flags & INSCHAR_FORMAT)
5462 || (!vim_iswhite(c)
5463 && !((State & REPLACE_FLAG)
5464 #ifdef FEAT_VREPLACE
5465 && !(State & VREPLACE_FLAG)
5466 #endif
5467 && *ml_get_cursor() != NUL)
5468 && (curwin->w_cursor.lnum != Insstart.lnum
5469 || ((!has_format_option(FO_INS_LONG)
5470 || Insstart_textlen <= (colnr_T)textwidth)
5471 && (!fo_ins_blank
5472 || Insstart_blank_vcol <= (colnr_T)textwidth
5473 ))))))
5475 /* Format with 'formatexpr' when it's set. Use internal formatting
5476 * when 'formatexpr' isn't set or it returns non-zero. */
5477 #if defined(FEAT_EVAL)
5478 int do_internal = TRUE;
5480 if (*curbuf->b_p_fex != NUL)
5482 do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0);
5483 /* It may be required to save for undo again, e.g. when setline()
5484 * was called. */
5485 ins_need_undo = TRUE;
5487 if (do_internal)
5488 #endif
5489 internal_format(textwidth, second_indent, flags, c == NUL);
5492 if (c == NUL) /* only formatting was wanted */
5493 return;
5495 #ifdef FEAT_COMMENTS
5496 /* Check whether this character should end a comment. */
5497 if (did_ai && (int)c == end_comment_pending)
5499 char_u *line;
5500 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5501 int middle_len, end_len;
5502 int i;
5505 * Need to remove existing (middle) comment leader and insert end
5506 * comment leader. First, check what comment leader we can find.
5508 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
5509 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
5511 /* Skip middle-comment string */
5512 while (*p && p[-1] != ':') /* find end of middle flags */
5513 ++p;
5514 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5515 /* Don't count trailing white space for middle_len */
5516 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5517 --middle_len;
5519 /* Find the end-comment string */
5520 while (*p && p[-1] != ':') /* find end of end flags */
5521 ++p;
5522 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5524 /* Skip white space before the cursor */
5525 i = curwin->w_cursor.col;
5526 while (--i >= 0 && vim_iswhite(line[i]))
5528 i++;
5530 /* Skip to before the middle leader */
5531 i -= middle_len;
5533 /* Check some expected things before we go on */
5534 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5536 /* Backspace over all the stuff we want to replace */
5537 backspace_until_column(i);
5540 * Insert the end-comment string, except for the last
5541 * character, which will get inserted as normal later.
5543 ins_bytes_len(lead_end, end_len - 1);
5547 end_comment_pending = NUL;
5548 #endif
5550 did_ai = FALSE;
5551 #ifdef FEAT_SMARTINDENT
5552 did_si = FALSE;
5553 can_si = FALSE;
5554 can_si_back = FALSE;
5555 #endif
5558 * If there's any pending input, grab up to INPUT_BUFLEN at once.
5559 * This speeds up normal text input considerably.
5560 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5561 * need to re-indent at a ':', or any other character (but not what
5562 * 'paste' is set)..
5564 #ifdef USE_ON_FLY_SCROLL
5565 dont_scroll = FALSE; /* allow scrolling here */
5566 #endif
5568 if ( !ISSPECIAL(c)
5569 #ifdef FEAT_MBYTE
5570 && (!has_mbyte || (*mb_char2len)(c) == 1)
5571 #endif
5572 && vpeekc() != NUL
5573 && !(State & REPLACE_FLAG)
5574 #ifdef FEAT_CINDENT
5575 && !cindent_on()
5576 #endif
5577 #ifdef FEAT_RIGHTLEFT
5578 && !p_ri
5579 #endif
5582 #define INPUT_BUFLEN 100
5583 char_u buf[INPUT_BUFLEN + 1];
5584 int i;
5585 colnr_T virtcol = 0;
5587 buf[0] = c;
5588 i = 1;
5589 if (textwidth > 0)
5590 virtcol = get_nolist_virtcol();
5592 * Stop the string when:
5593 * - no more chars available
5594 * - finding a special character (command key)
5595 * - buffer is full
5596 * - running into the 'textwidth' boundary
5597 * - need to check for abbreviation: A non-word char after a word-char
5599 while ( (c = vpeekc()) != NUL
5600 && !ISSPECIAL(c)
5601 #ifdef FEAT_MBYTE
5602 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5603 #endif
5604 && i < INPUT_BUFLEN
5605 && (textwidth == 0
5606 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5607 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5609 #ifdef FEAT_RIGHTLEFT
5610 c = vgetc();
5611 if (p_hkmap && KeyTyped)
5612 c = hkmap(c); /* Hebrew mode mapping */
5613 # ifdef FEAT_FKMAP
5614 if (p_fkmap && KeyTyped)
5615 c = fkmap(c); /* Farsi mode mapping */
5616 # endif
5617 buf[i++] = c;
5618 #else
5619 buf[i++] = vgetc();
5620 #endif
5623 #ifdef FEAT_DIGRAPHS
5624 do_digraph(-1); /* clear digraphs */
5625 do_digraph(buf[i-1]); /* may be the start of a digraph */
5626 #endif
5627 buf[i] = NUL;
5628 ins_str(buf);
5629 if (flags & INSCHAR_CTRLV)
5631 redo_literal(*buf);
5632 i = 1;
5634 else
5635 i = 0;
5636 if (buf[i] != NUL)
5637 AppendToRedobuffLit(buf + i, -1);
5639 else
5641 #ifdef FEAT_MBYTE
5642 int cc;
5644 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
5646 char_u buf[MB_MAXBYTES + 1];
5648 (*mb_char2bytes)(c, buf);
5649 buf[cc] = NUL;
5650 ins_char_bytes(buf, cc);
5651 AppendCharToRedobuff(c);
5653 else
5654 #endif
5656 ins_char(c);
5657 if (flags & INSCHAR_CTRLV)
5658 redo_literal(c);
5659 else
5660 AppendCharToRedobuff(c);
5666 * Format text at the current insert position.
5668 static void
5669 internal_format(textwidth, second_indent, flags, format_only)
5670 int textwidth;
5671 int second_indent;
5672 int flags;
5673 int format_only;
5675 int cc;
5676 int save_char = NUL;
5677 int haveto_redraw = FALSE;
5678 int fo_ins_blank = has_format_option(FO_INS_BLANK);
5679 #ifdef FEAT_MBYTE
5680 int fo_multibyte = has_format_option(FO_MBYTE_BREAK);
5681 #endif
5682 int fo_white_par = has_format_option(FO_WHITE_PAR);
5683 int first_line = TRUE;
5684 #ifdef FEAT_COMMENTS
5685 colnr_T leader_len;
5686 int no_leader = FALSE;
5687 int do_comments = (flags & INSCHAR_DO_COM);
5688 #endif
5691 * When 'ai' is off we don't want a space under the cursor to be
5692 * deleted. Replace it with an 'x' temporarily.
5694 if (!curbuf->b_p_ai)
5696 cc = gchar_cursor();
5697 if (vim_iswhite(cc))
5699 save_char = cc;
5700 pchar_cursor('x');
5705 * Repeat breaking lines, until the current line is not too long.
5707 while (!got_int)
5709 int startcol; /* Cursor column at entry */
5710 int wantcol; /* column at textwidth border */
5711 int foundcol; /* column for start of spaces */
5712 int end_foundcol = 0; /* column for start of word */
5713 colnr_T len;
5714 colnr_T virtcol;
5715 #ifdef FEAT_VREPLACE
5716 int orig_col = 0;
5717 char_u *saved_text = NULL;
5718 #endif
5719 colnr_T col;
5721 virtcol = get_nolist_virtcol();
5722 if (virtcol < (colnr_T)textwidth)
5723 break;
5725 #ifdef FEAT_COMMENTS
5726 if (no_leader)
5727 do_comments = FALSE;
5728 else if (!(flags & INSCHAR_FORMAT)
5729 && has_format_option(FO_WRAP_COMS))
5730 do_comments = TRUE;
5732 /* Don't break until after the comment leader */
5733 if (do_comments)
5734 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
5735 else
5736 leader_len = 0;
5738 /* If the line doesn't start with a comment leader, then don't
5739 * start one in a following broken line. Avoids that a %word
5740 * moved to the start of the next line causes all following lines
5741 * to start with %. */
5742 if (leader_len == 0)
5743 no_leader = TRUE;
5744 #endif
5745 if (!(flags & INSCHAR_FORMAT)
5746 #ifdef FEAT_COMMENTS
5747 && leader_len == 0
5748 #endif
5749 && !has_format_option(FO_WRAP))
5752 textwidth = 0;
5753 break;
5755 if ((startcol = curwin->w_cursor.col) == 0)
5756 break;
5758 /* find column of textwidth border */
5759 coladvance((colnr_T)textwidth);
5760 wantcol = curwin->w_cursor.col;
5762 curwin->w_cursor.col = startcol - 1;
5763 #ifdef FEAT_MBYTE
5764 /* Correct cursor for multi-byte character. */
5765 if (has_mbyte)
5766 mb_adjust_cursor();
5767 #endif
5768 foundcol = 0;
5771 * Find position to break at.
5772 * Stop at first entered white when 'formatoptions' has 'v'
5774 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
5775 || curwin->w_cursor.lnum != Insstart.lnum
5776 || curwin->w_cursor.col >= Insstart.col)
5778 cc = gchar_cursor();
5779 if (WHITECHAR(cc))
5781 /* remember position of blank just before text */
5782 end_foundcol = curwin->w_cursor.col;
5784 /* find start of sequence of blanks */
5785 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
5787 dec_cursor();
5788 cc = gchar_cursor();
5790 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
5791 break; /* only spaces in front of text */
5792 #ifdef FEAT_COMMENTS
5793 /* Don't break until after the comment leader */
5794 if (curwin->w_cursor.col < leader_len)
5795 break;
5796 #endif
5797 if (has_format_option(FO_ONE_LETTER))
5799 /* do not break after one-letter words */
5800 if (curwin->w_cursor.col == 0)
5801 break; /* one-letter word at begin */
5803 col = curwin->w_cursor.col;
5804 dec_cursor();
5805 cc = gchar_cursor();
5807 if (WHITECHAR(cc))
5808 continue; /* one-letter, continue */
5809 curwin->w_cursor.col = col;
5811 #ifdef FEAT_MBYTE
5812 if (has_mbyte)
5813 foundcol = curwin->w_cursor.col
5814 + (*mb_ptr2len)(ml_get_cursor());
5815 else
5816 #endif
5817 foundcol = curwin->w_cursor.col + 1;
5818 if (curwin->w_cursor.col < (colnr_T)wantcol)
5819 break;
5821 #ifdef FEAT_MBYTE
5822 else if (cc >= 0x100 && fo_multibyte
5823 && curwin->w_cursor.col <= (colnr_T)wantcol)
5825 /* Break after or before a multi-byte character. */
5826 foundcol = curwin->w_cursor.col;
5827 if (curwin->w_cursor.col < (colnr_T)wantcol)
5828 foundcol += (*mb_char2len)(cc);
5829 end_foundcol = foundcol;
5830 break;
5832 #endif
5833 if (curwin->w_cursor.col == 0)
5834 break;
5835 dec_cursor();
5838 if (foundcol == 0) /* no spaces, cannot break line */
5840 curwin->w_cursor.col = startcol;
5841 break;
5844 /* Going to break the line, remove any "$" now. */
5845 undisplay_dollar();
5848 * Offset between cursor position and line break is used by replace
5849 * stack functions. VREPLACE does not use this, and backspaces
5850 * over the text instead.
5852 #ifdef FEAT_VREPLACE
5853 if (State & VREPLACE_FLAG)
5854 orig_col = startcol; /* Will start backspacing from here */
5855 else
5856 #endif
5857 replace_offset = startcol - end_foundcol - 1;
5860 * adjust startcol for spaces that will be deleted and
5861 * characters that will remain on top line
5863 curwin->w_cursor.col = foundcol;
5864 while (cc = gchar_cursor(), WHITECHAR(cc))
5865 inc_cursor();
5866 startcol -= curwin->w_cursor.col;
5867 if (startcol < 0)
5868 startcol = 0;
5870 #ifdef FEAT_VREPLACE
5871 if (State & VREPLACE_FLAG)
5874 * In VREPLACE mode, we will backspace over the text to be
5875 * wrapped, so save a copy now to put on the next line.
5877 saved_text = vim_strsave(ml_get_cursor());
5878 curwin->w_cursor.col = orig_col;
5879 if (saved_text == NULL)
5880 break; /* Can't do it, out of memory */
5881 saved_text[startcol] = NUL;
5883 /* Backspace over characters that will move to the next line */
5884 if (!fo_white_par)
5885 backspace_until_column(foundcol);
5887 else
5888 #endif
5890 /* put cursor after pos. to break line */
5891 if (!fo_white_par)
5892 curwin->w_cursor.col = foundcol;
5896 * Split the line just before the margin.
5897 * Only insert/delete lines, but don't really redraw the window.
5899 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
5900 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
5901 #ifdef FEAT_COMMENTS
5902 + (do_comments ? OPENLINE_DO_COM : 0)
5903 #endif
5904 , old_indent);
5905 old_indent = 0;
5907 replace_offset = 0;
5908 if (first_line)
5910 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
5911 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
5912 if (second_indent >= 0)
5914 #ifdef FEAT_VREPLACE
5915 if (State & VREPLACE_FLAG)
5916 change_indent(INDENT_SET, second_indent, FALSE, NUL);
5917 else
5918 #endif
5919 (void)set_indent(second_indent, SIN_CHANGED);
5921 first_line = FALSE;
5924 #ifdef FEAT_VREPLACE
5925 if (State & VREPLACE_FLAG)
5928 * In VREPLACE mode we have backspaced over the text to be
5929 * moved, now we re-insert it into the new line.
5931 ins_bytes(saved_text);
5932 vim_free(saved_text);
5934 else
5935 #endif
5938 * Check if cursor is not past the NUL off the line, cindent
5939 * may have added or removed indent.
5941 curwin->w_cursor.col += startcol;
5942 len = (colnr_T)STRLEN(ml_get_curline());
5943 if (curwin->w_cursor.col > len)
5944 curwin->w_cursor.col = len;
5947 haveto_redraw = TRUE;
5948 #ifdef FEAT_CINDENT
5949 can_cindent = TRUE;
5950 #endif
5951 /* moved the cursor, don't autoindent or cindent now */
5952 did_ai = FALSE;
5953 #ifdef FEAT_SMARTINDENT
5954 did_si = FALSE;
5955 can_si = FALSE;
5956 can_si_back = FALSE;
5957 #endif
5958 line_breakcheck();
5961 if (save_char != NUL) /* put back space after cursor */
5962 pchar_cursor(save_char);
5964 if (!format_only && haveto_redraw)
5966 update_topline();
5967 redraw_curbuf_later(VALID);
5972 * Called after inserting or deleting text: When 'formatoptions' includes the
5973 * 'a' flag format from the current line until the end of the paragraph.
5974 * Keep the cursor at the same position relative to the text.
5975 * The caller must have saved the cursor line for undo, following ones will be
5976 * saved here.
5978 void
5979 auto_format(trailblank, prev_line)
5980 int trailblank; /* when TRUE also format with trailing blank */
5981 int prev_line; /* may start in previous line */
5983 pos_T pos;
5984 colnr_T len;
5985 char_u *old;
5986 char_u *new, *pnew;
5987 int wasatend;
5988 int cc;
5990 if (!has_format_option(FO_AUTO))
5991 return;
5993 pos = curwin->w_cursor;
5994 old = ml_get_curline();
5996 /* may remove added space */
5997 check_auto_format(FALSE);
5999 /* Don't format in Insert mode when the cursor is on a trailing blank, the
6000 * user might insert normal text next. Also skip formatting when "1" is
6001 * in 'formatoptions' and there is a single character before the cursor.
6002 * Otherwise the line would be broken and when typing another non-white
6003 * next they are not joined back together. */
6004 wasatend = (pos.col == STRLEN(old));
6005 if (*old != NUL && !trailblank && wasatend)
6007 dec_cursor();
6008 cc = gchar_cursor();
6009 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
6010 && has_format_option(FO_ONE_LETTER))
6011 dec_cursor();
6012 cc = gchar_cursor();
6013 if (WHITECHAR(cc))
6015 curwin->w_cursor = pos;
6016 return;
6018 curwin->w_cursor = pos;
6021 #ifdef FEAT_COMMENTS
6022 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
6023 * comments. */
6024 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
6025 && get_leader_len(old, NULL, FALSE) == 0)
6026 return;
6027 #endif
6030 * May start formatting in a previous line, so that after "x" a word is
6031 * moved to the previous line if it fits there now. Only when this is not
6032 * the start of a paragraph.
6034 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
6036 --curwin->w_cursor.lnum;
6037 if (u_save_cursor() == FAIL)
6038 return;
6042 * Do the formatting and restore the cursor position. "saved_cursor" will
6043 * be adjusted for the text formatting.
6045 saved_cursor = pos;
6046 format_lines((linenr_T)-1);
6047 curwin->w_cursor = saved_cursor;
6048 saved_cursor.lnum = 0;
6050 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6052 /* "cannot happen" */
6053 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6054 coladvance((colnr_T)MAXCOL);
6056 else
6057 check_cursor_col();
6059 /* Insert mode: If the cursor is now after the end of the line while it
6060 * previously wasn't, the line was broken. Because of the rule above we
6061 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
6062 * formatted. */
6063 if (!wasatend && has_format_option(FO_WHITE_PAR))
6065 new = ml_get_curline();
6066 len = (colnr_T)STRLEN(new);
6067 if (curwin->w_cursor.col == len)
6069 pnew = vim_strnsave(new, len + 2);
6070 pnew[len] = ' ';
6071 pnew[len + 1] = NUL;
6072 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
6073 /* remove the space later */
6074 did_add_space = TRUE;
6076 else
6077 /* may remove added space */
6078 check_auto_format(FALSE);
6081 check_cursor();
6085 * When an extra space was added to continue a paragraph for auto-formatting,
6086 * delete it now. The space must be under the cursor, just after the insert
6087 * position.
6089 static void
6090 check_auto_format(end_insert)
6091 int end_insert; /* TRUE when ending Insert mode */
6093 int c = ' ';
6094 int cc;
6096 if (did_add_space)
6098 cc = gchar_cursor();
6099 if (!WHITECHAR(cc))
6100 /* Somehow the space was removed already. */
6101 did_add_space = FALSE;
6102 else
6104 if (!end_insert)
6106 inc_cursor();
6107 c = gchar_cursor();
6108 dec_cursor();
6110 if (c != NUL)
6112 /* The space is no longer at the end of the line, delete it. */
6113 del_char(FALSE);
6114 did_add_space = FALSE;
6121 * Find out textwidth to be used for formatting:
6122 * if 'textwidth' option is set, use it
6123 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
6124 * if invalid value, use 0.
6125 * Set default to window width (maximum 79) for "gq" operator.
6128 comp_textwidth(ff)
6129 int ff; /* force formatting (for "gq" command) */
6131 int textwidth;
6133 textwidth = curbuf->b_p_tw;
6134 if (textwidth == 0 && curbuf->b_p_wm)
6136 /* The width is the window width minus 'wrapmargin' minus all the
6137 * things that add to the margin. */
6138 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
6139 #ifdef FEAT_CMDWIN
6140 if (cmdwin_type != 0)
6141 textwidth -= 1;
6142 #endif
6143 #ifdef FEAT_FOLDING
6144 textwidth -= curwin->w_p_fdc;
6145 #endif
6146 #ifdef FEAT_SIGNS
6147 if (curwin->w_buffer->b_signlist != NULL
6148 # ifdef FEAT_NETBEANS_INTG
6149 || usingNetbeans
6150 # endif
6152 textwidth -= 1;
6153 #endif
6154 if (curwin->w_p_nu)
6155 textwidth -= 8;
6157 if (textwidth < 0)
6158 textwidth = 0;
6159 if (ff && textwidth == 0)
6161 textwidth = W_WIDTH(curwin) - 1;
6162 if (textwidth > 79)
6163 textwidth = 79;
6165 return textwidth;
6169 * Put a character in the redo buffer, for when just after a CTRL-V.
6171 static void
6172 redo_literal(c)
6173 int c;
6175 char_u buf[10];
6177 /* Only digits need special treatment. Translate them into a string of
6178 * three digits. */
6179 if (VIM_ISDIGIT(c))
6181 sprintf((char *)buf, "%03d", c);
6182 AppendToRedobuff(buf);
6184 else
6185 AppendCharToRedobuff(c);
6189 * start_arrow() is called when an arrow key is used in insert mode.
6190 * For undo/redo it resembles hitting the <ESC> key.
6192 static void
6193 start_arrow(end_insert_pos)
6194 pos_T *end_insert_pos; /* can be NULL */
6196 if (!arrow_used) /* something has been inserted */
6198 AppendToRedobuff(ESC_STR);
6199 stop_insert(end_insert_pos, FALSE);
6200 arrow_used = TRUE; /* this means we stopped the current insert */
6202 #ifdef FEAT_SPELL
6203 check_spell_redraw();
6204 #endif
6207 #ifdef FEAT_SPELL
6209 * If we skipped highlighting word at cursor, do it now.
6210 * It may be skipped again, thus reset spell_redraw_lnum first.
6212 static void
6213 check_spell_redraw()
6215 if (spell_redraw_lnum != 0)
6217 linenr_T lnum = spell_redraw_lnum;
6219 spell_redraw_lnum = 0;
6220 redrawWinline(lnum, FALSE);
6225 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6226 * spelled word, if there is one.
6228 static void
6229 spell_back_to_badword()
6231 pos_T tpos = curwin->w_cursor;
6233 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
6234 if (curwin->w_cursor.col != tpos.col)
6235 start_arrow(&tpos);
6237 #endif
6240 * stop_arrow() is called before a change is made in insert mode.
6241 * If an arrow key has been used, start a new insertion.
6242 * Returns FAIL if undo is impossible, shouldn't insert then.
6245 stop_arrow()
6247 if (arrow_used)
6249 if (u_save_cursor() == OK)
6251 arrow_used = FALSE;
6252 ins_need_undo = FALSE;
6254 Insstart = curwin->w_cursor; /* new insertion starts here */
6255 Insstart_textlen = linetabsize(ml_get_curline());
6256 ai_col = 0;
6257 #ifdef FEAT_VREPLACE
6258 if (State & VREPLACE_FLAG)
6260 orig_line_count = curbuf->b_ml.ml_line_count;
6261 vr_lines_changed = 1;
6263 #endif
6264 ResetRedobuff();
6265 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
6266 new_insert_skip = 2;
6268 else if (ins_need_undo)
6270 if (u_save_cursor() == OK)
6271 ins_need_undo = FALSE;
6274 #ifdef FEAT_FOLDING
6275 /* Always open fold at the cursor line when inserting something. */
6276 foldOpenCursor();
6277 #endif
6279 return (arrow_used || ins_need_undo ? FAIL : OK);
6283 * Do a few things to stop inserting.
6284 * "end_insert_pos" is where insert ended. It is NULL when we already jumped
6285 * to another window/buffer.
6287 static void
6288 stop_insert(end_insert_pos, esc)
6289 pos_T *end_insert_pos;
6290 int esc; /* called by ins_esc() */
6292 int cc;
6293 char_u *ptr;
6295 stop_redo_ins();
6296 replace_flush(); /* abandon replace stack */
6299 * Save the inserted text for later redo with ^@ and CTRL-A.
6300 * Don't do it when "restart_edit" was set and nothing was inserted,
6301 * otherwise CTRL-O w and then <Left> will clear "last_insert".
6303 ptr = get_inserted();
6304 if (did_restart_edit == 0 || (ptr != NULL
6305 && (int)STRLEN(ptr) > new_insert_skip))
6307 vim_free(last_insert);
6308 last_insert = ptr;
6309 last_insert_skip = new_insert_skip;
6311 else
6312 vim_free(ptr);
6314 if (!arrow_used && end_insert_pos != NULL)
6316 /* Auto-format now. It may seem strange to do this when stopping an
6317 * insertion (or moving the cursor), but it's required when appending
6318 * a line and having it end in a space. But only do it when something
6319 * was actually inserted, otherwise undo won't work. */
6320 if (!ins_need_undo && has_format_option(FO_AUTO))
6322 pos_T tpos = curwin->w_cursor;
6324 /* When the cursor is at the end of the line after a space the
6325 * formatting will move it to the following word. Avoid that by
6326 * moving the cursor onto the space. */
6327 cc = 'x';
6328 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
6330 dec_cursor();
6331 cc = gchar_cursor();
6332 if (!vim_iswhite(cc))
6333 curwin->w_cursor = tpos;
6336 auto_format(TRUE, FALSE);
6338 if (vim_iswhite(cc))
6340 if (gchar_cursor() != NUL)
6341 inc_cursor();
6342 #ifdef FEAT_VIRTUALEDIT
6343 /* If the cursor is still at the same character, also keep
6344 * the "coladd". */
6345 if (gchar_cursor() == NUL
6346 && curwin->w_cursor.lnum == tpos.lnum
6347 && curwin->w_cursor.col == tpos.col)
6348 curwin->w_cursor.coladd = tpos.coladd;
6349 #endif
6353 /* If a space was inserted for auto-formatting, remove it now. */
6354 check_auto_format(TRUE);
6356 /* If we just did an auto-indent, remove the white space from the end
6357 * of the line, and put the cursor back.
6358 * Do this when ESC was used or moving the cursor up/down. */
6359 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6360 && curwin->w_cursor.lnum != end_insert_pos->lnum)))
6362 pos_T tpos = curwin->w_cursor;
6364 curwin->w_cursor = *end_insert_pos;
6365 for (;;)
6367 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6368 --curwin->w_cursor.col;
6369 cc = gchar_cursor();
6370 if (!vim_iswhite(cc))
6371 break;
6372 (void)del_char(TRUE);
6374 if (curwin->w_cursor.lnum != tpos.lnum)
6375 curwin->w_cursor = tpos;
6376 else if (cc != NUL)
6377 ++curwin->w_cursor.col; /* put cursor back on the NUL */
6379 #ifdef FEAT_VISUAL
6380 /* <C-S-Right> may have started Visual mode, adjust the position for
6381 * deleted characters. */
6382 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6384 cc = (int)STRLEN(ml_get_curline());
6385 if (VIsual.col > (colnr_T)cc)
6387 VIsual.col = cc;
6388 # ifdef FEAT_VIRTUALEDIT
6389 VIsual.coladd = 0;
6390 # endif
6393 #endif
6396 did_ai = FALSE;
6397 #ifdef FEAT_SMARTINDENT
6398 did_si = FALSE;
6399 can_si = FALSE;
6400 can_si_back = FALSE;
6401 #endif
6403 /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are
6404 * now in a different buffer. */
6405 if (end_insert_pos != NULL)
6407 curbuf->b_op_start = Insstart;
6408 curbuf->b_op_end = *end_insert_pos;
6413 * Set the last inserted text to a single character.
6414 * Used for the replace command.
6416 void
6417 set_last_insert(c)
6418 int c;
6420 char_u *s;
6422 vim_free(last_insert);
6423 #ifdef FEAT_MBYTE
6424 last_insert = alloc(MB_MAXBYTES * 3 + 5);
6425 #else
6426 last_insert = alloc(6);
6427 #endif
6428 if (last_insert != NULL)
6430 s = last_insert;
6431 /* Use the CTRL-V only when entering a special char */
6432 if (c < ' ' || c == DEL)
6433 *s++ = Ctrl_V;
6434 s = add_char2buf(c, s);
6435 *s++ = ESC;
6436 *s++ = NUL;
6437 last_insert_skip = 0;
6441 #if defined(EXITFREE) || defined(PROTO)
6442 void
6443 free_last_insert()
6445 vim_free(last_insert);
6446 last_insert = NULL;
6447 vim_free(compl_orig_text);
6448 compl_orig_text = NULL;
6450 #endif
6453 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
6454 * and CSI. Handle multi-byte characters.
6455 * Returns a pointer to after the added bytes.
6457 char_u *
6458 add_char2buf(c, s)
6459 int c;
6460 char_u *s;
6462 #ifdef FEAT_MBYTE
6463 char_u temp[MB_MAXBYTES];
6464 int i;
6465 int len;
6467 len = (*mb_char2bytes)(c, temp);
6468 for (i = 0; i < len; ++i)
6470 c = temp[i];
6471 #endif
6472 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6473 if (c == K_SPECIAL)
6475 *s++ = K_SPECIAL;
6476 *s++ = KS_SPECIAL;
6477 *s++ = KE_FILLER;
6479 #ifdef FEAT_GUI
6480 else if (c == CSI)
6482 *s++ = CSI;
6483 *s++ = KS_EXTRA;
6484 *s++ = (int)KE_CSI;
6486 #endif
6487 else
6488 *s++ = c;
6489 #ifdef FEAT_MBYTE
6491 #endif
6492 return s;
6496 * move cursor to start of line
6497 * if flags & BL_WHITE move to first non-white
6498 * if flags & BL_SOL move to first non-white if startofline is set,
6499 * otherwise keep "curswant" column
6500 * if flags & BL_FIX don't leave the cursor on a NUL.
6502 void
6503 beginline(flags)
6504 int flags;
6506 if ((flags & BL_SOL) && !p_sol)
6507 coladvance(curwin->w_curswant);
6508 else
6510 curwin->w_cursor.col = 0;
6511 #ifdef FEAT_VIRTUALEDIT
6512 curwin->w_cursor.coladd = 0;
6513 #endif
6515 if (flags & (BL_WHITE | BL_SOL))
6517 char_u *ptr;
6519 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6520 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6521 ++curwin->w_cursor.col;
6523 curwin->w_set_curswant = TRUE;
6528 * oneright oneleft cursor_down cursor_up
6530 * Move one char {right,left,down,up}.
6531 * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6532 * Return OK when successful, FAIL when we hit a line of file boundary.
6536 oneright()
6538 char_u *ptr;
6539 int l;
6541 #ifdef FEAT_VIRTUALEDIT
6542 if (virtual_active())
6544 pos_T prevpos = curwin->w_cursor;
6546 /* Adjust for multi-wide char (excluding TAB) */
6547 ptr = ml_get_cursor();
6548 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
6549 # ifdef FEAT_MBYTE
6550 (*mb_ptr2char)(ptr)
6551 # else
6552 *ptr
6553 # endif
6555 ? ptr2cells(ptr) : 1));
6556 curwin->w_set_curswant = TRUE;
6557 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
6558 return (prevpos.col != curwin->w_cursor.col
6559 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
6561 #endif
6563 ptr = ml_get_cursor();
6564 if (*ptr == NUL)
6565 return FAIL; /* already at the very end */
6567 #ifdef FEAT_MBYTE
6568 if (has_mbyte)
6569 l = (*mb_ptr2len)(ptr);
6570 else
6571 #endif
6572 l = 1;
6574 /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
6575 * contains "onemore". */
6576 if (ptr[l] == NUL
6577 #ifdef FEAT_VIRTUALEDIT
6578 && (ve_flags & VE_ONEMORE) == 0
6579 #endif
6581 return FAIL;
6582 curwin->w_cursor.col += l;
6584 curwin->w_set_curswant = TRUE;
6585 return OK;
6589 oneleft()
6591 #ifdef FEAT_VIRTUALEDIT
6592 if (virtual_active())
6594 int width;
6595 int v = getviscol();
6597 if (v == 0)
6598 return FAIL;
6600 # ifdef FEAT_LINEBREAK
6601 /* We might get stuck on 'showbreak', skip over it. */
6602 width = 1;
6603 for (;;)
6605 coladvance(v - width);
6606 /* getviscol() is slow, skip it when 'showbreak' is empty and
6607 * there are no multi-byte characters */
6608 if ((*p_sbr == NUL
6609 # ifdef FEAT_MBYTE
6610 && !has_mbyte
6611 # endif
6612 ) || getviscol() < v)
6613 break;
6614 ++width;
6616 # else
6617 coladvance(v - 1);
6618 # endif
6620 if (curwin->w_cursor.coladd == 1)
6622 char_u *ptr;
6624 /* Adjust for multi-wide char (not a TAB) */
6625 ptr = ml_get_cursor();
6626 if (*ptr != TAB && vim_isprintc(
6627 # ifdef FEAT_MBYTE
6628 (*mb_ptr2char)(ptr)
6629 # else
6630 *ptr
6631 # endif
6632 ) && ptr2cells(ptr) > 1)
6633 curwin->w_cursor.coladd = 0;
6636 curwin->w_set_curswant = TRUE;
6637 return OK;
6639 #endif
6641 if (curwin->w_cursor.col == 0)
6642 return FAIL;
6644 curwin->w_set_curswant = TRUE;
6645 --curwin->w_cursor.col;
6647 #ifdef FEAT_MBYTE
6648 /* if the character on the left of the current cursor is a multi-byte
6649 * character, move to its first byte */
6650 if (has_mbyte)
6651 mb_adjust_cursor();
6652 #endif
6653 return OK;
6657 cursor_up(n, upd_topline)
6658 long n;
6659 int upd_topline; /* When TRUE: update topline */
6661 linenr_T lnum;
6663 if (n > 0)
6665 lnum = curwin->w_cursor.lnum;
6666 /* This fails if the cursor is already in the first line or the count
6667 * is larger than the line number and '-' is in 'cpoptions' */
6668 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6669 return FAIL;
6670 if (n >= lnum)
6671 lnum = 1;
6672 else
6673 #ifdef FEAT_FOLDING
6674 if (hasAnyFolding(curwin))
6677 * Count each sequence of folded lines as one logical line.
6679 /* go to the the start of the current fold */
6680 (void)hasFolding(lnum, &lnum, NULL);
6682 while (n--)
6684 /* move up one line */
6685 --lnum;
6686 if (lnum <= 1)
6687 break;
6688 /* If we entered a fold, move to the beginning, unless in
6689 * Insert mode or when 'foldopen' contains "all": it will open
6690 * in a moment. */
6691 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
6692 (void)hasFolding(lnum, &lnum, NULL);
6694 if (lnum < 1)
6695 lnum = 1;
6697 else
6698 #endif
6699 lnum -= n;
6700 curwin->w_cursor.lnum = lnum;
6703 /* try to advance to the column we want to be at */
6704 coladvance(curwin->w_curswant);
6706 if (upd_topline)
6707 update_topline(); /* make sure curwin->w_topline is valid */
6709 return OK;
6713 * Cursor down a number of logical lines.
6716 cursor_down(n, upd_topline)
6717 long n;
6718 int upd_topline; /* When TRUE: update topline */
6720 linenr_T lnum;
6722 if (n > 0)
6724 lnum = curwin->w_cursor.lnum;
6725 #ifdef FEAT_FOLDING
6726 /* Move to last line of fold, will fail if it's the end-of-file. */
6727 (void)hasFolding(lnum, NULL, &lnum);
6728 #endif
6729 /* This fails if the cursor is already in the last line or would move
6730 * beyound the last line and '-' is in 'cpoptions' */
6731 if (lnum >= curbuf->b_ml.ml_line_count
6732 || (lnum + n > curbuf->b_ml.ml_line_count
6733 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6734 return FAIL;
6735 if (lnum + n >= curbuf->b_ml.ml_line_count)
6736 lnum = curbuf->b_ml.ml_line_count;
6737 else
6738 #ifdef FEAT_FOLDING
6739 if (hasAnyFolding(curwin))
6741 linenr_T last;
6743 /* count each sequence of folded lines as one logical line */
6744 while (n--)
6746 if (hasFolding(lnum, NULL, &last))
6747 lnum = last + 1;
6748 else
6749 ++lnum;
6750 if (lnum >= curbuf->b_ml.ml_line_count)
6751 break;
6753 if (lnum > curbuf->b_ml.ml_line_count)
6754 lnum = curbuf->b_ml.ml_line_count;
6756 else
6757 #endif
6758 lnum += n;
6759 curwin->w_cursor.lnum = lnum;
6762 /* try to advance to the column we want to be at */
6763 coladvance(curwin->w_curswant);
6765 if (upd_topline)
6766 update_topline(); /* make sure curwin->w_topline is valid */
6768 return OK;
6772 * Stuff the last inserted text in the read buffer.
6773 * Last_insert actually is a copy of the redo buffer, so we
6774 * first have to remove the command.
6777 stuff_inserted(c, count, no_esc)
6778 int c; /* Command character to be inserted */
6779 long count; /* Repeat this many times */
6780 int no_esc; /* Don't add an ESC at the end */
6782 char_u *esc_ptr;
6783 char_u *ptr;
6784 char_u *last_ptr;
6785 char_u last = NUL;
6787 ptr = get_last_insert();
6788 if (ptr == NULL)
6790 EMSG(_(e_noinstext));
6791 return FAIL;
6794 /* may want to stuff the command character, to start Insert mode */
6795 if (c != NUL)
6796 stuffcharReadbuff(c);
6797 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
6798 *esc_ptr = NUL; /* remove the ESC */
6800 /* when the last char is either "0" or "^" it will be quoted if no ESC
6801 * comes after it OR if it will inserted more than once and "ptr"
6802 * starts with ^D. -- Acevedo
6804 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
6805 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
6806 && (no_esc || (*ptr == Ctrl_D && count > 1)))
6808 last = *last_ptr;
6809 *last_ptr = NUL;
6814 stuffReadbuff(ptr);
6815 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
6816 if (last)
6817 stuffReadbuff((char_u *)(last == '0'
6818 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
6819 : IF_EB("\026^", CTRL_V_STR "^")));
6821 while (--count > 0);
6823 if (last)
6824 *last_ptr = last;
6826 if (esc_ptr != NULL)
6827 *esc_ptr = ESC; /* put the ESC back */
6829 /* may want to stuff a trailing ESC, to get out of Insert mode */
6830 if (!no_esc)
6831 stuffcharReadbuff(ESC);
6833 return OK;
6836 char_u *
6837 get_last_insert()
6839 if (last_insert == NULL)
6840 return NULL;
6841 return last_insert + last_insert_skip;
6845 * Get last inserted string, and remove trailing <Esc>.
6846 * Returns pointer to allocated memory (must be freed) or NULL.
6848 char_u *
6849 get_last_insert_save()
6851 char_u *s;
6852 int len;
6854 if (last_insert == NULL)
6855 return NULL;
6856 s = vim_strsave(last_insert + last_insert_skip);
6857 if (s != NULL)
6859 len = (int)STRLEN(s);
6860 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
6861 s[len - 1] = NUL;
6863 return s;
6867 * Check the word in front of the cursor for an abbreviation.
6868 * Called when the non-id character "c" has been entered.
6869 * When an abbreviation is recognized it is removed from the text and
6870 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
6872 static int
6873 echeck_abbr(c)
6874 int c;
6876 /* Don't check for abbreviation in paste mode, when disabled and just
6877 * after moving around with cursor keys. */
6878 if (p_paste || no_abbr || arrow_used)
6879 return FALSE;
6881 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
6882 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
6886 * replace-stack functions
6888 * When replacing characters, the replaced characters are remembered for each
6889 * new character. This is used to re-insert the old text when backspacing.
6891 * There is a NUL headed list of characters for each character that is
6892 * currently in the file after the insertion point. When BS is used, one NUL
6893 * headed list is put back for the deleted character.
6895 * For a newline, there are two NUL headed lists. One contains the characters
6896 * that the NL replaced. The extra one stores the characters after the cursor
6897 * that were deleted (always white space).
6899 * Replace_offset is normally 0, in which case replace_push will add a new
6900 * character at the end of the stack. If replace_offset is not 0, that many
6901 * characters will be left on the stack above the newly inserted character.
6904 static char_u *replace_stack = NULL;
6905 static long replace_stack_nr = 0; /* next entry in replace stack */
6906 static long replace_stack_len = 0; /* max. number of entries */
6908 void
6909 replace_push(c)
6910 int c; /* character that is replaced (NUL is none) */
6912 char_u *p;
6914 if (replace_stack_nr < replace_offset) /* nothing to do */
6915 return;
6916 if (replace_stack_len <= replace_stack_nr)
6918 replace_stack_len += 50;
6919 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
6920 if (p == NULL) /* out of memory */
6922 replace_stack_len -= 50;
6923 return;
6925 if (replace_stack != NULL)
6927 mch_memmove(p, replace_stack,
6928 (size_t)(replace_stack_nr * sizeof(char_u)));
6929 vim_free(replace_stack);
6931 replace_stack = p;
6933 p = replace_stack + replace_stack_nr - replace_offset;
6934 if (replace_offset)
6935 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
6936 *p = c;
6937 ++replace_stack_nr;
6940 #if 0
6942 * call replace_push(c) with replace_offset set to the first NUL.
6944 static void
6945 replace_push_off(c)
6946 int c;
6948 char_u *p;
6950 p = replace_stack + replace_stack_nr;
6951 for (replace_offset = 1; replace_offset < replace_stack_nr;
6952 ++replace_offset)
6953 if (*--p == NUL)
6954 break;
6955 replace_push(c);
6956 replace_offset = 0;
6958 #endif
6961 * Pop one item from the replace stack.
6962 * return -1 if stack empty
6963 * return replaced character or NUL otherwise
6965 static int
6966 replace_pop()
6968 if (replace_stack_nr == 0)
6969 return -1;
6970 return (int)replace_stack[--replace_stack_nr];
6974 * Join the top two items on the replace stack. This removes to "off"'th NUL
6975 * encountered.
6977 static void
6978 replace_join(off)
6979 int off; /* offset for which NUL to remove */
6981 int i;
6983 for (i = replace_stack_nr; --i >= 0; )
6984 if (replace_stack[i] == NUL && off-- <= 0)
6986 --replace_stack_nr;
6987 mch_memmove(replace_stack + i, replace_stack + i + 1,
6988 (size_t)(replace_stack_nr - i));
6989 return;
6994 * Pop bytes from the replace stack until a NUL is found, and insert them
6995 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
6997 static void
6998 replace_pop_ins()
7000 int cc;
7001 int oldState = State;
7003 State = NORMAL; /* don't want REPLACE here */
7004 while ((cc = replace_pop()) > 0)
7006 #ifdef FEAT_MBYTE
7007 mb_replace_pop_ins(cc);
7008 #else
7009 ins_char(cc);
7010 #endif
7011 dec_cursor();
7013 State = oldState;
7016 #ifdef FEAT_MBYTE
7018 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
7019 * indicates a multi-byte char, pop the other bytes too.
7021 static void
7022 mb_replace_pop_ins(cc)
7023 int cc;
7025 int n;
7026 char_u buf[MB_MAXBYTES];
7027 int i;
7028 int c;
7030 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
7032 buf[0] = cc;
7033 for (i = 1; i < n; ++i)
7034 buf[i] = replace_pop();
7035 ins_bytes_len(buf, n);
7037 else
7038 ins_char(cc);
7040 if (enc_utf8)
7041 /* Handle composing chars. */
7042 for (;;)
7044 c = replace_pop();
7045 if (c == -1) /* stack empty */
7046 break;
7047 if ((n = MB_BYTE2LEN(c)) == 1)
7049 /* Not a multi-byte char, put it back. */
7050 replace_push(c);
7051 break;
7053 else
7055 buf[0] = c;
7056 for (i = 1; i < n; ++i)
7057 buf[i] = replace_pop();
7058 if (utf_iscomposing(utf_ptr2char(buf)))
7059 ins_bytes_len(buf, n);
7060 else
7062 /* Not a composing char, put it back. */
7063 for (i = n - 1; i >= 0; --i)
7064 replace_push(buf[i]);
7065 break;
7070 #endif
7073 * make the replace stack empty
7074 * (called when exiting replace mode)
7076 static void
7077 replace_flush()
7079 vim_free(replace_stack);
7080 replace_stack = NULL;
7081 replace_stack_len = 0;
7082 replace_stack_nr = 0;
7086 * Handle doing a BS for one character.
7087 * cc < 0: replace stack empty, just move cursor
7088 * cc == 0: character was inserted, delete it
7089 * cc > 0: character was replaced, put cc (first byte of original char) back
7090 * and check for more characters to be put back
7092 static void
7093 replace_do_bs()
7095 int cc;
7096 #ifdef FEAT_VREPLACE
7097 int orig_len = 0;
7098 int ins_len;
7099 int orig_vcols = 0;
7100 colnr_T start_vcol;
7101 char_u *p;
7102 int i;
7103 int vcol;
7104 #endif
7106 cc = replace_pop();
7107 if (cc > 0)
7109 #ifdef FEAT_VREPLACE
7110 if (State & VREPLACE_FLAG)
7112 /* Get the number of screen cells used by the character we are
7113 * going to delete. */
7114 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
7115 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
7117 #endif
7118 #ifdef FEAT_MBYTE
7119 if (has_mbyte)
7121 del_char(FALSE);
7122 # ifdef FEAT_VREPLACE
7123 if (State & VREPLACE_FLAG)
7124 orig_len = (int)STRLEN(ml_get_cursor());
7125 # endif
7126 replace_push(cc);
7128 else
7129 #endif
7131 pchar_cursor(cc);
7132 #ifdef FEAT_VREPLACE
7133 if (State & VREPLACE_FLAG)
7134 orig_len = (int)STRLEN(ml_get_cursor()) - 1;
7135 #endif
7137 replace_pop_ins();
7139 #ifdef FEAT_VREPLACE
7140 if (State & VREPLACE_FLAG)
7142 /* Get the number of screen cells used by the inserted characters */
7143 p = ml_get_cursor();
7144 ins_len = (int)STRLEN(p) - orig_len;
7145 vcol = start_vcol;
7146 for (i = 0; i < ins_len; ++i)
7148 vcol += chartabsize(p + i, vcol);
7149 #ifdef FEAT_MBYTE
7150 i += (*mb_ptr2len)(p) - 1;
7151 #endif
7153 vcol -= start_vcol;
7155 /* Delete spaces that were inserted after the cursor to keep the
7156 * text aligned. */
7157 curwin->w_cursor.col += ins_len;
7158 while (vcol > orig_vcols && gchar_cursor() == ' ')
7160 del_char(FALSE);
7161 ++orig_vcols;
7163 curwin->w_cursor.col -= ins_len;
7165 #endif
7167 /* mark the buffer as changed and prepare for displaying */
7168 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
7170 else if (cc == 0)
7171 (void)del_char(FALSE);
7174 #ifdef FEAT_CINDENT
7176 * Return TRUE if C-indenting is on.
7178 static int
7179 cindent_on()
7181 return (!p_paste && (curbuf->b_p_cin
7182 # ifdef FEAT_EVAL
7183 || *curbuf->b_p_inde != NUL
7184 # endif
7187 #endif
7189 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
7191 * Re-indent the current line, based on the current contents of it and the
7192 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
7193 * confused what all the part that handles Control-T is doing that I'm not.
7194 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
7197 void
7198 fixthisline(get_the_indent)
7199 int (*get_the_indent) __ARGS((void));
7201 change_indent(INDENT_SET, get_the_indent(), FALSE, 0);
7202 if (linewhite(curwin->w_cursor.lnum))
7203 did_ai = TRUE; /* delete the indent if the line stays empty */
7206 void
7207 fix_indent()
7209 if (p_paste)
7210 return;
7211 # ifdef FEAT_LISP
7212 if (curbuf->b_p_lisp && curbuf->b_p_ai)
7213 fixthisline(get_lisp_indent);
7214 # endif
7215 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
7216 else
7217 # endif
7218 # ifdef FEAT_CINDENT
7219 if (cindent_on())
7220 do_c_expr_indent();
7221 # endif
7224 #endif
7226 #ifdef FEAT_CINDENT
7228 * return TRUE if 'cinkeys' contains the key "keytyped",
7229 * when == '*': Only if key is preceded with '*' (indent before insert)
7230 * when == '!': Only if key is prededed with '!' (don't insert)
7231 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
7233 * "keytyped" can have a few special values:
7234 * KEY_OPEN_FORW
7235 * KEY_OPEN_BACK
7236 * KEY_COMPLETE just finished completion.
7238 * If line_is_empty is TRUE accept keys with '0' before them.
7241 in_cinkeys(keytyped, when, line_is_empty)
7242 int keytyped;
7243 int when;
7244 int line_is_empty;
7246 char_u *look;
7247 int try_match;
7248 int try_match_word;
7249 char_u *p;
7250 char_u *line;
7251 int icase;
7252 int i;
7254 #ifdef FEAT_EVAL
7255 if (*curbuf->b_p_inde != NUL)
7256 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
7257 else
7258 #endif
7259 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
7260 while (*look)
7263 * Find out if we want to try a match with this key, depending on
7264 * 'when' and a '*' or '!' before the key.
7266 switch (when)
7268 case '*': try_match = (*look == '*'); break;
7269 case '!': try_match = (*look == '!'); break;
7270 default: try_match = (*look != '*'); break;
7272 if (*look == '*' || *look == '!')
7273 ++look;
7276 * If there is a '0', only accept a match if the line is empty.
7277 * But may still match when typing last char of a word.
7279 if (*look == '0')
7281 try_match_word = try_match;
7282 if (!line_is_empty)
7283 try_match = FALSE;
7284 ++look;
7286 else
7287 try_match_word = FALSE;
7290 * does it look like a control character?
7292 if (*look == '^'
7293 #ifdef EBCDIC
7294 && (Ctrl_chr(look[1]) != 0)
7295 #else
7296 && look[1] >= '?' && look[1] <= '_'
7297 #endif
7300 if (try_match && keytyped == Ctrl_chr(look[1]))
7301 return TRUE;
7302 look += 2;
7305 * 'o' means "o" command, open forward.
7306 * 'O' means "O" command, open backward.
7308 else if (*look == 'o')
7310 if (try_match && keytyped == KEY_OPEN_FORW)
7311 return TRUE;
7312 ++look;
7314 else if (*look == 'O')
7316 if (try_match && keytyped == KEY_OPEN_BACK)
7317 return TRUE;
7318 ++look;
7322 * 'e' means to check for "else" at start of line and just before the
7323 * cursor.
7325 else if (*look == 'e')
7327 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
7329 p = ml_get_curline();
7330 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
7331 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
7332 return TRUE;
7334 ++look;
7338 * ':' only causes an indent if it is at the end of a label or case
7339 * statement, or when it was before typing the ':' (to fix
7340 * class::method for C++).
7342 else if (*look == ':')
7344 if (try_match && keytyped == ':')
7346 p = ml_get_curline();
7347 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
7348 return TRUE;
7349 /* Need to get the line again after cin_islabel(). */
7350 p = ml_get_curline();
7351 if (curwin->w_cursor.col > 2
7352 && p[curwin->w_cursor.col - 1] == ':'
7353 && p[curwin->w_cursor.col - 2] == ':')
7355 p[curwin->w_cursor.col - 1] = ' ';
7356 i = (cin_iscase(p) || cin_isscopedecl(p)
7357 || cin_islabel(30));
7358 p = ml_get_curline();
7359 p[curwin->w_cursor.col - 1] = ':';
7360 if (i)
7361 return TRUE;
7364 ++look;
7369 * Is it a key in <>, maybe?
7371 else if (*look == '<')
7373 if (try_match)
7376 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7377 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7378 * >, *, : and ! keys if they really really want to.
7380 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7381 && keytyped == look[1])
7382 return TRUE;
7384 if (keytyped == get_special_key_code(look + 1))
7385 return TRUE;
7387 while (*look && *look != '>')
7388 look++;
7389 while (*look == '>')
7390 look++;
7394 * Is it a word: "=word"?
7396 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7398 ++look;
7399 if (*look == '~')
7401 icase = TRUE;
7402 ++look;
7404 else
7405 icase = FALSE;
7406 p = vim_strchr(look, ',');
7407 if (p == NULL)
7408 p = look + STRLEN(look);
7409 if ((try_match || try_match_word)
7410 && curwin->w_cursor.col >= (colnr_T)(p - look))
7412 int match = FALSE;
7414 #ifdef FEAT_INS_EXPAND
7415 if (keytyped == KEY_COMPLETE)
7417 char_u *s;
7419 /* Just completed a word, check if it starts with "look".
7420 * search back for the start of a word. */
7421 line = ml_get_curline();
7422 # ifdef FEAT_MBYTE
7423 if (has_mbyte)
7425 char_u *n;
7427 for (s = line + curwin->w_cursor.col; s > line; s = n)
7429 n = mb_prevptr(line, s);
7430 if (!vim_iswordp(n))
7431 break;
7434 else
7435 # endif
7436 for (s = line + curwin->w_cursor.col; s > line; --s)
7437 if (!vim_iswordc(s[-1]))
7438 break;
7439 if (s + (p - look) <= line + curwin->w_cursor.col
7440 && (icase
7441 ? MB_STRNICMP(s, look, p - look)
7442 : STRNCMP(s, look, p - look)) == 0)
7443 match = TRUE;
7445 else
7446 #endif
7447 /* TODO: multi-byte */
7448 if (keytyped == (int)p[-1] || (icase && keytyped < 256
7449 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7451 line = ml_get_cursor();
7452 if ((curwin->w_cursor.col == (colnr_T)(p - look)
7453 || !vim_iswordc(line[-(p - look) - 1]))
7454 && (icase
7455 ? MB_STRNICMP(line - (p - look), look, p - look)
7456 : STRNCMP(line - (p - look), look, p - look))
7457 == 0)
7458 match = TRUE;
7460 if (match && try_match_word && !try_match)
7462 /* "0=word": Check if there are only blanks before the
7463 * word. */
7464 line = ml_get_curline();
7465 if ((int)(skipwhite(line) - line) !=
7466 (int)(curwin->w_cursor.col - (p - look)))
7467 match = FALSE;
7469 if (match)
7470 return TRUE;
7472 look = p;
7476 * ok, it's a boring generic character.
7478 else
7480 if (try_match && *look == keytyped)
7481 return TRUE;
7482 ++look;
7486 * Skip over ", ".
7488 look = skip_to_option_part(look);
7490 return FALSE;
7492 #endif /* FEAT_CINDENT */
7494 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7496 * Map Hebrew keyboard when in hkmap mode.
7499 hkmap(c)
7500 int c;
7502 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
7504 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7505 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7506 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7507 static char_u map[26] =
7508 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
7509 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
7510 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
7511 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
7512 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
7513 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
7514 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
7515 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
7516 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
7518 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7519 return (int)(map[CharOrd(c)] - 1 + p_aleph);
7520 /* '-1'='sofit' */
7521 else if (c == 'x')
7522 return 'X';
7523 else if (c == 'q')
7524 return '\''; /* {geresh}={'} */
7525 else if (c == 246)
7526 return ' '; /* \"o --> ' ' for a german keyboard */
7527 else if (c == 228)
7528 return ' '; /* \"a --> ' ' -- / -- */
7529 else if (c == 252)
7530 return ' '; /* \"u --> ' ' -- / -- */
7531 #ifdef EBCDIC
7532 else if (islower(c))
7533 #else
7534 /* NOTE: islower() does not do the right thing for us on Linux so we
7535 * do this the same was as 5.7 and previous, so it works correctly on
7536 * all systems. Specifically, the e.g. Delete and Arrow keys are
7537 * munged and won't work if e.g. searching for Hebrew text.
7539 else if (c >= 'a' && c <= 'z')
7540 #endif
7541 return (int)(map[CharOrdLow(c)] + p_aleph);
7542 else
7543 return c;
7545 else
7547 switch (c)
7549 case '`': return ';';
7550 case '/': return '.';
7551 case '\'': return ',';
7552 case 'q': return '/';
7553 case 'w': return '\'';
7555 /* Hebrew letters - set offset from 'a' */
7556 case ',': c = '{'; break;
7557 case '.': c = 'v'; break;
7558 case ';': c = 't'; break;
7559 default: {
7560 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
7562 #ifdef EBCDIC
7563 /* see note about islower() above */
7564 if (!islower(c))
7565 #else
7566 if (c < 'a' || c > 'z')
7567 #endif
7568 return c;
7569 c = str[CharOrdLow(c)];
7570 break;
7574 return (int)(CharOrdLow(c) + p_aleph);
7577 #endif
7579 static void
7580 ins_reg()
7582 int need_redraw = FALSE;
7583 int regname;
7584 int literally = 0;
7585 #ifdef FEAT_VISUAL
7586 int vis_active = VIsual_active;
7587 #endif
7590 * If we are going to wait for a character, show a '"'.
7592 pc_status = PC_STATUS_UNSET;
7593 if (redrawing() && !char_avail())
7595 /* may need to redraw when no more chars available now */
7596 ins_redraw(FALSE);
7598 edit_putchar('"', TRUE);
7599 #ifdef FEAT_CMDL_INFO
7600 add_to_showcmd_c(Ctrl_R);
7601 #endif
7604 #ifdef USE_ON_FLY_SCROLL
7605 dont_scroll = TRUE; /* disallow scrolling here */
7606 #endif
7609 * Don't map the register name. This also prevents the mode message to be
7610 * deleted when ESC is hit.
7612 ++no_mapping;
7613 regname = plain_vgetc();
7614 #ifdef FEAT_LANGMAP
7615 LANGMAP_ADJUST(regname, TRUE);
7616 #endif
7617 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
7619 /* Get a third key for literal register insertion */
7620 literally = regname;
7621 #ifdef FEAT_CMDL_INFO
7622 add_to_showcmd_c(literally);
7623 #endif
7624 regname = plain_vgetc();
7625 #ifdef FEAT_LANGMAP
7626 LANGMAP_ADJUST(regname, TRUE);
7627 #endif
7629 --no_mapping;
7631 #ifdef FEAT_EVAL
7633 * Don't call u_sync() while getting the expression,
7634 * evaluating it or giving an error message for it!
7636 ++no_u_sync;
7637 if (regname == '=')
7639 # ifdef USE_IM_CONTROL
7640 int im_on = im_get_status();
7641 # endif
7642 regname = get_expr_register();
7643 # ifdef USE_IM_CONTROL
7644 /* Restore the Input Method. */
7645 if (im_on)
7646 im_set_active(TRUE);
7647 # endif
7649 if (regname == NUL || !valid_yank_reg(regname, FALSE))
7651 vim_beep();
7652 need_redraw = TRUE; /* remove the '"' */
7654 else
7656 #endif
7657 if (literally == Ctrl_O || literally == Ctrl_P)
7659 /* Append the command to the redo buffer. */
7660 AppendCharToRedobuff(Ctrl_R);
7661 AppendCharToRedobuff(literally);
7662 AppendCharToRedobuff(regname);
7664 do_put(regname, BACKWARD, 1L,
7665 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
7667 else if (insert_reg(regname, literally) == FAIL)
7669 vim_beep();
7670 need_redraw = TRUE; /* remove the '"' */
7672 else if (stop_insert_mode)
7673 /* When the '=' register was used and a function was invoked that
7674 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
7675 * insert anything, need to remove the '"' */
7676 need_redraw = TRUE;
7678 #ifdef FEAT_EVAL
7680 --no_u_sync;
7681 #endif
7682 #ifdef FEAT_CMDL_INFO
7683 clear_showcmd();
7684 #endif
7686 /* If the inserted register is empty, we need to remove the '"' */
7687 if (need_redraw || stuff_empty())
7688 edit_unputchar();
7690 #ifdef FEAT_VISUAL
7691 /* Disallow starting Visual mode here, would get a weird mode. */
7692 if (!vis_active && VIsual_active)
7693 end_visual_mode();
7694 #endif
7698 * CTRL-G commands in Insert mode.
7700 static void
7701 ins_ctrl_g()
7703 int c;
7705 #ifdef FEAT_INS_EXPAND
7706 /* Right after CTRL-X the cursor will be after the ruler. */
7707 setcursor();
7708 #endif
7711 * Don't map the second key. This also prevents the mode message to be
7712 * deleted when ESC is hit.
7714 ++no_mapping;
7715 c = plain_vgetc();
7716 --no_mapping;
7717 switch (c)
7719 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
7720 case K_UP:
7721 case Ctrl_K:
7722 case 'k': ins_up(TRUE);
7723 break;
7725 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
7726 case K_DOWN:
7727 case Ctrl_J:
7728 case 'j': ins_down(TRUE);
7729 break;
7731 /* CTRL-G u: start new undoable edit */
7732 case 'u': u_sync(TRUE);
7733 ins_need_undo = TRUE;
7735 /* Need to reset Insstart, esp. because a BS that joins
7736 * a line to the previous one must save for undo. */
7737 Insstart = curwin->w_cursor;
7738 break;
7740 /* Unknown CTRL-G command, reserved for future expansion. */
7741 default: vim_beep();
7746 * CTRL-^ in Insert mode.
7748 static void
7749 ins_ctrl_hat()
7751 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
7753 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
7754 if (State & LANGMAP)
7756 curbuf->b_p_iminsert = B_IMODE_NONE;
7757 State &= ~LANGMAP;
7759 else
7761 curbuf->b_p_iminsert = B_IMODE_LMAP;
7762 State |= LANGMAP;
7763 #ifdef USE_IM_CONTROL
7764 im_set_active(FALSE);
7765 #endif
7768 #ifdef USE_IM_CONTROL
7769 else
7771 /* There are no ":lmap" mappings, toggle IM */
7772 if (im_get_status())
7774 curbuf->b_p_iminsert = B_IMODE_NONE;
7775 im_set_active(FALSE);
7777 else
7779 curbuf->b_p_iminsert = B_IMODE_IM;
7780 State &= ~LANGMAP;
7781 im_set_active(TRUE);
7784 #endif
7785 set_iminsert_global();
7786 showmode();
7787 #ifdef FEAT_GUI
7788 /* may show different cursor shape or color */
7789 if (gui.in_use)
7790 gui_update_cursor(TRUE, FALSE);
7791 #endif
7792 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
7793 /* Show/unshow value of 'keymap' in status lines. */
7794 status_redraw_curbuf();
7795 #endif
7799 * Handle ESC in insert mode.
7800 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
7801 * insert.
7803 static int
7804 ins_esc(count, cmdchar, nomove)
7805 long *count;
7806 int cmdchar;
7807 int nomove; /* don't move cursor */
7809 int temp;
7810 static int disabled_redraw = FALSE;
7812 #ifdef FEAT_SPELL
7813 check_spell_redraw();
7814 #endif
7815 #if defined(FEAT_HANGULIN)
7816 # if defined(ESC_CHG_TO_ENG_MODE)
7817 hangul_input_state_set(0);
7818 # endif
7819 if (composing_hangul)
7821 push_raw_key(composing_hangul_buffer, 2);
7822 composing_hangul = 0;
7824 #endif
7826 temp = curwin->w_cursor.col;
7827 if (disabled_redraw)
7829 --RedrawingDisabled;
7830 disabled_redraw = FALSE;
7832 if (!arrow_used)
7835 * Don't append the ESC for "r<CR>" and "grx".
7836 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
7837 * when "count" is non-zero.
7839 if (cmdchar != 'r' && cmdchar != 'v')
7840 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
7843 * Repeating insert may take a long time. Check for
7844 * interrupt now and then.
7846 if (*count > 0)
7848 line_breakcheck();
7849 if (got_int)
7850 *count = 0;
7853 if (--*count > 0) /* repeat what was typed */
7855 /* Vi repeats the insert without replacing characters. */
7856 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
7857 State &= ~REPLACE_FLAG;
7859 (void)start_redo_ins();
7860 if (cmdchar == 'r' || cmdchar == 'v')
7861 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
7862 ++RedrawingDisabled;
7863 disabled_redraw = TRUE;
7864 return FALSE; /* repeat the insert */
7866 stop_insert(&curwin->w_cursor, TRUE);
7867 undisplay_dollar();
7870 /* When an autoindent was removed, curswant stays after the
7871 * indent */
7872 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
7873 curwin->w_set_curswant = TRUE;
7875 /* Remember the last Insert position in the '^ mark. */
7876 if (!cmdmod.keepjumps)
7877 curbuf->b_last_insert = curwin->w_cursor;
7880 * The cursor should end up on the last inserted character.
7881 * Don't do it for CTRL-O, unless past the end of the line.
7883 if (!nomove
7884 && (curwin->w_cursor.col != 0
7885 #ifdef FEAT_VIRTUALEDIT
7886 || curwin->w_cursor.coladd > 0
7887 #endif
7889 && (restart_edit == NUL
7890 || (gchar_cursor() == NUL
7891 #ifdef FEAT_VISUAL
7892 && !VIsual_active
7893 #endif
7895 #ifdef FEAT_RIGHTLEFT
7896 && !revins_on
7897 #endif
7900 #ifdef FEAT_VIRTUALEDIT
7901 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
7903 oneleft();
7904 if (restart_edit != NUL)
7905 ++curwin->w_cursor.coladd;
7907 else
7908 #endif
7910 --curwin->w_cursor.col;
7911 #ifdef FEAT_MBYTE
7912 /* Correct cursor for multi-byte character. */
7913 if (has_mbyte)
7914 mb_adjust_cursor();
7915 #endif
7919 #ifdef USE_IM_CONTROL
7920 /* Disable IM to allow typing English directly for Normal mode commands.
7921 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
7922 * well). */
7923 if (!(State & LANGMAP))
7924 im_save_status(&curbuf->b_p_iminsert);
7925 im_set_active(FALSE);
7926 #endif
7928 State = NORMAL;
7929 /* need to position cursor again (e.g. when on a TAB ) */
7930 changed_cline_bef_curs();
7932 #ifdef FEAT_MOUSE
7933 setmouse();
7934 #endif
7935 #ifdef CURSOR_SHAPE
7936 ui_cursor_shape(); /* may show different cursor shape */
7937 #endif
7940 * When recording or for CTRL-O, need to display the new mode.
7941 * Otherwise remove the mode message.
7943 if (Recording || restart_edit != NUL)
7944 showmode();
7945 else if (p_smd)
7946 MSG("");
7948 return TRUE; /* exit Insert mode */
7951 #ifdef FEAT_RIGHTLEFT
7953 * Toggle language: hkmap and revins_on.
7954 * Move to end of reverse inserted text.
7956 static void
7957 ins_ctrl_()
7959 if (revins_on && revins_chars && revins_scol >= 0)
7961 while (gchar_cursor() != NUL && revins_chars--)
7962 ++curwin->w_cursor.col;
7964 p_ri = !p_ri;
7965 revins_on = (State == INSERT && p_ri);
7966 if (revins_on)
7968 revins_scol = curwin->w_cursor.col;
7969 revins_legal++;
7970 revins_chars = 0;
7971 undisplay_dollar();
7973 else
7974 revins_scol = -1;
7975 #ifdef FEAT_FKMAP
7976 if (p_altkeymap)
7979 * to be consistent also for redo command, using '.'
7980 * set arrow_used to true and stop it - causing to redo
7981 * characters entered in one mode (normal/reverse insert).
7983 arrow_used = TRUE;
7984 (void)stop_arrow();
7985 p_fkmap = curwin->w_p_rl ^ p_ri;
7986 if (p_fkmap && p_ri)
7987 State = INSERT;
7989 else
7990 #endif
7991 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
7992 showmode();
7994 #endif
7996 #ifdef FEAT_VISUAL
7998 * If 'keymodel' contains "startsel", may start selection.
7999 * Returns TRUE when a CTRL-O and other keys stuffed.
8001 static int
8002 ins_start_select(c)
8003 int c;
8005 if (km_startsel)
8006 switch (c)
8008 case K_KHOME:
8009 case K_KEND:
8010 case K_PAGEUP:
8011 case K_KPAGEUP:
8012 case K_PAGEDOWN:
8013 case K_KPAGEDOWN:
8014 # ifdef MACOS
8015 case K_LEFT:
8016 case K_RIGHT:
8017 case K_UP:
8018 case K_DOWN:
8019 case K_END:
8020 case K_HOME:
8021 # endif
8022 if (!(mod_mask & MOD_MASK_SHIFT))
8023 break;
8024 /* FALLTHROUGH */
8025 case K_S_LEFT:
8026 case K_S_RIGHT:
8027 case K_S_UP:
8028 case K_S_DOWN:
8029 case K_S_END:
8030 case K_S_HOME:
8031 /* Start selection right away, the cursor can move with
8032 * CTRL-O when beyond the end of the line. */
8033 start_selection();
8035 /* Execute the key in (insert) Select mode. */
8036 stuffcharReadbuff(Ctrl_O);
8037 if (mod_mask)
8039 char_u buf[4];
8041 buf[0] = K_SPECIAL;
8042 buf[1] = KS_MODIFIER;
8043 buf[2] = mod_mask;
8044 buf[3] = NUL;
8045 stuffReadbuff(buf);
8047 stuffcharReadbuff(c);
8048 return TRUE;
8050 return FALSE;
8052 #endif
8055 * <Insert> key in Insert mode: toggle insert/remplace mode.
8057 static void
8058 ins_insert(replaceState)
8059 int replaceState;
8061 #ifdef FEAT_FKMAP
8062 if (p_fkmap && p_ri)
8064 beep_flush();
8065 EMSG(farsi_text_3); /* encoded in Farsi */
8066 return;
8068 #endif
8070 #ifdef FEAT_AUTOCMD
8071 # ifdef FEAT_EVAL
8072 set_vim_var_string(VV_INSERTMODE,
8073 (char_u *)((State & REPLACE_FLAG) ? "i" :
8074 # ifdef FEAT_VREPLACE
8075 replaceState == VREPLACE ? "v" :
8076 # endif
8077 "r"), 1);
8078 # endif
8079 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
8080 #endif
8081 if (State & REPLACE_FLAG)
8082 State = INSERT | (State & LANGMAP);
8083 else
8084 State = replaceState | (State & LANGMAP);
8085 AppendCharToRedobuff(K_INS);
8086 showmode();
8087 #ifdef CURSOR_SHAPE
8088 ui_cursor_shape(); /* may show different cursor shape */
8089 #endif
8093 * Pressed CTRL-O in Insert mode.
8095 static void
8096 ins_ctrl_o()
8098 #ifdef FEAT_VREPLACE
8099 if (State & VREPLACE_FLAG)
8100 restart_edit = 'V';
8101 else
8102 #endif
8103 if (State & REPLACE_FLAG)
8104 restart_edit = 'R';
8105 else
8106 restart_edit = 'I';
8107 #ifdef FEAT_VIRTUALEDIT
8108 if (virtual_active())
8109 ins_at_eol = FALSE; /* cursor always keeps its column */
8110 else
8111 #endif
8112 ins_at_eol = (gchar_cursor() == NUL);
8116 * If the cursor is on an indent, ^T/^D insert/delete one
8117 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
8118 * Always round the indent to 'shiftwith', this is compatible
8119 * with vi. But vi only supports ^T and ^D after an
8120 * autoindent, we support it everywhere.
8122 static void
8123 ins_shift(c, lastc)
8124 int c;
8125 int lastc;
8127 if (stop_arrow() == FAIL)
8128 return;
8129 AppendCharToRedobuff(c);
8132 * 0^D and ^^D: remove all indent.
8134 if (c == Ctrl_D && (lastc == '0' || lastc == '^')
8135 && curwin->w_cursor.col > 0)
8137 --curwin->w_cursor.col;
8138 (void)del_char(FALSE); /* delete the '^' or '0' */
8139 /* In Replace mode, restore the characters that '^' or '0' replaced. */
8140 if (State & REPLACE_FLAG)
8141 replace_pop_ins();
8142 if (lastc == '^')
8143 old_indent = get_indent(); /* remember curr. indent */
8144 change_indent(INDENT_SET, 0, TRUE, 0);
8146 else
8147 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0);
8149 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
8150 did_ai = FALSE;
8151 #ifdef FEAT_SMARTINDENT
8152 did_si = FALSE;
8153 can_si = FALSE;
8154 can_si_back = FALSE;
8155 #endif
8156 #ifdef FEAT_CINDENT
8157 can_cindent = FALSE; /* no cindenting after ^D or ^T */
8158 #endif
8161 static void
8162 ins_del()
8164 int temp;
8166 if (stop_arrow() == FAIL)
8167 return;
8168 if (gchar_cursor() == NUL) /* delete newline */
8170 temp = curwin->w_cursor.col;
8171 if (!can_bs(BS_EOL) /* only if "eol" included */
8172 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
8173 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
8174 || do_join(FALSE) == FAIL)
8175 vim_beep();
8176 else
8177 curwin->w_cursor.col = temp;
8179 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
8180 vim_beep();
8181 did_ai = FALSE;
8182 #ifdef FEAT_SMARTINDENT
8183 did_si = FALSE;
8184 can_si = FALSE;
8185 can_si_back = FALSE;
8186 #endif
8187 AppendCharToRedobuff(K_DEL);
8191 * Handle Backspace, delete-word and delete-line in Insert mode.
8192 * Return TRUE when backspace was actually used.
8194 static int
8195 ins_bs(c, mode, inserted_space_p)
8196 int c;
8197 int mode;
8198 int *inserted_space_p;
8200 linenr_T lnum;
8201 int cc;
8202 int temp = 0; /* init for GCC */
8203 colnr_T mincol;
8204 int did_backspace = FALSE;
8205 int in_indent;
8206 int oldState;
8207 #ifdef FEAT_MBYTE
8208 int cpc[MAX_MCO]; /* composing characters */
8209 #endif
8212 * can't delete anything in an empty file
8213 * can't backup past first character in buffer
8214 * can't backup past starting point unless 'backspace' > 1
8215 * can backup to a previous line if 'backspace' == 0
8217 if ( bufempty()
8218 || (
8219 #ifdef FEAT_RIGHTLEFT
8220 !revins_on &&
8221 #endif
8222 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
8223 || (!can_bs(BS_START)
8224 && (arrow_used
8225 || (curwin->w_cursor.lnum == Insstart.lnum
8226 && curwin->w_cursor.col <= Insstart.col)))
8227 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
8228 && curwin->w_cursor.col <= ai_col)
8229 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
8231 vim_beep();
8232 return FALSE;
8235 if (stop_arrow() == FAIL)
8236 return FALSE;
8237 in_indent = inindent(0);
8238 #ifdef FEAT_CINDENT
8239 if (in_indent)
8240 can_cindent = FALSE;
8241 #endif
8242 #ifdef FEAT_COMMENTS
8243 end_comment_pending = NUL; /* After BS, don't auto-end comment */
8244 #endif
8245 #ifdef FEAT_RIGHTLEFT
8246 if (revins_on) /* put cursor after last inserted char */
8247 inc_cursor();
8248 #endif
8250 #ifdef FEAT_VIRTUALEDIT
8251 /* Virtualedit:
8252 * BACKSPACE_CHAR eats a virtual space
8253 * BACKSPACE_WORD eats all coladd
8254 * BACKSPACE_LINE eats all coladd and keeps going
8256 if (curwin->w_cursor.coladd > 0)
8258 if (mode == BACKSPACE_CHAR)
8260 --curwin->w_cursor.coladd;
8261 return TRUE;
8263 if (mode == BACKSPACE_WORD)
8265 curwin->w_cursor.coladd = 0;
8266 return TRUE;
8268 curwin->w_cursor.coladd = 0;
8270 #endif
8273 * delete newline!
8275 if (curwin->w_cursor.col == 0)
8277 lnum = Insstart.lnum;
8278 if (curwin->w_cursor.lnum == Insstart.lnum
8279 #ifdef FEAT_RIGHTLEFT
8280 || revins_on
8281 #endif
8284 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
8285 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
8286 return FALSE;
8287 --Insstart.lnum;
8288 Insstart.col = MAXCOL;
8291 * In replace mode:
8292 * cc < 0: NL was inserted, delete it
8293 * cc >= 0: NL was replaced, put original characters back
8295 cc = -1;
8296 if (State & REPLACE_FLAG)
8297 cc = replace_pop(); /* returns -1 if NL was inserted */
8299 * In replace mode, in the line we started replacing, we only move the
8300 * cursor.
8302 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
8304 dec_cursor();
8306 else
8308 #ifdef FEAT_VREPLACE
8309 if (!(State & VREPLACE_FLAG)
8310 || curwin->w_cursor.lnum > orig_line_count)
8311 #endif
8313 temp = gchar_cursor(); /* remember current char */
8314 --curwin->w_cursor.lnum;
8316 /* When "aw" is in 'formatoptions' we must delete the space at
8317 * the end of the line, otherwise the line will be broken
8318 * again when auto-formatting. */
8319 if (has_format_option(FO_AUTO)
8320 && has_format_option(FO_WHITE_PAR))
8322 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
8323 TRUE);
8324 int len;
8326 len = (int)STRLEN(ptr);
8327 if (len > 0 && ptr[len - 1] == ' ')
8328 ptr[len - 1] = NUL;
8331 (void)do_join(FALSE);
8332 if (temp == NUL && gchar_cursor() != NUL)
8333 inc_cursor();
8335 #ifdef FEAT_VREPLACE
8336 else
8337 dec_cursor();
8338 #endif
8341 * In REPLACE mode we have to put back the text that was replaced
8342 * by the NL. On the replace stack is first a NUL-terminated
8343 * sequence of characters that were deleted and then the
8344 * characters that NL replaced.
8346 if (State & REPLACE_FLAG)
8349 * Do the next ins_char() in NORMAL state, to
8350 * prevent ins_char() from replacing characters and
8351 * avoiding showmatch().
8353 oldState = State;
8354 State = NORMAL;
8356 * restore characters (blanks) deleted after cursor
8358 while (cc > 0)
8360 temp = curwin->w_cursor.col;
8361 #ifdef FEAT_MBYTE
8362 mb_replace_pop_ins(cc);
8363 #else
8364 ins_char(cc);
8365 #endif
8366 curwin->w_cursor.col = temp;
8367 cc = replace_pop();
8369 /* restore the characters that NL replaced */
8370 replace_pop_ins();
8371 State = oldState;
8374 did_ai = FALSE;
8376 else
8379 * Delete character(s) before the cursor.
8381 #ifdef FEAT_RIGHTLEFT
8382 if (revins_on) /* put cursor on last inserted char */
8383 dec_cursor();
8384 #endif
8385 mincol = 0;
8386 /* keep indent */
8387 if (mode == BACKSPACE_LINE
8388 && (curbuf->b_p_ai
8389 #ifdef FEAT_CINDENT
8390 || cindent_on()
8391 #endif
8393 #ifdef FEAT_RIGHTLEFT
8394 && !revins_on
8395 #endif
8398 temp = curwin->w_cursor.col;
8399 beginline(BL_WHITE);
8400 if (curwin->w_cursor.col < (colnr_T)temp)
8401 mincol = curwin->w_cursor.col;
8402 curwin->w_cursor.col = temp;
8406 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8408 if ( mode == BACKSPACE_CHAR
8409 && ((p_sta && in_indent)
8410 || (curbuf->b_p_sts != 0
8411 && (*(ml_get_cursor() - 1) == TAB
8412 || (*(ml_get_cursor() - 1) == ' '
8413 && (!*inserted_space_p
8414 || arrow_used))))))
8416 int ts;
8417 colnr_T vcol;
8418 colnr_T want_vcol;
8419 #if 0
8420 int extra = 0;
8421 #endif
8423 *inserted_space_p = FALSE;
8424 if (p_sta && in_indent)
8425 ts = curbuf->b_p_sw;
8426 else
8427 ts = curbuf->b_p_sts;
8428 /* Compute the virtual column where we want to be. Since
8429 * 'showbreak' may get in the way, need to get the last column of
8430 * the previous character. */
8431 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8432 dec_cursor();
8433 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8434 inc_cursor();
8435 want_vcol = (want_vcol / ts) * ts;
8437 /* delete characters until we are at or before want_vcol */
8438 while (vcol > want_vcol
8439 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8441 dec_cursor();
8442 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8443 if (State & REPLACE_FLAG)
8445 /* Don't delete characters before the insert point when in
8446 * Replace mode */
8447 if (curwin->w_cursor.lnum != Insstart.lnum
8448 || curwin->w_cursor.col >= Insstart.col)
8450 #if 0 /* what was this for? It causes problems when sw != ts. */
8451 if (State == REPLACE && (int)vcol < want_vcol)
8453 (void)del_char(FALSE);
8454 extra = 2; /* don't pop too much */
8456 else
8457 #endif
8458 replace_do_bs();
8461 else
8462 (void)del_char(FALSE);
8465 /* insert extra spaces until we are at want_vcol */
8466 while (vcol < want_vcol)
8468 /* Remember the first char we inserted */
8469 if (curwin->w_cursor.lnum == Insstart.lnum
8470 && curwin->w_cursor.col < Insstart.col)
8471 Insstart.col = curwin->w_cursor.col;
8473 #ifdef FEAT_VREPLACE
8474 if (State & VREPLACE_FLAG)
8475 ins_char(' ');
8476 else
8477 #endif
8479 ins_str((char_u *)" ");
8480 if ((State & REPLACE_FLAG) /* && extra <= 1 */)
8482 #if 0
8483 if (extra)
8484 replace_push_off(NUL);
8485 else
8486 #endif
8487 replace_push(NUL);
8489 #if 0
8490 if (extra == 2)
8491 extra = 1;
8492 #endif
8494 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8499 * Delete upto starting point, start of line or previous word.
8501 else do
8503 #ifdef FEAT_RIGHTLEFT
8504 if (!revins_on) /* put cursor on char to be deleted */
8505 #endif
8506 dec_cursor();
8508 /* start of word? */
8509 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8511 mode = BACKSPACE_WORD_NOT_SPACE;
8512 temp = vim_iswordc(gchar_cursor());
8514 /* end of word? */
8515 else if (mode == BACKSPACE_WORD_NOT_SPACE
8516 && (vim_isspace(cc = gchar_cursor())
8517 || vim_iswordc(cc) != temp))
8519 #ifdef FEAT_RIGHTLEFT
8520 if (!revins_on)
8521 #endif
8522 inc_cursor();
8523 #ifdef FEAT_RIGHTLEFT
8524 else if (State & REPLACE_FLAG)
8525 dec_cursor();
8526 #endif
8527 break;
8529 if (State & REPLACE_FLAG)
8530 replace_do_bs();
8531 else
8533 #ifdef FEAT_MBYTE
8534 if (enc_utf8 && p_deco)
8535 (void)utfc_ptr2char(ml_get_cursor(), cpc);
8536 #endif
8537 (void)del_char(FALSE);
8538 #ifdef FEAT_MBYTE
8540 * If there are combining characters and 'delcombine' is set
8541 * move the cursor back. Don't back up before the base
8542 * character.
8544 if (enc_utf8 && p_deco && cpc[0] != NUL)
8545 inc_cursor();
8546 #endif
8547 #ifdef FEAT_RIGHTLEFT
8548 if (revins_chars)
8550 revins_chars--;
8551 revins_legal++;
8553 if (revins_on && gchar_cursor() == NUL)
8554 break;
8555 #endif
8557 /* Just a single backspace?: */
8558 if (mode == BACKSPACE_CHAR)
8559 break;
8560 } while (
8561 #ifdef FEAT_RIGHTLEFT
8562 revins_on ||
8563 #endif
8564 (curwin->w_cursor.col > mincol
8565 && (curwin->w_cursor.lnum != Insstart.lnum
8566 || curwin->w_cursor.col != Insstart.col)));
8567 did_backspace = TRUE;
8569 #ifdef FEAT_SMARTINDENT
8570 did_si = FALSE;
8571 can_si = FALSE;
8572 can_si_back = FALSE;
8573 #endif
8574 if (curwin->w_cursor.col <= 1)
8575 did_ai = FALSE;
8577 * It's a little strange to put backspaces into the redo
8578 * buffer, but it makes auto-indent a lot easier to deal
8579 * with.
8581 AppendCharToRedobuff(c);
8583 /* If deleted before the insertion point, adjust it */
8584 if (curwin->w_cursor.lnum == Insstart.lnum
8585 && curwin->w_cursor.col < Insstart.col)
8586 Insstart.col = curwin->w_cursor.col;
8588 /* vi behaviour: the cursor moves backward but the character that
8589 * was there remains visible
8590 * Vim behaviour: the cursor moves backward and the character that
8591 * was there is erased from the screen.
8592 * We can emulate the vi behaviour by pretending there is a dollar
8593 * displayed even when there isn't.
8594 * --pkv Sun Jan 19 01:56:40 EST 2003 */
8595 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
8596 dollar_vcol = curwin->w_virtcol;
8598 return did_backspace;
8601 #ifdef FEAT_MOUSE
8602 static void
8603 ins_mouse(c)
8604 int c;
8606 pos_T tpos;
8607 win_T *old_curwin = curwin;
8609 # ifdef FEAT_GUI
8610 /* When GUI is active, also move/paste when 'mouse' is empty */
8611 if (!gui.in_use)
8612 # endif
8613 if (!mouse_has(MOUSE_INSERT))
8614 return;
8616 undisplay_dollar();
8617 tpos = curwin->w_cursor;
8618 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
8620 #ifdef FEAT_WINDOWS
8621 win_T *new_curwin = curwin;
8623 if (curwin != old_curwin && win_valid(old_curwin))
8625 /* Mouse took us to another window. We need to go back to the
8626 * previous one to stop insert there properly. */
8627 curwin = old_curwin;
8628 curbuf = curwin->w_buffer;
8630 #endif
8631 start_arrow(curwin == old_curwin ? &tpos : NULL);
8632 #ifdef FEAT_WINDOWS
8633 if (curwin != new_curwin && win_valid(new_curwin))
8635 curwin = new_curwin;
8636 curbuf = curwin->w_buffer;
8638 #endif
8639 # ifdef FEAT_CINDENT
8640 can_cindent = TRUE;
8641 # endif
8644 #ifdef FEAT_WINDOWS
8645 /* redraw status lines (in case another window became active) */
8646 redraw_statuslines();
8647 #endif
8650 static void
8651 ins_mousescroll(up)
8652 int up;
8654 pos_T tpos;
8655 # if defined(FEAT_WINDOWS)
8656 win_T *old_curwin = curwin;
8657 # endif
8658 # ifdef FEAT_INS_EXPAND
8659 int did_scroll = FALSE;
8660 # endif
8662 tpos = curwin->w_cursor;
8664 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8665 /* Currently the mouse coordinates are only known in the GUI. */
8666 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
8668 int row, col;
8670 row = mouse_row;
8671 col = mouse_col;
8673 /* find the window at the pointer coordinates */
8674 curwin = mouse_find_win(&row, &col);
8675 curbuf = curwin->w_buffer;
8677 if (curwin == old_curwin)
8678 # endif
8679 undisplay_dollar();
8681 # ifdef FEAT_INS_EXPAND
8682 /* Don't scroll the window in which completion is being done. */
8683 if (!pum_visible()
8684 # if defined(FEAT_WINDOWS)
8685 || curwin != old_curwin
8686 # endif
8688 # endif
8690 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
8691 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
8692 else
8693 scroll_redraw(up, 3L);
8694 # ifdef FEAT_INS_EXPAND
8695 did_scroll = TRUE;
8696 # endif
8699 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8700 curwin->w_redr_status = TRUE;
8702 curwin = old_curwin;
8703 curbuf = curwin->w_buffer;
8704 # endif
8706 # ifdef FEAT_INS_EXPAND
8707 /* The popup menu may overlay the window, need to redraw it.
8708 * TODO: Would be more efficient to only redraw the windows that are
8709 * overlapped by the popup menu. */
8710 if (pum_visible() && did_scroll)
8712 redraw_all_later(NOT_VALID);
8713 ins_compl_show_pum();
8715 # endif
8717 if (!equalpos(curwin->w_cursor, tpos))
8719 start_arrow(&tpos);
8720 # ifdef FEAT_CINDENT
8721 can_cindent = TRUE;
8722 # endif
8725 #endif
8727 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
8728 static void
8729 ins_tabline(c)
8730 int c;
8732 /* We will be leaving the current window, unless closing another tab. */
8733 if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
8734 || (current_tab != 0 && current_tab != tabpage_index(curtab)))
8736 undisplay_dollar();
8737 start_arrow(&curwin->w_cursor);
8738 # ifdef FEAT_CINDENT
8739 can_cindent = TRUE;
8740 # endif
8743 if (c == K_TABLINE)
8744 goto_tabpage(current_tab);
8745 else
8747 handle_tabmenu();
8748 redraw_statuslines(); /* will redraw the tabline when needed */
8751 #endif
8753 #if defined(FEAT_GUI) || defined(PROTO)
8754 void
8755 ins_scroll()
8757 pos_T tpos;
8759 undisplay_dollar();
8760 tpos = curwin->w_cursor;
8761 if (gui_do_scroll())
8763 start_arrow(&tpos);
8764 # ifdef FEAT_CINDENT
8765 can_cindent = TRUE;
8766 # endif
8770 void
8771 ins_horscroll()
8773 pos_T tpos;
8775 undisplay_dollar();
8776 tpos = curwin->w_cursor;
8777 if (gui_do_horiz_scroll())
8779 start_arrow(&tpos);
8780 # ifdef FEAT_CINDENT
8781 can_cindent = TRUE;
8782 # endif
8785 #endif
8787 static void
8788 ins_left()
8790 pos_T tpos;
8792 #ifdef FEAT_FOLDING
8793 if ((fdo_flags & FDO_HOR) && KeyTyped)
8794 foldOpenCursor();
8795 #endif
8796 undisplay_dollar();
8797 tpos = curwin->w_cursor;
8798 if (oneleft() == OK)
8800 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
8801 /* Only call start_arrow() when not busy with preediting, it will
8802 * break undo. K_LEFT is inserted in im_correct_cursor(). */
8803 if (!im_is_preediting())
8804 #endif
8805 start_arrow(&tpos);
8806 #ifdef FEAT_RIGHTLEFT
8807 /* If exit reversed string, position is fixed */
8808 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
8809 revins_legal++;
8810 revins_chars++;
8811 #endif
8815 * if 'whichwrap' set for cursor in insert mode may go to
8816 * previous line
8818 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
8820 start_arrow(&tpos);
8821 --(curwin->w_cursor.lnum);
8822 coladvance((colnr_T)MAXCOL);
8823 curwin->w_set_curswant = TRUE; /* so we stay at the end */
8825 else
8826 vim_beep();
8829 static void
8830 ins_home(c)
8831 int c;
8833 pos_T tpos;
8835 #ifdef FEAT_FOLDING
8836 if ((fdo_flags & FDO_HOR) && KeyTyped)
8837 foldOpenCursor();
8838 #endif
8839 undisplay_dollar();
8840 tpos = curwin->w_cursor;
8841 if (c == K_C_HOME)
8842 curwin->w_cursor.lnum = 1;
8843 curwin->w_cursor.col = 0;
8844 #ifdef FEAT_VIRTUALEDIT
8845 curwin->w_cursor.coladd = 0;
8846 #endif
8847 curwin->w_curswant = 0;
8848 start_arrow(&tpos);
8851 static void
8852 ins_end(c)
8853 int c;
8855 pos_T tpos;
8857 #ifdef FEAT_FOLDING
8858 if ((fdo_flags & FDO_HOR) && KeyTyped)
8859 foldOpenCursor();
8860 #endif
8861 undisplay_dollar();
8862 tpos = curwin->w_cursor;
8863 if (c == K_C_END)
8864 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
8865 coladvance((colnr_T)MAXCOL);
8866 curwin->w_curswant = MAXCOL;
8868 start_arrow(&tpos);
8871 static void
8872 ins_s_left()
8874 #ifdef FEAT_FOLDING
8875 if ((fdo_flags & FDO_HOR) && KeyTyped)
8876 foldOpenCursor();
8877 #endif
8878 undisplay_dollar();
8879 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
8881 start_arrow(&curwin->w_cursor);
8882 (void)bck_word(1L, FALSE, FALSE);
8883 curwin->w_set_curswant = TRUE;
8885 else
8886 vim_beep();
8889 static void
8890 ins_right()
8892 #ifdef FEAT_FOLDING
8893 if ((fdo_flags & FDO_HOR) && KeyTyped)
8894 foldOpenCursor();
8895 #endif
8896 undisplay_dollar();
8897 if (gchar_cursor() != NUL || virtual_active()
8900 start_arrow(&curwin->w_cursor);
8901 curwin->w_set_curswant = TRUE;
8902 #ifdef FEAT_VIRTUALEDIT
8903 if (virtual_active())
8904 oneright();
8905 else
8906 #endif
8908 #ifdef FEAT_MBYTE
8909 if (has_mbyte)
8910 curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
8911 else
8912 #endif
8913 ++curwin->w_cursor.col;
8916 #ifdef FEAT_RIGHTLEFT
8917 revins_legal++;
8918 if (revins_chars)
8919 revins_chars--;
8920 #endif
8922 /* if 'whichwrap' set for cursor in insert mode, may move the
8923 * cursor to the next line */
8924 else if (vim_strchr(p_ww, ']') != NULL
8925 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
8927 start_arrow(&curwin->w_cursor);
8928 curwin->w_set_curswant = TRUE;
8929 ++curwin->w_cursor.lnum;
8930 curwin->w_cursor.col = 0;
8932 else
8933 vim_beep();
8936 static void
8937 ins_s_right()
8939 #ifdef FEAT_FOLDING
8940 if ((fdo_flags & FDO_HOR) && KeyTyped)
8941 foldOpenCursor();
8942 #endif
8943 undisplay_dollar();
8944 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
8945 || gchar_cursor() != NUL)
8947 start_arrow(&curwin->w_cursor);
8948 (void)fwd_word(1L, FALSE, 0);
8949 curwin->w_set_curswant = TRUE;
8951 else
8952 vim_beep();
8955 static void
8956 ins_up(startcol)
8957 int startcol; /* when TRUE move to Insstart.col */
8959 pos_T tpos;
8960 linenr_T old_topline = curwin->w_topline;
8961 #ifdef FEAT_DIFF
8962 int old_topfill = curwin->w_topfill;
8963 #endif
8965 undisplay_dollar();
8966 tpos = curwin->w_cursor;
8967 if (cursor_up(1L, TRUE) == OK)
8969 if (startcol)
8970 coladvance(getvcol_nolist(&Insstart));
8971 if (old_topline != curwin->w_topline
8972 #ifdef FEAT_DIFF
8973 || old_topfill != curwin->w_topfill
8974 #endif
8976 redraw_later(VALID);
8977 start_arrow(&tpos);
8978 #ifdef FEAT_CINDENT
8979 can_cindent = TRUE;
8980 #endif
8982 else
8983 vim_beep();
8986 static void
8987 ins_pageup()
8989 pos_T tpos;
8991 undisplay_dollar();
8993 #ifdef FEAT_WINDOWS
8994 if (mod_mask & MOD_MASK_CTRL)
8996 /* <C-PageUp>: tab page back */
8997 if (first_tabpage->tp_next != NULL)
8999 start_arrow(&curwin->w_cursor);
9000 goto_tabpage(-1);
9002 return;
9004 #endif
9006 tpos = curwin->w_cursor;
9007 if (onepage(BACKWARD, 1L) == OK)
9009 start_arrow(&tpos);
9010 #ifdef FEAT_CINDENT
9011 can_cindent = TRUE;
9012 #endif
9014 else
9015 vim_beep();
9018 static void
9019 ins_down(startcol)
9020 int startcol; /* when TRUE move to Insstart.col */
9022 pos_T tpos;
9023 linenr_T old_topline = curwin->w_topline;
9024 #ifdef FEAT_DIFF
9025 int old_topfill = curwin->w_topfill;
9026 #endif
9028 undisplay_dollar();
9029 tpos = curwin->w_cursor;
9030 if (cursor_down(1L, TRUE) == OK)
9032 if (startcol)
9033 coladvance(getvcol_nolist(&Insstart));
9034 if (old_topline != curwin->w_topline
9035 #ifdef FEAT_DIFF
9036 || old_topfill != curwin->w_topfill
9037 #endif
9039 redraw_later(VALID);
9040 start_arrow(&tpos);
9041 #ifdef FEAT_CINDENT
9042 can_cindent = TRUE;
9043 #endif
9045 else
9046 vim_beep();
9049 static void
9050 ins_pagedown()
9052 pos_T tpos;
9054 undisplay_dollar();
9056 #ifdef FEAT_WINDOWS
9057 if (mod_mask & MOD_MASK_CTRL)
9059 /* <C-PageDown>: tab page forward */
9060 if (first_tabpage->tp_next != NULL)
9062 start_arrow(&curwin->w_cursor);
9063 goto_tabpage(0);
9065 return;
9067 #endif
9069 tpos = curwin->w_cursor;
9070 if (onepage(FORWARD, 1L) == OK)
9072 start_arrow(&tpos);
9073 #ifdef FEAT_CINDENT
9074 can_cindent = TRUE;
9075 #endif
9077 else
9078 vim_beep();
9081 #ifdef FEAT_DND
9082 static void
9083 ins_drop()
9085 do_put('~', BACKWARD, 1L, PUT_CURSEND);
9087 #endif
9090 * Handle TAB in Insert or Replace mode.
9091 * Return TRUE when the TAB needs to be inserted like a normal character.
9093 static int
9094 ins_tab()
9096 int ind;
9097 int i;
9098 int temp;
9100 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
9101 Insstart_blank_vcol = get_nolist_virtcol();
9102 if (echeck_abbr(TAB + ABBR_OFF))
9103 return FALSE;
9105 ind = inindent(0);
9106 #ifdef FEAT_CINDENT
9107 if (ind)
9108 can_cindent = FALSE;
9109 #endif
9112 * When nothing special, insert TAB like a normal character
9114 if (!curbuf->b_p_et
9115 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
9116 && curbuf->b_p_sts == 0)
9117 return TRUE;
9119 if (stop_arrow() == FAIL)
9120 return TRUE;
9122 did_ai = FALSE;
9123 #ifdef FEAT_SMARTINDENT
9124 did_si = FALSE;
9125 can_si = FALSE;
9126 can_si_back = FALSE;
9127 #endif
9128 AppendToRedobuff((char_u *)"\t");
9130 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9131 temp = (int)curbuf->b_p_sw;
9132 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
9133 temp = (int)curbuf->b_p_sts;
9134 else /* otherwise use 'tabstop' */
9135 temp = (int)curbuf->b_p_ts;
9136 temp -= get_nolist_virtcol() % temp;
9139 * Insert the first space with ins_char(). It will delete one char in
9140 * replace mode. Insert the rest with ins_str(); it will not delete any
9141 * chars. For VREPLACE mode, we use ins_char() for all characters.
9143 ins_char(' ');
9144 while (--temp > 0)
9146 #ifdef FEAT_VREPLACE
9147 if (State & VREPLACE_FLAG)
9148 ins_char(' ');
9149 else
9150 #endif
9152 ins_str((char_u *)" ");
9153 if (State & REPLACE_FLAG) /* no char replaced */
9154 replace_push(NUL);
9159 * When 'expandtab' not set: Replace spaces by TABs where possible.
9161 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
9163 char_u *ptr;
9164 #ifdef FEAT_VREPLACE
9165 char_u *saved_line = NULL; /* init for GCC */
9166 pos_T pos;
9167 #endif
9168 pos_T fpos;
9169 pos_T *cursor;
9170 colnr_T want_vcol, vcol;
9171 int change_col = -1;
9172 int save_list = curwin->w_p_list;
9175 * Get the current line. For VREPLACE mode, don't make real changes
9176 * yet, just work on a copy of the line.
9178 #ifdef FEAT_VREPLACE
9179 if (State & VREPLACE_FLAG)
9181 pos = curwin->w_cursor;
9182 cursor = &pos;
9183 saved_line = vim_strsave(ml_get_curline());
9184 if (saved_line == NULL)
9185 return FALSE;
9186 ptr = saved_line + pos.col;
9188 else
9189 #endif
9191 ptr = ml_get_cursor();
9192 cursor = &curwin->w_cursor;
9195 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
9196 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9197 curwin->w_p_list = FALSE;
9199 /* Find first white before the cursor */
9200 fpos = curwin->w_cursor;
9201 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
9203 --fpos.col;
9204 --ptr;
9207 /* In Replace mode, don't change characters before the insert point. */
9208 if ((State & REPLACE_FLAG)
9209 && fpos.lnum == Insstart.lnum
9210 && fpos.col < Insstart.col)
9212 ptr += Insstart.col - fpos.col;
9213 fpos.col = Insstart.col;
9216 /* compute virtual column numbers of first white and cursor */
9217 getvcol(curwin, &fpos, &vcol, NULL, NULL);
9218 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
9220 /* Use as many TABs as possible. Beware of 'showbreak' and
9221 * 'linebreak' adding extra virtual columns. */
9222 while (vim_iswhite(*ptr))
9224 i = lbr_chartabsize((char_u *)"\t", vcol);
9225 if (vcol + i > want_vcol)
9226 break;
9227 if (*ptr != TAB)
9229 *ptr = TAB;
9230 if (change_col < 0)
9232 change_col = fpos.col; /* Column of first change */
9233 /* May have to adjust Insstart */
9234 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
9235 Insstart.col = fpos.col;
9238 ++fpos.col;
9239 ++ptr;
9240 vcol += i;
9243 if (change_col >= 0)
9245 int repl_off = 0;
9247 /* Skip over the spaces we need. */
9248 while (vcol < want_vcol && *ptr == ' ')
9250 vcol += lbr_chartabsize(ptr, vcol);
9251 ++ptr;
9252 ++repl_off;
9254 if (vcol > want_vcol)
9256 /* Must have a char with 'showbreak' just before it. */
9257 --ptr;
9258 --repl_off;
9260 fpos.col += repl_off;
9262 /* Delete following spaces. */
9263 i = cursor->col - fpos.col;
9264 if (i > 0)
9266 mch_memmove(ptr, ptr + i, STRLEN(ptr + i) + 1);
9267 /* correct replace stack. */
9268 if ((State & REPLACE_FLAG)
9269 #ifdef FEAT_VREPLACE
9270 && !(State & VREPLACE_FLAG)
9271 #endif
9273 for (temp = i; --temp >= 0; )
9274 replace_join(repl_off);
9276 #ifdef FEAT_NETBEANS_INTG
9277 if (usingNetbeans)
9279 netbeans_removed(curbuf, fpos.lnum, cursor->col,
9280 (long)(i + 1));
9281 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
9282 (char_u *)"\t", 1);
9284 #endif
9285 cursor->col -= i;
9287 #ifdef FEAT_VREPLACE
9289 * In VREPLACE mode, we haven't changed anything yet. Do it now by
9290 * backspacing over the changed spacing and then inserting the new
9291 * spacing.
9293 if (State & VREPLACE_FLAG)
9295 /* Backspace from real cursor to change_col */
9296 backspace_until_column(change_col);
9298 /* Insert each char in saved_line from changed_col to
9299 * ptr-cursor */
9300 ins_bytes_len(saved_line + change_col,
9301 cursor->col - change_col);
9303 #endif
9306 #ifdef FEAT_VREPLACE
9307 if (State & VREPLACE_FLAG)
9308 vim_free(saved_line);
9309 #endif
9310 curwin->w_p_list = save_list;
9313 return FALSE;
9317 * Handle CR or NL in insert mode.
9318 * Return TRUE when out of memory or can't undo.
9320 static int
9321 ins_eol(c)
9322 int c;
9324 int i;
9326 if (echeck_abbr(c + ABBR_OFF))
9327 return FALSE;
9328 if (stop_arrow() == FAIL)
9329 return TRUE;
9330 undisplay_dollar();
9333 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
9334 * character under the cursor. Only push a NUL on the replace stack,
9335 * nothing to put back when the NL is deleted.
9337 if ((State & REPLACE_FLAG)
9338 #ifdef FEAT_VREPLACE
9339 && !(State & VREPLACE_FLAG)
9340 #endif
9342 replace_push(NUL);
9345 * In VREPLACE mode, a NL replaces the rest of the line, and starts
9346 * replacing the next line, so we push all of the characters left on the
9347 * line onto the replace stack. This is not done here though, it is done
9348 * in open_line().
9351 #ifdef FEAT_VIRTUALEDIT
9352 /* Put cursor on NUL if on the last char and coladd is 1 (happens after
9353 * CTRL-O). */
9354 if (virtual_active() && curwin->w_cursor.coladd > 0)
9355 coladvance(getviscol());
9356 #endif
9358 #ifdef FEAT_RIGHTLEFT
9359 # ifdef FEAT_FKMAP
9360 if (p_altkeymap && p_fkmap)
9361 fkmap(NL);
9362 # endif
9363 /* NL in reverse insert will always start in the end of
9364 * current line. */
9365 if (revins_on)
9366 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9367 #endif
9369 AppendToRedobuff(NL_STR);
9370 i = open_line(FORWARD,
9371 #ifdef FEAT_COMMENTS
9372 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
9373 #endif
9374 0, old_indent);
9375 old_indent = 0;
9376 #ifdef FEAT_CINDENT
9377 can_cindent = TRUE;
9378 #endif
9379 #ifdef FEAT_FOLDING
9380 /* When inserting a line the cursor line must never be in a closed fold. */
9381 foldOpenCursor();
9382 #endif
9384 return (!i);
9387 #ifdef FEAT_DIGRAPHS
9389 * Handle digraph in insert mode.
9390 * Returns character still to be inserted, or NUL when nothing remaining to be
9391 * done.
9393 static int
9394 ins_digraph()
9396 int c;
9397 int cc;
9399 pc_status = PC_STATUS_UNSET;
9400 if (redrawing() && !char_avail())
9402 /* may need to redraw when no more chars available now */
9403 ins_redraw(FALSE);
9405 edit_putchar('?', TRUE);
9406 #ifdef FEAT_CMDL_INFO
9407 add_to_showcmd_c(Ctrl_K);
9408 #endif
9411 #ifdef USE_ON_FLY_SCROLL
9412 dont_scroll = TRUE; /* disallow scrolling here */
9413 #endif
9415 /* don't map the digraph chars. This also prevents the
9416 * mode message to be deleted when ESC is hit */
9417 ++no_mapping;
9418 ++allow_keys;
9419 c = plain_vgetc();
9420 --no_mapping;
9421 --allow_keys;
9422 if (IS_SPECIAL(c) || mod_mask) /* special key */
9424 #ifdef FEAT_CMDL_INFO
9425 clear_showcmd();
9426 #endif
9427 insert_special(c, TRUE, FALSE);
9428 return NUL;
9430 if (c != ESC)
9432 if (redrawing() && !char_avail())
9434 /* may need to redraw when no more chars available now */
9435 ins_redraw(FALSE);
9437 if (char2cells(c) == 1)
9439 /* first remove the '?', otherwise it's restored when typing
9440 * an ESC next */
9441 edit_unputchar();
9442 ins_redraw(FALSE);
9443 edit_putchar(c, TRUE);
9445 #ifdef FEAT_CMDL_INFO
9446 add_to_showcmd_c(c);
9447 #endif
9449 ++no_mapping;
9450 ++allow_keys;
9451 cc = plain_vgetc();
9452 --no_mapping;
9453 --allow_keys;
9454 if (cc != ESC)
9456 AppendToRedobuff((char_u *)CTRL_V_STR);
9457 c = getdigraph(c, cc, TRUE);
9458 #ifdef FEAT_CMDL_INFO
9459 clear_showcmd();
9460 #endif
9461 return c;
9464 edit_unputchar();
9465 #ifdef FEAT_CMDL_INFO
9466 clear_showcmd();
9467 #endif
9468 return NUL;
9470 #endif
9473 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9474 * Returns the char to be inserted, or NUL if none found.
9476 static int
9477 ins_copychar(lnum)
9478 linenr_T lnum;
9480 int c;
9481 int temp;
9482 char_u *ptr, *prev_ptr;
9484 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9486 vim_beep();
9487 return NUL;
9490 /* try to advance to the cursor column */
9491 temp = 0;
9492 ptr = ml_get(lnum);
9493 prev_ptr = ptr;
9494 validate_virtcol();
9495 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9497 prev_ptr = ptr;
9498 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
9500 if ((colnr_T)temp > curwin->w_virtcol)
9501 ptr = prev_ptr;
9503 #ifdef FEAT_MBYTE
9504 c = (*mb_ptr2char)(ptr);
9505 #else
9506 c = *ptr;
9507 #endif
9508 if (c == NUL)
9509 vim_beep();
9510 return c;
9514 * CTRL-Y or CTRL-E typed in Insert mode.
9516 static int
9517 ins_ctrl_ey(tc)
9518 int tc;
9520 int c = tc;
9522 #ifdef FEAT_INS_EXPAND
9523 if (ctrl_x_mode == CTRL_X_SCROLL)
9525 if (c == Ctrl_Y)
9526 scrolldown_clamp();
9527 else
9528 scrollup_clamp();
9529 redraw_later(VALID);
9531 else
9532 #endif
9534 c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
9535 if (c != NUL)
9537 long tw_save;
9539 /* The character must be taken literally, insert like it
9540 * was typed after a CTRL-V, and pretend 'textwidth'
9541 * wasn't set. Digits, 'o' and 'x' are special after a
9542 * CTRL-V, don't use it for these. */
9543 if (c < 256 && !isalnum(c))
9544 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
9545 tw_save = curbuf->b_p_tw;
9546 curbuf->b_p_tw = -1;
9547 insert_special(c, TRUE, FALSE);
9548 curbuf->b_p_tw = tw_save;
9549 #ifdef FEAT_RIGHTLEFT
9550 revins_chars++;
9551 revins_legal++;
9552 #endif
9553 c = Ctrl_V; /* pretend CTRL-V is last character */
9554 auto_format(FALSE, TRUE);
9557 return c;
9560 #ifdef FEAT_SMARTINDENT
9562 * Try to do some very smart auto-indenting.
9563 * Used when inserting a "normal" character.
9565 static void
9566 ins_try_si(c)
9567 int c;
9569 pos_T *pos, old_pos;
9570 char_u *ptr;
9571 int i;
9572 int temp;
9575 * do some very smart indenting when entering '{' or '}'
9577 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
9580 * for '}' set indent equal to indent of line containing matching '{'
9582 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
9584 old_pos = curwin->w_cursor;
9586 * If the matching '{' has a ')' immediately before it (ignoring
9587 * white-space), then line up with the start of the line
9588 * containing the matching '(' if there is one. This handles the
9589 * case where an "if (..\n..) {" statement continues over multiple
9590 * lines -- webb
9592 ptr = ml_get(pos->lnum);
9593 i = pos->col;
9594 if (i > 0) /* skip blanks before '{' */
9595 while (--i > 0 && vim_iswhite(ptr[i]))
9597 curwin->w_cursor.lnum = pos->lnum;
9598 curwin->w_cursor.col = i;
9599 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
9600 curwin->w_cursor = *pos;
9601 i = get_indent();
9602 curwin->w_cursor = old_pos;
9603 #ifdef FEAT_VREPLACE
9604 if (State & VREPLACE_FLAG)
9605 change_indent(INDENT_SET, i, FALSE, NUL);
9606 else
9607 #endif
9608 (void)set_indent(i, SIN_CHANGED);
9610 else if (curwin->w_cursor.col > 0)
9613 * when inserting '{' after "O" reduce indent, but not
9614 * more than indent of previous line
9616 temp = TRUE;
9617 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
9619 old_pos = curwin->w_cursor;
9620 i = get_indent();
9621 while (curwin->w_cursor.lnum > 1)
9623 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
9625 /* ignore empty lines and lines starting with '#'. */
9626 if (*ptr != '#' && *ptr != NUL)
9627 break;
9629 if (get_indent() >= i)
9630 temp = FALSE;
9631 curwin->w_cursor = old_pos;
9633 if (temp)
9634 shift_line(TRUE, FALSE, 1);
9639 * set indent of '#' always to 0
9641 if (curwin->w_cursor.col > 0 && can_si && c == '#')
9643 /* remember current indent for next line */
9644 old_indent = get_indent();
9645 (void)set_indent(0, SIN_CHANGED);
9648 /* Adjust ai_col, the char at this position can be deleted. */
9649 if (ai_col > curwin->w_cursor.col)
9650 ai_col = curwin->w_cursor.col;
9652 #endif
9655 * Get the value that w_virtcol would have when 'list' is off.
9656 * Unless 'cpo' contains the 'L' flag.
9658 static colnr_T
9659 get_nolist_virtcol()
9661 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9662 return getvcol_nolist(&curwin->w_cursor);
9663 validate_virtcol();
9664 return curwin->w_virtcol;