Merge branch 'vim-with-runtime' into feat/tagfunc
[vim_extended.git] / src / edit.c
blob01603d6318d0e40a0ac89664759abf8cd1ee1090
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 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 /* Set when doing something for completion that may call edit() recursively,
118 * which is not allowed. */
119 static int compl_busy = FALSE;
121 static int compl_matches = 0;
122 static char_u *compl_pattern = NULL;
123 static int compl_direction = FORWARD;
124 static int compl_shows_dir = FORWARD;
125 static int compl_pending = 0; /* > 1 for postponed CTRL-N */
126 static pos_T compl_startpos;
127 static colnr_T compl_col = 0; /* column where the text starts
128 * that is being completed */
129 static char_u *compl_orig_text = NULL; /* text as it was before
130 * completion started */
131 static int compl_cont_mode = 0;
132 static expand_T compl_xp;
134 static void ins_ctrl_x __ARGS((void));
135 static int has_compl_option __ARGS((int dict_opt));
136 static int ins_compl_accept_char __ARGS((int c));
137 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));
138 static int ins_compl_equal __ARGS((compl_T *match, char_u *str, int len));
139 static void ins_compl_longest_match __ARGS((compl_T *match));
140 static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int icase));
141 static int ins_compl_make_cyclic __ARGS((void));
142 static void ins_compl_upd_pum __ARGS((void));
143 static void ins_compl_del_pum __ARGS((void));
144 static int pum_wanted __ARGS((void));
145 static int pum_enough_matches __ARGS((void));
146 static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int flags, int thesaurus));
147 static void ins_compl_files __ARGS((int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir));
148 static char_u *find_line_end __ARGS((char_u *ptr));
149 static void ins_compl_free __ARGS((void));
150 static void ins_compl_clear __ARGS((void));
151 static int ins_compl_bs __ARGS((void));
152 static void ins_compl_new_leader __ARGS((void));
153 static void ins_compl_addleader __ARGS((int c));
154 static int ins_compl_len __ARGS((void));
155 static void ins_compl_restart __ARGS((void));
156 static void ins_compl_set_original_text __ARGS((char_u *str));
157 static void ins_compl_addfrommatch __ARGS((void));
158 static int ins_compl_prep __ARGS((int c));
159 static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag));
160 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
161 static void ins_compl_add_list __ARGS((list_T *list));
162 #endif
163 static int ins_compl_get_exp __ARGS((pos_T *ini));
164 static void ins_compl_delete __ARGS((void));
165 static void ins_compl_insert __ARGS((void));
166 static int ins_compl_next __ARGS((int allow_get_expansion, int count, int insert_match));
167 static int ins_compl_key2dir __ARGS((int c));
168 static int ins_compl_pum_key __ARGS((int c));
169 static int ins_compl_key2count __ARGS((int c));
170 static int ins_compl_use_match __ARGS((int c));
171 static int ins_complete __ARGS((int c));
172 static unsigned quote_meta __ARGS((char_u *dest, char_u *str, int len));
173 #endif /* FEAT_INS_EXPAND */
175 #define BACKSPACE_CHAR 1
176 #define BACKSPACE_WORD 2
177 #define BACKSPACE_WORD_NOT_SPACE 3
178 #define BACKSPACE_LINE 4
180 static void ins_redraw __ARGS((int ready));
181 static void ins_ctrl_v __ARGS((void));
182 static void undisplay_dollar __ARGS((void));
183 static void insert_special __ARGS((int, int, int));
184 static void internal_format __ARGS((int textwidth, int second_indent, int flags, int format_only, int c));
185 static void check_auto_format __ARGS((int));
186 static void redo_literal __ARGS((int c));
187 static void start_arrow __ARGS((pos_T *end_insert_pos));
188 #ifdef FEAT_SPELL
189 static void check_spell_redraw __ARGS((void));
190 static void spell_back_to_badword __ARGS((void));
191 static int spell_bad_len = 0; /* length of located bad word */
192 #endif
193 static void stop_insert __ARGS((pos_T *end_insert_pos, int esc));
194 static int echeck_abbr __ARGS((int));
195 #if 0
196 static void replace_push_off __ARGS((int c));
197 #endif
198 static int replace_pop __ARGS((void));
199 static void replace_join __ARGS((int off));
200 static void replace_pop_ins __ARGS((void));
201 #ifdef FEAT_MBYTE
202 static void mb_replace_pop_ins __ARGS((int cc));
203 #endif
204 static void replace_flush __ARGS((void));
205 static void replace_do_bs __ARGS((int limit_col));
206 static int del_char_after_col __ARGS((int limit_col));
207 #ifdef FEAT_CINDENT
208 static int cindent_on __ARGS((void));
209 #endif
210 static void ins_reg __ARGS((void));
211 static void ins_ctrl_g __ARGS((void));
212 static void ins_ctrl_hat __ARGS((void));
213 static int ins_esc __ARGS((long *count, int cmdchar, int nomove));
214 #ifdef FEAT_RIGHTLEFT
215 static void ins_ctrl_ __ARGS((void));
216 #endif
217 #ifdef FEAT_VISUAL
218 static int ins_start_select __ARGS((int c));
219 #endif
220 static void ins_insert __ARGS((int replaceState));
221 static void ins_ctrl_o __ARGS((void));
222 static void ins_shift __ARGS((int c, int lastc));
223 static void ins_del __ARGS((void));
224 static int ins_bs __ARGS((int c, int mode, int *inserted_space_p));
225 #ifdef FEAT_MOUSE
226 static void ins_mouse __ARGS((int c));
227 static void ins_mousescroll __ARGS((int up));
228 #endif
229 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
230 static void ins_tabline __ARGS((int c));
231 #endif
232 static void ins_left __ARGS((void));
233 static void ins_home __ARGS((int c));
234 static void ins_end __ARGS((int c));
235 static void ins_s_left __ARGS((void));
236 static void ins_right __ARGS((void));
237 static void ins_s_right __ARGS((void));
238 static void ins_up __ARGS((int startcol));
239 static void ins_pageup __ARGS((void));
240 static void ins_down __ARGS((int startcol));
241 static void ins_pagedown __ARGS((void));
242 #ifdef FEAT_DND
243 static void ins_drop __ARGS((void));
244 #endif
245 static int ins_tab __ARGS((void));
246 static int ins_eol __ARGS((int c));
247 #ifdef FEAT_DIGRAPHS
248 static int ins_digraph __ARGS((void));
249 #endif
250 static int ins_copychar __ARGS((linenr_T lnum));
251 static int ins_ctrl_ey __ARGS((int tc));
252 #ifdef FEAT_SMARTINDENT
253 static void ins_try_si __ARGS((int c));
254 #endif
255 static colnr_T get_nolist_virtcol __ARGS((void));
257 static colnr_T Insstart_textlen; /* length of line when insert started */
258 static colnr_T Insstart_blank_vcol; /* vcol for first inserted blank */
260 static char_u *last_insert = NULL; /* the text of the previous insert,
261 K_SPECIAL and CSI are escaped */
262 static int last_insert_skip; /* nr of chars in front of previous insert */
263 static int new_insert_skip; /* nr of chars in front of current insert */
264 static int did_restart_edit; /* "restart_edit" when calling edit() */
266 #ifdef FEAT_CINDENT
267 static int can_cindent; /* may do cindenting on this line */
268 #endif
270 static int old_indent = 0; /* for ^^D command in insert mode */
272 #ifdef FEAT_RIGHTLEFT
273 static int revins_on; /* reverse insert mode on */
274 static int revins_chars; /* how much to skip after edit */
275 static int revins_legal; /* was the last char 'legal'? */
276 static int revins_scol; /* start column of revins session */
277 #endif
279 static int ins_need_undo; /* call u_save() before inserting a
280 char. Set when edit() is called.
281 after that arrow_used is used. */
283 static int did_add_space = FALSE; /* auto_format() added an extra space
284 under the cursor */
287 * edit(): Start inserting text.
289 * "cmdchar" can be:
290 * 'i' normal insert command
291 * 'a' normal append command
292 * 'R' replace command
293 * 'r' "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo,
294 * but still only one <CR> is inserted. The <Esc> is not used for redo.
295 * 'g' "gI" command.
296 * 'V' "gR" command for Virtual Replace mode.
297 * 'v' "gr" command for single character Virtual Replace mode.
299 * This function is not called recursively. For CTRL-O commands, it returns
300 * and lets the caller handle the Normal-mode command.
302 * Return TRUE if a CTRL-O command caused the return (insert mode pending).
305 edit(cmdchar, startln, count)
306 int cmdchar;
307 int startln; /* if set, insert at start of line */
308 long count;
310 int c = 0;
311 char_u *ptr;
312 int lastc;
313 int mincol;
314 static linenr_T o_lnum = 0;
315 int i;
316 int did_backspace = TRUE; /* previous char was backspace */
317 #ifdef FEAT_CINDENT
318 int line_is_white = FALSE; /* line is empty before insert */
319 #endif
320 linenr_T old_topline = 0; /* topline before insertion */
321 #ifdef FEAT_DIFF
322 int old_topfill = -1;
323 #endif
324 int inserted_space = FALSE; /* just inserted a space */
325 int replaceState = REPLACE;
326 int nomove = FALSE; /* don't move cursor on return */
328 /* Remember whether editing was restarted after CTRL-O. */
329 did_restart_edit = restart_edit;
331 /* sleep before redrawing, needed for "CTRL-O :" that results in an
332 * error message */
333 check_for_delay(TRUE);
335 #ifdef HAVE_SANDBOX
336 /* Don't allow inserting in the sandbox. */
337 if (sandbox != 0)
339 EMSG(_(e_sandbox));
340 return FALSE;
342 #endif
343 /* Don't allow changes in the buffer while editing the cmdline. The
344 * caller of getcmdline() may get confused. */
345 if (textlock != 0)
347 EMSG(_(e_secure));
348 return FALSE;
351 #ifdef FEAT_INS_EXPAND
352 /* Don't allow recursive insert mode when busy with completion. */
353 if (compl_started || compl_busy || pum_visible())
355 EMSG(_(e_secure));
356 return FALSE;
358 ins_compl_clear(); /* clear stuff for CTRL-X mode */
359 #endif
361 #ifdef FEAT_AUTOCMD
363 * Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx".
365 if (cmdchar != 'r' && cmdchar != 'v')
367 # ifdef FEAT_EVAL
368 if (cmdchar == 'R')
369 ptr = (char_u *)"r";
370 else if (cmdchar == 'V')
371 ptr = (char_u *)"v";
372 else
373 ptr = (char_u *)"i";
374 set_vim_var_string(VV_INSERTMODE, ptr, 1);
375 # endif
376 apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf);
378 #endif
380 #ifdef FEAT_MOUSE
382 * When doing a paste with the middle mouse button, Insstart is set to
383 * where the paste started.
385 if (where_paste_started.lnum != 0)
386 Insstart = where_paste_started;
387 else
388 #endif
390 Insstart = curwin->w_cursor;
391 if (startln)
392 Insstart.col = 0;
394 Insstart_textlen = (colnr_T)linetabsize(ml_get_curline());
395 Insstart_blank_vcol = MAXCOL;
396 if (!did_ai)
397 ai_col = 0;
399 if (cmdchar != NUL && restart_edit == 0)
401 ResetRedobuff();
402 AppendNumberToRedobuff(count);
403 #ifdef FEAT_VREPLACE
404 if (cmdchar == 'V' || cmdchar == 'v')
406 /* "gR" or "gr" command */
407 AppendCharToRedobuff('g');
408 AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R');
410 else
411 #endif
413 AppendCharToRedobuff(cmdchar);
414 if (cmdchar == 'g') /* "gI" command */
415 AppendCharToRedobuff('I');
416 else if (cmdchar == 'r') /* "r<CR>" command */
417 count = 1; /* insert only one <CR> */
421 if (cmdchar == 'R')
423 #ifdef FEAT_FKMAP
424 if (p_fkmap && p_ri)
426 beep_flush();
427 EMSG(farsi_text_3); /* encoded in Farsi */
428 State = INSERT;
430 else
431 #endif
432 State = REPLACE;
434 #ifdef FEAT_VREPLACE
435 else if (cmdchar == 'V' || cmdchar == 'v')
437 State = VREPLACE;
438 replaceState = VREPLACE;
439 orig_line_count = curbuf->b_ml.ml_line_count;
440 vr_lines_changed = 1;
442 #endif
443 else
444 State = INSERT;
446 stop_insert_mode = FALSE;
449 * Need to recompute the cursor position, it might move when the cursor is
450 * on a TAB or special character.
452 curs_columns(TRUE);
455 * Enable langmap or IME, indicated by 'iminsert'.
456 * Note that IME may enabled/disabled without us noticing here, thus the
457 * 'iminsert' value may not reflect what is actually used. It is updated
458 * when hitting <Esc>.
460 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
461 State |= LANGMAP;
462 #ifdef USE_IM_CONTROL
463 im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
464 #endif
466 #ifdef FEAT_MOUSE
467 setmouse();
468 #endif
469 #ifdef FEAT_CMDL_INFO
470 clear_showcmd();
471 #endif
472 #ifdef FEAT_RIGHTLEFT
473 /* there is no reverse replace mode */
474 revins_on = (State == INSERT && p_ri);
475 if (revins_on)
476 undisplay_dollar();
477 revins_chars = 0;
478 revins_legal = 0;
479 revins_scol = -1;
480 #endif
483 * Handle restarting Insert mode.
484 * Don't do this for "CTRL-O ." (repeat an insert): we get here with
485 * restart_edit non-zero, and something in the stuff buffer.
487 if (restart_edit != 0 && stuff_empty())
489 #ifdef FEAT_MOUSE
491 * After a paste we consider text typed to be part of the insert for
492 * the pasted text. You can backspace over the pasted text too.
494 if (where_paste_started.lnum)
495 arrow_used = FALSE;
496 else
497 #endif
498 arrow_used = TRUE;
499 restart_edit = 0;
502 * If the cursor was after the end-of-line before the CTRL-O and it is
503 * now at the end-of-line, put it after the end-of-line (this is not
504 * correct in very rare cases).
505 * Also do this if curswant is greater than the current virtual
506 * column. Eg after "^O$" or "^O80|".
508 validate_virtcol();
509 update_curswant();
510 if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
511 || curwin->w_curswant > curwin->w_virtcol)
512 && *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL)
514 if (ptr[1] == NUL)
515 ++curwin->w_cursor.col;
516 #ifdef FEAT_MBYTE
517 else if (has_mbyte)
519 i = (*mb_ptr2len)(ptr);
520 if (ptr[i] == NUL)
521 curwin->w_cursor.col += i;
523 #endif
525 ins_at_eol = FALSE;
527 else
528 arrow_used = FALSE;
530 /* we are in insert mode now, don't need to start it anymore */
531 need_start_insertmode = FALSE;
533 /* Need to save the line for undo before inserting the first char. */
534 ins_need_undo = TRUE;
536 #ifdef FEAT_MOUSE
537 where_paste_started.lnum = 0;
538 #endif
539 #ifdef FEAT_CINDENT
540 can_cindent = TRUE;
541 #endif
542 #ifdef FEAT_FOLDING
543 /* The cursor line is not in a closed fold, unless 'insertmode' is set or
544 * restarting. */
545 if (!p_im && did_restart_edit == 0)
546 foldOpenCursor();
547 #endif
550 * If 'showmode' is set, show the current (insert/replace/..) mode.
551 * A warning message for changing a readonly file is given here, before
552 * actually changing anything. It's put after the mode, if any.
554 i = 0;
555 if (p_smd && msg_silent == 0)
556 i = showmode();
558 if (!p_im && did_restart_edit == 0)
559 change_warning(i == 0 ? 0 : i + 1);
561 #ifdef CURSOR_SHAPE
562 ui_cursor_shape(); /* may show different cursor shape */
563 #endif
564 #ifdef FEAT_DIGRAPHS
565 do_digraph(-1); /* clear digraphs */
566 #endif
569 * Get the current length of the redo buffer, those characters have to be
570 * skipped if we want to get to the inserted characters.
572 ptr = get_inserted();
573 if (ptr == NULL)
574 new_insert_skip = 0;
575 else
577 new_insert_skip = (int)STRLEN(ptr);
578 vim_free(ptr);
581 old_indent = 0;
584 * Main loop in Insert mode: repeat until Insert mode is left.
586 for (;;)
588 #ifdef FEAT_RIGHTLEFT
589 if (!revins_legal)
590 revins_scol = -1; /* reset on illegal motions */
591 else
592 revins_legal = 0;
593 #endif
594 if (arrow_used) /* don't repeat insert when arrow key used */
595 count = 0;
597 if (stop_insert_mode)
599 /* ":stopinsert" used or 'insertmode' reset */
600 count = 0;
601 goto doESCkey;
604 /* set curwin->w_curswant for next K_DOWN or K_UP */
605 if (!arrow_used)
606 curwin->w_set_curswant = TRUE;
608 /* If there is no typeahead may check for timestamps (e.g., for when a
609 * menu invoked a shell command). */
610 if (stuff_empty())
612 did_check_timestamps = FALSE;
613 if (need_check_timestamps)
614 check_timestamps(FALSE);
618 * When emsg() was called msg_scroll will have been set.
620 msg_scroll = FALSE;
622 #ifdef FEAT_GUI
623 /* When 'mousefocus' is set a mouse movement may have taken us to
624 * another window. "need_mouse_correct" may then be set because of an
625 * autocommand. */
626 if (need_mouse_correct)
627 gui_mouse_correct();
628 #endif
630 #ifdef FEAT_FOLDING
631 /* Open fold at the cursor line, according to 'foldopen'. */
632 if (fdo_flags & FDO_INSERT)
633 foldOpenCursor();
634 /* Close folds where the cursor isn't, according to 'foldclose' */
635 if (!char_avail())
636 foldCheckClose();
637 #endif
640 * If we inserted a character at the last position of the last line in
641 * the window, scroll the window one line up. This avoids an extra
642 * redraw.
643 * This is detected when the cursor column is smaller after inserting
644 * something.
645 * Don't do this when the topline changed already, it has
646 * already been adjusted (by insertchar() calling open_line())).
648 if (curbuf->b_mod_set
649 && curwin->w_p_wrap
650 && !did_backspace
651 && curwin->w_topline == old_topline
652 #ifdef FEAT_DIFF
653 && curwin->w_topfill == old_topfill
654 #endif
657 mincol = curwin->w_wcol;
658 validate_cursor_col();
660 if ((int)curwin->w_wcol < mincol - curbuf->b_p_ts
661 && curwin->w_wrow == W_WINROW(curwin)
662 + curwin->w_height - 1 - p_so
663 && (curwin->w_cursor.lnum != curwin->w_topline
664 #ifdef FEAT_DIFF
665 || curwin->w_topfill > 0
666 #endif
669 #ifdef FEAT_DIFF
670 if (curwin->w_topfill > 0)
671 --curwin->w_topfill;
672 else
673 #endif
674 #ifdef FEAT_FOLDING
675 if (hasFolding(curwin->w_topline, NULL, &old_topline))
676 set_topline(curwin, old_topline + 1);
677 else
678 #endif
679 set_topline(curwin, curwin->w_topline + 1);
683 /* May need to adjust w_topline to show the cursor. */
684 update_topline();
686 did_backspace = FALSE;
688 validate_cursor(); /* may set must_redraw */
691 * Redraw the display when no characters are waiting.
692 * Also shows mode, ruler and positions cursor.
694 ins_redraw(TRUE);
696 #ifdef FEAT_SCROLLBIND
697 if (curwin->w_p_scb)
698 do_check_scrollbind(TRUE);
699 #endif
701 update_curswant();
702 old_topline = curwin->w_topline;
703 #ifdef FEAT_DIFF
704 old_topfill = curwin->w_topfill;
705 #endif
707 #ifdef USE_ON_FLY_SCROLL
708 dont_scroll = FALSE; /* allow scrolling here */
709 #endif
712 * Get a character for Insert mode. Ignore K_IGNORE.
714 lastc = c; /* remember previous char for CTRL-D */
717 c = safe_vgetc();
718 } while (c == K_IGNORE);
720 #ifdef FEAT_AUTOCMD
721 /* Don't want K_CURSORHOLD for the second key, e.g., after CTRL-V. */
722 did_cursorhold = TRUE;
723 #endif
725 #ifdef FEAT_RIGHTLEFT
726 if (p_hkmap && KeyTyped)
727 c = hkmap(c); /* Hebrew mode mapping */
728 #endif
729 #ifdef FEAT_FKMAP
730 if (p_fkmap && KeyTyped)
731 c = fkmap(c); /* Farsi mode mapping */
732 #endif
734 #ifdef FEAT_INS_EXPAND
736 * Special handling of keys while the popup menu is visible or wanted
737 * and the cursor is still in the completed word. Only when there is
738 * a match, skip this when no matches were found.
740 if (compl_started
741 && pum_wanted()
742 && curwin->w_cursor.col >= compl_col
743 && (compl_shown_match == NULL
744 || compl_shown_match != compl_shown_match->cp_next))
746 /* BS: Delete one character from "compl_leader". */
747 if ((c == K_BS || c == Ctrl_H)
748 && curwin->w_cursor.col > compl_col
749 && (c = ins_compl_bs()) == NUL)
750 continue;
752 /* When no match was selected or it was edited. */
753 if (!compl_used_match)
755 /* CTRL-L: Add one character from the current match to
756 * "compl_leader". Except when at the original match and
757 * there is nothing to add, CTRL-L works like CTRL-P then. */
758 if (c == Ctrl_L
759 && (ctrl_x_mode != CTRL_X_WHOLE_LINE
760 || (int)STRLEN(compl_shown_match->cp_str)
761 > curwin->w_cursor.col - compl_col))
763 ins_compl_addfrommatch();
764 continue;
767 /* A non-white character that fits in with the current
768 * completion: Add to "compl_leader". */
769 if (ins_compl_accept_char(c))
771 ins_compl_addleader(c);
772 continue;
775 /* Pressing CTRL-Y selects the current match. When
776 * compl_enter_selects is set the Enter key does the same. */
777 if (c == Ctrl_Y || (compl_enter_selects
778 && (c == CAR || c == K_KENTER || c == NL)))
780 ins_compl_delete();
781 ins_compl_insert();
786 /* Prepare for or stop CTRL-X mode. This doesn't do completion, but
787 * it does fix up the text when finishing completion. */
788 compl_get_longest = FALSE;
789 if (ins_compl_prep(c))
790 continue;
791 #endif
793 /* CTRL-\ CTRL-N goes to Normal mode,
794 * CTRL-\ CTRL-G goes to mode selected with 'insertmode',
795 * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor. */
796 if (c == Ctrl_BSL)
798 /* may need to redraw when no more chars available now */
799 ins_redraw(FALSE);
800 ++no_mapping;
801 ++allow_keys;
802 c = plain_vgetc();
803 --no_mapping;
804 --allow_keys;
805 if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O)
807 /* it's something else */
808 vungetc(c);
809 c = Ctrl_BSL;
811 else if (c == Ctrl_G && p_im)
812 continue;
813 else
815 if (c == Ctrl_O)
817 ins_ctrl_o();
818 ins_at_eol = FALSE; /* cursor keeps its column */
819 nomove = TRUE;
821 count = 0;
822 goto doESCkey;
826 #ifdef FEAT_DIGRAPHS
827 c = do_digraph(c);
828 #endif
830 #ifdef FEAT_INS_EXPAND
831 if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
832 goto docomplete;
833 #endif
834 if (c == Ctrl_V || c == Ctrl_Q)
836 ins_ctrl_v();
837 c = Ctrl_V; /* pretend CTRL-V is last typed character */
838 continue;
841 #ifdef FEAT_CINDENT
842 if (cindent_on()
843 # ifdef FEAT_INS_EXPAND
844 && ctrl_x_mode == 0
845 # endif
848 /* A key name preceded by a bang means this key is not to be
849 * inserted. Skip ahead to the re-indenting below.
850 * A key name preceded by a star means that indenting has to be
851 * done before inserting the key. */
852 line_is_white = inindent(0);
853 if (in_cinkeys(c, '!', line_is_white))
854 goto force_cindent;
855 if (can_cindent && in_cinkeys(c, '*', line_is_white)
856 && stop_arrow() == OK)
857 do_c_expr_indent();
859 #endif
861 #ifdef FEAT_RIGHTLEFT
862 if (curwin->w_p_rl)
863 switch (c)
865 case K_LEFT: c = K_RIGHT; break;
866 case K_S_LEFT: c = K_S_RIGHT; break;
867 case K_C_LEFT: c = K_C_RIGHT; break;
868 case K_RIGHT: c = K_LEFT; break;
869 case K_S_RIGHT: c = K_S_LEFT; break;
870 case K_C_RIGHT: c = K_C_LEFT; break;
872 #endif
874 #ifdef FEAT_VISUAL
876 * If 'keymodel' contains "startsel", may start selection. If it
877 * does, a CTRL-O and c will be stuffed, we need to get these
878 * characters.
880 if (ins_start_select(c))
881 continue;
882 #endif
885 * The big switch to handle a character in insert mode.
887 switch (c)
889 case ESC: /* End input mode */
890 if (echeck_abbr(ESC + ABBR_OFF))
891 break;
892 /*FALLTHROUGH*/
894 case Ctrl_C: /* End input mode */
895 #ifdef FEAT_CMDWIN
896 if (c == Ctrl_C && cmdwin_type != 0)
898 /* Close the cmdline window. */
899 cmdwin_result = K_IGNORE;
900 got_int = FALSE; /* don't stop executing autocommands et al. */
901 nomove = TRUE;
902 goto doESCkey;
904 #endif
906 #ifdef UNIX
907 do_intr:
908 #endif
909 /* when 'insertmode' set, and not halfway a mapping, don't leave
910 * Insert mode */
911 if (goto_im())
913 if (got_int)
915 (void)vgetc(); /* flush all buffers */
916 got_int = FALSE;
918 else
919 vim_beep();
920 break;
922 doESCkey:
924 * This is the ONLY return from edit()!
926 /* Always update o_lnum, so that a "CTRL-O ." that adds a line
927 * still puts the cursor back after the inserted text. */
928 if (ins_at_eol && gchar_cursor() == NUL)
929 o_lnum = curwin->w_cursor.lnum;
931 if (ins_esc(&count, cmdchar, nomove))
933 #ifdef FEAT_AUTOCMD
934 if (cmdchar != 'r' && cmdchar != 'v')
935 apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
936 FALSE, curbuf);
937 did_cursorhold = FALSE;
938 #endif
939 return (c == Ctrl_O);
941 continue;
943 case Ctrl_Z: /* suspend when 'insertmode' set */
944 if (!p_im)
945 goto normalchar; /* insert CTRL-Z as normal char */
946 stuffReadbuff((char_u *)":st\r");
947 c = Ctrl_O;
948 /*FALLTHROUGH*/
950 case Ctrl_O: /* execute one command */
951 #ifdef FEAT_COMPL_FUNC
952 if (ctrl_x_mode == CTRL_X_OMNI)
953 goto docomplete;
954 #endif
955 if (echeck_abbr(Ctrl_O + ABBR_OFF))
956 break;
957 ins_ctrl_o();
959 #ifdef FEAT_VIRTUALEDIT
960 /* don't move the cursor left when 'virtualedit' has "onemore". */
961 if (ve_flags & VE_ONEMORE)
963 ins_at_eol = FALSE;
964 nomove = TRUE;
966 #endif
967 count = 0;
968 goto doESCkey;
970 case K_INS: /* toggle insert/replace mode */
971 case K_KINS:
972 ins_insert(replaceState);
973 break;
975 case K_SELECT: /* end of Select mode mapping - ignore */
976 break;
978 #ifdef FEAT_SNIFF
979 case K_SNIFF: /* Sniff command received */
980 stuffcharReadbuff(K_SNIFF);
981 goto doESCkey;
982 #endif
984 case K_HELP: /* Help key works like <ESC> <Help> */
985 case K_F1:
986 case K_XF1:
987 stuffcharReadbuff(K_HELP);
988 if (p_im)
989 need_start_insertmode = TRUE;
990 goto doESCkey;
992 #ifdef FEAT_NETBEANS_INTG
993 case K_F21: /* NetBeans command */
994 ++no_mapping; /* don't map the next key hits */
995 i = plain_vgetc();
996 --no_mapping;
997 netbeans_keycommand(i);
998 break;
999 #endif
1001 case K_ZERO: /* Insert the previously inserted text. */
1002 case NUL:
1003 case Ctrl_A:
1004 /* For ^@ the trailing ESC will end the insert, unless there is an
1005 * error. */
1006 if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
1007 && c != Ctrl_A && !p_im)
1008 goto doESCkey; /* quit insert mode */
1009 inserted_space = FALSE;
1010 break;
1012 case Ctrl_R: /* insert the contents of a register */
1013 ins_reg();
1014 auto_format(FALSE, TRUE);
1015 inserted_space = FALSE;
1016 break;
1018 case Ctrl_G: /* commands starting with CTRL-G */
1019 ins_ctrl_g();
1020 break;
1022 case Ctrl_HAT: /* switch input mode and/or langmap */
1023 ins_ctrl_hat();
1024 break;
1026 #ifdef FEAT_RIGHTLEFT
1027 case Ctrl__: /* switch between languages */
1028 if (!p_ari)
1029 goto normalchar;
1030 ins_ctrl_();
1031 break;
1032 #endif
1034 case Ctrl_D: /* Make indent one shiftwidth smaller. */
1035 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1036 if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
1037 goto docomplete;
1038 #endif
1039 /* FALLTHROUGH */
1041 case Ctrl_T: /* Make indent one shiftwidth greater. */
1042 # ifdef FEAT_INS_EXPAND
1043 if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
1045 if (has_compl_option(FALSE))
1046 goto docomplete;
1047 break;
1049 # endif
1050 ins_shift(c, lastc);
1051 auto_format(FALSE, TRUE);
1052 inserted_space = FALSE;
1053 break;
1055 case K_DEL: /* delete character under the cursor */
1056 case K_KDEL:
1057 ins_del();
1058 auto_format(FALSE, TRUE);
1059 break;
1061 case K_BS: /* delete character before the cursor */
1062 case Ctrl_H:
1063 did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1064 auto_format(FALSE, TRUE);
1065 break;
1067 case Ctrl_W: /* delete word before the cursor */
1068 did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1069 auto_format(FALSE, TRUE);
1070 break;
1072 case Ctrl_U: /* delete all inserted text in current line */
1073 # ifdef FEAT_COMPL_FUNC
1074 /* CTRL-X CTRL-U completes with 'completefunc'. */
1075 if (ctrl_x_mode == CTRL_X_FUNCTION)
1076 goto docomplete;
1077 # endif
1078 did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1079 auto_format(FALSE, TRUE);
1080 inserted_space = FALSE;
1081 break;
1083 #ifdef FEAT_MOUSE
1084 case K_LEFTMOUSE: /* mouse keys */
1085 case K_LEFTMOUSE_NM:
1086 case K_LEFTDRAG:
1087 case K_LEFTRELEASE:
1088 case K_LEFTRELEASE_NM:
1089 case K_MIDDLEMOUSE:
1090 case K_MIDDLEDRAG:
1091 case K_MIDDLERELEASE:
1092 case K_RIGHTMOUSE:
1093 case K_RIGHTDRAG:
1094 case K_RIGHTRELEASE:
1095 case K_X1MOUSE:
1096 case K_X1DRAG:
1097 case K_X1RELEASE:
1098 case K_X2MOUSE:
1099 case K_X2DRAG:
1100 case K_X2RELEASE:
1101 ins_mouse(c);
1102 break;
1104 case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */
1105 ins_mousescroll(FALSE);
1106 break;
1108 case K_MOUSEUP: /* Default action for scroll wheel down: scroll down */
1109 ins_mousescroll(TRUE);
1110 break;
1111 #endif
1112 #ifdef FEAT_GUI_TABLINE
1113 case K_TABLINE:
1114 case K_TABMENU:
1115 ins_tabline(c);
1116 break;
1117 #endif
1119 case K_IGNORE: /* Something mapped to nothing */
1120 break;
1122 #ifdef FEAT_AUTOCMD
1123 case K_CURSORHOLD: /* Didn't type something for a while. */
1124 apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf);
1125 did_cursorhold = TRUE;
1126 break;
1127 #endif
1129 #ifdef FEAT_GUI_W32
1130 /* On Win32 ignore <M-F4>, we get it when closing the window was
1131 * cancelled. */
1132 case K_F4:
1133 if (mod_mask != MOD_MASK_ALT)
1134 goto normalchar;
1135 break;
1136 #endif
1138 #ifdef FEAT_GUI
1139 case K_VER_SCROLLBAR:
1140 ins_scroll();
1141 break;
1143 case K_HOR_SCROLLBAR:
1144 ins_horscroll();
1145 break;
1146 #endif
1148 case K_HOME: /* <Home> */
1149 case K_KHOME:
1150 case K_S_HOME:
1151 case K_C_HOME:
1152 ins_home(c);
1153 break;
1155 case K_END: /* <End> */
1156 case K_KEND:
1157 case K_S_END:
1158 case K_C_END:
1159 ins_end(c);
1160 break;
1162 case K_LEFT: /* <Left> */
1163 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1164 ins_s_left();
1165 else
1166 ins_left();
1167 break;
1169 case K_S_LEFT: /* <S-Left> */
1170 case K_C_LEFT:
1171 ins_s_left();
1172 break;
1174 case K_RIGHT: /* <Right> */
1175 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1176 ins_s_right();
1177 else
1178 ins_right();
1179 break;
1181 case K_S_RIGHT: /* <S-Right> */
1182 case K_C_RIGHT:
1183 ins_s_right();
1184 break;
1186 case K_UP: /* <Up> */
1187 #ifdef FEAT_INS_EXPAND
1188 if (pum_visible())
1189 goto docomplete;
1190 #endif
1191 if (mod_mask & MOD_MASK_SHIFT)
1192 ins_pageup();
1193 else
1194 ins_up(FALSE);
1195 break;
1197 case K_S_UP: /* <S-Up> */
1198 case K_PAGEUP:
1199 case K_KPAGEUP:
1200 #ifdef FEAT_INS_EXPAND
1201 if (pum_visible())
1202 goto docomplete;
1203 #endif
1204 ins_pageup();
1205 break;
1207 case K_DOWN: /* <Down> */
1208 #ifdef FEAT_INS_EXPAND
1209 if (pum_visible())
1210 goto docomplete;
1211 #endif
1212 if (mod_mask & MOD_MASK_SHIFT)
1213 ins_pagedown();
1214 else
1215 ins_down(FALSE);
1216 break;
1218 case K_S_DOWN: /* <S-Down> */
1219 case K_PAGEDOWN:
1220 case K_KPAGEDOWN:
1221 #ifdef FEAT_INS_EXPAND
1222 if (pum_visible())
1223 goto docomplete;
1224 #endif
1225 ins_pagedown();
1226 break;
1228 #ifdef FEAT_DND
1229 case K_DROP: /* drag-n-drop event */
1230 ins_drop();
1231 break;
1232 #endif
1234 case K_S_TAB: /* When not mapped, use like a normal TAB */
1235 c = TAB;
1236 /* FALLTHROUGH */
1238 case TAB: /* TAB or Complete patterns along path */
1239 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1240 if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1241 goto docomplete;
1242 #endif
1243 inserted_space = FALSE;
1244 if (ins_tab())
1245 goto normalchar; /* insert TAB as a normal char */
1246 auto_format(FALSE, TRUE);
1247 break;
1249 case K_KENTER: /* <Enter> */
1250 c = CAR;
1251 /* FALLTHROUGH */
1252 case CAR:
1253 case NL:
1254 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1255 /* In a quickfix window a <CR> jumps to the error under the
1256 * cursor. */
1257 if (bt_quickfix(curbuf) && c == CAR)
1259 if (curwin->w_llist_ref == NULL) /* quickfix window */
1260 do_cmdline_cmd((char_u *)".cc");
1261 else /* location list window */
1262 do_cmdline_cmd((char_u *)".ll");
1263 break;
1265 #endif
1266 #ifdef FEAT_CMDWIN
1267 if (cmdwin_type != 0)
1269 /* Execute the command in the cmdline window. */
1270 cmdwin_result = CAR;
1271 goto doESCkey;
1273 #endif
1274 if (ins_eol(c) && !p_im)
1275 goto doESCkey; /* out of memory */
1276 auto_format(FALSE, FALSE);
1277 inserted_space = FALSE;
1278 break;
1280 #if defined(FEAT_DIGRAPHS) || defined (FEAT_INS_EXPAND)
1281 case Ctrl_K: /* digraph or keyword completion */
1282 # ifdef FEAT_INS_EXPAND
1283 if (ctrl_x_mode == CTRL_X_DICTIONARY)
1285 if (has_compl_option(TRUE))
1286 goto docomplete;
1287 break;
1289 # endif
1290 # ifdef FEAT_DIGRAPHS
1291 c = ins_digraph();
1292 if (c == NUL)
1293 break;
1294 # endif
1295 goto normalchar;
1296 #endif
1298 #ifdef FEAT_INS_EXPAND
1299 case Ctrl_X: /* Enter CTRL-X mode */
1300 ins_ctrl_x();
1301 break;
1303 case Ctrl_RSB: /* Tag name completion after ^X */
1304 if (ctrl_x_mode != CTRL_X_TAGS)
1305 goto normalchar;
1306 goto docomplete;
1308 case Ctrl_F: /* File name completion after ^X */
1309 if (ctrl_x_mode != CTRL_X_FILES)
1310 goto normalchar;
1311 goto docomplete;
1313 case 's': /* Spelling completion after ^X */
1314 case Ctrl_S:
1315 if (ctrl_x_mode != CTRL_X_SPELL)
1316 goto normalchar;
1317 goto docomplete;
1318 #endif
1320 case Ctrl_L: /* Whole line completion after ^X */
1321 #ifdef FEAT_INS_EXPAND
1322 if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1323 #endif
1325 /* CTRL-L with 'insertmode' set: Leave Insert mode */
1326 if (p_im)
1328 if (echeck_abbr(Ctrl_L + ABBR_OFF))
1329 break;
1330 goto doESCkey;
1332 goto normalchar;
1334 #ifdef FEAT_INS_EXPAND
1335 /* FALLTHROUGH */
1337 case Ctrl_P: /* Do previous/next pattern completion */
1338 case Ctrl_N:
1339 /* if 'complete' is empty then plain ^P is no longer special,
1340 * but it is under other ^X modes */
1341 if (*curbuf->b_p_cpt == NUL
1342 && ctrl_x_mode != 0
1343 && !(compl_cont_status & CONT_LOCAL))
1344 goto normalchar;
1346 docomplete:
1347 compl_busy = TRUE;
1348 if (ins_complete(c) == FAIL)
1349 compl_cont_status = 0;
1350 compl_busy = FALSE;
1351 break;
1352 #endif /* FEAT_INS_EXPAND */
1354 case Ctrl_Y: /* copy from previous line or scroll down */
1355 case Ctrl_E: /* copy from next line or scroll up */
1356 c = ins_ctrl_ey(c);
1357 break;
1359 default:
1360 #ifdef UNIX
1361 if (c == intr_char) /* special interrupt char */
1362 goto do_intr;
1363 #endif
1366 * Insert a nomal character.
1368 normalchar:
1369 #ifdef FEAT_SMARTINDENT
1370 /* Try to perform smart-indenting. */
1371 ins_try_si(c);
1372 #endif
1374 if (c == ' ')
1376 inserted_space = TRUE;
1377 #ifdef FEAT_CINDENT
1378 if (inindent(0))
1379 can_cindent = FALSE;
1380 #endif
1381 if (Insstart_blank_vcol == MAXCOL
1382 && curwin->w_cursor.lnum == Insstart.lnum)
1383 Insstart_blank_vcol = get_nolist_virtcol();
1386 if (vim_iswordc(c) || !echeck_abbr(
1387 #ifdef FEAT_MBYTE
1388 /* Add ABBR_OFF for characters above 0x100, this is
1389 * what check_abbr() expects. */
1390 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1391 #endif
1394 insert_special(c, FALSE, FALSE);
1395 #ifdef FEAT_RIGHTLEFT
1396 revins_legal++;
1397 revins_chars++;
1398 #endif
1401 auto_format(FALSE, TRUE);
1403 #ifdef FEAT_FOLDING
1404 /* When inserting a character the cursor line must never be in a
1405 * closed fold. */
1406 foldOpenCursor();
1407 #endif
1408 break;
1409 } /* end of switch (c) */
1411 #ifdef FEAT_AUTOCMD
1412 /* If typed something may trigger CursorHoldI again. */
1413 if (c != K_CURSORHOLD)
1414 did_cursorhold = FALSE;
1415 #endif
1417 /* If the cursor was moved we didn't just insert a space */
1418 if (arrow_used)
1419 inserted_space = FALSE;
1421 #ifdef FEAT_CINDENT
1422 if (can_cindent && cindent_on()
1423 # ifdef FEAT_INS_EXPAND
1424 && ctrl_x_mode == 0
1425 # endif
1428 force_cindent:
1430 * Indent now if a key was typed that is in 'cinkeys'.
1432 if (in_cinkeys(c, ' ', line_is_white))
1434 if (stop_arrow() == OK)
1435 /* re-indent the current line */
1436 do_c_expr_indent();
1439 #endif /* FEAT_CINDENT */
1441 } /* for (;;) */
1442 /* NOTREACHED */
1446 * Redraw for Insert mode.
1447 * This is postponed until getting the next character to make '$' in the 'cpo'
1448 * option work correctly.
1449 * Only redraw when there are no characters available. This speeds up
1450 * inserting sequences of characters (e.g., for CTRL-R).
1452 static void
1453 ins_redraw(ready)
1454 int ready UNUSED; /* not busy with something */
1456 if (!char_avail())
1458 #ifdef FEAT_AUTOCMD
1459 /* Trigger CursorMoved if the cursor moved. Not when the popup menu is
1460 * visible, the command might delete it. */
1461 if (ready && has_cursormovedI()
1462 && !equalpos(last_cursormoved, curwin->w_cursor)
1463 # ifdef FEAT_INS_EXPAND
1464 && !pum_visible()
1465 # endif
1468 # ifdef FEAT_SYN_HL
1469 /* Need to update the screen first, to make sure syntax
1470 * highlighting is correct after making a change (e.g., inserting
1471 * a "(". The autocommand may also require a redraw, so it's done
1472 * again below, unfortunately. */
1473 if (syntax_present(curbuf) && must_redraw)
1474 update_screen(0);
1475 # endif
1476 apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf);
1477 last_cursormoved = curwin->w_cursor;
1479 #endif
1480 if (must_redraw)
1481 update_screen(0);
1482 else if (clear_cmdline || redraw_cmdline)
1483 showmode(); /* clear cmdline and show mode */
1484 showruler(FALSE);
1485 setcursor();
1486 emsg_on_display = FALSE; /* may remove error message now */
1491 * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1493 static void
1494 ins_ctrl_v()
1496 int c;
1498 /* may need to redraw when no more chars available now */
1499 ins_redraw(FALSE);
1501 if (redrawing() && !char_avail())
1502 edit_putchar('^', TRUE);
1503 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1505 #ifdef FEAT_CMDL_INFO
1506 add_to_showcmd_c(Ctrl_V);
1507 #endif
1509 c = get_literal();
1510 #ifdef FEAT_CMDL_INFO
1511 clear_showcmd();
1512 #endif
1513 insert_special(c, FALSE, TRUE);
1514 #ifdef FEAT_RIGHTLEFT
1515 revins_chars++;
1516 revins_legal++;
1517 #endif
1521 * Put a character directly onto the screen. It's not stored in a buffer.
1522 * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1524 static int pc_status;
1525 #define PC_STATUS_UNSET 0 /* pc_bytes was not set */
1526 #define PC_STATUS_RIGHT 1 /* right halve of double-wide char */
1527 #define PC_STATUS_LEFT 2 /* left halve of double-wide char */
1528 #define PC_STATUS_SET 3 /* pc_bytes was filled */
1529 #ifdef FEAT_MBYTE
1530 static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1531 #else
1532 static char_u pc_bytes[2]; /* saved bytes */
1533 #endif
1534 static int pc_attr;
1535 static int pc_row;
1536 static int pc_col;
1538 void
1539 edit_putchar(c, highlight)
1540 int c;
1541 int highlight;
1543 int attr;
1545 if (ScreenLines != NULL)
1547 update_topline(); /* just in case w_topline isn't valid */
1548 validate_cursor();
1549 if (highlight)
1550 attr = hl_attr(HLF_8);
1551 else
1552 attr = 0;
1553 pc_row = W_WINROW(curwin) + curwin->w_wrow;
1554 pc_col = W_WINCOL(curwin);
1555 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1556 pc_status = PC_STATUS_UNSET;
1557 #endif
1558 #ifdef FEAT_RIGHTLEFT
1559 if (curwin->w_p_rl)
1561 pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1562 # ifdef FEAT_MBYTE
1563 if (has_mbyte)
1565 int fix_col = mb_fix_col(pc_col, pc_row);
1567 if (fix_col != pc_col)
1569 screen_putchar(' ', pc_row, fix_col, attr);
1570 --curwin->w_wcol;
1571 pc_status = PC_STATUS_RIGHT;
1574 # endif
1576 else
1577 #endif
1579 pc_col += curwin->w_wcol;
1580 #ifdef FEAT_MBYTE
1581 if (mb_lefthalve(pc_row, pc_col))
1582 pc_status = PC_STATUS_LEFT;
1583 #endif
1586 /* save the character to be able to put it back */
1587 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1588 if (pc_status == PC_STATUS_UNSET)
1589 #endif
1591 screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1592 pc_status = PC_STATUS_SET;
1594 screen_putchar(c, pc_row, pc_col, attr);
1599 * Undo the previous edit_putchar().
1601 void
1602 edit_unputchar()
1604 if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1606 #if defined(FEAT_MBYTE)
1607 if (pc_status == PC_STATUS_RIGHT)
1608 ++curwin->w_wcol;
1609 if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1610 redrawWinline(curwin->w_cursor.lnum, FALSE);
1611 else
1612 #endif
1613 screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1618 * Called when p_dollar is set: display a '$' at the end of the changed text
1619 * Only works when cursor is in the line that changes.
1621 void
1622 display_dollar(col)
1623 colnr_T col;
1625 colnr_T save_col;
1627 if (!redrawing())
1628 return;
1630 cursor_off();
1631 save_col = curwin->w_cursor.col;
1632 curwin->w_cursor.col = col;
1633 #ifdef FEAT_MBYTE
1634 if (has_mbyte)
1636 char_u *p;
1638 /* If on the last byte of a multi-byte move to the first byte. */
1639 p = ml_get_curline();
1640 curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1642 #endif
1643 curs_columns(FALSE); /* recompute w_wrow and w_wcol */
1644 if (curwin->w_wcol < W_WIDTH(curwin))
1646 edit_putchar('$', FALSE);
1647 dollar_vcol = curwin->w_virtcol;
1649 curwin->w_cursor.col = save_col;
1653 * Call this function before moving the cursor from the normal insert position
1654 * in insert mode.
1656 static void
1657 undisplay_dollar()
1659 if (dollar_vcol)
1661 dollar_vcol = 0;
1662 redrawWinline(curwin->w_cursor.lnum, FALSE);
1667 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1668 * Keep the cursor on the same character.
1669 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1670 * type == INDENT_DEC decrease indent (for CTRL-D)
1671 * type == INDENT_SET set indent to "amount"
1672 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1674 void
1675 change_indent(type, amount, round, replaced, call_changed_bytes)
1676 int type;
1677 int amount;
1678 int round;
1679 int replaced; /* replaced character, put on replace stack */
1680 int call_changed_bytes; /* call changed_bytes() */
1682 int vcol;
1683 int last_vcol;
1684 int insstart_less; /* reduction for Insstart.col */
1685 int new_cursor_col;
1686 int i;
1687 char_u *ptr;
1688 int save_p_list;
1689 int start_col;
1690 colnr_T vc;
1691 #ifdef FEAT_VREPLACE
1692 colnr_T orig_col = 0; /* init for GCC */
1693 char_u *new_line, *orig_line = NULL; /* init for GCC */
1695 /* VREPLACE mode needs to know what the line was like before changing */
1696 if (State & VREPLACE_FLAG)
1698 orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */
1699 orig_col = curwin->w_cursor.col;
1701 #endif
1703 /* for the following tricks we don't want list mode */
1704 save_p_list = curwin->w_p_list;
1705 curwin->w_p_list = FALSE;
1706 vc = getvcol_nolist(&curwin->w_cursor);
1707 vcol = vc;
1710 * For Replace mode we need to fix the replace stack later, which is only
1711 * possible when the cursor is in the indent. Remember the number of
1712 * characters before the cursor if it's possible.
1714 start_col = curwin->w_cursor.col;
1716 /* determine offset from first non-blank */
1717 new_cursor_col = curwin->w_cursor.col;
1718 beginline(BL_WHITE);
1719 new_cursor_col -= curwin->w_cursor.col;
1721 insstart_less = curwin->w_cursor.col;
1724 * If the cursor is in the indent, compute how many screen columns the
1725 * cursor is to the left of the first non-blank.
1727 if (new_cursor_col < 0)
1728 vcol = get_indent() - vcol;
1730 if (new_cursor_col > 0) /* can't fix replace stack */
1731 start_col = -1;
1734 * Set the new indent. The cursor will be put on the first non-blank.
1736 if (type == INDENT_SET)
1737 (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
1738 else
1740 #ifdef FEAT_VREPLACE
1741 int save_State = State;
1743 /* Avoid being called recursively. */
1744 if (State & VREPLACE_FLAG)
1745 State = INSERT;
1746 #endif
1747 shift_line(type == INDENT_DEC, round, 1, call_changed_bytes);
1748 #ifdef FEAT_VREPLACE
1749 State = save_State;
1750 #endif
1752 insstart_less -= curwin->w_cursor.col;
1755 * Try to put cursor on same character.
1756 * If the cursor is at or after the first non-blank in the line,
1757 * compute the cursor column relative to the column of the first
1758 * non-blank character.
1759 * If we are not in insert mode, leave the cursor on the first non-blank.
1760 * If the cursor is before the first non-blank, position it relative
1761 * to the first non-blank, counted in screen columns.
1763 if (new_cursor_col >= 0)
1766 * When changing the indent while the cursor is touching it, reset
1767 * Insstart_col to 0.
1769 if (new_cursor_col == 0)
1770 insstart_less = MAXCOL;
1771 new_cursor_col += curwin->w_cursor.col;
1773 else if (!(State & INSERT))
1774 new_cursor_col = curwin->w_cursor.col;
1775 else
1778 * Compute the screen column where the cursor should be.
1780 vcol = get_indent() - vcol;
1781 curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);
1784 * Advance the cursor until we reach the right screen column.
1786 vcol = last_vcol = 0;
1787 new_cursor_col = -1;
1788 ptr = ml_get_curline();
1789 while (vcol <= (int)curwin->w_virtcol)
1791 last_vcol = vcol;
1792 #ifdef FEAT_MBYTE
1793 if (has_mbyte && new_cursor_col >= 0)
1794 new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1795 else
1796 #endif
1797 ++new_cursor_col;
1798 vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol);
1800 vcol = last_vcol;
1803 * May need to insert spaces to be able to position the cursor on
1804 * the right screen column.
1806 if (vcol != (int)curwin->w_virtcol)
1808 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1809 i = (int)curwin->w_virtcol - vcol;
1810 ptr = alloc((unsigned)(i + 1));
1811 if (ptr != NULL)
1813 new_cursor_col += i;
1814 ptr[i] = NUL;
1815 while (--i >= 0)
1816 ptr[i] = ' ';
1817 ins_str(ptr);
1818 vim_free(ptr);
1823 * When changing the indent while the cursor is in it, reset
1824 * Insstart_col to 0.
1826 insstart_less = MAXCOL;
1829 curwin->w_p_list = save_p_list;
1831 if (new_cursor_col <= 0)
1832 curwin->w_cursor.col = 0;
1833 else
1834 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1835 curwin->w_set_curswant = TRUE;
1836 changed_cline_bef_curs();
1839 * May have to adjust the start of the insert.
1841 if (State & INSERT)
1843 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1845 if ((int)Insstart.col <= insstart_less)
1846 Insstart.col = 0;
1847 else
1848 Insstart.col -= insstart_less;
1850 if ((int)ai_col <= insstart_less)
1851 ai_col = 0;
1852 else
1853 ai_col -= insstart_less;
1857 * For REPLACE mode, may have to fix the replace stack, if it's possible.
1858 * If the number of characters before the cursor decreased, need to pop a
1859 * few characters from the replace stack.
1860 * If the number of characters before the cursor increased, need to push a
1861 * few NULs onto the replace stack.
1863 if (REPLACE_NORMAL(State) && start_col >= 0)
1865 while (start_col > (int)curwin->w_cursor.col)
1867 replace_join(0); /* remove a NUL from the replace stack */
1868 --start_col;
1870 while (start_col < (int)curwin->w_cursor.col || replaced)
1872 replace_push(NUL);
1873 if (replaced)
1875 replace_push(replaced);
1876 replaced = NUL;
1878 ++start_col;
1882 #ifdef FEAT_VREPLACE
1884 * For VREPLACE mode, we also have to fix the replace stack. In this case
1885 * it is always possible because we backspace over the whole line and then
1886 * put it back again the way we wanted it.
1888 if (State & VREPLACE_FLAG)
1890 /* If orig_line didn't allocate, just return. At least we did the job,
1891 * even if you can't backspace. */
1892 if (orig_line == NULL)
1893 return;
1895 /* Save new line */
1896 new_line = vim_strsave(ml_get_curline());
1897 if (new_line == NULL)
1898 return;
1900 /* We only put back the new line up to the cursor */
1901 new_line[curwin->w_cursor.col] = NUL;
1903 /* Put back original line */
1904 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1905 curwin->w_cursor.col = orig_col;
1907 /* Backspace from cursor to start of line */
1908 backspace_until_column(0);
1910 /* Insert new stuff into line again */
1911 ins_bytes(new_line);
1913 vim_free(new_line);
1915 #endif
1919 * Truncate the space at the end of a line. This is to be used only in an
1920 * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE
1921 * modes.
1923 void
1924 truncate_spaces(line)
1925 char_u *line;
1927 int i;
1929 /* find start of trailing white space */
1930 for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
1932 if (State & REPLACE_FLAG)
1933 replace_join(0); /* remove a NUL from the replace stack */
1935 line[i + 1] = NUL;
1938 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1939 || defined(FEAT_COMMENTS) || defined(PROTO)
1941 * Backspace the cursor until the given column. Handles REPLACE and VREPLACE
1942 * modes correctly. May also be used when not in insert mode at all.
1943 * Will attempt not to go before "col" even when there is a composing
1944 * character.
1946 void
1947 backspace_until_column(col)
1948 int col;
1950 while ((int)curwin->w_cursor.col > col)
1952 curwin->w_cursor.col--;
1953 if (State & REPLACE_FLAG)
1954 replace_do_bs(col);
1955 else if (!del_char_after_col(col))
1956 break;
1959 #endif
1962 * Like del_char(), but make sure not to go before column "limit_col".
1963 * Only matters when there are composing characters.
1964 * Return TRUE when something was deleted.
1966 static int
1967 del_char_after_col(limit_col)
1968 int limit_col UNUSED;
1970 #ifdef FEAT_MBYTE
1971 if (enc_utf8 && limit_col >= 0)
1973 colnr_T ecol = curwin->w_cursor.col + 1;
1975 /* Make sure the cursor is at the start of a character, but
1976 * skip forward again when going too far back because of a
1977 * composing character. */
1978 mb_adjust_cursor();
1979 while (curwin->w_cursor.col < (colnr_T)limit_col)
1981 int l = utf_ptr2len(ml_get_cursor());
1983 if (l == 0) /* end of line */
1984 break;
1985 curwin->w_cursor.col += l;
1987 if (*ml_get_cursor() == NUL || curwin->w_cursor.col == ecol)
1988 return FALSE;
1989 del_bytes((long)((int)ecol - curwin->w_cursor.col), FALSE, TRUE);
1991 else
1992 #endif
1993 (void)del_char(FALSE);
1994 return TRUE;
1997 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1999 * CTRL-X pressed in Insert mode.
2001 static void
2002 ins_ctrl_x()
2004 /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
2005 * CTRL-V works like CTRL-N */
2006 if (ctrl_x_mode != CTRL_X_CMDLINE)
2008 /* if the next ^X<> won't ADD nothing, then reset
2009 * compl_cont_status */
2010 if (compl_cont_status & CONT_N_ADDS)
2011 compl_cont_status |= CONT_INTRPT;
2012 else
2013 compl_cont_status = 0;
2014 /* We're not sure which CTRL-X mode it will be yet */
2015 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2016 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
2017 edit_submode_pre = NULL;
2018 showmode();
2023 * Return TRUE if the 'dict' or 'tsr' option can be used.
2025 static int
2026 has_compl_option(dict_opt)
2027 int dict_opt;
2029 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
2030 # ifdef FEAT_SPELL
2031 && !curwin->w_p_spell
2032 # endif
2034 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
2036 ctrl_x_mode = 0;
2037 edit_submode = NULL;
2038 msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty")
2039 : (char_u *)_("'thesaurus' option is empty"),
2040 hl_attr(HLF_E));
2041 if (emsg_silent == 0)
2043 vim_beep();
2044 setcursor();
2045 out_flush();
2046 ui_delay(2000L, FALSE);
2048 return FALSE;
2050 return TRUE;
2054 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
2055 * This depends on the current mode.
2058 vim_is_ctrl_x_key(c)
2059 int c;
2061 /* Always allow ^R - let it's results then be checked */
2062 if (c == Ctrl_R)
2063 return TRUE;
2065 /* Accept <PageUp> and <PageDown> if the popup menu is visible. */
2066 if (ins_compl_pum_key(c))
2067 return TRUE;
2069 switch (ctrl_x_mode)
2071 case 0: /* Not in any CTRL-X mode */
2072 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
2073 case CTRL_X_NOT_DEFINED_YET:
2074 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
2075 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
2076 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
2077 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
2078 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
2079 || c == Ctrl_S || c == 's');
2080 case CTRL_X_SCROLL:
2081 return (c == Ctrl_Y || c == Ctrl_E);
2082 case CTRL_X_WHOLE_LINE:
2083 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
2084 case CTRL_X_FILES:
2085 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
2086 case CTRL_X_DICTIONARY:
2087 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
2088 case CTRL_X_THESAURUS:
2089 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
2090 case CTRL_X_TAGS:
2091 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
2092 #ifdef FEAT_FIND_ID
2093 case CTRL_X_PATH_PATTERNS:
2094 return (c == Ctrl_P || c == Ctrl_N);
2095 case CTRL_X_PATH_DEFINES:
2096 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
2097 #endif
2098 case CTRL_X_CMDLINE:
2099 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
2100 || c == Ctrl_X);
2101 #ifdef FEAT_COMPL_FUNC
2102 case CTRL_X_FUNCTION:
2103 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
2104 case CTRL_X_OMNI:
2105 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
2106 #endif
2107 case CTRL_X_SPELL:
2108 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
2110 EMSG(_(e_internal));
2111 return FALSE;
2115 * Return TRUE when character "c" is part of the item currently being
2116 * completed. Used to decide whether to abandon complete mode when the menu
2117 * is visible.
2119 static int
2120 ins_compl_accept_char(c)
2121 int c;
2123 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
2124 /* When expanding an identifier only accept identifier chars. */
2125 return vim_isIDc(c);
2127 switch (ctrl_x_mode)
2129 case CTRL_X_FILES:
2130 /* When expanding file name only accept file name chars. But not
2131 * path separators, so that "proto/<Tab>" expands files in
2132 * "proto", not "proto/" as a whole */
2133 return vim_isfilec(c) && !vim_ispathsep(c);
2135 case CTRL_X_CMDLINE:
2136 case CTRL_X_OMNI:
2137 /* Command line and Omni completion can work with just about any
2138 * printable character, but do stop at white space. */
2139 return vim_isprintc(c) && !vim_iswhite(c);
2141 case CTRL_X_WHOLE_LINE:
2142 /* For while line completion a space can be part of the line. */
2143 return vim_isprintc(c);
2145 return vim_iswordc(c);
2149 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
2150 * case of the originally typed text is used, and the case of the completed
2151 * text is inferred, ie this tries to work out what case you probably wanted
2152 * the rest of the word to be in -- webb
2155 ins_compl_add_infercase(str, len, icase, fname, dir, flags)
2156 char_u *str;
2157 int len;
2158 int icase;
2159 char_u *fname;
2160 int dir;
2161 int flags;
2163 char_u *p;
2164 int i, c;
2165 int actual_len; /* Take multi-byte characters */
2166 int actual_compl_length; /* into account. */
2167 int min_len;
2168 int *wca; /* Wide character array. */
2169 int has_lower = FALSE;
2170 int was_letter = FALSE;
2172 if (p_ic && curbuf->b_p_inf && len > 0)
2174 /* Infer case of completed part. */
2176 /* Find actual length of completion. */
2177 #ifdef FEAT_MBYTE
2178 if (has_mbyte)
2180 p = str;
2181 actual_len = 0;
2182 while (*p != NUL)
2184 mb_ptr_adv(p);
2185 ++actual_len;
2188 else
2189 #endif
2190 actual_len = len;
2192 /* Find actual length of original text. */
2193 #ifdef FEAT_MBYTE
2194 if (has_mbyte)
2196 p = compl_orig_text;
2197 actual_compl_length = 0;
2198 while (*p != NUL)
2200 mb_ptr_adv(p);
2201 ++actual_compl_length;
2204 else
2205 #endif
2206 actual_compl_length = compl_length;
2208 /* "actual_len" may be smaller than "actual_compl_length" when using
2209 * thesaurus, only use the minimum when comparing. */
2210 min_len = actual_len < actual_compl_length
2211 ? actual_len : actual_compl_length;
2213 /* Allocate wide character array for the completion and fill it. */
2214 wca = (int *)alloc((unsigned)(actual_len * sizeof(int)));
2215 if (wca != NULL)
2217 p = str;
2218 for (i = 0; i < actual_len; ++i)
2219 #ifdef FEAT_MBYTE
2220 if (has_mbyte)
2221 wca[i] = mb_ptr2char_adv(&p);
2222 else
2223 #endif
2224 wca[i] = *(p++);
2226 /* Rule 1: Were any chars converted to lower? */
2227 p = compl_orig_text;
2228 for (i = 0; i < min_len; ++i)
2230 #ifdef FEAT_MBYTE
2231 if (has_mbyte)
2232 c = mb_ptr2char_adv(&p);
2233 else
2234 #endif
2235 c = *(p++);
2236 if (MB_ISLOWER(c))
2238 has_lower = TRUE;
2239 if (MB_ISUPPER(wca[i]))
2241 /* Rule 1 is satisfied. */
2242 for (i = actual_compl_length; i < actual_len; ++i)
2243 wca[i] = MB_TOLOWER(wca[i]);
2244 break;
2250 * Rule 2: No lower case, 2nd consecutive letter converted to
2251 * upper case.
2253 if (!has_lower)
2255 p = compl_orig_text;
2256 for (i = 0; i < min_len; ++i)
2258 #ifdef FEAT_MBYTE
2259 if (has_mbyte)
2260 c = mb_ptr2char_adv(&p);
2261 else
2262 #endif
2263 c = *(p++);
2264 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
2266 /* Rule 2 is satisfied. */
2267 for (i = actual_compl_length; i < actual_len; ++i)
2268 wca[i] = MB_TOUPPER(wca[i]);
2269 break;
2271 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
2275 /* Copy the original case of the part we typed. */
2276 p = compl_orig_text;
2277 for (i = 0; i < min_len; ++i)
2279 #ifdef FEAT_MBYTE
2280 if (has_mbyte)
2281 c = mb_ptr2char_adv(&p);
2282 else
2283 #endif
2284 c = *(p++);
2285 if (MB_ISLOWER(c))
2286 wca[i] = MB_TOLOWER(wca[i]);
2287 else if (MB_ISUPPER(c))
2288 wca[i] = MB_TOUPPER(wca[i]);
2292 * Generate encoding specific output from wide character array.
2293 * Multi-byte characters can occupy up to five bytes more than
2294 * ASCII characters, and we also need one byte for NUL, so stay
2295 * six bytes away from the edge of IObuff.
2297 p = IObuff;
2298 i = 0;
2299 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
2300 #ifdef FEAT_MBYTE
2301 if (has_mbyte)
2302 p += (*mb_char2bytes)(wca[i++], p);
2303 else
2304 #endif
2305 *(p++) = wca[i++];
2306 *p = NUL;
2308 vim_free(wca);
2311 return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2312 flags, FALSE);
2314 return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2318 * Add a match to the list of matches.
2319 * If the given string is already in the list of completions, then return
2320 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2321 * maybe because alloc() returns NULL, then FAIL is returned.
2323 static int
2324 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup)
2325 char_u *str;
2326 int len;
2327 int icase;
2328 char_u *fname;
2329 char_u **cptext; /* extra text for popup menu or NULL */
2330 int cdir;
2331 int flags;
2332 int adup; /* accept duplicate match */
2334 compl_T *match;
2335 int dir = (cdir == 0 ? compl_direction : cdir);
2337 ui_breakcheck();
2338 if (got_int)
2339 return FAIL;
2340 if (len < 0)
2341 len = (int)STRLEN(str);
2344 * If the same match is already present, don't add it.
2346 if (compl_first_match != NULL && !adup)
2348 match = compl_first_match;
2351 if ( !(match->cp_flags & ORIGINAL_TEXT)
2352 && STRNCMP(match->cp_str, str, len) == 0
2353 && match->cp_str[len] == NUL)
2354 return NOTDONE;
2355 match = match->cp_next;
2356 } while (match != NULL && match != compl_first_match);
2359 /* Remove any popup menu before changing the list of matches. */
2360 ins_compl_del_pum();
2363 * Allocate a new match structure.
2364 * Copy the values to the new match structure.
2366 match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2367 if (match == NULL)
2368 return FAIL;
2369 match->cp_number = -1;
2370 if (flags & ORIGINAL_TEXT)
2371 match->cp_number = 0;
2372 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2374 vim_free(match);
2375 return FAIL;
2377 match->cp_icase = icase;
2379 /* match-fname is:
2380 * - compl_curr_match->cp_fname if it is a string equal to fname.
2381 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2382 * - NULL otherwise. --Acevedo */
2383 if (fname != NULL
2384 && compl_curr_match != NULL
2385 && compl_curr_match->cp_fname != NULL
2386 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2387 match->cp_fname = compl_curr_match->cp_fname;
2388 else if (fname != NULL)
2390 match->cp_fname = vim_strsave(fname);
2391 flags |= FREE_FNAME;
2393 else
2394 match->cp_fname = NULL;
2395 match->cp_flags = flags;
2397 if (cptext != NULL)
2399 int i;
2401 for (i = 0; i < CPT_COUNT; ++i)
2402 if (cptext[i] != NULL && *cptext[i] != NUL)
2403 match->cp_text[i] = vim_strsave(cptext[i]);
2407 * Link the new match structure in the list of matches.
2409 if (compl_first_match == NULL)
2410 match->cp_next = match->cp_prev = NULL;
2411 else if (dir == FORWARD)
2413 match->cp_next = compl_curr_match->cp_next;
2414 match->cp_prev = compl_curr_match;
2416 else /* BACKWARD */
2418 match->cp_next = compl_curr_match;
2419 match->cp_prev = compl_curr_match->cp_prev;
2421 if (match->cp_next)
2422 match->cp_next->cp_prev = match;
2423 if (match->cp_prev)
2424 match->cp_prev->cp_next = match;
2425 else /* if there's nothing before, it is the first match */
2426 compl_first_match = match;
2427 compl_curr_match = match;
2430 * Find the longest common string if still doing that.
2432 if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2433 ins_compl_longest_match(match);
2435 return OK;
2439 * Return TRUE if "str[len]" matches with match->cp_str, considering
2440 * match->cp_icase.
2442 static int
2443 ins_compl_equal(match, str, len)
2444 compl_T *match;
2445 char_u *str;
2446 int len;
2448 if (match->cp_icase)
2449 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2450 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2454 * Reduce the longest common string for match "match".
2456 static void
2457 ins_compl_longest_match(match)
2458 compl_T *match;
2460 char_u *p, *s;
2461 int c1, c2;
2462 int had_match;
2464 if (compl_leader == NULL)
2466 /* First match, use it as a whole. */
2467 compl_leader = vim_strsave(match->cp_str);
2468 if (compl_leader != NULL)
2470 had_match = (curwin->w_cursor.col > compl_col);
2471 ins_compl_delete();
2472 ins_bytes(compl_leader + ins_compl_len());
2473 ins_redraw(FALSE);
2475 /* When the match isn't there (to avoid matching itself) remove it
2476 * again after redrawing. */
2477 if (!had_match)
2478 ins_compl_delete();
2479 compl_used_match = FALSE;
2482 else
2484 /* Reduce the text if this match differs from compl_leader. */
2485 p = compl_leader;
2486 s = match->cp_str;
2487 while (*p != NUL)
2489 #ifdef FEAT_MBYTE
2490 if (has_mbyte)
2492 c1 = mb_ptr2char(p);
2493 c2 = mb_ptr2char(s);
2495 else
2496 #endif
2498 c1 = *p;
2499 c2 = *s;
2501 if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2502 : (c1 != c2))
2503 break;
2504 #ifdef FEAT_MBYTE
2505 if (has_mbyte)
2507 mb_ptr_adv(p);
2508 mb_ptr_adv(s);
2510 else
2511 #endif
2513 ++p;
2514 ++s;
2518 if (*p != NUL)
2520 /* Leader was shortened, need to change the inserted text. */
2521 *p = NUL;
2522 had_match = (curwin->w_cursor.col > compl_col);
2523 ins_compl_delete();
2524 ins_bytes(compl_leader + ins_compl_len());
2525 ins_redraw(FALSE);
2527 /* When the match isn't there (to avoid matching itself) remove it
2528 * again after redrawing. */
2529 if (!had_match)
2530 ins_compl_delete();
2533 compl_used_match = FALSE;
2538 * Add an array of matches to the list of matches.
2539 * Frees matches[].
2541 static void
2542 ins_compl_add_matches(num_matches, matches, icase)
2543 int num_matches;
2544 char_u **matches;
2545 int icase;
2547 int i;
2548 int add_r = OK;
2549 int dir = compl_direction;
2551 for (i = 0; i < num_matches && add_r != FAIL; i++)
2552 if ((add_r = ins_compl_add(matches[i], -1, icase,
2553 NULL, NULL, dir, 0, FALSE)) == OK)
2554 /* if dir was BACKWARD then honor it just once */
2555 dir = FORWARD;
2556 FreeWild(num_matches, matches);
2559 /* Make the completion list cyclic.
2560 * Return the number of matches (excluding the original).
2562 static int
2563 ins_compl_make_cyclic()
2565 compl_T *match;
2566 int count = 0;
2568 if (compl_first_match != NULL)
2571 * Find the end of the list.
2573 match = compl_first_match;
2574 /* there's always an entry for the compl_orig_text, it doesn't count. */
2575 while (match->cp_next != NULL && match->cp_next != compl_first_match)
2577 match = match->cp_next;
2578 ++count;
2580 match->cp_next = compl_first_match;
2581 compl_first_match->cp_prev = match;
2583 return count;
2587 * Start completion for the complete() function.
2588 * "startcol" is where the matched text starts (1 is first column).
2589 * "list" is the list of matches.
2591 void
2592 set_completion(startcol, list)
2593 colnr_T startcol;
2594 list_T *list;
2596 /* If already doing completions stop it. */
2597 if (ctrl_x_mode != 0)
2598 ins_compl_prep(' ');
2599 ins_compl_clear();
2601 if (stop_arrow() == FAIL)
2602 return;
2604 if (startcol > curwin->w_cursor.col)
2605 startcol = curwin->w_cursor.col;
2606 compl_col = startcol;
2607 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2608 /* compl_pattern doesn't need to be set */
2609 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2610 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2611 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2612 return;
2614 /* Handle like dictionary completion. */
2615 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2617 ins_compl_add_list(list);
2618 compl_matches = ins_compl_make_cyclic();
2619 compl_started = TRUE;
2620 compl_used_match = TRUE;
2621 compl_cont_status = 0;
2623 compl_curr_match = compl_first_match;
2624 ins_complete(Ctrl_N);
2625 out_flush();
2629 /* "compl_match_array" points the currently displayed list of entries in the
2630 * popup menu. It is NULL when there is no popup menu. */
2631 static pumitem_T *compl_match_array = NULL;
2632 static int compl_match_arraysize;
2635 * Update the screen and when there is any scrolling remove the popup menu.
2637 static void
2638 ins_compl_upd_pum()
2640 int h;
2642 if (compl_match_array != NULL)
2644 h = curwin->w_cline_height;
2645 update_screen(0);
2646 if (h != curwin->w_cline_height)
2647 ins_compl_del_pum();
2652 * Remove any popup menu.
2654 static void
2655 ins_compl_del_pum()
2657 if (compl_match_array != NULL)
2659 pum_undisplay();
2660 vim_free(compl_match_array);
2661 compl_match_array = NULL;
2666 * Return TRUE if the popup menu should be displayed.
2668 static int
2669 pum_wanted()
2671 /* 'completeopt' must contain "menu" or "menuone" */
2672 if (vim_strchr(p_cot, 'm') == NULL)
2673 return FALSE;
2675 /* The display looks bad on a B&W display. */
2676 if (t_colors < 8
2677 #ifdef FEAT_GUI
2678 && !gui.in_use
2679 #endif
2681 return FALSE;
2682 return TRUE;
2686 * Return TRUE if there are two or more matches to be shown in the popup menu.
2687 * One if 'completopt' contains "menuone".
2689 static int
2690 pum_enough_matches()
2692 compl_T *compl;
2693 int i;
2695 /* Don't display the popup menu if there are no matches or there is only
2696 * one (ignoring the original text). */
2697 compl = compl_first_match;
2698 i = 0;
2701 if (compl == NULL
2702 || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2703 break;
2704 compl = compl->cp_next;
2705 } while (compl != compl_first_match);
2707 if (strstr((char *)p_cot, "menuone") != NULL)
2708 return (i >= 1);
2709 return (i >= 2);
2713 * Show the popup menu for the list of matches.
2714 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2716 void
2717 ins_compl_show_pum()
2719 compl_T *compl;
2720 compl_T *shown_compl = NULL;
2721 int did_find_shown_match = FALSE;
2722 int shown_match_ok = FALSE;
2723 int i;
2724 int cur = -1;
2725 colnr_T col;
2726 int lead_len = 0;
2728 if (!pum_wanted() || !pum_enough_matches())
2729 return;
2731 #if defined(FEAT_EVAL)
2732 /* Dirty hard-coded hack: remove any matchparen highlighting. */
2733 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2734 #endif
2736 /* Update the screen before drawing the popup menu over it. */
2737 update_screen(0);
2739 if (compl_match_array == NULL)
2741 /* Need to build the popup menu list. */
2742 compl_match_arraysize = 0;
2743 compl = compl_first_match;
2744 if (compl_leader != NULL)
2745 lead_len = (int)STRLEN(compl_leader);
2748 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2749 && (compl_leader == NULL
2750 || ins_compl_equal(compl, compl_leader, lead_len)))
2751 ++compl_match_arraysize;
2752 compl = compl->cp_next;
2753 } while (compl != NULL && compl != compl_first_match);
2754 if (compl_match_arraysize == 0)
2755 return;
2756 compl_match_array = (pumitem_T *)alloc_clear(
2757 (unsigned)(sizeof(pumitem_T)
2758 * compl_match_arraysize));
2759 if (compl_match_array != NULL)
2761 /* If the current match is the original text don't find the first
2762 * match after it, don't highlight anything. */
2763 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2764 shown_match_ok = TRUE;
2766 i = 0;
2767 compl = compl_first_match;
2770 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2771 && (compl_leader == NULL
2772 || ins_compl_equal(compl, compl_leader, lead_len)))
2774 if (!shown_match_ok)
2776 if (compl == compl_shown_match || did_find_shown_match)
2778 /* This item is the shown match or this is the
2779 * first displayed item after the shown match. */
2780 compl_shown_match = compl;
2781 did_find_shown_match = TRUE;
2782 shown_match_ok = TRUE;
2784 else
2785 /* Remember this displayed match for when the
2786 * shown match is just below it. */
2787 shown_compl = compl;
2788 cur = i;
2791 if (compl->cp_text[CPT_ABBR] != NULL)
2792 compl_match_array[i].pum_text =
2793 compl->cp_text[CPT_ABBR];
2794 else
2795 compl_match_array[i].pum_text = compl->cp_str;
2796 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2797 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2798 if (compl->cp_text[CPT_MENU] != NULL)
2799 compl_match_array[i++].pum_extra =
2800 compl->cp_text[CPT_MENU];
2801 else
2802 compl_match_array[i++].pum_extra = compl->cp_fname;
2805 if (compl == compl_shown_match)
2807 did_find_shown_match = TRUE;
2809 /* When the original text is the shown match don't set
2810 * compl_shown_match. */
2811 if (compl->cp_flags & ORIGINAL_TEXT)
2812 shown_match_ok = TRUE;
2814 if (!shown_match_ok && shown_compl != NULL)
2816 /* The shown match isn't displayed, set it to the
2817 * previously displayed match. */
2818 compl_shown_match = shown_compl;
2819 shown_match_ok = TRUE;
2822 compl = compl->cp_next;
2823 } while (compl != NULL && compl != compl_first_match);
2825 if (!shown_match_ok) /* no displayed match at all */
2826 cur = -1;
2829 else
2831 /* popup menu already exists, only need to find the current item.*/
2832 for (i = 0; i < compl_match_arraysize; ++i)
2833 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2834 || compl_match_array[i].pum_text
2835 == compl_shown_match->cp_text[CPT_ABBR])
2837 cur = i;
2838 break;
2842 if (compl_match_array != NULL)
2844 /* Compute the screen column of the start of the completed text.
2845 * Use the cursor to get all wrapping and other settings right. */
2846 col = curwin->w_cursor.col;
2847 curwin->w_cursor.col = compl_col;
2848 pum_display(compl_match_array, compl_match_arraysize, cur);
2849 curwin->w_cursor.col = col;
2853 #define DICT_FIRST (1) /* use just first element in "dict" */
2854 #define DICT_EXACT (2) /* "dict" is the exact name of a file */
2857 * Add any identifiers that match the given pattern in the list of dictionary
2858 * files "dict_start" to the list of completions.
2860 static void
2861 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2862 char_u *dict_start;
2863 char_u *pat;
2864 int flags; /* DICT_FIRST and/or DICT_EXACT */
2865 int thesaurus; /* Thesaurus completion */
2867 char_u *dict = dict_start;
2868 char_u *ptr;
2869 char_u *buf;
2870 regmatch_T regmatch;
2871 char_u **files;
2872 int count;
2873 int save_p_scs;
2874 int dir = compl_direction;
2876 if (*dict == NUL)
2878 #ifdef FEAT_SPELL
2879 /* When 'dictionary' is empty and spell checking is enabled use
2880 * "spell". */
2881 if (!thesaurus && curwin->w_p_spell)
2882 dict = (char_u *)"spell";
2883 else
2884 #endif
2885 return;
2888 buf = alloc(LSIZE);
2889 if (buf == NULL)
2890 return;
2891 regmatch.regprog = NULL; /* so that we can goto theend */
2893 /* If 'infercase' is set, don't use 'smartcase' here */
2894 save_p_scs = p_scs;
2895 if (curbuf->b_p_inf)
2896 p_scs = FALSE;
2898 /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
2899 * to only match at the start of a line. Otherwise just match the
2900 * pattern. Also need to double backslashes. */
2901 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2903 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
2904 size_t len;
2906 if (pat_esc == NULL)
2907 goto theend;
2908 len = STRLEN(pat_esc) + 10;
2909 ptr = alloc((unsigned)len);
2910 if (ptr == NULL)
2912 vim_free(pat_esc);
2913 goto theend;
2915 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
2916 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
2917 vim_free(pat_esc);
2918 vim_free(ptr);
2920 else
2922 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2923 if (regmatch.regprog == NULL)
2924 goto theend;
2927 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2928 regmatch.rm_ic = ignorecase(pat);
2929 while (*dict != NUL && !got_int && !compl_interrupted)
2931 /* copy one dictionary file name into buf */
2932 if (flags == DICT_EXACT)
2934 count = 1;
2935 files = &dict;
2937 else
2939 /* Expand wildcards in the dictionary name, but do not allow
2940 * backticks (for security, the 'dict' option may have been set in
2941 * a modeline). */
2942 copy_option_part(&dict, buf, LSIZE, ",");
2943 # ifdef FEAT_SPELL
2944 if (!thesaurus && STRCMP(buf, "spell") == 0)
2945 count = -1;
2946 else
2947 # endif
2948 if (vim_strchr(buf, '`') != NULL
2949 || expand_wildcards(1, &buf, &count, &files,
2950 EW_FILE|EW_SILENT) != OK)
2951 count = 0;
2954 # ifdef FEAT_SPELL
2955 if (count == -1)
2957 /* Complete from active spelling. Skip "\<" in the pattern, we
2958 * don't use it as a RE. */
2959 if (pat[0] == '\\' && pat[1] == '<')
2960 ptr = pat + 2;
2961 else
2962 ptr = pat;
2963 spell_dump_compl(curbuf, ptr, regmatch.rm_ic, &dir, 0);
2965 else
2966 # endif
2967 if (count > 0) /* avoid warning for using "files" uninit */
2969 ins_compl_files(count, files, thesaurus, flags,
2970 &regmatch, buf, &dir);
2971 if (flags != DICT_EXACT)
2972 FreeWild(count, files);
2974 if (flags != 0)
2975 break;
2978 theend:
2979 p_scs = save_p_scs;
2980 vim_free(regmatch.regprog);
2981 vim_free(buf);
2984 static void
2985 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
2986 int count;
2987 char_u **files;
2988 int thesaurus;
2989 int flags;
2990 regmatch_T *regmatch;
2991 char_u *buf;
2992 int *dir;
2994 char_u *ptr;
2995 int i;
2996 FILE *fp;
2997 int add_r;
2999 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
3001 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
3002 if (flags != DICT_EXACT)
3004 vim_snprintf((char *)IObuff, IOSIZE,
3005 _("Scanning dictionary: %s"), (char *)files[i]);
3006 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3009 if (fp != NULL)
3012 * Read dictionary file line by line.
3013 * Check each line for a match.
3015 while (!got_int && !compl_interrupted
3016 && !vim_fgets(buf, LSIZE, fp))
3018 ptr = buf;
3019 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
3021 ptr = regmatch->startp[0];
3022 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3023 ptr = find_line_end(ptr);
3024 else
3025 ptr = find_word_end(ptr);
3026 add_r = ins_compl_add_infercase(regmatch->startp[0],
3027 (int)(ptr - regmatch->startp[0]),
3028 p_ic, files[i], *dir, 0);
3029 if (thesaurus)
3031 char_u *wstart;
3034 * Add the other matches on the line
3036 ptr = buf;
3037 while (!got_int)
3039 /* Find start of the next word. Skip white
3040 * space and punctuation. */
3041 ptr = find_word_start(ptr);
3042 if (*ptr == NUL || *ptr == NL)
3043 break;
3044 wstart = ptr;
3046 /* Find end of the word. */
3047 #ifdef FEAT_MBYTE
3048 if (has_mbyte)
3049 /* Japanese words may have characters in
3050 * different classes, only separate words
3051 * with single-byte non-word characters. */
3052 while (*ptr != NUL)
3054 int l = (*mb_ptr2len)(ptr);
3056 if (l < 2 && !vim_iswordc(*ptr))
3057 break;
3058 ptr += l;
3060 else
3061 #endif
3062 ptr = find_word_end(ptr);
3064 /* Add the word. Skip the regexp match. */
3065 if (wstart != regmatch->startp[0])
3066 add_r = ins_compl_add_infercase(wstart,
3067 (int)(ptr - wstart),
3068 p_ic, files[i], *dir, 0);
3071 if (add_r == OK)
3072 /* if dir was BACKWARD then honor it just once */
3073 *dir = FORWARD;
3074 else if (add_r == FAIL)
3075 break;
3076 /* avoid expensive call to vim_regexec() when at end
3077 * of line */
3078 if (*ptr == '\n' || got_int)
3079 break;
3081 line_breakcheck();
3082 ins_compl_check_keys(50);
3084 fclose(fp);
3090 * Find the start of the next word.
3091 * Returns a pointer to the first char of the word. Also stops at a NUL.
3093 char_u *
3094 find_word_start(ptr)
3095 char_u *ptr;
3097 #ifdef FEAT_MBYTE
3098 if (has_mbyte)
3099 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
3100 ptr += (*mb_ptr2len)(ptr);
3101 else
3102 #endif
3103 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
3104 ++ptr;
3105 return ptr;
3109 * Find the end of the word. Assumes it starts inside a word.
3110 * Returns a pointer to just after the word.
3112 char_u *
3113 find_word_end(ptr)
3114 char_u *ptr;
3116 #ifdef FEAT_MBYTE
3117 int start_class;
3119 if (has_mbyte)
3121 start_class = mb_get_class(ptr);
3122 if (start_class > 1)
3123 while (*ptr != NUL)
3125 ptr += (*mb_ptr2len)(ptr);
3126 if (mb_get_class(ptr) != start_class)
3127 break;
3130 else
3131 #endif
3132 while (vim_iswordc(*ptr))
3133 ++ptr;
3134 return ptr;
3138 * Find the end of the line, omitting CR and NL at the end.
3139 * Returns a pointer to just after the line.
3141 static char_u *
3142 find_line_end(ptr)
3143 char_u *ptr;
3145 char_u *s;
3147 s = ptr + STRLEN(ptr);
3148 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
3149 --s;
3150 return s;
3154 * Free the list of completions
3156 static void
3157 ins_compl_free()
3159 compl_T *match;
3160 int i;
3162 vim_free(compl_pattern);
3163 compl_pattern = NULL;
3164 vim_free(compl_leader);
3165 compl_leader = NULL;
3167 if (compl_first_match == NULL)
3168 return;
3170 ins_compl_del_pum();
3171 pum_clear();
3173 compl_curr_match = compl_first_match;
3176 match = compl_curr_match;
3177 compl_curr_match = compl_curr_match->cp_next;
3178 vim_free(match->cp_str);
3179 /* several entries may use the same fname, free it just once. */
3180 if (match->cp_flags & FREE_FNAME)
3181 vim_free(match->cp_fname);
3182 for (i = 0; i < CPT_COUNT; ++i)
3183 vim_free(match->cp_text[i]);
3184 vim_free(match);
3185 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
3186 compl_first_match = compl_curr_match = NULL;
3187 compl_shown_match = NULL;
3190 static void
3191 ins_compl_clear()
3193 compl_cont_status = 0;
3194 compl_started = FALSE;
3195 compl_matches = 0;
3196 vim_free(compl_pattern);
3197 compl_pattern = NULL;
3198 vim_free(compl_leader);
3199 compl_leader = NULL;
3200 edit_submode_extra = NULL;
3201 vim_free(compl_orig_text);
3202 compl_orig_text = NULL;
3203 compl_enter_selects = FALSE;
3207 * Return TRUE when Insert completion is active.
3210 ins_compl_active()
3212 return compl_started;
3216 * Delete one character before the cursor and show the subset of the matches
3217 * that match the word that is now before the cursor.
3218 * Returns the character to be used, NUL if the work is done and another char
3219 * to be got from the user.
3221 static int
3222 ins_compl_bs()
3224 char_u *line;
3225 char_u *p;
3227 line = ml_get_curline();
3228 p = line + curwin->w_cursor.col;
3229 mb_ptr_back(line, p);
3231 /* Stop completion when the whole word was deleted. For Omni completion
3232 * allow the word to be deleted, we won't match everything. */
3233 if ((int)(p - line) - (int)compl_col < 0
3234 || ((int)(p - line) - (int)compl_col == 0
3235 && (ctrl_x_mode & CTRL_X_OMNI) == 0))
3236 return K_BS;
3238 /* Deleted more than what was used to find matches or didn't finish
3239 * finding all matches: need to look for matches all over again. */
3240 if (curwin->w_cursor.col <= compl_col + compl_length
3241 || compl_was_interrupted)
3242 ins_compl_restart();
3244 vim_free(compl_leader);
3245 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3246 if (compl_leader != NULL)
3248 ins_compl_new_leader();
3249 return NUL;
3251 return K_BS;
3255 * Called after changing "compl_leader".
3256 * Show the popup menu with a different set of matches.
3257 * May also search for matches again if the previous search was interrupted.
3259 static void
3260 ins_compl_new_leader()
3262 ins_compl_del_pum();
3263 ins_compl_delete();
3264 ins_bytes(compl_leader + ins_compl_len());
3265 compl_used_match = FALSE;
3267 if (compl_started)
3268 ins_compl_set_original_text(compl_leader);
3269 else
3271 #ifdef FEAT_SPELL
3272 spell_bad_len = 0; /* need to redetect bad word */
3273 #endif
3275 * Matches were cleared, need to search for them now. First display
3276 * the changed text before the cursor. Set "compl_restarting" to
3277 * avoid that the first match is inserted.
3279 update_screen(0);
3280 #ifdef FEAT_GUI
3281 if (gui.in_use)
3283 /* Show the cursor after the match, not after the redrawn text. */
3284 setcursor();
3285 out_flush();
3286 gui_update_cursor(FALSE, FALSE);
3288 #endif
3289 compl_restarting = TRUE;
3290 if (ins_complete(Ctrl_N) == FAIL)
3291 compl_cont_status = 0;
3292 compl_restarting = FALSE;
3295 #if 0 /* disabled, made CTRL-L, BS and typing char jump to original text. */
3296 if (!compl_used_match)
3298 /* Go to the original text, since none of the matches is inserted. */
3299 if (compl_first_match->cp_prev != NULL
3300 && (compl_first_match->cp_prev->cp_flags & ORIGINAL_TEXT))
3301 compl_shown_match = compl_first_match->cp_prev;
3302 else
3303 compl_shown_match = compl_first_match;
3304 compl_curr_match = compl_shown_match;
3305 compl_shows_dir = compl_direction;
3307 #endif
3308 compl_enter_selects = !compl_used_match;
3310 /* Show the popup menu with a different set of matches. */
3311 ins_compl_show_pum();
3313 /* Don't let Enter select the original text when there is no popup menu. */
3314 if (compl_match_array == NULL)
3315 compl_enter_selects = FALSE;
3319 * Return the length of the completion, from the completion start column to
3320 * the cursor column. Making sure it never goes below zero.
3322 static int
3323 ins_compl_len()
3325 int off = (int)curwin->w_cursor.col - (int)compl_col;
3327 if (off < 0)
3328 return 0;
3329 return off;
3333 * Append one character to the match leader. May reduce the number of
3334 * matches.
3336 static void
3337 ins_compl_addleader(c)
3338 int c;
3340 #ifdef FEAT_MBYTE
3341 int cc;
3343 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3345 char_u buf[MB_MAXBYTES + 1];
3347 (*mb_char2bytes)(c, buf);
3348 buf[cc] = NUL;
3349 ins_char_bytes(buf, cc);
3351 else
3352 #endif
3353 ins_char(c);
3355 /* If we didn't complete finding matches we must search again. */
3356 if (compl_was_interrupted)
3357 ins_compl_restart();
3359 vim_free(compl_leader);
3360 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3361 (int)(curwin->w_cursor.col - compl_col));
3362 if (compl_leader != NULL)
3363 ins_compl_new_leader();
3367 * Setup for finding completions again without leaving CTRL-X mode. Used when
3368 * BS or a key was typed while still searching for matches.
3370 static void
3371 ins_compl_restart()
3373 ins_compl_free();
3374 compl_started = FALSE;
3375 compl_matches = 0;
3376 compl_cont_status = 0;
3377 compl_cont_mode = 0;
3381 * Set the first match, the original text.
3383 static void
3384 ins_compl_set_original_text(str)
3385 char_u *str;
3387 char_u *p;
3389 /* Replace the original text entry. */
3390 if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */
3392 p = vim_strsave(str);
3393 if (p != NULL)
3395 vim_free(compl_first_match->cp_str);
3396 compl_first_match->cp_str = p;
3402 * Append one character to the match leader. May reduce the number of
3403 * matches.
3405 static void
3406 ins_compl_addfrommatch()
3408 char_u *p;
3409 int len = (int)curwin->w_cursor.col - (int)compl_col;
3410 int c;
3411 compl_T *cp;
3413 p = compl_shown_match->cp_str;
3414 if ((int)STRLEN(p) <= len) /* the match is too short */
3416 /* When still at the original match use the first entry that matches
3417 * the leader. */
3418 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
3420 p = NULL;
3421 for (cp = compl_shown_match->cp_next; cp != NULL
3422 && cp != compl_first_match; cp = cp->cp_next)
3424 if (compl_leader == NULL
3425 || ins_compl_equal(cp, compl_leader,
3426 (int)STRLEN(compl_leader)))
3428 p = cp->cp_str;
3429 break;
3432 if (p == NULL || (int)STRLEN(p) <= len)
3433 return;
3435 else
3436 return;
3438 p += len;
3439 #ifdef FEAT_MBYTE
3440 c = mb_ptr2char(p);
3441 #else
3442 c = *p;
3443 #endif
3444 ins_compl_addleader(c);
3448 * Prepare for Insert mode completion, or stop it.
3449 * Called just after typing a character in Insert mode.
3450 * Returns TRUE when the character is not to be inserted;
3452 static int
3453 ins_compl_prep(c)
3454 int c;
3456 char_u *ptr;
3457 int want_cindent;
3458 int retval = FALSE;
3460 /* Forget any previous 'special' messages if this is actually
3461 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3463 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3464 edit_submode_extra = NULL;
3466 /* Ignore end of Select mode mapping and mouse scroll buttons. */
3467 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP)
3468 return retval;
3470 /* Set "compl_get_longest" when finding the first matches. */
3471 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3472 || (ctrl_x_mode == 0 && !compl_started))
3474 compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3475 compl_used_match = TRUE;
3478 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3481 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3482 * it will be yet. Now we decide.
3484 switch (c)
3486 case Ctrl_E:
3487 case Ctrl_Y:
3488 ctrl_x_mode = CTRL_X_SCROLL;
3489 if (!(State & REPLACE_FLAG))
3490 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3491 else
3492 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3493 edit_submode_pre = NULL;
3494 showmode();
3495 break;
3496 case Ctrl_L:
3497 ctrl_x_mode = CTRL_X_WHOLE_LINE;
3498 break;
3499 case Ctrl_F:
3500 ctrl_x_mode = CTRL_X_FILES;
3501 break;
3502 case Ctrl_K:
3503 ctrl_x_mode = CTRL_X_DICTIONARY;
3504 break;
3505 case Ctrl_R:
3506 /* Simply allow ^R to happen without affecting ^X mode */
3507 break;
3508 case Ctrl_T:
3509 ctrl_x_mode = CTRL_X_THESAURUS;
3510 break;
3511 #ifdef FEAT_COMPL_FUNC
3512 case Ctrl_U:
3513 ctrl_x_mode = CTRL_X_FUNCTION;
3514 break;
3515 case Ctrl_O:
3516 ctrl_x_mode = CTRL_X_OMNI;
3517 break;
3518 #endif
3519 case 's':
3520 case Ctrl_S:
3521 ctrl_x_mode = CTRL_X_SPELL;
3522 #ifdef FEAT_SPELL
3523 ++emsg_off; /* Avoid getting the E756 error twice. */
3524 spell_back_to_badword();
3525 --emsg_off;
3526 #endif
3527 break;
3528 case Ctrl_RSB:
3529 ctrl_x_mode = CTRL_X_TAGS;
3530 break;
3531 #ifdef FEAT_FIND_ID
3532 case Ctrl_I:
3533 case K_S_TAB:
3534 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3535 break;
3536 case Ctrl_D:
3537 ctrl_x_mode = CTRL_X_PATH_DEFINES;
3538 break;
3539 #endif
3540 case Ctrl_V:
3541 case Ctrl_Q:
3542 ctrl_x_mode = CTRL_X_CMDLINE;
3543 break;
3544 case Ctrl_P:
3545 case Ctrl_N:
3546 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
3547 * just started ^X mode, or there were enough ^X's to cancel
3548 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3549 * do normal expansion when interrupting a different mode (say
3550 * ^X^F^X^P or ^P^X^X^P, see below)
3551 * nothing changes if interrupting mode 0, (eg, the flag
3552 * doesn't change when going to ADDING mode -- Acevedo */
3553 if (!(compl_cont_status & CONT_INTRPT))
3554 compl_cont_status |= CONT_LOCAL;
3555 else if (compl_cont_mode != 0)
3556 compl_cont_status &= ~CONT_LOCAL;
3557 /* FALLTHROUGH */
3558 default:
3559 /* If we have typed at least 2 ^X's... for modes != 0, we set
3560 * compl_cont_status = 0 (eg, as if we had just started ^X
3561 * mode).
3562 * For mode 0, we set "compl_cont_mode" to an impossible
3563 * value, in both cases ^X^X can be used to restart the same
3564 * mode (avoiding ADDING mode).
3565 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3566 * 'complete' and local ^P expansions respectively.
3567 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3568 * mode -- Acevedo */
3569 if (c == Ctrl_X)
3571 if (compl_cont_mode != 0)
3572 compl_cont_status = 0;
3573 else
3574 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3576 ctrl_x_mode = 0;
3577 edit_submode = NULL;
3578 showmode();
3579 break;
3582 else if (ctrl_x_mode != 0)
3584 /* We're already in CTRL-X mode, do we stay in it? */
3585 if (!vim_is_ctrl_x_key(c))
3587 if (ctrl_x_mode == CTRL_X_SCROLL)
3588 ctrl_x_mode = 0;
3589 else
3590 ctrl_x_mode = CTRL_X_FINISHED;
3591 edit_submode = NULL;
3593 showmode();
3596 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3598 /* Show error message from attempted keyword completion (probably
3599 * 'Pattern not found') until another key is hit, then go back to
3600 * showing what mode we are in. */
3601 showmode();
3602 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3603 && !ins_compl_pum_key(c))
3604 || ctrl_x_mode == CTRL_X_FINISHED)
3606 /* Get here when we have finished typing a sequence of ^N and
3607 * ^P or other completion characters in CTRL-X mode. Free up
3608 * memory that was used, and make sure we can redo the insert. */
3609 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3611 char_u *p;
3612 int temp = 0;
3615 * If any of the original typed text has been changed, eg when
3616 * ignorecase is set, we must add back-spaces to the redo
3617 * buffer. We add as few as necessary to delete just the part
3618 * of the original text that has changed.
3619 * When using the longest match, edited the match or used
3620 * CTRL-E then don't use the current match.
3622 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3623 ptr = compl_curr_match->cp_str;
3624 else if (compl_leader != NULL)
3625 ptr = compl_leader;
3626 else
3627 ptr = compl_orig_text;
3628 if (compl_orig_text != NULL)
3630 p = compl_orig_text;
3631 for (temp = 0; p[temp] != NUL && p[temp] == ptr[temp];
3632 ++temp)
3634 #ifdef FEAT_MBYTE
3635 if (temp > 0)
3636 temp -= (*mb_head_off)(compl_orig_text, p + temp);
3637 #endif
3638 for (p += temp; *p != NUL; mb_ptr_adv(p))
3639 AppendCharToRedobuff(K_BS);
3641 if (ptr != NULL)
3642 AppendToRedobuffLit(ptr + temp, -1);
3645 #ifdef FEAT_CINDENT
3646 want_cindent = (can_cindent && cindent_on());
3647 #endif
3649 * When completing whole lines: fix indent for 'cindent'.
3650 * Otherwise, break line if it's too long.
3652 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3654 #ifdef FEAT_CINDENT
3655 /* re-indent the current line */
3656 if (want_cindent)
3658 do_c_expr_indent();
3659 want_cindent = FALSE; /* don't do it again */
3661 #endif
3663 else
3665 int prev_col = curwin->w_cursor.col;
3667 /* put the cursor on the last char, for 'tw' formatting */
3668 if (prev_col > 0)
3669 dec_cursor();
3670 if (stop_arrow() == OK)
3671 insertchar(NUL, 0, -1);
3672 if (prev_col > 0
3673 && ml_get_curline()[curwin->w_cursor.col] != NUL)
3674 inc_cursor();
3677 /* If the popup menu is displayed pressing CTRL-Y means accepting
3678 * the selection without inserting anything. When
3679 * compl_enter_selects is set the Enter key does the same. */
3680 if ((c == Ctrl_Y || (compl_enter_selects
3681 && (c == CAR || c == K_KENTER || c == NL)))
3682 && pum_visible())
3683 retval = TRUE;
3685 /* CTRL-E means completion is Ended, go back to the typed text. */
3686 if (c == Ctrl_E)
3688 ins_compl_delete();
3689 if (compl_leader != NULL)
3690 ins_bytes(compl_leader + ins_compl_len());
3691 else if (compl_first_match != NULL)
3692 ins_bytes(compl_orig_text + ins_compl_len());
3693 retval = TRUE;
3696 auto_format(FALSE, TRUE);
3698 ins_compl_free();
3699 compl_started = FALSE;
3700 compl_matches = 0;
3701 msg_clr_cmdline(); /* necessary for "noshowmode" */
3702 ctrl_x_mode = 0;
3703 compl_enter_selects = FALSE;
3704 if (edit_submode != NULL)
3706 edit_submode = NULL;
3707 showmode();
3710 #ifdef FEAT_CINDENT
3712 * Indent now if a key was typed that is in 'cinkeys'.
3714 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3715 do_c_expr_indent();
3716 #endif
3720 /* reset continue_* if we left expansion-mode, if we stay they'll be
3721 * (re)set properly in ins_complete() */
3722 if (!vim_is_ctrl_x_key(c))
3724 compl_cont_status = 0;
3725 compl_cont_mode = 0;
3728 return retval;
3732 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3733 * (depending on flag) starting from buf and looking for a non-scanned
3734 * buffer (other than curbuf). curbuf is special, if it is called with
3735 * buf=curbuf then it has to be the first call for a given flag/expansion.
3737 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3739 static buf_T *
3740 ins_compl_next_buf(buf, flag)
3741 buf_T *buf;
3742 int flag;
3744 #ifdef FEAT_WINDOWS
3745 static win_T *wp;
3746 #endif
3748 if (flag == 'w') /* just windows */
3750 #ifdef FEAT_WINDOWS
3751 if (buf == curbuf) /* first call for this flag/expansion */
3752 wp = curwin;
3753 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3754 && wp->w_buffer->b_scanned)
3756 buf = wp->w_buffer;
3757 #else
3758 buf = curbuf;
3759 #endif
3761 else
3762 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3763 * (unlisted buffers)
3764 * When completing whole lines skip unloaded buffers. */
3765 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3766 && ((flag == 'U'
3767 ? buf->b_p_bl
3768 : (!buf->b_p_bl
3769 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3770 || buf->b_scanned))
3772 return buf;
3775 #ifdef FEAT_COMPL_FUNC
3776 static void expand_by_function __ARGS((int type, char_u *base));
3779 * Execute user defined complete function 'completefunc' or 'omnifunc', and
3780 * get matches in "matches".
3782 static void
3783 expand_by_function(type, base)
3784 int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3785 char_u *base;
3787 list_T *matchlist;
3788 char_u *args[2];
3789 char_u *funcname;
3790 pos_T pos;
3792 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3793 if (*funcname == NUL)
3794 return;
3796 /* Call 'completefunc' to obtain the list of matches. */
3797 args[0] = (char_u *)"0";
3798 args[1] = base;
3800 pos = curwin->w_cursor;
3801 matchlist = call_func_retlist(funcname, 2, args, FALSE);
3802 curwin->w_cursor = pos; /* restore the cursor position */
3803 if (matchlist == NULL)
3804 return;
3806 ins_compl_add_list(matchlist);
3807 list_unref(matchlist);
3809 #endif /* FEAT_COMPL_FUNC */
3811 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
3813 * Add completions from a list.
3815 static void
3816 ins_compl_add_list(list)
3817 list_T *list;
3819 listitem_T *li;
3820 int dir = compl_direction;
3822 /* Go through the List with matches and add each of them. */
3823 for (li = list->lv_first; li != NULL; li = li->li_next)
3825 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
3826 /* if dir was BACKWARD then honor it just once */
3827 dir = FORWARD;
3828 else if (did_emsg)
3829 break;
3834 * Add a match to the list of matches from a typeval_T.
3835 * If the given string is already in the list of completions, then return
3836 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3837 * maybe because alloc() returns NULL, then FAIL is returned.
3840 ins_compl_add_tv(tv, dir)
3841 typval_T *tv;
3842 int dir;
3844 char_u *word;
3845 int icase = FALSE;
3846 int adup = FALSE;
3847 char_u *(cptext[CPT_COUNT]);
3849 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3851 word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
3852 cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
3853 (char_u *)"abbr", FALSE);
3854 cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
3855 (char_u *)"menu", FALSE);
3856 cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
3857 (char_u *)"kind", FALSE);
3858 cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
3859 (char_u *)"info", FALSE);
3860 if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
3861 icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
3862 if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
3863 adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
3865 else
3867 word = get_tv_string_chk(tv);
3868 vim_memset(cptext, 0, sizeof(cptext));
3870 if (word == NULL || *word == NUL)
3871 return FAIL;
3872 return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup);
3874 #endif
3877 * Get the next expansion(s), using "compl_pattern".
3878 * The search starts at position "ini" in curbuf and in the direction
3879 * compl_direction.
3880 * When "compl_started" is FALSE start at that position, otherwise continue
3881 * where we stopped searching before.
3882 * This may return before finding all the matches.
3883 * Return the total number of matches or -1 if still unknown -- Acevedo
3885 static int
3886 ins_compl_get_exp(ini)
3887 pos_T *ini;
3889 static pos_T first_match_pos;
3890 static pos_T last_match_pos;
3891 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
3892 static int found_all = FALSE; /* Found all matches of a
3893 certain type. */
3894 static buf_T *ins_buf = NULL; /* buffer being scanned */
3896 pos_T *pos;
3897 char_u **matches;
3898 int save_p_scs;
3899 int save_p_ws;
3900 int save_p_ic;
3901 int i;
3902 int num_matches;
3903 int len;
3904 int found_new_match;
3905 int type = ctrl_x_mode;
3906 char_u *ptr;
3907 char_u *dict = NULL;
3908 int dict_f = 0;
3909 compl_T *old_match;
3911 if (!compl_started)
3913 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
3914 ins_buf->b_scanned = 0;
3915 found_all = FALSE;
3916 ins_buf = curbuf;
3917 e_cpt = (compl_cont_status & CONT_LOCAL)
3918 ? (char_u *)"." : curbuf->b_p_cpt;
3919 last_match_pos = first_match_pos = *ini;
3922 old_match = compl_curr_match; /* remember the last current match */
3923 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3924 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
3925 for (;;)
3927 found_new_match = FAIL;
3929 /* For ^N/^P pick a new entry from e_cpt if compl_started is off,
3930 * or if found_all says this entry is done. For ^X^L only use the
3931 * entries from 'complete' that look in loaded buffers. */
3932 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3933 && (!compl_started || found_all))
3935 found_all = FALSE;
3936 while (*e_cpt == ',' || *e_cpt == ' ')
3937 e_cpt++;
3938 if (*e_cpt == '.' && !curbuf->b_scanned)
3940 ins_buf = curbuf;
3941 first_match_pos = *ini;
3942 /* So that ^N can match word immediately after cursor */
3943 if (ctrl_x_mode == 0)
3944 dec(&first_match_pos);
3945 last_match_pos = first_match_pos;
3946 type = 0;
3948 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3949 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
3951 /* Scan a buffer, but not the current one. */
3952 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
3954 compl_started = TRUE;
3955 first_match_pos.col = last_match_pos.col = 0;
3956 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
3957 last_match_pos.lnum = 0;
3958 type = 0;
3960 else /* unloaded buffer, scan like dictionary */
3962 found_all = TRUE;
3963 if (ins_buf->b_fname == NULL)
3964 continue;
3965 type = CTRL_X_DICTIONARY;
3966 dict = ins_buf->b_fname;
3967 dict_f = DICT_EXACT;
3969 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3970 ins_buf->b_fname == NULL
3971 ? buf_spname(ins_buf)
3972 : ins_buf->b_sfname == NULL
3973 ? (char *)ins_buf->b_fname
3974 : (char *)ins_buf->b_sfname);
3975 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3977 else if (*e_cpt == NUL)
3978 break;
3979 else
3981 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3982 type = -1;
3983 else if (*e_cpt == 'k' || *e_cpt == 's')
3985 if (*e_cpt == 'k')
3986 type = CTRL_X_DICTIONARY;
3987 else
3988 type = CTRL_X_THESAURUS;
3989 if (*++e_cpt != ',' && *e_cpt != NUL)
3991 dict = e_cpt;
3992 dict_f = DICT_FIRST;
3995 #ifdef FEAT_FIND_ID
3996 else if (*e_cpt == 'i')
3997 type = CTRL_X_PATH_PATTERNS;
3998 else if (*e_cpt == 'd')
3999 type = CTRL_X_PATH_DEFINES;
4000 #endif
4001 else if (*e_cpt == ']' || *e_cpt == 't')
4003 type = CTRL_X_TAGS;
4004 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4005 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
4007 else
4008 type = -1;
4010 /* in any case e_cpt is advanced to the next entry */
4011 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
4013 found_all = TRUE;
4014 if (type == -1)
4015 continue;
4019 switch (type)
4021 case -1:
4022 break;
4023 #ifdef FEAT_FIND_ID
4024 case CTRL_X_PATH_PATTERNS:
4025 case CTRL_X_PATH_DEFINES:
4026 find_pattern_in_path(compl_pattern, compl_direction,
4027 (int)STRLEN(compl_pattern), FALSE, FALSE,
4028 (type == CTRL_X_PATH_DEFINES
4029 && !(compl_cont_status & CONT_SOL))
4030 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
4031 (linenr_T)1, (linenr_T)MAXLNUM);
4032 break;
4033 #endif
4035 case CTRL_X_DICTIONARY:
4036 case CTRL_X_THESAURUS:
4037 ins_compl_dictionaries(
4038 dict != NULL ? dict
4039 : (type == CTRL_X_THESAURUS
4040 ? (*curbuf->b_p_tsr == NUL
4041 ? p_tsr
4042 : curbuf->b_p_tsr)
4043 : (*curbuf->b_p_dict == NUL
4044 ? p_dict
4045 : curbuf->b_p_dict)),
4046 compl_pattern,
4047 dict != NULL ? dict_f
4048 : 0, type == CTRL_X_THESAURUS);
4049 dict = NULL;
4050 break;
4052 case CTRL_X_TAGS:
4053 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
4054 save_p_ic = p_ic;
4055 p_ic = ignorecase(compl_pattern);
4057 /* Find up to TAG_MANY matches. Avoids that an enormous number
4058 * of matches is found when compl_pattern is empty */
4059 g_tag_at_cursor = 1;
4060 if (find_tags(compl_pattern, &num_matches, &matches,
4061 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
4062 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
4063 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4065 ins_compl_add_matches(num_matches, matches, p_ic);
4067 g_tag_at_cursor = 0;
4068 p_ic = save_p_ic;
4069 break;
4071 case CTRL_X_FILES:
4072 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
4073 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
4076 /* May change home directory back to "~". */
4077 tilde_replace(compl_pattern, num_matches, matches);
4078 ins_compl_add_matches(num_matches, matches,
4079 #ifdef CASE_INSENSITIVE_FILENAME
4080 TRUE
4081 #else
4082 FALSE
4083 #endif
4086 break;
4088 case CTRL_X_CMDLINE:
4089 if (expand_cmdline(&compl_xp, compl_pattern,
4090 (int)STRLEN(compl_pattern),
4091 &num_matches, &matches) == EXPAND_OK)
4092 ins_compl_add_matches(num_matches, matches, FALSE);
4093 break;
4095 #ifdef FEAT_COMPL_FUNC
4096 case CTRL_X_FUNCTION:
4097 case CTRL_X_OMNI:
4098 expand_by_function(type, compl_pattern);
4099 break;
4100 #endif
4102 case CTRL_X_SPELL:
4103 #ifdef FEAT_SPELL
4104 num_matches = expand_spelling(first_match_pos.lnum,
4105 compl_pattern, &matches);
4106 if (num_matches > 0)
4107 ins_compl_add_matches(num_matches, matches, p_ic);
4108 #endif
4109 break;
4111 default: /* normal ^P/^N and ^X^L */
4113 * If 'infercase' is set, don't use 'smartcase' here
4115 save_p_scs = p_scs;
4116 if (ins_buf->b_p_inf)
4117 p_scs = FALSE;
4119 /* buffers other than curbuf are scanned from the beginning or the
4120 * end but never from the middle, thus setting nowrapscan in this
4121 * buffers is a good idea, on the other hand, we always set
4122 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
4123 save_p_ws = p_ws;
4124 if (ins_buf != curbuf)
4125 p_ws = FALSE;
4126 else if (*e_cpt == '.')
4127 p_ws = TRUE;
4128 for (;;)
4130 int flags = 0;
4132 ++msg_silent; /* Don't want messages for wrapscan. */
4134 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
4135 * has added a word that was at the beginning of the line */
4136 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
4137 || (compl_cont_status & CONT_SOL))
4138 found_new_match = search_for_exact_line(ins_buf, pos,
4139 compl_direction, compl_pattern);
4140 else
4141 found_new_match = searchit(NULL, ins_buf, pos,
4142 compl_direction,
4143 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
4144 RE_LAST, (linenr_T)0, NULL);
4145 --msg_silent;
4146 if (!compl_started)
4148 /* set "compl_started" even on fail */
4149 compl_started = TRUE;
4150 first_match_pos = *pos;
4151 last_match_pos = *pos;
4153 else if (first_match_pos.lnum == last_match_pos.lnum
4154 && first_match_pos.col == last_match_pos.col)
4155 found_new_match = FAIL;
4156 if (found_new_match == FAIL)
4158 if (ins_buf == curbuf)
4159 found_all = TRUE;
4160 break;
4163 /* when ADDING, the text before the cursor matches, skip it */
4164 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
4165 && ini->lnum == pos->lnum
4166 && ini->col == pos->col)
4167 continue;
4168 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
4169 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4171 if (compl_cont_status & CONT_ADDING)
4173 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
4174 continue;
4175 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4176 if (!p_paste)
4177 ptr = skipwhite(ptr);
4179 len = (int)STRLEN(ptr);
4181 else
4183 char_u *tmp_ptr = ptr;
4185 if (compl_cont_status & CONT_ADDING)
4187 tmp_ptr += compl_length;
4188 /* Skip if already inside a word. */
4189 if (vim_iswordp(tmp_ptr))
4190 continue;
4191 /* Find start of next word. */
4192 tmp_ptr = find_word_start(tmp_ptr);
4194 /* Find end of this word. */
4195 tmp_ptr = find_word_end(tmp_ptr);
4196 len = (int)(tmp_ptr - ptr);
4198 if ((compl_cont_status & CONT_ADDING)
4199 && len == compl_length)
4201 if (pos->lnum < ins_buf->b_ml.ml_line_count)
4203 /* Try next line, if any. the new word will be
4204 * "join" as if the normal command "J" was used.
4205 * IOSIZE is always greater than
4206 * compl_length, so the next STRNCPY always
4207 * works -- Acevedo */
4208 STRNCPY(IObuff, ptr, len);
4209 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4210 tmp_ptr = ptr = skipwhite(ptr);
4211 /* Find start of next word. */
4212 tmp_ptr = find_word_start(tmp_ptr);
4213 /* Find end of next word. */
4214 tmp_ptr = find_word_end(tmp_ptr);
4215 if (tmp_ptr > ptr)
4217 if (*ptr != ')' && IObuff[len - 1] != TAB)
4219 if (IObuff[len - 1] != ' ')
4220 IObuff[len++] = ' ';
4221 /* IObuf =~ "\k.* ", thus len >= 2 */
4222 if (p_js
4223 && (IObuff[len - 2] == '.'
4224 || (vim_strchr(p_cpo, CPO_JOINSP)
4225 == NULL
4226 && (IObuff[len - 2] == '?'
4227 || IObuff[len - 2] == '!'))))
4228 IObuff[len++] = ' ';
4230 /* copy as much as possible of the new word */
4231 if (tmp_ptr - ptr >= IOSIZE - len)
4232 tmp_ptr = ptr + IOSIZE - len - 1;
4233 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4234 len += (int)(tmp_ptr - ptr);
4235 flags |= CONT_S_IPOS;
4237 IObuff[len] = NUL;
4238 ptr = IObuff;
4240 if (len == compl_length)
4241 continue;
4244 if (ins_compl_add_infercase(ptr, len, p_ic,
4245 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
4246 0, flags) != NOTDONE)
4248 found_new_match = OK;
4249 break;
4252 p_scs = save_p_scs;
4253 p_ws = save_p_ws;
4256 /* check if compl_curr_match has changed, (e.g. other type of
4257 * expansion added something) */
4258 if (type != 0 && compl_curr_match != old_match)
4259 found_new_match = OK;
4261 /* break the loop for specialized modes (use 'complete' just for the
4262 * generic ctrl_x_mode == 0) or when we've found a new match */
4263 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4264 || found_new_match != FAIL)
4266 if (got_int)
4267 break;
4268 /* Fill the popup menu as soon as possible. */
4269 if (type != -1)
4270 ins_compl_check_keys(0);
4272 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4273 || compl_interrupted)
4274 break;
4275 compl_started = TRUE;
4277 else
4279 /* Mark a buffer scanned when it has been scanned completely */
4280 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
4281 ins_buf->b_scanned = TRUE;
4283 compl_started = FALSE;
4286 compl_started = TRUE;
4288 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4289 && *e_cpt == NUL) /* Got to end of 'complete' */
4290 found_new_match = FAIL;
4292 i = -1; /* total of matches, unknown */
4293 if (found_new_match == FAIL
4294 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
4295 i = ins_compl_make_cyclic();
4297 /* If several matches were added (FORWARD) or the search failed and has
4298 * just been made cyclic then we have to move compl_curr_match to the next
4299 * or previous entry (if any) -- Acevedo */
4300 compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
4301 : old_match->cp_prev;
4302 if (compl_curr_match == NULL)
4303 compl_curr_match = old_match;
4304 return i;
4307 /* Delete the old text being completed. */
4308 static void
4309 ins_compl_delete()
4311 int i;
4314 * In insert mode: Delete the typed part.
4315 * In replace mode: Put the old characters back, if any.
4317 i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
4318 backspace_until_column(i);
4319 changed_cline_bef_curs();
4322 /* Insert the new text being completed. */
4323 static void
4324 ins_compl_insert()
4326 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
4327 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4328 compl_used_match = FALSE;
4329 else
4330 compl_used_match = TRUE;
4334 * Fill in the next completion in the current direction.
4335 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4336 * get more completions. If it is FALSE, then we just do nothing when there
4337 * are no more completions in a given direction. The latter case is used when
4338 * we are still in the middle of finding completions, to allow browsing
4339 * through the ones found so far.
4340 * Return the total number of matches, or -1 if still unknown -- webb.
4342 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4343 * compl_shown_match here.
4345 * Note that this function may be called recursively once only. First with
4346 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4347 * calls this function with "allow_get_expansion" FALSE.
4349 static int
4350 ins_compl_next(allow_get_expansion, count, insert_match)
4351 int allow_get_expansion;
4352 int count; /* repeat completion this many times; should
4353 be at least 1 */
4354 int insert_match; /* Insert the newly selected match */
4356 int num_matches = -1;
4357 int i;
4358 int todo = count;
4359 compl_T *found_compl = NULL;
4360 int found_end = FALSE;
4361 int advance;
4363 if (compl_leader != NULL
4364 && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4366 /* Set "compl_shown_match" to the actually shown match, it may differ
4367 * when "compl_leader" is used to omit some of the matches. */
4368 while (!ins_compl_equal(compl_shown_match,
4369 compl_leader, (int)STRLEN(compl_leader))
4370 && compl_shown_match->cp_next != NULL
4371 && compl_shown_match->cp_next != compl_first_match)
4372 compl_shown_match = compl_shown_match->cp_next;
4374 /* If we didn't find it searching forward, and compl_shows_dir is
4375 * backward, find the last match. */
4376 if (compl_shows_dir == BACKWARD
4377 && !ins_compl_equal(compl_shown_match,
4378 compl_leader, (int)STRLEN(compl_leader))
4379 && (compl_shown_match->cp_next == NULL
4380 || compl_shown_match->cp_next == compl_first_match))
4382 while (!ins_compl_equal(compl_shown_match,
4383 compl_leader, (int)STRLEN(compl_leader))
4384 && compl_shown_match->cp_prev != NULL
4385 && compl_shown_match->cp_prev != compl_first_match)
4386 compl_shown_match = compl_shown_match->cp_prev;
4390 if (allow_get_expansion && insert_match
4391 && (!(compl_get_longest || compl_restarting) || compl_used_match))
4392 /* Delete old text to be replaced */
4393 ins_compl_delete();
4395 /* When finding the longest common text we stick at the original text,
4396 * don't let CTRL-N or CTRL-P move to the first match. */
4397 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4399 /* When restarting the search don't insert the first match either. */
4400 if (compl_restarting)
4402 advance = FALSE;
4403 compl_restarting = FALSE;
4406 /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4407 * around. */
4408 while (--todo >= 0)
4410 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4412 compl_shown_match = compl_shown_match->cp_next;
4413 found_end = (compl_first_match != NULL
4414 && (compl_shown_match->cp_next == compl_first_match
4415 || compl_shown_match == compl_first_match));
4417 else if (compl_shows_dir == BACKWARD
4418 && compl_shown_match->cp_prev != NULL)
4420 found_end = (compl_shown_match == compl_first_match);
4421 compl_shown_match = compl_shown_match->cp_prev;
4422 found_end |= (compl_shown_match == compl_first_match);
4424 else
4426 if (!allow_get_expansion)
4428 if (advance)
4430 if (compl_shows_dir == BACKWARD)
4431 compl_pending -= todo + 1;
4432 else
4433 compl_pending += todo + 1;
4435 return -1;
4438 if (advance)
4440 if (compl_shows_dir == BACKWARD)
4441 --compl_pending;
4442 else
4443 ++compl_pending;
4446 /* Find matches. */
4447 num_matches = ins_compl_get_exp(&compl_startpos);
4449 /* handle any pending completions */
4450 while (compl_pending != 0 && compl_direction == compl_shows_dir
4451 && advance)
4453 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4455 compl_shown_match = compl_shown_match->cp_next;
4456 --compl_pending;
4458 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4460 compl_shown_match = compl_shown_match->cp_prev;
4461 ++compl_pending;
4463 else
4464 break;
4466 found_end = FALSE;
4468 if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4469 && compl_leader != NULL
4470 && !ins_compl_equal(compl_shown_match,
4471 compl_leader, (int)STRLEN(compl_leader)))
4472 ++todo;
4473 else
4474 /* Remember a matching item. */
4475 found_compl = compl_shown_match;
4477 /* Stop at the end of the list when we found a usable match. */
4478 if (found_end)
4480 if (found_compl != NULL)
4482 compl_shown_match = found_compl;
4483 break;
4485 todo = 1; /* use first usable match after wrapping around */
4489 /* Insert the text of the new completion, or the compl_leader. */
4490 if (insert_match)
4492 if (!compl_get_longest || compl_used_match)
4493 ins_compl_insert();
4494 else
4495 ins_bytes(compl_leader + ins_compl_len());
4497 else
4498 compl_used_match = FALSE;
4500 if (!allow_get_expansion)
4502 /* may undisplay the popup menu first */
4503 ins_compl_upd_pum();
4505 /* redraw to show the user what was inserted */
4506 update_screen(0);
4508 /* display the updated popup menu */
4509 ins_compl_show_pum();
4510 #ifdef FEAT_GUI
4511 if (gui.in_use)
4513 /* Show the cursor after the match, not after the redrawn text. */
4514 setcursor();
4515 out_flush();
4516 gui_update_cursor(FALSE, FALSE);
4518 #endif
4520 /* Delete old text to be replaced, since we're still searching and
4521 * don't want to match ourselves! */
4522 ins_compl_delete();
4525 /* Enter will select a match when the match wasn't inserted and the popup
4526 * menu is visible. */
4527 compl_enter_selects = !insert_match && compl_match_array != NULL;
4530 * Show the file name for the match (if any)
4531 * Truncate the file name to avoid a wait for return.
4533 if (compl_shown_match->cp_fname != NULL)
4535 STRCPY(IObuff, "match in file ");
4536 i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4537 if (i <= 0)
4538 i = 0;
4539 else
4540 STRCAT(IObuff, "<");
4541 STRCAT(IObuff, compl_shown_match->cp_fname + i);
4542 msg(IObuff);
4543 redraw_cmdline = FALSE; /* don't overwrite! */
4546 return num_matches;
4550 * Call this while finding completions, to check whether the user has hit a key
4551 * that should change the currently displayed completion, or exit completion
4552 * mode. Also, when compl_pending is not zero, show a completion as soon as
4553 * possible. -- webb
4554 * "frequency" specifies out of how many calls we actually check.
4556 void
4557 ins_compl_check_keys(frequency)
4558 int frequency;
4560 static int count = 0;
4562 int c;
4564 /* Don't check when reading keys from a script. That would break the test
4565 * scripts */
4566 if (using_script())
4567 return;
4569 /* Only do this at regular intervals */
4570 if (++count < frequency)
4571 return;
4572 count = 0;
4574 /* Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4575 * can't do its work correctly. */
4576 c = vpeekc_any();
4577 if (c != NUL)
4579 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4581 c = safe_vgetc(); /* Eat the character */
4582 compl_shows_dir = ins_compl_key2dir(c);
4583 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4584 c != K_UP && c != K_DOWN);
4586 else
4588 /* Need to get the character to have KeyTyped set. We'll put it
4589 * back with vungetc() below. But skip K_IGNORE. */
4590 c = safe_vgetc();
4591 if (c != K_IGNORE)
4593 /* Don't interrupt completion when the character wasn't typed,
4594 * e.g., when doing @q to replay keys. */
4595 if (c != Ctrl_R && KeyTyped)
4596 compl_interrupted = TRUE;
4598 vungetc(c);
4602 if (compl_pending != 0 && !got_int)
4604 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4606 compl_pending = 0;
4607 (void)ins_compl_next(FALSE, todo, TRUE);
4612 * Decide the direction of Insert mode complete from the key typed.
4613 * Returns BACKWARD or FORWARD.
4615 static int
4616 ins_compl_key2dir(c)
4617 int c;
4619 if (c == Ctrl_P || c == Ctrl_L
4620 || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4621 || c == K_S_UP || c == K_UP)))
4622 return BACKWARD;
4623 return FORWARD;
4627 * Return TRUE for keys that are used for completion only when the popup menu
4628 * is visible.
4630 static int
4631 ins_compl_pum_key(c)
4632 int c;
4634 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4635 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4636 || c == K_UP || c == K_DOWN);
4640 * Decide the number of completions to move forward.
4641 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4643 static int
4644 ins_compl_key2count(c)
4645 int c;
4647 int h;
4649 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4651 h = pum_get_height();
4652 if (h > 3)
4653 h -= 2; /* keep some context */
4654 return h;
4656 return 1;
4660 * Return TRUE if completion with "c" should insert the match, FALSE if only
4661 * to change the currently selected completion.
4663 static int
4664 ins_compl_use_match(c)
4665 int c;
4667 switch (c)
4669 case K_UP:
4670 case K_DOWN:
4671 case K_PAGEDOWN:
4672 case K_KPAGEDOWN:
4673 case K_S_DOWN:
4674 case K_PAGEUP:
4675 case K_KPAGEUP:
4676 case K_S_UP:
4677 return FALSE;
4679 return TRUE;
4683 * Do Insert mode completion.
4684 * Called when character "c" was typed, which has a meaning for completion.
4685 * Returns OK if completion was done, FAIL if something failed (out of mem).
4687 static int
4688 ins_complete(c)
4689 int c;
4691 char_u *line;
4692 int startcol = 0; /* column where searched text starts */
4693 colnr_T curs_col; /* cursor column */
4694 int n;
4695 int save_w_wrow;
4697 compl_direction = ins_compl_key2dir(c);
4698 if (!compl_started)
4700 /* First time we hit ^N or ^P (in a row, I mean) */
4702 did_ai = FALSE;
4703 #ifdef FEAT_SMARTINDENT
4704 did_si = FALSE;
4705 can_si = FALSE;
4706 can_si_back = FALSE;
4707 #endif
4708 if (stop_arrow() == FAIL)
4709 return FAIL;
4711 line = ml_get(curwin->w_cursor.lnum);
4712 curs_col = curwin->w_cursor.col;
4713 compl_pending = 0;
4715 /* If this same ctrl_x_mode has been interrupted use the text from
4716 * "compl_startpos" to the cursor as a pattern to add a new word
4717 * instead of expand the one before the cursor, in word-wise if
4718 * "compl_startpos" is not in the same line as the cursor then fix it
4719 * (the line has been split because it was longer than 'tw'). if SOL
4720 * is set then skip the previous pattern, a word at the beginning of
4721 * the line has been inserted, we'll look for that -- Acevedo. */
4722 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4723 && compl_cont_mode == ctrl_x_mode)
4726 * it is a continued search
4728 compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */
4729 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4730 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4732 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4734 /* line (probably) wrapped, set compl_startpos to the
4735 * first non_blank in the line, if it is not a wordchar
4736 * include it to get a better pattern, but then we don't
4737 * want the "\\<" prefix, check it bellow */
4738 compl_col = (colnr_T)(skipwhite(line) - line);
4739 compl_startpos.col = compl_col;
4740 compl_startpos.lnum = curwin->w_cursor.lnum;
4741 compl_cont_status &= ~CONT_SOL; /* clear SOL if present */
4743 else
4745 /* S_IPOS was set when we inserted a word that was at the
4746 * beginning of the line, which means that we'll go to SOL
4747 * mode but first we need to redefine compl_startpos */
4748 if (compl_cont_status & CONT_S_IPOS)
4750 compl_cont_status |= CONT_SOL;
4751 compl_startpos.col = (colnr_T)(skipwhite(
4752 line + compl_length
4753 + compl_startpos.col) - line);
4755 compl_col = compl_startpos.col;
4757 compl_length = curwin->w_cursor.col - (int)compl_col;
4758 /* IObuff is used to add a "word from the next line" would we
4759 * have enough space? just being paranoid */
4760 #define MIN_SPACE 75
4761 if (compl_length > (IOSIZE - MIN_SPACE))
4763 compl_cont_status &= ~CONT_SOL;
4764 compl_length = (IOSIZE - MIN_SPACE);
4765 compl_col = curwin->w_cursor.col - compl_length;
4767 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4768 if (compl_length < 1)
4769 compl_cont_status &= CONT_LOCAL;
4771 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4772 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4773 else
4774 compl_cont_status = 0;
4776 else
4777 compl_cont_status &= CONT_LOCAL;
4779 if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */
4781 compl_cont_mode = ctrl_x_mode;
4782 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
4783 compl_cont_status = 0;
4784 compl_cont_status |= CONT_N_ADDS;
4785 compl_startpos = curwin->w_cursor;
4786 startcol = (int)curs_col;
4787 compl_col = 0;
4790 /* Work out completion pattern and original text -- webb */
4791 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
4793 if ((compl_cont_status & CONT_SOL)
4794 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4796 if (!(compl_cont_status & CONT_ADDING))
4798 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4800 compl_col += ++startcol;
4801 compl_length = curs_col - startcol;
4803 if (p_ic)
4804 compl_pattern = str_foldcase(line + compl_col,
4805 compl_length, NULL, 0);
4806 else
4807 compl_pattern = vim_strnsave(line + compl_col,
4808 compl_length);
4809 if (compl_pattern == NULL)
4810 return FAIL;
4812 else if (compl_cont_status & CONT_ADDING)
4814 char_u *prefix = (char_u *)"\\<";
4816 /* we need up to 2 extra chars for the prefix */
4817 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4818 compl_length) + 2);
4819 if (compl_pattern == NULL)
4820 return FAIL;
4821 if (!vim_iswordp(line + compl_col)
4822 || (compl_col > 0
4823 && (
4824 #ifdef FEAT_MBYTE
4825 vim_iswordp(mb_prevptr(line, line + compl_col))
4826 #else
4827 vim_iswordc(line[compl_col - 1])
4828 #endif
4830 prefix = (char_u *)"";
4831 STRCPY((char *)compl_pattern, prefix);
4832 (void)quote_meta(compl_pattern + STRLEN(prefix),
4833 line + compl_col, compl_length);
4835 else if (--startcol < 0 ||
4836 #ifdef FEAT_MBYTE
4837 !vim_iswordp(mb_prevptr(line, line + startcol + 1))
4838 #else
4839 !vim_iswordc(line[startcol])
4840 #endif
4843 /* Match any word of at least two chars */
4844 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4845 if (compl_pattern == NULL)
4846 return FAIL;
4847 compl_col += curs_col;
4848 compl_length = 0;
4850 else
4852 #ifdef FEAT_MBYTE
4853 /* Search the point of change class of multibyte character
4854 * or not a word single byte character backward. */
4855 if (has_mbyte)
4857 int base_class;
4858 int head_off;
4860 startcol -= (*mb_head_off)(line, line + startcol);
4861 base_class = mb_get_class(line + startcol);
4862 while (--startcol >= 0)
4864 head_off = (*mb_head_off)(line, line + startcol);
4865 if (base_class != mb_get_class(line + startcol
4866 - head_off))
4867 break;
4868 startcol -= head_off;
4871 else
4872 #endif
4873 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4875 compl_col += ++startcol;
4876 compl_length = (int)curs_col - startcol;
4877 if (compl_length == 1)
4879 /* Only match word with at least two chars -- webb
4880 * there's no need to call quote_meta,
4881 * alloc(7) is enough -- Acevedo
4883 compl_pattern = alloc(7);
4884 if (compl_pattern == NULL)
4885 return FAIL;
4886 STRCPY((char *)compl_pattern, "\\<");
4887 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4888 STRCAT((char *)compl_pattern, "\\k");
4890 else
4892 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4893 compl_length) + 2);
4894 if (compl_pattern == NULL)
4895 return FAIL;
4896 STRCPY((char *)compl_pattern, "\\<");
4897 (void)quote_meta(compl_pattern + 2, line + compl_col,
4898 compl_length);
4902 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4904 compl_col = (colnr_T)(skipwhite(line) - line);
4905 compl_length = (int)curs_col - (int)compl_col;
4906 if (compl_length < 0) /* cursor in indent: empty pattern */
4907 compl_length = 0;
4908 if (p_ic)
4909 compl_pattern = str_foldcase(line + compl_col, compl_length,
4910 NULL, 0);
4911 else
4912 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4913 if (compl_pattern == NULL)
4914 return FAIL;
4916 else if (ctrl_x_mode == CTRL_X_FILES)
4918 while (--startcol >= 0 && vim_isfilec(line[startcol]))
4920 compl_col += ++startcol;
4921 compl_length = (int)curs_col - startcol;
4922 compl_pattern = addstar(line + compl_col, compl_length,
4923 EXPAND_FILES);
4924 if (compl_pattern == NULL)
4925 return FAIL;
4927 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4929 compl_pattern = vim_strnsave(line, curs_col);
4930 if (compl_pattern == NULL)
4931 return FAIL;
4932 set_cmd_context(&compl_xp, compl_pattern,
4933 (int)STRLEN(compl_pattern), curs_col);
4934 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4935 || compl_xp.xp_context == EXPAND_NOTHING)
4936 /* No completion possible, use an empty pattern to get a
4937 * "pattern not found" message. */
4938 compl_col = curs_col;
4939 else
4940 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4941 compl_length = curs_col - compl_col;
4943 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
4945 #ifdef FEAT_COMPL_FUNC
4947 * Call user defined function 'completefunc' with "a:findstart"
4948 * set to 1 to obtain the length of text to use for completion.
4950 char_u *args[2];
4951 int col;
4952 char_u *funcname;
4953 pos_T pos;
4955 /* Call 'completefunc' or 'omnifunc' and get pattern length as a
4956 * string */
4957 funcname = ctrl_x_mode == CTRL_X_FUNCTION
4958 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
4959 if (*funcname == NUL)
4961 EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4962 ? "completefunc" : "omnifunc");
4963 return FAIL;
4966 args[0] = (char_u *)"1";
4967 args[1] = NULL;
4968 pos = curwin->w_cursor;
4969 col = call_func_retnr(funcname, 2, args, FALSE);
4970 curwin->w_cursor = pos; /* restore the cursor position */
4972 if (col < 0)
4973 col = curs_col;
4974 compl_col = col;
4975 if (compl_col > curs_col)
4976 compl_col = curs_col;
4978 /* Setup variables for completion. Need to obtain "line" again,
4979 * it may have become invalid. */
4980 line = ml_get(curwin->w_cursor.lnum);
4981 compl_length = curs_col - compl_col;
4982 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4983 if (compl_pattern == NULL)
4984 #endif
4985 return FAIL;
4987 else if (ctrl_x_mode == CTRL_X_SPELL)
4989 #ifdef FEAT_SPELL
4990 if (spell_bad_len > 0)
4991 compl_col = curs_col - spell_bad_len;
4992 else
4993 compl_col = spell_word_start(startcol);
4994 if (compl_col >= (colnr_T)startcol)
4996 compl_length = 0;
4997 compl_col = curs_col;
4999 else
5001 spell_expand_check_cap(compl_col);
5002 compl_length = (int)curs_col - compl_col;
5004 /* Need to obtain "line" again, it may have become invalid. */
5005 line = ml_get(curwin->w_cursor.lnum);
5006 compl_pattern = vim_strnsave(line + compl_col, compl_length);
5007 if (compl_pattern == NULL)
5008 #endif
5009 return FAIL;
5011 else
5013 EMSG2(_(e_intern2), "ins_complete()");
5014 return FAIL;
5017 if (compl_cont_status & CONT_ADDING)
5019 edit_submode_pre = (char_u *)_(" Adding");
5020 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
5022 /* Insert a new line, keep indentation but ignore 'comments' */
5023 #ifdef FEAT_COMMENTS
5024 char_u *old = curbuf->b_p_com;
5026 curbuf->b_p_com = (char_u *)"";
5027 #endif
5028 compl_startpos.lnum = curwin->w_cursor.lnum;
5029 compl_startpos.col = compl_col;
5030 ins_eol('\r');
5031 #ifdef FEAT_COMMENTS
5032 curbuf->b_p_com = old;
5033 #endif
5034 compl_length = 0;
5035 compl_col = curwin->w_cursor.col;
5038 else
5040 edit_submode_pre = NULL;
5041 compl_startpos.col = compl_col;
5044 if (compl_cont_status & CONT_LOCAL)
5045 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5046 else
5047 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5049 /* Always add completion for the original text. */
5050 vim_free(compl_orig_text);
5051 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5052 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5053 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
5055 vim_free(compl_pattern);
5056 compl_pattern = NULL;
5057 vim_free(compl_orig_text);
5058 compl_orig_text = NULL;
5059 return FAIL;
5062 /* showmode might reset the internal line pointers, so it must
5063 * be called before line = ml_get(), or when this address is no
5064 * longer needed. -- Acevedo.
5066 edit_submode_extra = (char_u *)_("-- Searching...");
5067 edit_submode_highl = HLF_COUNT;
5068 showmode();
5069 edit_submode_extra = NULL;
5070 out_flush();
5073 compl_shown_match = compl_curr_match;
5074 compl_shows_dir = compl_direction;
5077 * Find next match (and following matches).
5079 save_w_wrow = curwin->w_wrow;
5080 n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
5082 /* may undisplay the popup menu */
5083 ins_compl_upd_pum();
5085 if (n > 1) /* all matches have been found */
5086 compl_matches = n;
5087 compl_curr_match = compl_shown_match;
5088 compl_direction = compl_shows_dir;
5090 /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5091 * mode. */
5092 if (got_int && !global_busy)
5094 (void)vgetc();
5095 got_int = FALSE;
5098 /* we found no match if the list has only the "compl_orig_text"-entry */
5099 if (compl_first_match == compl_first_match->cp_next)
5101 edit_submode_extra = (compl_cont_status & CONT_ADDING)
5102 && compl_length > 1
5103 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
5104 edit_submode_highl = HLF_E;
5105 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5106 * because we couldn't expand anything at first place, but if we used
5107 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5108 * (such as M in M'exico) if not tried already. -- Acevedo */
5109 if ( compl_length > 1
5110 || (compl_cont_status & CONT_ADDING)
5111 || (ctrl_x_mode != 0
5112 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
5113 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
5114 compl_cont_status &= ~CONT_N_ADDS;
5117 if (compl_curr_match->cp_flags & CONT_S_IPOS)
5118 compl_cont_status |= CONT_S_IPOS;
5119 else
5120 compl_cont_status &= ~CONT_S_IPOS;
5122 if (edit_submode_extra == NULL)
5124 if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
5126 edit_submode_extra = (char_u *)_("Back at original");
5127 edit_submode_highl = HLF_W;
5129 else if (compl_cont_status & CONT_S_IPOS)
5131 edit_submode_extra = (char_u *)_("Word from other line");
5132 edit_submode_highl = HLF_COUNT;
5134 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5136 edit_submode_extra = (char_u *)_("The only match");
5137 edit_submode_highl = HLF_COUNT;
5139 else
5141 /* Update completion sequence number when needed. */
5142 if (compl_curr_match->cp_number == -1)
5144 int number = 0;
5145 compl_T *match;
5147 if (compl_direction == FORWARD)
5149 /* search backwards for the first valid (!= -1) number.
5150 * This should normally succeed already at the first loop
5151 * cycle, so it's fast! */
5152 for (match = compl_curr_match->cp_prev; match != NULL
5153 && match != compl_first_match;
5154 match = match->cp_prev)
5155 if (match->cp_number != -1)
5157 number = match->cp_number;
5158 break;
5160 if (match != NULL)
5161 /* go up and assign all numbers which are not assigned
5162 * yet */
5163 for (match = match->cp_next;
5164 match != NULL && match->cp_number == -1;
5165 match = match->cp_next)
5166 match->cp_number = ++number;
5168 else /* BACKWARD */
5170 /* search forwards (upwards) for the first valid (!= -1)
5171 * number. This should normally succeed already at the
5172 * first loop cycle, so it's fast! */
5173 for (match = compl_curr_match->cp_next; match != NULL
5174 && match != compl_first_match;
5175 match = match->cp_next)
5176 if (match->cp_number != -1)
5178 number = match->cp_number;
5179 break;
5181 if (match != NULL)
5182 /* go down and assign all numbers which are not
5183 * assigned yet */
5184 for (match = match->cp_prev; match
5185 && match->cp_number == -1;
5186 match = match->cp_prev)
5187 match->cp_number = ++number;
5191 /* The match should always have a sequence number now, this is
5192 * just a safety check. */
5193 if (compl_curr_match->cp_number != -1)
5195 /* Space for 10 text chars. + 2x10-digit no.s = 31.
5196 * Translations may need more than twice that. */
5197 static char_u match_ref[81];
5199 if (compl_matches > 0)
5200 vim_snprintf((char *)match_ref, sizeof(match_ref),
5201 _("match %d of %d"),
5202 compl_curr_match->cp_number, compl_matches);
5203 else
5204 vim_snprintf((char *)match_ref, sizeof(match_ref),
5205 _("match %d"),
5206 compl_curr_match->cp_number);
5207 edit_submode_extra = match_ref;
5208 edit_submode_highl = HLF_R;
5209 if (dollar_vcol)
5210 curs_columns(FALSE);
5215 /* Show a message about what (completion) mode we're in. */
5216 showmode();
5217 if (edit_submode_extra != NULL)
5219 if (!p_smd)
5220 msg_attr(edit_submode_extra,
5221 edit_submode_highl < HLF_COUNT
5222 ? hl_attr(edit_submode_highl) : 0);
5224 else
5225 msg_clr_cmdline(); /* necessary for "noshowmode" */
5227 /* Show the popup menu, unless we got interrupted. */
5228 if (!compl_interrupted)
5230 /* RedrawingDisabled may be set when invoked through complete(). */
5231 n = RedrawingDisabled;
5232 RedrawingDisabled = 0;
5234 /* If the cursor moved we need to remove the pum first. */
5235 setcursor();
5236 if (save_w_wrow != curwin->w_wrow)
5237 ins_compl_del_pum();
5239 ins_compl_show_pum();
5240 setcursor();
5241 RedrawingDisabled = n;
5243 compl_was_interrupted = compl_interrupted;
5244 compl_interrupted = FALSE;
5246 return OK;
5250 * Looks in the first "len" chars. of "src" for search-metachars.
5251 * If dest is not NULL the chars. are copied there quoting (with
5252 * a backslash) the metachars, and dest would be NUL terminated.
5253 * Returns the length (needed) of dest
5255 static unsigned
5256 quote_meta(dest, src, len)
5257 char_u *dest;
5258 char_u *src;
5259 int len;
5261 unsigned m = (unsigned)len + 1; /* one extra for the NUL */
5263 for ( ; --len >= 0; src++)
5265 switch (*src)
5267 case '.':
5268 case '*':
5269 case '[':
5270 if (ctrl_x_mode == CTRL_X_DICTIONARY
5271 || ctrl_x_mode == CTRL_X_THESAURUS)
5272 break;
5273 case '~':
5274 if (!p_magic) /* quote these only if magic is set */
5275 break;
5276 case '\\':
5277 if (ctrl_x_mode == CTRL_X_DICTIONARY
5278 || ctrl_x_mode == CTRL_X_THESAURUS)
5279 break;
5280 case '^': /* currently it's not needed. */
5281 case '$':
5282 m++;
5283 if (dest != NULL)
5284 *dest++ = '\\';
5285 break;
5287 if (dest != NULL)
5288 *dest++ = *src;
5289 # ifdef FEAT_MBYTE
5290 /* Copy remaining bytes of a multibyte character. */
5291 if (has_mbyte)
5293 int i, mb_len;
5295 mb_len = (*mb_ptr2len)(src) - 1;
5296 if (mb_len > 0 && len >= mb_len)
5297 for (i = 0; i < mb_len; ++i)
5299 --len;
5300 ++src;
5301 if (dest != NULL)
5302 *dest++ = *src;
5305 # endif
5307 if (dest != NULL)
5308 *dest = NUL;
5310 return m;
5312 #endif /* FEAT_INS_EXPAND */
5315 * Next character is interpreted literally.
5316 * A one, two or three digit decimal number is interpreted as its byte value.
5317 * If one or two digits are entered, the next character is given to vungetc().
5318 * For Unicode a character > 255 may be returned.
5321 get_literal()
5323 int cc;
5324 int nc;
5325 int i;
5326 int hex = FALSE;
5327 int octal = FALSE;
5328 #ifdef FEAT_MBYTE
5329 int unicode = 0;
5330 #endif
5332 if (got_int)
5333 return Ctrl_C;
5335 #ifdef FEAT_GUI
5337 * In GUI there is no point inserting the internal code for a special key.
5338 * It is more useful to insert the string "<KEY>" instead. This would
5339 * probably be useful in a text window too, but it would not be
5340 * vi-compatible (maybe there should be an option for it?) -- webb
5342 if (gui.in_use)
5343 ++allow_keys;
5344 #endif
5345 #ifdef USE_ON_FLY_SCROLL
5346 dont_scroll = TRUE; /* disallow scrolling here */
5347 #endif
5348 ++no_mapping; /* don't map the next key hits */
5349 cc = 0;
5350 i = 0;
5351 for (;;)
5353 nc = plain_vgetc();
5354 #ifdef FEAT_CMDL_INFO
5355 if (!(State & CMDLINE)
5356 # ifdef FEAT_MBYTE
5357 && MB_BYTE2LEN_CHECK(nc) == 1
5358 # endif
5360 add_to_showcmd(nc);
5361 #endif
5362 if (nc == 'x' || nc == 'X')
5363 hex = TRUE;
5364 else if (nc == 'o' || nc == 'O')
5365 octal = TRUE;
5366 #ifdef FEAT_MBYTE
5367 else if (nc == 'u' || nc == 'U')
5368 unicode = nc;
5369 #endif
5370 else
5372 if (hex
5373 #ifdef FEAT_MBYTE
5374 || unicode != 0
5375 #endif
5378 if (!vim_isxdigit(nc))
5379 break;
5380 cc = cc * 16 + hex2nr(nc);
5382 else if (octal)
5384 if (nc < '0' || nc > '7')
5385 break;
5386 cc = cc * 8 + nc - '0';
5388 else
5390 if (!VIM_ISDIGIT(nc))
5391 break;
5392 cc = cc * 10 + nc - '0';
5395 ++i;
5398 if (cc > 255
5399 #ifdef FEAT_MBYTE
5400 && unicode == 0
5401 #endif
5403 cc = 255; /* limit range to 0-255 */
5404 nc = 0;
5406 if (hex) /* hex: up to two chars */
5408 if (i >= 2)
5409 break;
5411 #ifdef FEAT_MBYTE
5412 else if (unicode) /* Unicode: up to four or eight chars */
5414 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
5415 break;
5417 #endif
5418 else if (i >= 3) /* decimal or octal: up to three chars */
5419 break;
5421 if (i == 0) /* no number entered */
5423 if (nc == K_ZERO) /* NUL is stored as NL */
5425 cc = '\n';
5426 nc = 0;
5428 else
5430 cc = nc;
5431 nc = 0;
5435 if (cc == 0) /* NUL is stored as NL */
5436 cc = '\n';
5437 #ifdef FEAT_MBYTE
5438 if (enc_dbcs && (cc & 0xff) == 0)
5439 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
5440 second byte will cause trouble! */
5441 #endif
5443 --no_mapping;
5444 #ifdef FEAT_GUI
5445 if (gui.in_use)
5446 --allow_keys;
5447 #endif
5448 if (nc)
5449 vungetc(nc);
5450 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
5451 return cc;
5455 * Insert character, taking care of special keys and mod_mask
5457 static void
5458 insert_special(c, allow_modmask, ctrlv)
5459 int c;
5460 int allow_modmask;
5461 int ctrlv; /* c was typed after CTRL-V */
5463 char_u *p;
5464 int len;
5467 * Special function key, translate into "<Key>". Up to the last '>' is
5468 * inserted with ins_str(), so as not to replace characters in replace
5469 * mode.
5470 * Only use mod_mask for special keys, to avoid things like <S-Space>,
5471 * unless 'allow_modmask' is TRUE.
5473 #ifdef MACOS
5474 /* Command-key never produces a normal key */
5475 if (mod_mask & MOD_MASK_CMD)
5476 allow_modmask = TRUE;
5477 #endif
5478 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5480 p = get_special_key_name(c, mod_mask);
5481 len = (int)STRLEN(p);
5482 c = p[len - 1];
5483 if (len > 2)
5485 if (stop_arrow() == FAIL)
5486 return;
5487 p[len - 1] = NUL;
5488 ins_str(p);
5489 AppendToRedobuffLit(p, -1);
5490 ctrlv = FALSE;
5493 if (stop_arrow() == OK)
5494 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5498 * Special characters in this context are those that need processing other
5499 * than the simple insertion that can be performed here. This includes ESC
5500 * which terminates the insert, and CR/NL which need special processing to
5501 * open up a new line. This routine tries to optimize insertions performed by
5502 * the "redo", "undo" or "put" commands, so it needs to know when it should
5503 * stop and defer processing to the "normal" mechanism.
5504 * '0' and '^' are special, because they can be followed by CTRL-D.
5506 #ifdef EBCDIC
5507 # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
5508 #else
5509 # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5510 #endif
5512 #ifdef FEAT_MBYTE
5513 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5514 #else
5515 # define WHITECHAR(cc) vim_iswhite(cc)
5516 #endif
5518 void
5519 insertchar(c, flags, second_indent)
5520 int c; /* character to insert or NUL */
5521 int flags; /* INSCHAR_FORMAT, etc. */
5522 int second_indent; /* indent for second line if >= 0 */
5524 int textwidth;
5525 #ifdef FEAT_COMMENTS
5526 char_u *p;
5527 #endif
5528 int fo_ins_blank;
5530 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5531 fo_ins_blank = has_format_option(FO_INS_BLANK);
5534 * Try to break the line in two or more pieces when:
5535 * - Always do this if we have been called to do formatting only.
5536 * - Always do this when 'formatoptions' has the 'a' flag and the line
5537 * ends in white space.
5538 * - Otherwise:
5539 * - Don't do this if inserting a blank
5540 * - Don't do this if an existing character is being replaced, unless
5541 * we're in VREPLACE mode.
5542 * - Do this if the cursor is not on the line where insert started
5543 * or - 'formatoptions' doesn't have 'l' or the line was not too long
5544 * before the insert.
5545 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5546 * before 'textwidth'
5548 if (textwidth > 0
5549 && ((flags & INSCHAR_FORMAT)
5550 || (!vim_iswhite(c)
5551 && !((State & REPLACE_FLAG)
5552 #ifdef FEAT_VREPLACE
5553 && !(State & VREPLACE_FLAG)
5554 #endif
5555 && *ml_get_cursor() != NUL)
5556 && (curwin->w_cursor.lnum != Insstart.lnum
5557 || ((!has_format_option(FO_INS_LONG)
5558 || Insstart_textlen <= (colnr_T)textwidth)
5559 && (!fo_ins_blank
5560 || Insstart_blank_vcol <= (colnr_T)textwidth
5561 ))))))
5563 /* Format with 'formatexpr' when it's set. Use internal formatting
5564 * when 'formatexpr' isn't set or it returns non-zero. */
5565 #if defined(FEAT_EVAL)
5566 int do_internal = TRUE;
5568 if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0)
5570 do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0);
5571 /* It may be required to save for undo again, e.g. when setline()
5572 * was called. */
5573 ins_need_undo = TRUE;
5575 if (do_internal)
5576 #endif
5577 internal_format(textwidth, second_indent, flags, c == NUL, c);
5580 if (c == NUL) /* only formatting was wanted */
5581 return;
5583 #ifdef FEAT_COMMENTS
5584 /* Check whether this character should end a comment. */
5585 if (did_ai && (int)c == end_comment_pending)
5587 char_u *line;
5588 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5589 int middle_len, end_len;
5590 int i;
5593 * Need to remove existing (middle) comment leader and insert end
5594 * comment leader. First, check what comment leader we can find.
5596 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
5597 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
5599 /* Skip middle-comment string */
5600 while (*p && p[-1] != ':') /* find end of middle flags */
5601 ++p;
5602 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5603 /* Don't count trailing white space for middle_len */
5604 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5605 --middle_len;
5607 /* Find the end-comment string */
5608 while (*p && p[-1] != ':') /* find end of end flags */
5609 ++p;
5610 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5612 /* Skip white space before the cursor */
5613 i = curwin->w_cursor.col;
5614 while (--i >= 0 && vim_iswhite(line[i]))
5616 i++;
5618 /* Skip to before the middle leader */
5619 i -= middle_len;
5621 /* Check some expected things before we go on */
5622 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5624 /* Backspace over all the stuff we want to replace */
5625 backspace_until_column(i);
5628 * Insert the end-comment string, except for the last
5629 * character, which will get inserted as normal later.
5631 ins_bytes_len(lead_end, end_len - 1);
5635 end_comment_pending = NUL;
5636 #endif
5638 did_ai = FALSE;
5639 #ifdef FEAT_SMARTINDENT
5640 did_si = FALSE;
5641 can_si = FALSE;
5642 can_si_back = FALSE;
5643 #endif
5646 * If there's any pending input, grab up to INPUT_BUFLEN at once.
5647 * This speeds up normal text input considerably.
5648 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5649 * need to re-indent at a ':', or any other character (but not what
5650 * 'paste' is set)..
5652 #ifdef USE_ON_FLY_SCROLL
5653 dont_scroll = FALSE; /* allow scrolling here */
5654 #endif
5656 if ( !ISSPECIAL(c)
5657 #ifdef FEAT_MBYTE
5658 && (!has_mbyte || (*mb_char2len)(c) == 1)
5659 #endif
5660 && vpeekc() != NUL
5661 && !(State & REPLACE_FLAG)
5662 #ifdef FEAT_CINDENT
5663 && !cindent_on()
5664 #endif
5665 #ifdef FEAT_RIGHTLEFT
5666 && !p_ri
5667 #endif
5670 #define INPUT_BUFLEN 100
5671 char_u buf[INPUT_BUFLEN + 1];
5672 int i;
5673 colnr_T virtcol = 0;
5675 buf[0] = c;
5676 i = 1;
5677 if (textwidth > 0)
5678 virtcol = get_nolist_virtcol();
5680 * Stop the string when:
5681 * - no more chars available
5682 * - finding a special character (command key)
5683 * - buffer is full
5684 * - running into the 'textwidth' boundary
5685 * - need to check for abbreviation: A non-word char after a word-char
5687 while ( (c = vpeekc()) != NUL
5688 && !ISSPECIAL(c)
5689 #ifdef FEAT_MBYTE
5690 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5691 #endif
5692 && i < INPUT_BUFLEN
5693 && (textwidth == 0
5694 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5695 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5697 #ifdef FEAT_RIGHTLEFT
5698 c = vgetc();
5699 if (p_hkmap && KeyTyped)
5700 c = hkmap(c); /* Hebrew mode mapping */
5701 # ifdef FEAT_FKMAP
5702 if (p_fkmap && KeyTyped)
5703 c = fkmap(c); /* Farsi mode mapping */
5704 # endif
5705 buf[i++] = c;
5706 #else
5707 buf[i++] = vgetc();
5708 #endif
5711 #ifdef FEAT_DIGRAPHS
5712 do_digraph(-1); /* clear digraphs */
5713 do_digraph(buf[i-1]); /* may be the start of a digraph */
5714 #endif
5715 buf[i] = NUL;
5716 ins_str(buf);
5717 if (flags & INSCHAR_CTRLV)
5719 redo_literal(*buf);
5720 i = 1;
5722 else
5723 i = 0;
5724 if (buf[i] != NUL)
5725 AppendToRedobuffLit(buf + i, -1);
5727 else
5729 #ifdef FEAT_MBYTE
5730 int cc;
5732 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
5734 char_u buf[MB_MAXBYTES + 1];
5736 (*mb_char2bytes)(c, buf);
5737 buf[cc] = NUL;
5738 ins_char_bytes(buf, cc);
5739 AppendCharToRedobuff(c);
5741 else
5742 #endif
5744 ins_char(c);
5745 if (flags & INSCHAR_CTRLV)
5746 redo_literal(c);
5747 else
5748 AppendCharToRedobuff(c);
5754 * Format text at the current insert position.
5756 static void
5757 internal_format(textwidth, second_indent, flags, format_only, c)
5758 int textwidth;
5759 int second_indent;
5760 int flags;
5761 int format_only;
5762 int c; /* character to be inserted (can be NUL) */
5764 int cc;
5765 int save_char = NUL;
5766 int haveto_redraw = FALSE;
5767 int fo_ins_blank = has_format_option(FO_INS_BLANK);
5768 #ifdef FEAT_MBYTE
5769 int fo_multibyte = has_format_option(FO_MBYTE_BREAK);
5770 #endif
5771 int fo_white_par = has_format_option(FO_WHITE_PAR);
5772 int first_line = TRUE;
5773 #ifdef FEAT_COMMENTS
5774 colnr_T leader_len;
5775 int no_leader = FALSE;
5776 int do_comments = (flags & INSCHAR_DO_COM);
5777 #endif
5780 * When 'ai' is off we don't want a space under the cursor to be
5781 * deleted. Replace it with an 'x' temporarily.
5783 if (!curbuf->b_p_ai
5784 #ifdef FEAT_VREPLACE
5785 && !(State & VREPLACE_FLAG)
5786 #endif
5789 cc = gchar_cursor();
5790 if (vim_iswhite(cc))
5792 save_char = cc;
5793 pchar_cursor('x');
5798 * Repeat breaking lines, until the current line is not too long.
5800 while (!got_int)
5802 int startcol; /* Cursor column at entry */
5803 int wantcol; /* column at textwidth border */
5804 int foundcol; /* column for start of spaces */
5805 int end_foundcol = 0; /* column for start of word */
5806 colnr_T len;
5807 colnr_T virtcol;
5808 #ifdef FEAT_VREPLACE
5809 int orig_col = 0;
5810 char_u *saved_text = NULL;
5811 #endif
5812 colnr_T col;
5813 colnr_T end_col;
5815 virtcol = get_nolist_virtcol()
5816 + char2cells(c != NUL ? c : gchar_cursor());
5817 if (virtcol <= (colnr_T)textwidth)
5818 break;
5820 #ifdef FEAT_COMMENTS
5821 if (no_leader)
5822 do_comments = FALSE;
5823 else if (!(flags & INSCHAR_FORMAT)
5824 && has_format_option(FO_WRAP_COMS))
5825 do_comments = TRUE;
5827 /* Don't break until after the comment leader */
5828 if (do_comments)
5829 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
5830 else
5831 leader_len = 0;
5833 /* If the line doesn't start with a comment leader, then don't
5834 * start one in a following broken line. Avoids that a %word
5835 * moved to the start of the next line causes all following lines
5836 * to start with %. */
5837 if (leader_len == 0)
5838 no_leader = TRUE;
5839 #endif
5840 if (!(flags & INSCHAR_FORMAT)
5841 #ifdef FEAT_COMMENTS
5842 && leader_len == 0
5843 #endif
5844 && !has_format_option(FO_WRAP))
5846 break;
5847 if ((startcol = curwin->w_cursor.col) == 0)
5848 break;
5850 /* find column of textwidth border */
5851 coladvance((colnr_T)textwidth);
5852 wantcol = curwin->w_cursor.col;
5854 curwin->w_cursor.col = startcol;
5855 foundcol = 0;
5858 * Find position to break at.
5859 * Stop at first entered white when 'formatoptions' has 'v'
5861 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
5862 || curwin->w_cursor.lnum != Insstart.lnum
5863 || curwin->w_cursor.col >= Insstart.col)
5865 if (curwin->w_cursor.col == startcol && c != NUL)
5866 cc = c;
5867 else
5868 cc = gchar_cursor();
5869 if (WHITECHAR(cc))
5871 /* remember position of blank just before text */
5872 end_col = curwin->w_cursor.col;
5874 /* find start of sequence of blanks */
5875 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
5877 dec_cursor();
5878 cc = gchar_cursor();
5880 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
5881 break; /* only spaces in front of text */
5882 #ifdef FEAT_COMMENTS
5883 /* Don't break until after the comment leader */
5884 if (curwin->w_cursor.col < leader_len)
5885 break;
5886 #endif
5887 if (has_format_option(FO_ONE_LETTER))
5889 /* do not break after one-letter words */
5890 if (curwin->w_cursor.col == 0)
5891 break; /* one-letter word at begin */
5892 #ifdef FEAT_COMMENTS
5893 /* do not break "#a b" when 'tw' is 2 */
5894 if (curwin->w_cursor.col <= leader_len)
5895 break;
5896 #endif
5897 col = curwin->w_cursor.col;
5898 dec_cursor();
5899 cc = gchar_cursor();
5901 if (WHITECHAR(cc))
5902 continue; /* one-letter, continue */
5903 curwin->w_cursor.col = col;
5906 inc_cursor();
5908 end_foundcol = end_col + 1;
5909 foundcol = curwin->w_cursor.col;
5910 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5911 break;
5913 #ifdef FEAT_MBYTE
5914 else if (cc >= 0x100 && fo_multibyte)
5916 /* Break after or before a multi-byte character. */
5917 if (curwin->w_cursor.col != startcol)
5919 #ifdef FEAT_COMMENTS
5920 /* Don't break until after the comment leader */
5921 if (curwin->w_cursor.col < leader_len)
5922 break;
5923 #endif
5924 col = curwin->w_cursor.col;
5925 inc_cursor();
5926 /* Don't change end_foundcol if already set. */
5927 if (foundcol != curwin->w_cursor.col)
5929 foundcol = curwin->w_cursor.col;
5930 end_foundcol = foundcol;
5931 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5932 break;
5934 curwin->w_cursor.col = col;
5937 if (curwin->w_cursor.col == 0)
5938 break;
5940 col = curwin->w_cursor.col;
5942 dec_cursor();
5943 cc = gchar_cursor();
5945 if (WHITECHAR(cc))
5946 continue; /* break with space */
5947 #ifdef FEAT_COMMENTS
5948 /* Don't break until after the comment leader */
5949 if (curwin->w_cursor.col < leader_len)
5950 break;
5951 #endif
5953 curwin->w_cursor.col = col;
5955 foundcol = curwin->w_cursor.col;
5956 end_foundcol = foundcol;
5957 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5958 break;
5960 #endif
5961 if (curwin->w_cursor.col == 0)
5962 break;
5963 dec_cursor();
5966 if (foundcol == 0) /* no spaces, cannot break line */
5968 curwin->w_cursor.col = startcol;
5969 break;
5972 /* Going to break the line, remove any "$" now. */
5973 undisplay_dollar();
5976 * Offset between cursor position and line break is used by replace
5977 * stack functions. VREPLACE does not use this, and backspaces
5978 * over the text instead.
5980 #ifdef FEAT_VREPLACE
5981 if (State & VREPLACE_FLAG)
5982 orig_col = startcol; /* Will start backspacing from here */
5983 else
5984 #endif
5985 replace_offset = startcol - end_foundcol;
5988 * adjust startcol for spaces that will be deleted and
5989 * characters that will remain on top line
5991 curwin->w_cursor.col = foundcol;
5992 while ((cc = gchar_cursor(), WHITECHAR(cc))
5993 && (!fo_white_par || curwin->w_cursor.col < startcol))
5994 inc_cursor();
5995 startcol -= curwin->w_cursor.col;
5996 if (startcol < 0)
5997 startcol = 0;
5999 #ifdef FEAT_VREPLACE
6000 if (State & VREPLACE_FLAG)
6003 * In VREPLACE mode, we will backspace over the text to be
6004 * wrapped, so save a copy now to put on the next line.
6006 saved_text = vim_strsave(ml_get_cursor());
6007 curwin->w_cursor.col = orig_col;
6008 if (saved_text == NULL)
6009 break; /* Can't do it, out of memory */
6010 saved_text[startcol] = NUL;
6012 /* Backspace over characters that will move to the next line */
6013 if (!fo_white_par)
6014 backspace_until_column(foundcol);
6016 else
6017 #endif
6019 /* put cursor after pos. to break line */
6020 if (!fo_white_par)
6021 curwin->w_cursor.col = foundcol;
6025 * Split the line just before the margin.
6026 * Only insert/delete lines, but don't really redraw the window.
6028 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
6029 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
6030 #ifdef FEAT_COMMENTS
6031 + (do_comments ? OPENLINE_DO_COM : 0)
6032 #endif
6033 , old_indent);
6034 old_indent = 0;
6036 replace_offset = 0;
6037 if (first_line)
6039 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
6040 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
6041 if (second_indent >= 0)
6043 #ifdef FEAT_VREPLACE
6044 if (State & VREPLACE_FLAG)
6045 change_indent(INDENT_SET, second_indent, FALSE, NUL, TRUE);
6046 else
6047 #endif
6048 (void)set_indent(second_indent, SIN_CHANGED);
6050 first_line = FALSE;
6053 #ifdef FEAT_VREPLACE
6054 if (State & VREPLACE_FLAG)
6057 * In VREPLACE mode we have backspaced over the text to be
6058 * moved, now we re-insert it into the new line.
6060 ins_bytes(saved_text);
6061 vim_free(saved_text);
6063 else
6064 #endif
6067 * Check if cursor is not past the NUL off the line, cindent
6068 * may have added or removed indent.
6070 curwin->w_cursor.col += startcol;
6071 len = (colnr_T)STRLEN(ml_get_curline());
6072 if (curwin->w_cursor.col > len)
6073 curwin->w_cursor.col = len;
6076 haveto_redraw = TRUE;
6077 #ifdef FEAT_CINDENT
6078 can_cindent = TRUE;
6079 #endif
6080 /* moved the cursor, don't autoindent or cindent now */
6081 did_ai = FALSE;
6082 #ifdef FEAT_SMARTINDENT
6083 did_si = FALSE;
6084 can_si = FALSE;
6085 can_si_back = FALSE;
6086 #endif
6087 line_breakcheck();
6090 if (save_char != NUL) /* put back space after cursor */
6091 pchar_cursor(save_char);
6093 if (!format_only && haveto_redraw)
6095 update_topline();
6096 redraw_curbuf_later(VALID);
6101 * Called after inserting or deleting text: When 'formatoptions' includes the
6102 * 'a' flag format from the current line until the end of the paragraph.
6103 * Keep the cursor at the same position relative to the text.
6104 * The caller must have saved the cursor line for undo, following ones will be
6105 * saved here.
6107 void
6108 auto_format(trailblank, prev_line)
6109 int trailblank; /* when TRUE also format with trailing blank */
6110 int prev_line; /* may start in previous line */
6112 pos_T pos;
6113 colnr_T len;
6114 char_u *old;
6115 char_u *new, *pnew;
6116 int wasatend;
6117 int cc;
6119 if (!has_format_option(FO_AUTO))
6120 return;
6122 pos = curwin->w_cursor;
6123 old = ml_get_curline();
6125 /* may remove added space */
6126 check_auto_format(FALSE);
6128 /* Don't format in Insert mode when the cursor is on a trailing blank, the
6129 * user might insert normal text next. Also skip formatting when "1" is
6130 * in 'formatoptions' and there is a single character before the cursor.
6131 * Otherwise the line would be broken and when typing another non-white
6132 * next they are not joined back together. */
6133 wasatend = (pos.col == (colnr_T)STRLEN(old));
6134 if (*old != NUL && !trailblank && wasatend)
6136 dec_cursor();
6137 cc = gchar_cursor();
6138 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
6139 && has_format_option(FO_ONE_LETTER))
6140 dec_cursor();
6141 cc = gchar_cursor();
6142 if (WHITECHAR(cc))
6144 curwin->w_cursor = pos;
6145 return;
6147 curwin->w_cursor = pos;
6150 #ifdef FEAT_COMMENTS
6151 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
6152 * comments. */
6153 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
6154 && get_leader_len(old, NULL, FALSE) == 0)
6155 return;
6156 #endif
6159 * May start formatting in a previous line, so that after "x" a word is
6160 * moved to the previous line if it fits there now. Only when this is not
6161 * the start of a paragraph.
6163 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
6165 --curwin->w_cursor.lnum;
6166 if (u_save_cursor() == FAIL)
6167 return;
6171 * Do the formatting and restore the cursor position. "saved_cursor" will
6172 * be adjusted for the text formatting.
6174 saved_cursor = pos;
6175 format_lines((linenr_T)-1, FALSE);
6176 curwin->w_cursor = saved_cursor;
6177 saved_cursor.lnum = 0;
6179 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6181 /* "cannot happen" */
6182 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6183 coladvance((colnr_T)MAXCOL);
6185 else
6186 check_cursor_col();
6188 /* Insert mode: If the cursor is now after the end of the line while it
6189 * previously wasn't, the line was broken. Because of the rule above we
6190 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
6191 * formatted. */
6192 if (!wasatend && has_format_option(FO_WHITE_PAR))
6194 new = ml_get_curline();
6195 len = (colnr_T)STRLEN(new);
6196 if (curwin->w_cursor.col == len)
6198 pnew = vim_strnsave(new, len + 2);
6199 pnew[len] = ' ';
6200 pnew[len + 1] = NUL;
6201 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
6202 /* remove the space later */
6203 did_add_space = TRUE;
6205 else
6206 /* may remove added space */
6207 check_auto_format(FALSE);
6210 check_cursor();
6214 * When an extra space was added to continue a paragraph for auto-formatting,
6215 * delete it now. The space must be under the cursor, just after the insert
6216 * position.
6218 static void
6219 check_auto_format(end_insert)
6220 int end_insert; /* TRUE when ending Insert mode */
6222 int c = ' ';
6223 int cc;
6225 if (did_add_space)
6227 cc = gchar_cursor();
6228 if (!WHITECHAR(cc))
6229 /* Somehow the space was removed already. */
6230 did_add_space = FALSE;
6231 else
6233 if (!end_insert)
6235 inc_cursor();
6236 c = gchar_cursor();
6237 dec_cursor();
6239 if (c != NUL)
6241 /* The space is no longer at the end of the line, delete it. */
6242 del_char(FALSE);
6243 did_add_space = FALSE;
6250 * Find out textwidth to be used for formatting:
6251 * if 'textwidth' option is set, use it
6252 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
6253 * if invalid value, use 0.
6254 * Set default to window width (maximum 79) for "gq" operator.
6257 comp_textwidth(ff)
6258 int ff; /* force formatting (for "gq" command) */
6260 int textwidth;
6262 textwidth = curbuf->b_p_tw;
6263 if (textwidth == 0 && curbuf->b_p_wm)
6265 /* The width is the window width minus 'wrapmargin' minus all the
6266 * things that add to the margin. */
6267 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
6268 #ifdef FEAT_CMDWIN
6269 if (cmdwin_type != 0)
6270 textwidth -= 1;
6271 #endif
6272 #ifdef FEAT_FOLDING
6273 textwidth -= curwin->w_p_fdc;
6274 #endif
6275 #ifdef FEAT_SIGNS
6276 if (curwin->w_buffer->b_signlist != NULL
6277 # ifdef FEAT_NETBEANS_INTG
6278 || usingNetbeans
6279 # endif
6281 textwidth -= 1;
6282 #endif
6283 if (curwin->w_p_nu)
6284 textwidth -= 8;
6286 if (textwidth < 0)
6287 textwidth = 0;
6288 if (ff && textwidth == 0)
6290 textwidth = W_WIDTH(curwin) - 1;
6291 if (textwidth > 79)
6292 textwidth = 79;
6294 return textwidth;
6298 * Put a character in the redo buffer, for when just after a CTRL-V.
6300 static void
6301 redo_literal(c)
6302 int c;
6304 char_u buf[10];
6306 /* Only digits need special treatment. Translate them into a string of
6307 * three digits. */
6308 if (VIM_ISDIGIT(c))
6310 vim_snprintf((char *)buf, sizeof(buf), "%03d", c);
6311 AppendToRedobuff(buf);
6313 else
6314 AppendCharToRedobuff(c);
6318 * start_arrow() is called when an arrow key is used in insert mode.
6319 * For undo/redo it resembles hitting the <ESC> key.
6321 static void
6322 start_arrow(end_insert_pos)
6323 pos_T *end_insert_pos; /* can be NULL */
6325 if (!arrow_used) /* something has been inserted */
6327 AppendToRedobuff(ESC_STR);
6328 stop_insert(end_insert_pos, FALSE);
6329 arrow_used = TRUE; /* this means we stopped the current insert */
6331 #ifdef FEAT_SPELL
6332 check_spell_redraw();
6333 #endif
6336 #ifdef FEAT_SPELL
6338 * If we skipped highlighting word at cursor, do it now.
6339 * It may be skipped again, thus reset spell_redraw_lnum first.
6341 static void
6342 check_spell_redraw()
6344 if (spell_redraw_lnum != 0)
6346 linenr_T lnum = spell_redraw_lnum;
6348 spell_redraw_lnum = 0;
6349 redrawWinline(lnum, FALSE);
6354 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6355 * spelled word, if there is one.
6357 static void
6358 spell_back_to_badword()
6360 pos_T tpos = curwin->w_cursor;
6362 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
6363 if (curwin->w_cursor.col != tpos.col)
6364 start_arrow(&tpos);
6366 #endif
6369 * stop_arrow() is called before a change is made in insert mode.
6370 * If an arrow key has been used, start a new insertion.
6371 * Returns FAIL if undo is impossible, shouldn't insert then.
6374 stop_arrow()
6376 if (arrow_used)
6378 if (u_save_cursor() == OK)
6380 arrow_used = FALSE;
6381 ins_need_undo = FALSE;
6383 Insstart = curwin->w_cursor; /* new insertion starts here */
6384 Insstart_textlen = (colnr_T)linetabsize(ml_get_curline());
6385 ai_col = 0;
6386 #ifdef FEAT_VREPLACE
6387 if (State & VREPLACE_FLAG)
6389 orig_line_count = curbuf->b_ml.ml_line_count;
6390 vr_lines_changed = 1;
6392 #endif
6393 ResetRedobuff();
6394 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
6395 new_insert_skip = 2;
6397 else if (ins_need_undo)
6399 if (u_save_cursor() == OK)
6400 ins_need_undo = FALSE;
6403 #ifdef FEAT_FOLDING
6404 /* Always open fold at the cursor line when inserting something. */
6405 foldOpenCursor();
6406 #endif
6408 return (arrow_used || ins_need_undo ? FAIL : OK);
6412 * Do a few things to stop inserting.
6413 * "end_insert_pos" is where insert ended. It is NULL when we already jumped
6414 * to another window/buffer.
6416 static void
6417 stop_insert(end_insert_pos, esc)
6418 pos_T *end_insert_pos;
6419 int esc; /* called by ins_esc() */
6421 int cc;
6422 char_u *ptr;
6424 stop_redo_ins();
6425 replace_flush(); /* abandon replace stack */
6428 * Save the inserted text for later redo with ^@ and CTRL-A.
6429 * Don't do it when "restart_edit" was set and nothing was inserted,
6430 * otherwise CTRL-O w and then <Left> will clear "last_insert".
6432 ptr = get_inserted();
6433 if (did_restart_edit == 0 || (ptr != NULL
6434 && (int)STRLEN(ptr) > new_insert_skip))
6436 vim_free(last_insert);
6437 last_insert = ptr;
6438 last_insert_skip = new_insert_skip;
6440 else
6441 vim_free(ptr);
6443 if (!arrow_used && end_insert_pos != NULL)
6445 /* Auto-format now. It may seem strange to do this when stopping an
6446 * insertion (or moving the cursor), but it's required when appending
6447 * a line and having it end in a space. But only do it when something
6448 * was actually inserted, otherwise undo won't work. */
6449 if (!ins_need_undo && has_format_option(FO_AUTO))
6451 pos_T tpos = curwin->w_cursor;
6453 /* When the cursor is at the end of the line after a space the
6454 * formatting will move it to the following word. Avoid that by
6455 * moving the cursor onto the space. */
6456 cc = 'x';
6457 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
6459 dec_cursor();
6460 cc = gchar_cursor();
6461 if (!vim_iswhite(cc))
6462 curwin->w_cursor = tpos;
6465 auto_format(TRUE, FALSE);
6467 if (vim_iswhite(cc))
6469 if (gchar_cursor() != NUL)
6470 inc_cursor();
6471 #ifdef FEAT_VIRTUALEDIT
6472 /* If the cursor is still at the same character, also keep
6473 * the "coladd". */
6474 if (gchar_cursor() == NUL
6475 && curwin->w_cursor.lnum == tpos.lnum
6476 && curwin->w_cursor.col == tpos.col)
6477 curwin->w_cursor.coladd = tpos.coladd;
6478 #endif
6482 /* If a space was inserted for auto-formatting, remove it now. */
6483 check_auto_format(TRUE);
6485 /* If we just did an auto-indent, remove the white space from the end
6486 * of the line, and put the cursor back.
6487 * Do this when ESC was used or moving the cursor up/down.
6488 * Check for the old position still being valid, just in case the text
6489 * got changed unexpectedly. */
6490 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6491 && curwin->w_cursor.lnum != end_insert_pos->lnum))
6492 && end_insert_pos->lnum <= curbuf->b_ml.ml_line_count)
6494 pos_T tpos = curwin->w_cursor;
6496 curwin->w_cursor = *end_insert_pos;
6497 check_cursor_col(); /* make sure it is not past the line */
6498 for (;;)
6500 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6501 --curwin->w_cursor.col;
6502 cc = gchar_cursor();
6503 if (!vim_iswhite(cc))
6504 break;
6505 if (del_char(TRUE) == FAIL)
6506 break; /* should not happen */
6508 if (curwin->w_cursor.lnum != tpos.lnum)
6509 curwin->w_cursor = tpos;
6510 else if (cc != NUL)
6511 ++curwin->w_cursor.col; /* put cursor back on the NUL */
6513 #ifdef FEAT_VISUAL
6514 /* <C-S-Right> may have started Visual mode, adjust the position for
6515 * deleted characters. */
6516 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6518 int len = (int)STRLEN(ml_get_curline());
6520 if (VIsual.col > len)
6522 VIsual.col = len;
6523 # ifdef FEAT_VIRTUALEDIT
6524 VIsual.coladd = 0;
6525 # endif
6528 #endif
6531 did_ai = FALSE;
6532 #ifdef FEAT_SMARTINDENT
6533 did_si = FALSE;
6534 can_si = FALSE;
6535 can_si_back = FALSE;
6536 #endif
6538 /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are
6539 * now in a different buffer. */
6540 if (end_insert_pos != NULL)
6542 curbuf->b_op_start = Insstart;
6543 curbuf->b_op_end = *end_insert_pos;
6548 * Set the last inserted text to a single character.
6549 * Used for the replace command.
6551 void
6552 set_last_insert(c)
6553 int c;
6555 char_u *s;
6557 vim_free(last_insert);
6558 #ifdef FEAT_MBYTE
6559 last_insert = alloc(MB_MAXBYTES * 3 + 5);
6560 #else
6561 last_insert = alloc(6);
6562 #endif
6563 if (last_insert != NULL)
6565 s = last_insert;
6566 /* Use the CTRL-V only when entering a special char */
6567 if (c < ' ' || c == DEL)
6568 *s++ = Ctrl_V;
6569 s = add_char2buf(c, s);
6570 *s++ = ESC;
6571 *s++ = NUL;
6572 last_insert_skip = 0;
6576 #if defined(EXITFREE) || defined(PROTO)
6577 void
6578 free_last_insert()
6580 vim_free(last_insert);
6581 last_insert = NULL;
6582 # ifdef FEAT_INS_EXPAND
6583 vim_free(compl_orig_text);
6584 compl_orig_text = NULL;
6585 # endif
6587 #endif
6590 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
6591 * and CSI. Handle multi-byte characters.
6592 * Returns a pointer to after the added bytes.
6594 char_u *
6595 add_char2buf(c, s)
6596 int c;
6597 char_u *s;
6599 #ifdef FEAT_MBYTE
6600 char_u temp[MB_MAXBYTES];
6601 int i;
6602 int len;
6604 len = (*mb_char2bytes)(c, temp);
6605 for (i = 0; i < len; ++i)
6607 c = temp[i];
6608 #endif
6609 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6610 if (c == K_SPECIAL)
6612 *s++ = K_SPECIAL;
6613 *s++ = KS_SPECIAL;
6614 *s++ = KE_FILLER;
6616 #ifdef FEAT_GUI
6617 else if (c == CSI)
6619 *s++ = CSI;
6620 *s++ = KS_EXTRA;
6621 *s++ = (int)KE_CSI;
6623 #endif
6624 else
6625 *s++ = c;
6626 #ifdef FEAT_MBYTE
6628 #endif
6629 return s;
6633 * move cursor to start of line
6634 * if flags & BL_WHITE move to first non-white
6635 * if flags & BL_SOL move to first non-white if startofline is set,
6636 * otherwise keep "curswant" column
6637 * if flags & BL_FIX don't leave the cursor on a NUL.
6639 void
6640 beginline(flags)
6641 int flags;
6643 if ((flags & BL_SOL) && !p_sol)
6644 coladvance(curwin->w_curswant);
6645 else
6647 curwin->w_cursor.col = 0;
6648 #ifdef FEAT_VIRTUALEDIT
6649 curwin->w_cursor.coladd = 0;
6650 #endif
6652 if (flags & (BL_WHITE | BL_SOL))
6654 char_u *ptr;
6656 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6657 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6658 ++curwin->w_cursor.col;
6660 curwin->w_set_curswant = TRUE;
6665 * oneright oneleft cursor_down cursor_up
6667 * Move one char {right,left,down,up}.
6668 * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6669 * Return OK when successful, FAIL when we hit a line of file boundary.
6673 oneright()
6675 char_u *ptr;
6676 int l;
6678 #ifdef FEAT_VIRTUALEDIT
6679 if (virtual_active())
6681 pos_T prevpos = curwin->w_cursor;
6683 /* Adjust for multi-wide char (excluding TAB) */
6684 ptr = ml_get_cursor();
6685 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
6686 # ifdef FEAT_MBYTE
6687 (*mb_ptr2char)(ptr)
6688 # else
6689 *ptr
6690 # endif
6692 ? ptr2cells(ptr) : 1));
6693 curwin->w_set_curswant = TRUE;
6694 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
6695 return (prevpos.col != curwin->w_cursor.col
6696 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
6698 #endif
6700 ptr = ml_get_cursor();
6701 if (*ptr == NUL)
6702 return FAIL; /* already at the very end */
6704 #ifdef FEAT_MBYTE
6705 if (has_mbyte)
6706 l = (*mb_ptr2len)(ptr);
6707 else
6708 #endif
6709 l = 1;
6711 /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
6712 * contains "onemore". */
6713 if (ptr[l] == NUL
6714 #ifdef FEAT_VIRTUALEDIT
6715 && (ve_flags & VE_ONEMORE) == 0
6716 #endif
6718 return FAIL;
6719 curwin->w_cursor.col += l;
6721 curwin->w_set_curswant = TRUE;
6722 return OK;
6726 oneleft()
6728 #ifdef FEAT_VIRTUALEDIT
6729 if (virtual_active())
6731 int width;
6732 int v = getviscol();
6734 if (v == 0)
6735 return FAIL;
6737 # ifdef FEAT_LINEBREAK
6738 /* We might get stuck on 'showbreak', skip over it. */
6739 width = 1;
6740 for (;;)
6742 coladvance(v - width);
6743 /* getviscol() is slow, skip it when 'showbreak' is empty and
6744 * there are no multi-byte characters */
6745 if ((*p_sbr == NUL
6746 # ifdef FEAT_MBYTE
6747 && !has_mbyte
6748 # endif
6749 ) || getviscol() < v)
6750 break;
6751 ++width;
6753 # else
6754 coladvance(v - 1);
6755 # endif
6757 if (curwin->w_cursor.coladd == 1)
6759 char_u *ptr;
6761 /* Adjust for multi-wide char (not a TAB) */
6762 ptr = ml_get_cursor();
6763 if (*ptr != TAB && vim_isprintc(
6764 # ifdef FEAT_MBYTE
6765 (*mb_ptr2char)(ptr)
6766 # else
6767 *ptr
6768 # endif
6769 ) && ptr2cells(ptr) > 1)
6770 curwin->w_cursor.coladd = 0;
6773 curwin->w_set_curswant = TRUE;
6774 return OK;
6776 #endif
6778 if (curwin->w_cursor.col == 0)
6779 return FAIL;
6781 curwin->w_set_curswant = TRUE;
6782 --curwin->w_cursor.col;
6784 #ifdef FEAT_MBYTE
6785 /* if the character on the left of the current cursor is a multi-byte
6786 * character, move to its first byte */
6787 if (has_mbyte)
6788 mb_adjust_cursor();
6789 #endif
6790 return OK;
6794 cursor_up(n, upd_topline)
6795 long n;
6796 int upd_topline; /* When TRUE: update topline */
6798 linenr_T lnum;
6800 if (n > 0)
6802 lnum = curwin->w_cursor.lnum;
6803 /* This fails if the cursor is already in the first line or the count
6804 * is larger than the line number and '-' is in 'cpoptions' */
6805 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6806 return FAIL;
6807 if (n >= lnum)
6808 lnum = 1;
6809 else
6810 #ifdef FEAT_FOLDING
6811 if (hasAnyFolding(curwin))
6814 * Count each sequence of folded lines as one logical line.
6816 /* go to the the start of the current fold */
6817 (void)hasFolding(lnum, &lnum, NULL);
6819 while (n--)
6821 /* move up one line */
6822 --lnum;
6823 if (lnum <= 1)
6824 break;
6825 /* If we entered a fold, move to the beginning, unless in
6826 * Insert mode or when 'foldopen' contains "all": it will open
6827 * in a moment. */
6828 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
6829 (void)hasFolding(lnum, &lnum, NULL);
6831 if (lnum < 1)
6832 lnum = 1;
6834 else
6835 #endif
6836 lnum -= n;
6837 curwin->w_cursor.lnum = lnum;
6840 /* try to advance to the column we want to be at */
6841 coladvance(curwin->w_curswant);
6843 if (upd_topline)
6844 update_topline(); /* make sure curwin->w_topline is valid */
6846 return OK;
6850 * Cursor down a number of logical lines.
6853 cursor_down(n, upd_topline)
6854 long n;
6855 int upd_topline; /* When TRUE: update topline */
6857 linenr_T lnum;
6859 if (n > 0)
6861 lnum = curwin->w_cursor.lnum;
6862 #ifdef FEAT_FOLDING
6863 /* Move to last line of fold, will fail if it's the end-of-file. */
6864 (void)hasFolding(lnum, NULL, &lnum);
6865 #endif
6866 /* This fails if the cursor is already in the last line or would move
6867 * beyound the last line and '-' is in 'cpoptions' */
6868 if (lnum >= curbuf->b_ml.ml_line_count
6869 || (lnum + n > curbuf->b_ml.ml_line_count
6870 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6871 return FAIL;
6872 if (lnum + n >= curbuf->b_ml.ml_line_count)
6873 lnum = curbuf->b_ml.ml_line_count;
6874 else
6875 #ifdef FEAT_FOLDING
6876 if (hasAnyFolding(curwin))
6878 linenr_T last;
6880 /* count each sequence of folded lines as one logical line */
6881 while (n--)
6883 if (hasFolding(lnum, NULL, &last))
6884 lnum = last + 1;
6885 else
6886 ++lnum;
6887 if (lnum >= curbuf->b_ml.ml_line_count)
6888 break;
6890 if (lnum > curbuf->b_ml.ml_line_count)
6891 lnum = curbuf->b_ml.ml_line_count;
6893 else
6894 #endif
6895 lnum += n;
6896 curwin->w_cursor.lnum = lnum;
6899 /* try to advance to the column we want to be at */
6900 coladvance(curwin->w_curswant);
6902 if (upd_topline)
6903 update_topline(); /* make sure curwin->w_topline is valid */
6905 return OK;
6909 * Stuff the last inserted text in the read buffer.
6910 * Last_insert actually is a copy of the redo buffer, so we
6911 * first have to remove the command.
6914 stuff_inserted(c, count, no_esc)
6915 int c; /* Command character to be inserted */
6916 long count; /* Repeat this many times */
6917 int no_esc; /* Don't add an ESC at the end */
6919 char_u *esc_ptr;
6920 char_u *ptr;
6921 char_u *last_ptr;
6922 char_u last = NUL;
6924 ptr = get_last_insert();
6925 if (ptr == NULL)
6927 EMSG(_(e_noinstext));
6928 return FAIL;
6931 /* may want to stuff the command character, to start Insert mode */
6932 if (c != NUL)
6933 stuffcharReadbuff(c);
6934 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
6935 *esc_ptr = NUL; /* remove the ESC */
6937 /* when the last char is either "0" or "^" it will be quoted if no ESC
6938 * comes after it OR if it will inserted more than once and "ptr"
6939 * starts with ^D. -- Acevedo
6941 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
6942 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
6943 && (no_esc || (*ptr == Ctrl_D && count > 1)))
6945 last = *last_ptr;
6946 *last_ptr = NUL;
6951 stuffReadbuff(ptr);
6952 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
6953 if (last)
6954 stuffReadbuff((char_u *)(last == '0'
6955 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
6956 : IF_EB("\026^", CTRL_V_STR "^")));
6958 while (--count > 0);
6960 if (last)
6961 *last_ptr = last;
6963 if (esc_ptr != NULL)
6964 *esc_ptr = ESC; /* put the ESC back */
6966 /* may want to stuff a trailing ESC, to get out of Insert mode */
6967 if (!no_esc)
6968 stuffcharReadbuff(ESC);
6970 return OK;
6973 char_u *
6974 get_last_insert()
6976 if (last_insert == NULL)
6977 return NULL;
6978 return last_insert + last_insert_skip;
6982 * Get last inserted string, and remove trailing <Esc>.
6983 * Returns pointer to allocated memory (must be freed) or NULL.
6985 char_u *
6986 get_last_insert_save()
6988 char_u *s;
6989 int len;
6991 if (last_insert == NULL)
6992 return NULL;
6993 s = vim_strsave(last_insert + last_insert_skip);
6994 if (s != NULL)
6996 len = (int)STRLEN(s);
6997 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
6998 s[len - 1] = NUL;
7000 return s;
7004 * Check the word in front of the cursor for an abbreviation.
7005 * Called when the non-id character "c" has been entered.
7006 * When an abbreviation is recognized it is removed from the text and
7007 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
7009 static int
7010 echeck_abbr(c)
7011 int c;
7013 /* Don't check for abbreviation in paste mode, when disabled and just
7014 * after moving around with cursor keys. */
7015 if (p_paste || no_abbr || arrow_used)
7016 return FALSE;
7018 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
7019 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
7023 * replace-stack functions
7025 * When replacing characters, the replaced characters are remembered for each
7026 * new character. This is used to re-insert the old text when backspacing.
7028 * There is a NUL headed list of characters for each character that is
7029 * currently in the file after the insertion point. When BS is used, one NUL
7030 * headed list is put back for the deleted character.
7032 * For a newline, there are two NUL headed lists. One contains the characters
7033 * that the NL replaced. The extra one stores the characters after the cursor
7034 * that were deleted (always white space).
7036 * Replace_offset is normally 0, in which case replace_push will add a new
7037 * character at the end of the stack. If replace_offset is not 0, that many
7038 * characters will be left on the stack above the newly inserted character.
7041 static char_u *replace_stack = NULL;
7042 static long replace_stack_nr = 0; /* next entry in replace stack */
7043 static long replace_stack_len = 0; /* max. number of entries */
7045 void
7046 replace_push(c)
7047 int c; /* character that is replaced (NUL is none) */
7049 char_u *p;
7051 if (replace_stack_nr < replace_offset) /* nothing to do */
7052 return;
7053 if (replace_stack_len <= replace_stack_nr)
7055 replace_stack_len += 50;
7056 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
7057 if (p == NULL) /* out of memory */
7059 replace_stack_len -= 50;
7060 return;
7062 if (replace_stack != NULL)
7064 mch_memmove(p, replace_stack,
7065 (size_t)(replace_stack_nr * sizeof(char_u)));
7066 vim_free(replace_stack);
7068 replace_stack = p;
7070 p = replace_stack + replace_stack_nr - replace_offset;
7071 if (replace_offset)
7072 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
7073 *p = c;
7074 ++replace_stack_nr;
7077 #if defined(FEAT_MBYTE) || defined(PROTO)
7079 * Push a character onto the replace stack. Handles a multi-byte character in
7080 * reverse byte order, so that the first byte is popped off first.
7081 * Return the number of bytes done (includes composing characters).
7084 replace_push_mb(p)
7085 char_u *p;
7087 int l = (*mb_ptr2len)(p);
7088 int j;
7090 for (j = l - 1; j >= 0; --j)
7091 replace_push(p[j]);
7092 return l;
7094 #endif
7096 #if 0
7098 * call replace_push(c) with replace_offset set to the first NUL.
7100 static void
7101 replace_push_off(c)
7102 int c;
7104 char_u *p;
7106 p = replace_stack + replace_stack_nr;
7107 for (replace_offset = 1; replace_offset < replace_stack_nr;
7108 ++replace_offset)
7109 if (*--p == NUL)
7110 break;
7111 replace_push(c);
7112 replace_offset = 0;
7114 #endif
7117 * Pop one item from the replace stack.
7118 * return -1 if stack empty
7119 * return replaced character or NUL otherwise
7121 static int
7122 replace_pop()
7124 if (replace_stack_nr == 0)
7125 return -1;
7126 return (int)replace_stack[--replace_stack_nr];
7130 * Join the top two items on the replace stack. This removes to "off"'th NUL
7131 * encountered.
7133 static void
7134 replace_join(off)
7135 int off; /* offset for which NUL to remove */
7137 int i;
7139 for (i = replace_stack_nr; --i >= 0; )
7140 if (replace_stack[i] == NUL && off-- <= 0)
7142 --replace_stack_nr;
7143 mch_memmove(replace_stack + i, replace_stack + i + 1,
7144 (size_t)(replace_stack_nr - i));
7145 return;
7150 * Pop bytes from the replace stack until a NUL is found, and insert them
7151 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
7153 static void
7154 replace_pop_ins()
7156 int cc;
7157 int oldState = State;
7159 State = NORMAL; /* don't want REPLACE here */
7160 while ((cc = replace_pop()) > 0)
7162 #ifdef FEAT_MBYTE
7163 mb_replace_pop_ins(cc);
7164 #else
7165 ins_char(cc);
7166 #endif
7167 dec_cursor();
7169 State = oldState;
7172 #ifdef FEAT_MBYTE
7174 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
7175 * indicates a multi-byte char, pop the other bytes too.
7177 static void
7178 mb_replace_pop_ins(cc)
7179 int cc;
7181 int n;
7182 char_u buf[MB_MAXBYTES];
7183 int i;
7184 int c;
7186 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
7188 buf[0] = cc;
7189 for (i = 1; i < n; ++i)
7190 buf[i] = replace_pop();
7191 ins_bytes_len(buf, n);
7193 else
7194 ins_char(cc);
7196 if (enc_utf8)
7197 /* Handle composing chars. */
7198 for (;;)
7200 c = replace_pop();
7201 if (c == -1) /* stack empty */
7202 break;
7203 if ((n = MB_BYTE2LEN(c)) == 1)
7205 /* Not a multi-byte char, put it back. */
7206 replace_push(c);
7207 break;
7209 else
7211 buf[0] = c;
7212 for (i = 1; i < n; ++i)
7213 buf[i] = replace_pop();
7214 if (utf_iscomposing(utf_ptr2char(buf)))
7215 ins_bytes_len(buf, n);
7216 else
7218 /* Not a composing char, put it back. */
7219 for (i = n - 1; i >= 0; --i)
7220 replace_push(buf[i]);
7221 break;
7226 #endif
7229 * make the replace stack empty
7230 * (called when exiting replace mode)
7232 static void
7233 replace_flush()
7235 vim_free(replace_stack);
7236 replace_stack = NULL;
7237 replace_stack_len = 0;
7238 replace_stack_nr = 0;
7242 * Handle doing a BS for one character.
7243 * cc < 0: replace stack empty, just move cursor
7244 * cc == 0: character was inserted, delete it
7245 * cc > 0: character was replaced, put cc (first byte of original char) back
7246 * and check for more characters to be put back
7247 * When "limit_col" is >= 0, don't delete before this column. Matters when
7248 * using composing characters, use del_char_after_col() instead of del_char().
7250 static void
7251 replace_do_bs(limit_col)
7252 int limit_col;
7254 int cc;
7255 #ifdef FEAT_VREPLACE
7256 int orig_len = 0;
7257 int ins_len;
7258 int orig_vcols = 0;
7259 colnr_T start_vcol;
7260 char_u *p;
7261 int i;
7262 int vcol;
7263 #endif
7265 cc = replace_pop();
7266 if (cc > 0)
7268 #ifdef FEAT_VREPLACE
7269 if (State & VREPLACE_FLAG)
7271 /* Get the number of screen cells used by the character we are
7272 * going to delete. */
7273 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
7274 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
7276 #endif
7277 #ifdef FEAT_MBYTE
7278 if (has_mbyte)
7280 (void)del_char_after_col(limit_col);
7281 # ifdef FEAT_VREPLACE
7282 if (State & VREPLACE_FLAG)
7283 orig_len = (int)STRLEN(ml_get_cursor());
7284 # endif
7285 replace_push(cc);
7287 else
7288 #endif
7290 pchar_cursor(cc);
7291 #ifdef FEAT_VREPLACE
7292 if (State & VREPLACE_FLAG)
7293 orig_len = (int)STRLEN(ml_get_cursor()) - 1;
7294 #endif
7296 replace_pop_ins();
7298 #ifdef FEAT_VREPLACE
7299 if (State & VREPLACE_FLAG)
7301 /* Get the number of screen cells used by the inserted characters */
7302 p = ml_get_cursor();
7303 ins_len = (int)STRLEN(p) - orig_len;
7304 vcol = start_vcol;
7305 for (i = 0; i < ins_len; ++i)
7307 vcol += chartabsize(p + i, vcol);
7308 #ifdef FEAT_MBYTE
7309 i += (*mb_ptr2len)(p) - 1;
7310 #endif
7312 vcol -= start_vcol;
7314 /* Delete spaces that were inserted after the cursor to keep the
7315 * text aligned. */
7316 curwin->w_cursor.col += ins_len;
7317 while (vcol > orig_vcols && gchar_cursor() == ' ')
7319 del_char(FALSE);
7320 ++orig_vcols;
7322 curwin->w_cursor.col -= ins_len;
7324 #endif
7326 /* mark the buffer as changed and prepare for displaying */
7327 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
7329 else if (cc == 0)
7330 (void)del_char_after_col(limit_col);
7333 #ifdef FEAT_CINDENT
7335 * Return TRUE if C-indenting is on.
7337 static int
7338 cindent_on()
7340 return (!p_paste && (curbuf->b_p_cin
7341 # ifdef FEAT_EVAL
7342 || *curbuf->b_p_inde != NUL
7343 # endif
7346 #endif
7348 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
7350 * Re-indent the current line, based on the current contents of it and the
7351 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
7352 * confused what all the part that handles Control-T is doing that I'm not.
7353 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
7356 void
7357 fixthisline(get_the_indent)
7358 int (*get_the_indent) __ARGS((void));
7360 change_indent(INDENT_SET, get_the_indent(), FALSE, 0, TRUE);
7361 if (linewhite(curwin->w_cursor.lnum))
7362 did_ai = TRUE; /* delete the indent if the line stays empty */
7365 void
7366 fix_indent()
7368 if (p_paste)
7369 return;
7370 # ifdef FEAT_LISP
7371 if (curbuf->b_p_lisp && curbuf->b_p_ai)
7372 fixthisline(get_lisp_indent);
7373 # endif
7374 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
7375 else
7376 # endif
7377 # ifdef FEAT_CINDENT
7378 if (cindent_on())
7379 do_c_expr_indent();
7380 # endif
7383 #endif
7385 #ifdef FEAT_CINDENT
7387 * return TRUE if 'cinkeys' contains the key "keytyped",
7388 * when == '*': Only if key is preceded with '*' (indent before insert)
7389 * when == '!': Only if key is prededed with '!' (don't insert)
7390 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
7392 * "keytyped" can have a few special values:
7393 * KEY_OPEN_FORW
7394 * KEY_OPEN_BACK
7395 * KEY_COMPLETE just finished completion.
7397 * If line_is_empty is TRUE accept keys with '0' before them.
7400 in_cinkeys(keytyped, when, line_is_empty)
7401 int keytyped;
7402 int when;
7403 int line_is_empty;
7405 char_u *look;
7406 int try_match;
7407 int try_match_word;
7408 char_u *p;
7409 char_u *line;
7410 int icase;
7411 int i;
7413 if (keytyped == NUL)
7414 /* Can happen with CTRL-Y and CTRL-E on a short line. */
7415 return FALSE;
7417 #ifdef FEAT_EVAL
7418 if (*curbuf->b_p_inde != NUL)
7419 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
7420 else
7421 #endif
7422 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
7423 while (*look)
7426 * Find out if we want to try a match with this key, depending on
7427 * 'when' and a '*' or '!' before the key.
7429 switch (when)
7431 case '*': try_match = (*look == '*'); break;
7432 case '!': try_match = (*look == '!'); break;
7433 default: try_match = (*look != '*'); break;
7435 if (*look == '*' || *look == '!')
7436 ++look;
7439 * If there is a '0', only accept a match if the line is empty.
7440 * But may still match when typing last char of a word.
7442 if (*look == '0')
7444 try_match_word = try_match;
7445 if (!line_is_empty)
7446 try_match = FALSE;
7447 ++look;
7449 else
7450 try_match_word = FALSE;
7453 * does it look like a control character?
7455 if (*look == '^'
7456 #ifdef EBCDIC
7457 && (Ctrl_chr(look[1]) != 0)
7458 #else
7459 && look[1] >= '?' && look[1] <= '_'
7460 #endif
7463 if (try_match && keytyped == Ctrl_chr(look[1]))
7464 return TRUE;
7465 look += 2;
7468 * 'o' means "o" command, open forward.
7469 * 'O' means "O" command, open backward.
7471 else if (*look == 'o')
7473 if (try_match && keytyped == KEY_OPEN_FORW)
7474 return TRUE;
7475 ++look;
7477 else if (*look == 'O')
7479 if (try_match && keytyped == KEY_OPEN_BACK)
7480 return TRUE;
7481 ++look;
7485 * 'e' means to check for "else" at start of line and just before the
7486 * cursor.
7488 else if (*look == 'e')
7490 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
7492 p = ml_get_curline();
7493 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
7494 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
7495 return TRUE;
7497 ++look;
7501 * ':' only causes an indent if it is at the end of a label or case
7502 * statement, or when it was before typing the ':' (to fix
7503 * class::method for C++).
7505 else if (*look == ':')
7507 if (try_match && keytyped == ':')
7509 p = ml_get_curline();
7510 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
7511 return TRUE;
7512 /* Need to get the line again after cin_islabel(). */
7513 p = ml_get_curline();
7514 if (curwin->w_cursor.col > 2
7515 && p[curwin->w_cursor.col - 1] == ':'
7516 && p[curwin->w_cursor.col - 2] == ':')
7518 p[curwin->w_cursor.col - 1] = ' ';
7519 i = (cin_iscase(p) || cin_isscopedecl(p)
7520 || cin_islabel(30));
7521 p = ml_get_curline();
7522 p[curwin->w_cursor.col - 1] = ':';
7523 if (i)
7524 return TRUE;
7527 ++look;
7532 * Is it a key in <>, maybe?
7534 else if (*look == '<')
7536 if (try_match)
7539 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7540 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7541 * >, *, : and ! keys if they really really want to.
7543 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7544 && keytyped == look[1])
7545 return TRUE;
7547 if (keytyped == get_special_key_code(look + 1))
7548 return TRUE;
7550 while (*look && *look != '>')
7551 look++;
7552 while (*look == '>')
7553 look++;
7557 * Is it a word: "=word"?
7559 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7561 ++look;
7562 if (*look == '~')
7564 icase = TRUE;
7565 ++look;
7567 else
7568 icase = FALSE;
7569 p = vim_strchr(look, ',');
7570 if (p == NULL)
7571 p = look + STRLEN(look);
7572 if ((try_match || try_match_word)
7573 && curwin->w_cursor.col >= (colnr_T)(p - look))
7575 int match = FALSE;
7577 #ifdef FEAT_INS_EXPAND
7578 if (keytyped == KEY_COMPLETE)
7580 char_u *s;
7582 /* Just completed a word, check if it starts with "look".
7583 * search back for the start of a word. */
7584 line = ml_get_curline();
7585 # ifdef FEAT_MBYTE
7586 if (has_mbyte)
7588 char_u *n;
7590 for (s = line + curwin->w_cursor.col; s > line; s = n)
7592 n = mb_prevptr(line, s);
7593 if (!vim_iswordp(n))
7594 break;
7597 else
7598 # endif
7599 for (s = line + curwin->w_cursor.col; s > line; --s)
7600 if (!vim_iswordc(s[-1]))
7601 break;
7602 if (s + (p - look) <= line + curwin->w_cursor.col
7603 && (icase
7604 ? MB_STRNICMP(s, look, p - look)
7605 : STRNCMP(s, look, p - look)) == 0)
7606 match = TRUE;
7608 else
7609 #endif
7610 /* TODO: multi-byte */
7611 if (keytyped == (int)p[-1] || (icase && keytyped < 256
7612 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7614 line = ml_get_cursor();
7615 if ((curwin->w_cursor.col == (colnr_T)(p - look)
7616 || !vim_iswordc(line[-(p - look) - 1]))
7617 && (icase
7618 ? MB_STRNICMP(line - (p - look), look, p - look)
7619 : STRNCMP(line - (p - look), look, p - look))
7620 == 0)
7621 match = TRUE;
7623 if (match && try_match_word && !try_match)
7625 /* "0=word": Check if there are only blanks before the
7626 * word. */
7627 line = ml_get_curline();
7628 if ((int)(skipwhite(line) - line) !=
7629 (int)(curwin->w_cursor.col - (p - look)))
7630 match = FALSE;
7632 if (match)
7633 return TRUE;
7635 look = p;
7639 * ok, it's a boring generic character.
7641 else
7643 if (try_match && *look == keytyped)
7644 return TRUE;
7645 ++look;
7649 * Skip over ", ".
7651 look = skip_to_option_part(look);
7653 return FALSE;
7655 #endif /* FEAT_CINDENT */
7657 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7659 * Map Hebrew keyboard when in hkmap mode.
7662 hkmap(c)
7663 int c;
7665 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
7667 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7668 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7669 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7670 static char_u map[26] =
7671 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
7672 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
7673 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
7674 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
7675 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
7676 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
7677 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
7678 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
7679 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
7681 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7682 return (int)(map[CharOrd(c)] - 1 + p_aleph);
7683 /* '-1'='sofit' */
7684 else if (c == 'x')
7685 return 'X';
7686 else if (c == 'q')
7687 return '\''; /* {geresh}={'} */
7688 else if (c == 246)
7689 return ' '; /* \"o --> ' ' for a german keyboard */
7690 else if (c == 228)
7691 return ' '; /* \"a --> ' ' -- / -- */
7692 else if (c == 252)
7693 return ' '; /* \"u --> ' ' -- / -- */
7694 #ifdef EBCDIC
7695 else if (islower(c))
7696 #else
7697 /* NOTE: islower() does not do the right thing for us on Linux so we
7698 * do this the same was as 5.7 and previous, so it works correctly on
7699 * all systems. Specifically, the e.g. Delete and Arrow keys are
7700 * munged and won't work if e.g. searching for Hebrew text.
7702 else if (c >= 'a' && c <= 'z')
7703 #endif
7704 return (int)(map[CharOrdLow(c)] + p_aleph);
7705 else
7706 return c;
7708 else
7710 switch (c)
7712 case '`': return ';';
7713 case '/': return '.';
7714 case '\'': return ',';
7715 case 'q': return '/';
7716 case 'w': return '\'';
7718 /* Hebrew letters - set offset from 'a' */
7719 case ',': c = '{'; break;
7720 case '.': c = 'v'; break;
7721 case ';': c = 't'; break;
7722 default: {
7723 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
7725 #ifdef EBCDIC
7726 /* see note about islower() above */
7727 if (!islower(c))
7728 #else
7729 if (c < 'a' || c > 'z')
7730 #endif
7731 return c;
7732 c = str[CharOrdLow(c)];
7733 break;
7737 return (int)(CharOrdLow(c) + p_aleph);
7740 #endif
7742 static void
7743 ins_reg()
7745 int need_redraw = FALSE;
7746 int regname;
7747 int literally = 0;
7748 #ifdef FEAT_VISUAL
7749 int vis_active = VIsual_active;
7750 #endif
7753 * If we are going to wait for a character, show a '"'.
7755 pc_status = PC_STATUS_UNSET;
7756 if (redrawing() && !char_avail())
7758 /* may need to redraw when no more chars available now */
7759 ins_redraw(FALSE);
7761 edit_putchar('"', TRUE);
7762 #ifdef FEAT_CMDL_INFO
7763 add_to_showcmd_c(Ctrl_R);
7764 #endif
7767 #ifdef USE_ON_FLY_SCROLL
7768 dont_scroll = TRUE; /* disallow scrolling here */
7769 #endif
7772 * Don't map the register name. This also prevents the mode message to be
7773 * deleted when ESC is hit.
7775 ++no_mapping;
7776 regname = plain_vgetc();
7777 LANGMAP_ADJUST(regname, TRUE);
7778 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
7780 /* Get a third key for literal register insertion */
7781 literally = regname;
7782 #ifdef FEAT_CMDL_INFO
7783 add_to_showcmd_c(literally);
7784 #endif
7785 regname = plain_vgetc();
7786 LANGMAP_ADJUST(regname, TRUE);
7788 --no_mapping;
7790 #ifdef FEAT_EVAL
7792 * Don't call u_sync() while getting the expression,
7793 * evaluating it or giving an error message for it!
7795 ++no_u_sync;
7796 if (regname == '=')
7798 # ifdef USE_IM_CONTROL
7799 int im_on = im_get_status();
7800 # endif
7801 regname = get_expr_register();
7802 # ifdef USE_IM_CONTROL
7803 /* Restore the Input Method. */
7804 if (im_on)
7805 im_set_active(TRUE);
7806 # endif
7808 if (regname == NUL || !valid_yank_reg(regname, FALSE))
7810 vim_beep();
7811 need_redraw = TRUE; /* remove the '"' */
7813 else
7815 #endif
7816 if (literally == Ctrl_O || literally == Ctrl_P)
7818 /* Append the command to the redo buffer. */
7819 AppendCharToRedobuff(Ctrl_R);
7820 AppendCharToRedobuff(literally);
7821 AppendCharToRedobuff(regname);
7823 do_put(regname, BACKWARD, 1L,
7824 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
7826 else if (insert_reg(regname, literally) == FAIL)
7828 vim_beep();
7829 need_redraw = TRUE; /* remove the '"' */
7831 else if (stop_insert_mode)
7832 /* When the '=' register was used and a function was invoked that
7833 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
7834 * insert anything, need to remove the '"' */
7835 need_redraw = TRUE;
7837 #ifdef FEAT_EVAL
7839 --no_u_sync;
7840 #endif
7841 #ifdef FEAT_CMDL_INFO
7842 clear_showcmd();
7843 #endif
7845 /* If the inserted register is empty, we need to remove the '"' */
7846 if (need_redraw || stuff_empty())
7847 edit_unputchar();
7849 #ifdef FEAT_VISUAL
7850 /* Disallow starting Visual mode here, would get a weird mode. */
7851 if (!vis_active && VIsual_active)
7852 end_visual_mode();
7853 #endif
7857 * CTRL-G commands in Insert mode.
7859 static void
7860 ins_ctrl_g()
7862 int c;
7864 #ifdef FEAT_INS_EXPAND
7865 /* Right after CTRL-X the cursor will be after the ruler. */
7866 setcursor();
7867 #endif
7870 * Don't map the second key. This also prevents the mode message to be
7871 * deleted when ESC is hit.
7873 ++no_mapping;
7874 c = plain_vgetc();
7875 --no_mapping;
7876 switch (c)
7878 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
7879 case K_UP:
7880 case Ctrl_K:
7881 case 'k': ins_up(TRUE);
7882 break;
7884 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
7885 case K_DOWN:
7886 case Ctrl_J:
7887 case 'j': ins_down(TRUE);
7888 break;
7890 /* CTRL-G u: start new undoable edit */
7891 case 'u': u_sync(TRUE);
7892 ins_need_undo = TRUE;
7894 /* Need to reset Insstart, esp. because a BS that joins
7895 * a line to the previous one must save for undo. */
7896 Insstart = curwin->w_cursor;
7897 break;
7899 /* Unknown CTRL-G command, reserved for future expansion. */
7900 default: vim_beep();
7905 * CTRL-^ in Insert mode.
7907 static void
7908 ins_ctrl_hat()
7910 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
7912 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
7913 if (State & LANGMAP)
7915 curbuf->b_p_iminsert = B_IMODE_NONE;
7916 State &= ~LANGMAP;
7918 else
7920 curbuf->b_p_iminsert = B_IMODE_LMAP;
7921 State |= LANGMAP;
7922 #ifdef USE_IM_CONTROL
7923 im_set_active(FALSE);
7924 #endif
7927 #ifdef USE_IM_CONTROL
7928 else
7930 /* There are no ":lmap" mappings, toggle IM */
7931 if (im_get_status())
7933 curbuf->b_p_iminsert = B_IMODE_NONE;
7934 im_set_active(FALSE);
7936 else
7938 curbuf->b_p_iminsert = B_IMODE_IM;
7939 State &= ~LANGMAP;
7940 im_set_active(TRUE);
7943 #endif
7944 set_iminsert_global();
7945 showmode();
7946 #ifdef FEAT_GUI
7947 /* may show different cursor shape or color */
7948 if (gui.in_use)
7949 gui_update_cursor(TRUE, FALSE);
7950 #endif
7951 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
7952 /* Show/unshow value of 'keymap' in status lines. */
7953 status_redraw_curbuf();
7954 #endif
7958 * Handle ESC in insert mode.
7959 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
7960 * insert.
7962 static int
7963 ins_esc(count, cmdchar, nomove)
7964 long *count;
7965 int cmdchar;
7966 int nomove; /* don't move cursor */
7968 int temp;
7969 static int disabled_redraw = FALSE;
7971 #ifdef FEAT_SPELL
7972 check_spell_redraw();
7973 #endif
7974 #if defined(FEAT_HANGULIN)
7975 # if defined(ESC_CHG_TO_ENG_MODE)
7976 hangul_input_state_set(0);
7977 # endif
7978 if (composing_hangul)
7980 push_raw_key(composing_hangul_buffer, 2);
7981 composing_hangul = 0;
7983 #endif
7985 temp = curwin->w_cursor.col;
7986 if (disabled_redraw)
7988 --RedrawingDisabled;
7989 disabled_redraw = FALSE;
7991 if (!arrow_used)
7994 * Don't append the ESC for "r<CR>" and "grx".
7995 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
7996 * when "count" is non-zero.
7998 if (cmdchar != 'r' && cmdchar != 'v')
7999 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
8002 * Repeating insert may take a long time. Check for
8003 * interrupt now and then.
8005 if (*count > 0)
8007 line_breakcheck();
8008 if (got_int)
8009 *count = 0;
8012 if (--*count > 0) /* repeat what was typed */
8014 /* Vi repeats the insert without replacing characters. */
8015 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
8016 State &= ~REPLACE_FLAG;
8018 (void)start_redo_ins();
8019 if (cmdchar == 'r' || cmdchar == 'v')
8020 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
8021 ++RedrawingDisabled;
8022 disabled_redraw = TRUE;
8023 return FALSE; /* repeat the insert */
8025 stop_insert(&curwin->w_cursor, TRUE);
8026 undisplay_dollar();
8029 /* When an autoindent was removed, curswant stays after the
8030 * indent */
8031 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
8032 curwin->w_set_curswant = TRUE;
8034 /* Remember the last Insert position in the '^ mark. */
8035 if (!cmdmod.keepjumps)
8036 curbuf->b_last_insert = curwin->w_cursor;
8039 * The cursor should end up on the last inserted character.
8040 * Don't do it for CTRL-O, unless past the end of the line.
8042 if (!nomove
8043 && (curwin->w_cursor.col != 0
8044 #ifdef FEAT_VIRTUALEDIT
8045 || curwin->w_cursor.coladd > 0
8046 #endif
8048 && (restart_edit == NUL
8049 || (gchar_cursor() == NUL
8050 #ifdef FEAT_VISUAL
8051 && !VIsual_active
8052 #endif
8054 #ifdef FEAT_RIGHTLEFT
8055 && !revins_on
8056 #endif
8059 #ifdef FEAT_VIRTUALEDIT
8060 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
8062 oneleft();
8063 if (restart_edit != NUL)
8064 ++curwin->w_cursor.coladd;
8066 else
8067 #endif
8069 --curwin->w_cursor.col;
8070 #ifdef FEAT_MBYTE
8071 /* Correct cursor for multi-byte character. */
8072 if (has_mbyte)
8073 mb_adjust_cursor();
8074 #endif
8078 #ifdef USE_IM_CONTROL
8079 /* Disable IM to allow typing English directly for Normal mode commands.
8080 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
8081 * well). */
8082 if (!(State & LANGMAP))
8083 im_save_status(&curbuf->b_p_iminsert);
8084 im_set_active(FALSE);
8085 #endif
8087 State = NORMAL;
8088 /* need to position cursor again (e.g. when on a TAB ) */
8089 changed_cline_bef_curs();
8091 #ifdef FEAT_MOUSE
8092 setmouse();
8093 #endif
8094 #ifdef CURSOR_SHAPE
8095 ui_cursor_shape(); /* may show different cursor shape */
8096 #endif
8099 * When recording or for CTRL-O, need to display the new mode.
8100 * Otherwise remove the mode message.
8102 if (Recording || restart_edit != NUL)
8103 showmode();
8104 else if (p_smd)
8105 MSG("");
8107 return TRUE; /* exit Insert mode */
8110 #ifdef FEAT_RIGHTLEFT
8112 * Toggle language: hkmap and revins_on.
8113 * Move to end of reverse inserted text.
8115 static void
8116 ins_ctrl_()
8118 if (revins_on && revins_chars && revins_scol >= 0)
8120 while (gchar_cursor() != NUL && revins_chars--)
8121 ++curwin->w_cursor.col;
8123 p_ri = !p_ri;
8124 revins_on = (State == INSERT && p_ri);
8125 if (revins_on)
8127 revins_scol = curwin->w_cursor.col;
8128 revins_legal++;
8129 revins_chars = 0;
8130 undisplay_dollar();
8132 else
8133 revins_scol = -1;
8134 #ifdef FEAT_FKMAP
8135 if (p_altkeymap)
8138 * to be consistent also for redo command, using '.'
8139 * set arrow_used to true and stop it - causing to redo
8140 * characters entered in one mode (normal/reverse insert).
8142 arrow_used = TRUE;
8143 (void)stop_arrow();
8144 p_fkmap = curwin->w_p_rl ^ p_ri;
8145 if (p_fkmap && p_ri)
8146 State = INSERT;
8148 else
8149 #endif
8150 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
8151 showmode();
8153 #endif
8155 #ifdef FEAT_VISUAL
8157 * If 'keymodel' contains "startsel", may start selection.
8158 * Returns TRUE when a CTRL-O and other keys stuffed.
8160 static int
8161 ins_start_select(c)
8162 int c;
8164 if (km_startsel)
8165 switch (c)
8167 case K_KHOME:
8168 case K_KEND:
8169 case K_PAGEUP:
8170 case K_KPAGEUP:
8171 case K_PAGEDOWN:
8172 case K_KPAGEDOWN:
8173 # ifdef MACOS
8174 case K_LEFT:
8175 case K_RIGHT:
8176 case K_UP:
8177 case K_DOWN:
8178 case K_END:
8179 case K_HOME:
8180 # endif
8181 if (!(mod_mask & MOD_MASK_SHIFT))
8182 break;
8183 /* FALLTHROUGH */
8184 case K_S_LEFT:
8185 case K_S_RIGHT:
8186 case K_S_UP:
8187 case K_S_DOWN:
8188 case K_S_END:
8189 case K_S_HOME:
8190 /* Start selection right away, the cursor can move with
8191 * CTRL-O when beyond the end of the line. */
8192 start_selection();
8194 /* Execute the key in (insert) Select mode. */
8195 stuffcharReadbuff(Ctrl_O);
8196 if (mod_mask)
8198 char_u buf[4];
8200 buf[0] = K_SPECIAL;
8201 buf[1] = KS_MODIFIER;
8202 buf[2] = mod_mask;
8203 buf[3] = NUL;
8204 stuffReadbuff(buf);
8206 stuffcharReadbuff(c);
8207 return TRUE;
8209 return FALSE;
8211 #endif
8214 * <Insert> key in Insert mode: toggle insert/remplace mode.
8216 static void
8217 ins_insert(replaceState)
8218 int replaceState;
8220 #ifdef FEAT_FKMAP
8221 if (p_fkmap && p_ri)
8223 beep_flush();
8224 EMSG(farsi_text_3); /* encoded in Farsi */
8225 return;
8227 #endif
8229 #ifdef FEAT_AUTOCMD
8230 # ifdef FEAT_EVAL
8231 set_vim_var_string(VV_INSERTMODE,
8232 (char_u *)((State & REPLACE_FLAG) ? "i" :
8233 # ifdef FEAT_VREPLACE
8234 replaceState == VREPLACE ? "v" :
8235 # endif
8236 "r"), 1);
8237 # endif
8238 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
8239 #endif
8240 if (State & REPLACE_FLAG)
8241 State = INSERT | (State & LANGMAP);
8242 else
8243 State = replaceState | (State & LANGMAP);
8244 AppendCharToRedobuff(K_INS);
8245 showmode();
8246 #ifdef CURSOR_SHAPE
8247 ui_cursor_shape(); /* may show different cursor shape */
8248 #endif
8252 * Pressed CTRL-O in Insert mode.
8254 static void
8255 ins_ctrl_o()
8257 #ifdef FEAT_VREPLACE
8258 if (State & VREPLACE_FLAG)
8259 restart_edit = 'V';
8260 else
8261 #endif
8262 if (State & REPLACE_FLAG)
8263 restart_edit = 'R';
8264 else
8265 restart_edit = 'I';
8266 #ifdef FEAT_VIRTUALEDIT
8267 if (virtual_active())
8268 ins_at_eol = FALSE; /* cursor always keeps its column */
8269 else
8270 #endif
8271 ins_at_eol = (gchar_cursor() == NUL);
8275 * If the cursor is on an indent, ^T/^D insert/delete one
8276 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
8277 * Always round the indent to 'shiftwidth', this is compatible
8278 * with vi. But vi only supports ^T and ^D after an
8279 * autoindent, we support it everywhere.
8281 static void
8282 ins_shift(c, lastc)
8283 int c;
8284 int lastc;
8286 if (stop_arrow() == FAIL)
8287 return;
8288 AppendCharToRedobuff(c);
8291 * 0^D and ^^D: remove all indent.
8293 if (c == Ctrl_D && (lastc == '0' || lastc == '^')
8294 && curwin->w_cursor.col > 0)
8296 --curwin->w_cursor.col;
8297 (void)del_char(FALSE); /* delete the '^' or '0' */
8298 /* In Replace mode, restore the characters that '^' or '0' replaced. */
8299 if (State & REPLACE_FLAG)
8300 replace_pop_ins();
8301 if (lastc == '^')
8302 old_indent = get_indent(); /* remember curr. indent */
8303 change_indent(INDENT_SET, 0, TRUE, 0, TRUE);
8305 else
8306 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE);
8308 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
8309 did_ai = FALSE;
8310 #ifdef FEAT_SMARTINDENT
8311 did_si = FALSE;
8312 can_si = FALSE;
8313 can_si_back = FALSE;
8314 #endif
8315 #ifdef FEAT_CINDENT
8316 can_cindent = FALSE; /* no cindenting after ^D or ^T */
8317 #endif
8320 static void
8321 ins_del()
8323 int temp;
8325 if (stop_arrow() == FAIL)
8326 return;
8327 if (gchar_cursor() == NUL) /* delete newline */
8329 temp = curwin->w_cursor.col;
8330 if (!can_bs(BS_EOL) /* only if "eol" included */
8331 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
8332 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
8333 || do_join(FALSE) == FAIL)
8334 vim_beep();
8335 else
8336 curwin->w_cursor.col = temp;
8338 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
8339 vim_beep();
8340 did_ai = FALSE;
8341 #ifdef FEAT_SMARTINDENT
8342 did_si = FALSE;
8343 can_si = FALSE;
8344 can_si_back = FALSE;
8345 #endif
8346 AppendCharToRedobuff(K_DEL);
8349 static void ins_bs_one __ARGS((colnr_T *vcolp));
8352 * Delete one character for ins_bs().
8354 static void
8355 ins_bs_one(vcolp)
8356 colnr_T *vcolp;
8358 dec_cursor();
8359 getvcol(curwin, &curwin->w_cursor, vcolp, NULL, NULL);
8360 if (State & REPLACE_FLAG)
8362 /* Don't delete characters before the insert point when in
8363 * Replace mode */
8364 if (curwin->w_cursor.lnum != Insstart.lnum
8365 || curwin->w_cursor.col >= Insstart.col)
8366 replace_do_bs(-1);
8368 else
8369 (void)del_char(FALSE);
8373 * Handle Backspace, delete-word and delete-line in Insert mode.
8374 * Return TRUE when backspace was actually used.
8376 static int
8377 ins_bs(c, mode, inserted_space_p)
8378 int c;
8379 int mode;
8380 int *inserted_space_p;
8382 linenr_T lnum;
8383 int cc;
8384 int temp = 0; /* init for GCC */
8385 colnr_T save_col;
8386 colnr_T mincol;
8387 int did_backspace = FALSE;
8388 int in_indent;
8389 int oldState;
8390 #ifdef FEAT_MBYTE
8391 int cpc[MAX_MCO]; /* composing characters */
8392 #endif
8395 * can't delete anything in an empty file
8396 * can't backup past first character in buffer
8397 * can't backup past starting point unless 'backspace' > 1
8398 * can backup to a previous line if 'backspace' == 0
8400 if ( bufempty()
8401 || (
8402 #ifdef FEAT_RIGHTLEFT
8403 !revins_on &&
8404 #endif
8405 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
8406 || (!can_bs(BS_START)
8407 && (arrow_used
8408 || (curwin->w_cursor.lnum == Insstart.lnum
8409 && curwin->w_cursor.col <= Insstart.col)))
8410 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
8411 && curwin->w_cursor.col <= ai_col)
8412 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
8414 vim_beep();
8415 return FALSE;
8418 if (stop_arrow() == FAIL)
8419 return FALSE;
8420 in_indent = inindent(0);
8421 #ifdef FEAT_CINDENT
8422 if (in_indent)
8423 can_cindent = FALSE;
8424 #endif
8425 #ifdef FEAT_COMMENTS
8426 end_comment_pending = NUL; /* After BS, don't auto-end comment */
8427 #endif
8428 #ifdef FEAT_RIGHTLEFT
8429 if (revins_on) /* put cursor after last inserted char */
8430 inc_cursor();
8431 #endif
8433 #ifdef FEAT_VIRTUALEDIT
8434 /* Virtualedit:
8435 * BACKSPACE_CHAR eats a virtual space
8436 * BACKSPACE_WORD eats all coladd
8437 * BACKSPACE_LINE eats all coladd and keeps going
8439 if (curwin->w_cursor.coladd > 0)
8441 if (mode == BACKSPACE_CHAR)
8443 --curwin->w_cursor.coladd;
8444 return TRUE;
8446 if (mode == BACKSPACE_WORD)
8448 curwin->w_cursor.coladd = 0;
8449 return TRUE;
8451 curwin->w_cursor.coladd = 0;
8453 #endif
8456 * delete newline!
8458 if (curwin->w_cursor.col == 0)
8460 lnum = Insstart.lnum;
8461 if (curwin->w_cursor.lnum == Insstart.lnum
8462 #ifdef FEAT_RIGHTLEFT
8463 || revins_on
8464 #endif
8467 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
8468 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
8469 return FALSE;
8470 --Insstart.lnum;
8471 Insstart.col = MAXCOL;
8474 * In replace mode:
8475 * cc < 0: NL was inserted, delete it
8476 * cc >= 0: NL was replaced, put original characters back
8478 cc = -1;
8479 if (State & REPLACE_FLAG)
8480 cc = replace_pop(); /* returns -1 if NL was inserted */
8482 * In replace mode, in the line we started replacing, we only move the
8483 * cursor.
8485 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
8487 dec_cursor();
8489 else
8491 #ifdef FEAT_VREPLACE
8492 if (!(State & VREPLACE_FLAG)
8493 || curwin->w_cursor.lnum > orig_line_count)
8494 #endif
8496 temp = gchar_cursor(); /* remember current char */
8497 --curwin->w_cursor.lnum;
8499 /* When "aw" is in 'formatoptions' we must delete the space at
8500 * the end of the line, otherwise the line will be broken
8501 * again when auto-formatting. */
8502 if (has_format_option(FO_AUTO)
8503 && has_format_option(FO_WHITE_PAR))
8505 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
8506 TRUE);
8507 int len;
8509 len = (int)STRLEN(ptr);
8510 if (len > 0 && ptr[len - 1] == ' ')
8511 ptr[len - 1] = NUL;
8514 (void)do_join(FALSE);
8515 if (temp == NUL && gchar_cursor() != NUL)
8516 inc_cursor();
8518 #ifdef FEAT_VREPLACE
8519 else
8520 dec_cursor();
8521 #endif
8524 * In REPLACE mode we have to put back the text that was replaced
8525 * by the NL. On the replace stack is first a NUL-terminated
8526 * sequence of characters that were deleted and then the
8527 * characters that NL replaced.
8529 if (State & REPLACE_FLAG)
8532 * Do the next ins_char() in NORMAL state, to
8533 * prevent ins_char() from replacing characters and
8534 * avoiding showmatch().
8536 oldState = State;
8537 State = NORMAL;
8539 * restore characters (blanks) deleted after cursor
8541 while (cc > 0)
8543 save_col = curwin->w_cursor.col;
8544 #ifdef FEAT_MBYTE
8545 mb_replace_pop_ins(cc);
8546 #else
8547 ins_char(cc);
8548 #endif
8549 curwin->w_cursor.col = save_col;
8550 cc = replace_pop();
8552 /* restore the characters that NL replaced */
8553 replace_pop_ins();
8554 State = oldState;
8557 did_ai = FALSE;
8559 else
8562 * Delete character(s) before the cursor.
8564 #ifdef FEAT_RIGHTLEFT
8565 if (revins_on) /* put cursor on last inserted char */
8566 dec_cursor();
8567 #endif
8568 mincol = 0;
8569 /* keep indent */
8570 if (mode == BACKSPACE_LINE
8571 && (curbuf->b_p_ai
8572 #ifdef FEAT_CINDENT
8573 || cindent_on()
8574 #endif
8576 #ifdef FEAT_RIGHTLEFT
8577 && !revins_on
8578 #endif
8581 save_col = curwin->w_cursor.col;
8582 beginline(BL_WHITE);
8583 if (curwin->w_cursor.col < save_col)
8584 mincol = curwin->w_cursor.col;
8585 curwin->w_cursor.col = save_col;
8589 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8591 if ( mode == BACKSPACE_CHAR
8592 && ((p_sta && in_indent)
8593 || (curbuf->b_p_sts != 0
8594 && curwin->w_cursor.col > 0
8595 && (*(ml_get_cursor() - 1) == TAB
8596 || (*(ml_get_cursor() - 1) == ' '
8597 && (!*inserted_space_p
8598 || arrow_used))))))
8600 int ts;
8601 colnr_T vcol;
8602 colnr_T want_vcol;
8603 colnr_T start_vcol;
8605 *inserted_space_p = FALSE;
8606 if (p_sta && in_indent)
8607 ts = curbuf->b_p_sw;
8608 else
8609 ts = curbuf->b_p_sts;
8610 /* Compute the virtual column where we want to be. Since
8611 * 'showbreak' may get in the way, need to get the last column of
8612 * the previous character. */
8613 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8614 start_vcol = vcol;
8615 dec_cursor();
8616 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8617 inc_cursor();
8618 want_vcol = (want_vcol / ts) * ts;
8620 /* delete characters until we are at or before want_vcol */
8621 while (vcol > want_vcol
8622 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8623 ins_bs_one(&vcol);
8625 /* insert extra spaces until we are at want_vcol */
8626 while (vcol < want_vcol)
8628 /* Remember the first char we inserted */
8629 if (curwin->w_cursor.lnum == Insstart.lnum
8630 && curwin->w_cursor.col < Insstart.col)
8631 Insstart.col = curwin->w_cursor.col;
8633 #ifdef FEAT_VREPLACE
8634 if (State & VREPLACE_FLAG)
8635 ins_char(' ');
8636 else
8637 #endif
8639 ins_str((char_u *)" ");
8640 if ((State & REPLACE_FLAG))
8641 replace_push(NUL);
8643 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8646 /* If we are now back where we started delete one character. Can
8647 * happen when using 'sts' and 'linebreak'. */
8648 if (vcol >= start_vcol)
8649 ins_bs_one(&vcol);
8653 * Delete upto starting point, start of line or previous word.
8655 else do
8657 #ifdef FEAT_RIGHTLEFT
8658 if (!revins_on) /* put cursor on char to be deleted */
8659 #endif
8660 dec_cursor();
8662 /* start of word? */
8663 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8665 mode = BACKSPACE_WORD_NOT_SPACE;
8666 temp = vim_iswordc(gchar_cursor());
8668 /* end of word? */
8669 else if (mode == BACKSPACE_WORD_NOT_SPACE
8670 && (vim_isspace(cc = gchar_cursor())
8671 || vim_iswordc(cc) != temp))
8673 #ifdef FEAT_RIGHTLEFT
8674 if (!revins_on)
8675 #endif
8676 inc_cursor();
8677 #ifdef FEAT_RIGHTLEFT
8678 else if (State & REPLACE_FLAG)
8679 dec_cursor();
8680 #endif
8681 break;
8683 if (State & REPLACE_FLAG)
8684 replace_do_bs(-1);
8685 else
8687 #ifdef FEAT_MBYTE
8688 if (enc_utf8 && p_deco)
8689 (void)utfc_ptr2char(ml_get_cursor(), cpc);
8690 #endif
8691 (void)del_char(FALSE);
8692 #ifdef FEAT_MBYTE
8694 * If there are combining characters and 'delcombine' is set
8695 * move the cursor back. Don't back up before the base
8696 * character.
8698 if (enc_utf8 && p_deco && cpc[0] != NUL)
8699 inc_cursor();
8700 #endif
8701 #ifdef FEAT_RIGHTLEFT
8702 if (revins_chars)
8704 revins_chars--;
8705 revins_legal++;
8707 if (revins_on && gchar_cursor() == NUL)
8708 break;
8709 #endif
8711 /* Just a single backspace?: */
8712 if (mode == BACKSPACE_CHAR)
8713 break;
8714 } while (
8715 #ifdef FEAT_RIGHTLEFT
8716 revins_on ||
8717 #endif
8718 (curwin->w_cursor.col > mincol
8719 && (curwin->w_cursor.lnum != Insstart.lnum
8720 || curwin->w_cursor.col != Insstart.col)));
8721 did_backspace = TRUE;
8723 #ifdef FEAT_SMARTINDENT
8724 did_si = FALSE;
8725 can_si = FALSE;
8726 can_si_back = FALSE;
8727 #endif
8728 if (curwin->w_cursor.col <= 1)
8729 did_ai = FALSE;
8731 * It's a little strange to put backspaces into the redo
8732 * buffer, but it makes auto-indent a lot easier to deal
8733 * with.
8735 AppendCharToRedobuff(c);
8737 /* If deleted before the insertion point, adjust it */
8738 if (curwin->w_cursor.lnum == Insstart.lnum
8739 && curwin->w_cursor.col < Insstart.col)
8740 Insstart.col = curwin->w_cursor.col;
8742 /* vi behaviour: the cursor moves backward but the character that
8743 * was there remains visible
8744 * Vim behaviour: the cursor moves backward and the character that
8745 * was there is erased from the screen.
8746 * We can emulate the vi behaviour by pretending there is a dollar
8747 * displayed even when there isn't.
8748 * --pkv Sun Jan 19 01:56:40 EST 2003 */
8749 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
8750 dollar_vcol = curwin->w_virtcol;
8752 #ifdef FEAT_FOLDING
8753 /* When deleting a char the cursor line must never be in a closed fold.
8754 * E.g., when 'foldmethod' is indent and deleting the first non-white
8755 * char before a Tab. */
8756 if (did_backspace)
8757 foldOpenCursor();
8758 #endif
8760 return did_backspace;
8763 #ifdef FEAT_MOUSE
8764 static void
8765 ins_mouse(c)
8766 int c;
8768 pos_T tpos;
8769 win_T *old_curwin = curwin;
8771 # ifdef FEAT_GUI
8772 /* When GUI is active, also move/paste when 'mouse' is empty */
8773 if (!gui.in_use)
8774 # endif
8775 if (!mouse_has(MOUSE_INSERT))
8776 return;
8778 undisplay_dollar();
8779 tpos = curwin->w_cursor;
8780 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
8782 #ifdef FEAT_WINDOWS
8783 win_T *new_curwin = curwin;
8785 if (curwin != old_curwin && win_valid(old_curwin))
8787 /* Mouse took us to another window. We need to go back to the
8788 * previous one to stop insert there properly. */
8789 curwin = old_curwin;
8790 curbuf = curwin->w_buffer;
8792 #endif
8793 start_arrow(curwin == old_curwin ? &tpos : NULL);
8794 #ifdef FEAT_WINDOWS
8795 if (curwin != new_curwin && win_valid(new_curwin))
8797 curwin = new_curwin;
8798 curbuf = curwin->w_buffer;
8800 #endif
8801 # ifdef FEAT_CINDENT
8802 can_cindent = TRUE;
8803 # endif
8806 #ifdef FEAT_WINDOWS
8807 /* redraw status lines (in case another window became active) */
8808 redraw_statuslines();
8809 #endif
8812 static void
8813 ins_mousescroll(up)
8814 int up;
8816 pos_T tpos;
8817 # if defined(FEAT_WINDOWS)
8818 win_T *old_curwin = curwin;
8819 # endif
8820 # ifdef FEAT_INS_EXPAND
8821 int did_scroll = FALSE;
8822 # endif
8824 tpos = curwin->w_cursor;
8826 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8827 /* Currently the mouse coordinates are only known in the GUI. */
8828 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
8830 int row, col;
8832 row = mouse_row;
8833 col = mouse_col;
8835 /* find the window at the pointer coordinates */
8836 curwin = mouse_find_win(&row, &col);
8837 curbuf = curwin->w_buffer;
8839 if (curwin == old_curwin)
8840 # endif
8841 undisplay_dollar();
8843 # ifdef FEAT_INS_EXPAND
8844 /* Don't scroll the window in which completion is being done. */
8845 if (!pum_visible()
8846 # if defined(FEAT_WINDOWS)
8847 || curwin != old_curwin
8848 # endif
8850 # endif
8852 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
8853 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
8854 else
8855 scroll_redraw(up, 3L);
8856 # ifdef FEAT_INS_EXPAND
8857 did_scroll = TRUE;
8858 # endif
8861 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8862 curwin->w_redr_status = TRUE;
8864 curwin = old_curwin;
8865 curbuf = curwin->w_buffer;
8866 # endif
8868 # ifdef FEAT_INS_EXPAND
8869 /* The popup menu may overlay the window, need to redraw it.
8870 * TODO: Would be more efficient to only redraw the windows that are
8871 * overlapped by the popup menu. */
8872 if (pum_visible() && did_scroll)
8874 redraw_all_later(NOT_VALID);
8875 ins_compl_show_pum();
8877 # endif
8879 if (!equalpos(curwin->w_cursor, tpos))
8881 start_arrow(&tpos);
8882 # ifdef FEAT_CINDENT
8883 can_cindent = TRUE;
8884 # endif
8887 #endif
8889 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
8890 static void
8891 ins_tabline(c)
8892 int c;
8894 /* We will be leaving the current window, unless closing another tab. */
8895 if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
8896 || (current_tab != 0 && current_tab != tabpage_index(curtab)))
8898 undisplay_dollar();
8899 start_arrow(&curwin->w_cursor);
8900 # ifdef FEAT_CINDENT
8901 can_cindent = TRUE;
8902 # endif
8905 if (c == K_TABLINE)
8906 goto_tabpage(current_tab);
8907 else
8909 handle_tabmenu();
8910 redraw_statuslines(); /* will redraw the tabline when needed */
8913 #endif
8915 #if defined(FEAT_GUI) || defined(PROTO)
8916 void
8917 ins_scroll()
8919 pos_T tpos;
8921 undisplay_dollar();
8922 tpos = curwin->w_cursor;
8923 if (gui_do_scroll())
8925 start_arrow(&tpos);
8926 # ifdef FEAT_CINDENT
8927 can_cindent = TRUE;
8928 # endif
8932 void
8933 ins_horscroll()
8935 pos_T tpos;
8937 undisplay_dollar();
8938 tpos = curwin->w_cursor;
8939 if (gui_do_horiz_scroll())
8941 start_arrow(&tpos);
8942 # ifdef FEAT_CINDENT
8943 can_cindent = TRUE;
8944 # endif
8947 #endif
8949 static void
8950 ins_left()
8952 pos_T tpos;
8954 #ifdef FEAT_FOLDING
8955 if ((fdo_flags & FDO_HOR) && KeyTyped)
8956 foldOpenCursor();
8957 #endif
8958 undisplay_dollar();
8959 tpos = curwin->w_cursor;
8960 if (oneleft() == OK)
8962 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
8963 /* Only call start_arrow() when not busy with preediting, it will
8964 * break undo. K_LEFT is inserted in im_correct_cursor(). */
8965 if (!im_is_preediting())
8966 #endif
8967 start_arrow(&tpos);
8968 #ifdef FEAT_RIGHTLEFT
8969 /* If exit reversed string, position is fixed */
8970 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
8971 revins_legal++;
8972 revins_chars++;
8973 #endif
8977 * if 'whichwrap' set for cursor in insert mode may go to
8978 * previous line
8980 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
8982 start_arrow(&tpos);
8983 --(curwin->w_cursor.lnum);
8984 coladvance((colnr_T)MAXCOL);
8985 curwin->w_set_curswant = TRUE; /* so we stay at the end */
8987 else
8988 vim_beep();
8991 static void
8992 ins_home(c)
8993 int c;
8995 pos_T tpos;
8997 #ifdef FEAT_FOLDING
8998 if ((fdo_flags & FDO_HOR) && KeyTyped)
8999 foldOpenCursor();
9000 #endif
9001 undisplay_dollar();
9002 tpos = curwin->w_cursor;
9003 if (c == K_C_HOME)
9004 curwin->w_cursor.lnum = 1;
9005 curwin->w_cursor.col = 0;
9006 #ifdef FEAT_VIRTUALEDIT
9007 curwin->w_cursor.coladd = 0;
9008 #endif
9009 curwin->w_curswant = 0;
9010 start_arrow(&tpos);
9013 static void
9014 ins_end(c)
9015 int c;
9017 pos_T tpos;
9019 #ifdef FEAT_FOLDING
9020 if ((fdo_flags & FDO_HOR) && KeyTyped)
9021 foldOpenCursor();
9022 #endif
9023 undisplay_dollar();
9024 tpos = curwin->w_cursor;
9025 if (c == K_C_END)
9026 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9027 coladvance((colnr_T)MAXCOL);
9028 curwin->w_curswant = MAXCOL;
9030 start_arrow(&tpos);
9033 static void
9034 ins_s_left()
9036 #ifdef FEAT_FOLDING
9037 if ((fdo_flags & FDO_HOR) && KeyTyped)
9038 foldOpenCursor();
9039 #endif
9040 undisplay_dollar();
9041 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
9043 start_arrow(&curwin->w_cursor);
9044 (void)bck_word(1L, FALSE, FALSE);
9045 curwin->w_set_curswant = TRUE;
9047 else
9048 vim_beep();
9051 static void
9052 ins_right()
9054 #ifdef FEAT_FOLDING
9055 if ((fdo_flags & FDO_HOR) && KeyTyped)
9056 foldOpenCursor();
9057 #endif
9058 undisplay_dollar();
9059 if (gchar_cursor() != NUL
9060 #ifdef FEAT_VIRTUALEDIT
9061 || virtual_active()
9062 #endif
9065 start_arrow(&curwin->w_cursor);
9066 curwin->w_set_curswant = TRUE;
9067 #ifdef FEAT_VIRTUALEDIT
9068 if (virtual_active())
9069 oneright();
9070 else
9071 #endif
9073 #ifdef FEAT_MBYTE
9074 if (has_mbyte)
9075 curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
9076 else
9077 #endif
9078 ++curwin->w_cursor.col;
9081 #ifdef FEAT_RIGHTLEFT
9082 revins_legal++;
9083 if (revins_chars)
9084 revins_chars--;
9085 #endif
9087 /* if 'whichwrap' set for cursor in insert mode, may move the
9088 * cursor to the next line */
9089 else if (vim_strchr(p_ww, ']') != NULL
9090 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
9092 start_arrow(&curwin->w_cursor);
9093 curwin->w_set_curswant = TRUE;
9094 ++curwin->w_cursor.lnum;
9095 curwin->w_cursor.col = 0;
9097 else
9098 vim_beep();
9101 static void
9102 ins_s_right()
9104 #ifdef FEAT_FOLDING
9105 if ((fdo_flags & FDO_HOR) && KeyTyped)
9106 foldOpenCursor();
9107 #endif
9108 undisplay_dollar();
9109 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
9110 || gchar_cursor() != NUL)
9112 start_arrow(&curwin->w_cursor);
9113 (void)fwd_word(1L, FALSE, 0);
9114 curwin->w_set_curswant = TRUE;
9116 else
9117 vim_beep();
9120 static void
9121 ins_up(startcol)
9122 int startcol; /* when TRUE move to Insstart.col */
9124 pos_T tpos;
9125 linenr_T old_topline = curwin->w_topline;
9126 #ifdef FEAT_DIFF
9127 int old_topfill = curwin->w_topfill;
9128 #endif
9130 undisplay_dollar();
9131 tpos = curwin->w_cursor;
9132 if (cursor_up(1L, TRUE) == OK)
9134 if (startcol)
9135 coladvance(getvcol_nolist(&Insstart));
9136 if (old_topline != curwin->w_topline
9137 #ifdef FEAT_DIFF
9138 || old_topfill != curwin->w_topfill
9139 #endif
9141 redraw_later(VALID);
9142 start_arrow(&tpos);
9143 #ifdef FEAT_CINDENT
9144 can_cindent = TRUE;
9145 #endif
9147 else
9148 vim_beep();
9151 static void
9152 ins_pageup()
9154 pos_T tpos;
9156 undisplay_dollar();
9158 #ifdef FEAT_WINDOWS
9159 if (mod_mask & MOD_MASK_CTRL)
9161 /* <C-PageUp>: tab page back */
9162 if (first_tabpage->tp_next != NULL)
9164 start_arrow(&curwin->w_cursor);
9165 goto_tabpage(-1);
9167 return;
9169 #endif
9171 tpos = curwin->w_cursor;
9172 if (onepage(BACKWARD, 1L) == OK)
9174 start_arrow(&tpos);
9175 #ifdef FEAT_CINDENT
9176 can_cindent = TRUE;
9177 #endif
9179 else
9180 vim_beep();
9183 static void
9184 ins_down(startcol)
9185 int startcol; /* when TRUE move to Insstart.col */
9187 pos_T tpos;
9188 linenr_T old_topline = curwin->w_topline;
9189 #ifdef FEAT_DIFF
9190 int old_topfill = curwin->w_topfill;
9191 #endif
9193 undisplay_dollar();
9194 tpos = curwin->w_cursor;
9195 if (cursor_down(1L, TRUE) == OK)
9197 if (startcol)
9198 coladvance(getvcol_nolist(&Insstart));
9199 if (old_topline != curwin->w_topline
9200 #ifdef FEAT_DIFF
9201 || old_topfill != curwin->w_topfill
9202 #endif
9204 redraw_later(VALID);
9205 start_arrow(&tpos);
9206 #ifdef FEAT_CINDENT
9207 can_cindent = TRUE;
9208 #endif
9210 else
9211 vim_beep();
9214 static void
9215 ins_pagedown()
9217 pos_T tpos;
9219 undisplay_dollar();
9221 #ifdef FEAT_WINDOWS
9222 if (mod_mask & MOD_MASK_CTRL)
9224 /* <C-PageDown>: tab page forward */
9225 if (first_tabpage->tp_next != NULL)
9227 start_arrow(&curwin->w_cursor);
9228 goto_tabpage(0);
9230 return;
9232 #endif
9234 tpos = curwin->w_cursor;
9235 if (onepage(FORWARD, 1L) == OK)
9237 start_arrow(&tpos);
9238 #ifdef FEAT_CINDENT
9239 can_cindent = TRUE;
9240 #endif
9242 else
9243 vim_beep();
9246 #ifdef FEAT_DND
9247 static void
9248 ins_drop()
9250 do_put('~', BACKWARD, 1L, PUT_CURSEND);
9252 #endif
9255 * Handle TAB in Insert or Replace mode.
9256 * Return TRUE when the TAB needs to be inserted like a normal character.
9258 static int
9259 ins_tab()
9261 int ind;
9262 int i;
9263 int temp;
9265 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
9266 Insstart_blank_vcol = get_nolist_virtcol();
9267 if (echeck_abbr(TAB + ABBR_OFF))
9268 return FALSE;
9270 ind = inindent(0);
9271 #ifdef FEAT_CINDENT
9272 if (ind)
9273 can_cindent = FALSE;
9274 #endif
9277 * When nothing special, insert TAB like a normal character
9279 if (!curbuf->b_p_et
9280 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
9281 && curbuf->b_p_sts == 0)
9282 return TRUE;
9284 if (stop_arrow() == FAIL)
9285 return TRUE;
9287 did_ai = FALSE;
9288 #ifdef FEAT_SMARTINDENT
9289 did_si = FALSE;
9290 can_si = FALSE;
9291 can_si_back = FALSE;
9292 #endif
9293 AppendToRedobuff((char_u *)"\t");
9295 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9296 temp = (int)curbuf->b_p_sw;
9297 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
9298 temp = (int)curbuf->b_p_sts;
9299 else /* otherwise use 'tabstop' */
9300 temp = (int)curbuf->b_p_ts;
9301 temp -= get_nolist_virtcol() % temp;
9304 * Insert the first space with ins_char(). It will delete one char in
9305 * replace mode. Insert the rest with ins_str(); it will not delete any
9306 * chars. For VREPLACE mode, we use ins_char() for all characters.
9308 ins_char(' ');
9309 while (--temp > 0)
9311 #ifdef FEAT_VREPLACE
9312 if (State & VREPLACE_FLAG)
9313 ins_char(' ');
9314 else
9315 #endif
9317 ins_str((char_u *)" ");
9318 if (State & REPLACE_FLAG) /* no char replaced */
9319 replace_push(NUL);
9324 * When 'expandtab' not set: Replace spaces by TABs where possible.
9326 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
9328 char_u *ptr;
9329 #ifdef FEAT_VREPLACE
9330 char_u *saved_line = NULL; /* init for GCC */
9331 pos_T pos;
9332 #endif
9333 pos_T fpos;
9334 pos_T *cursor;
9335 colnr_T want_vcol, vcol;
9336 int change_col = -1;
9337 int save_list = curwin->w_p_list;
9340 * Get the current line. For VREPLACE mode, don't make real changes
9341 * yet, just work on a copy of the line.
9343 #ifdef FEAT_VREPLACE
9344 if (State & VREPLACE_FLAG)
9346 pos = curwin->w_cursor;
9347 cursor = &pos;
9348 saved_line = vim_strsave(ml_get_curline());
9349 if (saved_line == NULL)
9350 return FALSE;
9351 ptr = saved_line + pos.col;
9353 else
9354 #endif
9356 ptr = ml_get_cursor();
9357 cursor = &curwin->w_cursor;
9360 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
9361 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9362 curwin->w_p_list = FALSE;
9364 /* Find first white before the cursor */
9365 fpos = curwin->w_cursor;
9366 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
9368 --fpos.col;
9369 --ptr;
9372 /* In Replace mode, don't change characters before the insert point. */
9373 if ((State & REPLACE_FLAG)
9374 && fpos.lnum == Insstart.lnum
9375 && fpos.col < Insstart.col)
9377 ptr += Insstart.col - fpos.col;
9378 fpos.col = Insstart.col;
9381 /* compute virtual column numbers of first white and cursor */
9382 getvcol(curwin, &fpos, &vcol, NULL, NULL);
9383 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
9385 /* Use as many TABs as possible. Beware of 'showbreak' and
9386 * 'linebreak' adding extra virtual columns. */
9387 while (vim_iswhite(*ptr))
9389 i = lbr_chartabsize((char_u *)"\t", vcol);
9390 if (vcol + i > want_vcol)
9391 break;
9392 if (*ptr != TAB)
9394 *ptr = TAB;
9395 if (change_col < 0)
9397 change_col = fpos.col; /* Column of first change */
9398 /* May have to adjust Insstart */
9399 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
9400 Insstart.col = fpos.col;
9403 ++fpos.col;
9404 ++ptr;
9405 vcol += i;
9408 if (change_col >= 0)
9410 int repl_off = 0;
9412 /* Skip over the spaces we need. */
9413 while (vcol < want_vcol && *ptr == ' ')
9415 vcol += lbr_chartabsize(ptr, vcol);
9416 ++ptr;
9417 ++repl_off;
9419 if (vcol > want_vcol)
9421 /* Must have a char with 'showbreak' just before it. */
9422 --ptr;
9423 --repl_off;
9425 fpos.col += repl_off;
9427 /* Delete following spaces. */
9428 i = cursor->col - fpos.col;
9429 if (i > 0)
9431 STRMOVE(ptr, ptr + i);
9432 /* correct replace stack. */
9433 if ((State & REPLACE_FLAG)
9434 #ifdef FEAT_VREPLACE
9435 && !(State & VREPLACE_FLAG)
9436 #endif
9438 for (temp = i; --temp >= 0; )
9439 replace_join(repl_off);
9441 #ifdef FEAT_NETBEANS_INTG
9442 if (usingNetbeans)
9444 netbeans_removed(curbuf, fpos.lnum, cursor->col,
9445 (long)(i + 1));
9446 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
9447 (char_u *)"\t", 1);
9449 #endif
9450 cursor->col -= i;
9452 #ifdef FEAT_VREPLACE
9454 * In VREPLACE mode, we haven't changed anything yet. Do it now by
9455 * backspacing over the changed spacing and then inserting the new
9456 * spacing.
9458 if (State & VREPLACE_FLAG)
9460 /* Backspace from real cursor to change_col */
9461 backspace_until_column(change_col);
9463 /* Insert each char in saved_line from changed_col to
9464 * ptr-cursor */
9465 ins_bytes_len(saved_line + change_col,
9466 cursor->col - change_col);
9468 #endif
9471 #ifdef FEAT_VREPLACE
9472 if (State & VREPLACE_FLAG)
9473 vim_free(saved_line);
9474 #endif
9475 curwin->w_p_list = save_list;
9478 return FALSE;
9482 * Handle CR or NL in insert mode.
9483 * Return TRUE when out of memory or can't undo.
9485 static int
9486 ins_eol(c)
9487 int c;
9489 int i;
9491 if (echeck_abbr(c + ABBR_OFF))
9492 return FALSE;
9493 if (stop_arrow() == FAIL)
9494 return TRUE;
9495 undisplay_dollar();
9498 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
9499 * character under the cursor. Only push a NUL on the replace stack,
9500 * nothing to put back when the NL is deleted.
9502 if ((State & REPLACE_FLAG)
9503 #ifdef FEAT_VREPLACE
9504 && !(State & VREPLACE_FLAG)
9505 #endif
9507 replace_push(NUL);
9510 * In VREPLACE mode, a NL replaces the rest of the line, and starts
9511 * replacing the next line, so we push all of the characters left on the
9512 * line onto the replace stack. This is not done here though, it is done
9513 * in open_line().
9516 #ifdef FEAT_VIRTUALEDIT
9517 /* Put cursor on NUL if on the last char and coladd is 1 (happens after
9518 * CTRL-O). */
9519 if (virtual_active() && curwin->w_cursor.coladd > 0)
9520 coladvance(getviscol());
9521 #endif
9523 #ifdef FEAT_RIGHTLEFT
9524 # ifdef FEAT_FKMAP
9525 if (p_altkeymap && p_fkmap)
9526 fkmap(NL);
9527 # endif
9528 /* NL in reverse insert will always start in the end of
9529 * current line. */
9530 if (revins_on)
9531 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9532 #endif
9534 AppendToRedobuff(NL_STR);
9535 i = open_line(FORWARD,
9536 #ifdef FEAT_COMMENTS
9537 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
9538 #endif
9539 0, old_indent);
9540 old_indent = 0;
9541 #ifdef FEAT_CINDENT
9542 can_cindent = TRUE;
9543 #endif
9544 #ifdef FEAT_FOLDING
9545 /* When inserting a line the cursor line must never be in a closed fold. */
9546 foldOpenCursor();
9547 #endif
9549 return (!i);
9552 #ifdef FEAT_DIGRAPHS
9554 * Handle digraph in insert mode.
9555 * Returns character still to be inserted, or NUL when nothing remaining to be
9556 * done.
9558 static int
9559 ins_digraph()
9561 int c;
9562 int cc;
9564 pc_status = PC_STATUS_UNSET;
9565 if (redrawing() && !char_avail())
9567 /* may need to redraw when no more chars available now */
9568 ins_redraw(FALSE);
9570 edit_putchar('?', TRUE);
9571 #ifdef FEAT_CMDL_INFO
9572 add_to_showcmd_c(Ctrl_K);
9573 #endif
9576 #ifdef USE_ON_FLY_SCROLL
9577 dont_scroll = TRUE; /* disallow scrolling here */
9578 #endif
9580 /* don't map the digraph chars. This also prevents the
9581 * mode message to be deleted when ESC is hit */
9582 ++no_mapping;
9583 ++allow_keys;
9584 c = plain_vgetc();
9585 --no_mapping;
9586 --allow_keys;
9587 if (IS_SPECIAL(c) || mod_mask) /* special key */
9589 #ifdef FEAT_CMDL_INFO
9590 clear_showcmd();
9591 #endif
9592 insert_special(c, TRUE, FALSE);
9593 return NUL;
9595 if (c != ESC)
9597 if (redrawing() && !char_avail())
9599 /* may need to redraw when no more chars available now */
9600 ins_redraw(FALSE);
9602 if (char2cells(c) == 1)
9604 /* first remove the '?', otherwise it's restored when typing
9605 * an ESC next */
9606 edit_unputchar();
9607 ins_redraw(FALSE);
9608 edit_putchar(c, TRUE);
9610 #ifdef FEAT_CMDL_INFO
9611 add_to_showcmd_c(c);
9612 #endif
9614 ++no_mapping;
9615 ++allow_keys;
9616 cc = plain_vgetc();
9617 --no_mapping;
9618 --allow_keys;
9619 if (cc != ESC)
9621 AppendToRedobuff((char_u *)CTRL_V_STR);
9622 c = getdigraph(c, cc, TRUE);
9623 #ifdef FEAT_CMDL_INFO
9624 clear_showcmd();
9625 #endif
9626 return c;
9629 edit_unputchar();
9630 #ifdef FEAT_CMDL_INFO
9631 clear_showcmd();
9632 #endif
9633 return NUL;
9635 #endif
9638 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9639 * Returns the char to be inserted, or NUL if none found.
9641 static int
9642 ins_copychar(lnum)
9643 linenr_T lnum;
9645 int c;
9646 int temp;
9647 char_u *ptr, *prev_ptr;
9649 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9651 vim_beep();
9652 return NUL;
9655 /* try to advance to the cursor column */
9656 temp = 0;
9657 ptr = ml_get(lnum);
9658 prev_ptr = ptr;
9659 validate_virtcol();
9660 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9662 prev_ptr = ptr;
9663 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
9665 if ((colnr_T)temp > curwin->w_virtcol)
9666 ptr = prev_ptr;
9668 #ifdef FEAT_MBYTE
9669 c = (*mb_ptr2char)(ptr);
9670 #else
9671 c = *ptr;
9672 #endif
9673 if (c == NUL)
9674 vim_beep();
9675 return c;
9679 * CTRL-Y or CTRL-E typed in Insert mode.
9681 static int
9682 ins_ctrl_ey(tc)
9683 int tc;
9685 int c = tc;
9687 #ifdef FEAT_INS_EXPAND
9688 if (ctrl_x_mode == CTRL_X_SCROLL)
9690 if (c == Ctrl_Y)
9691 scrolldown_clamp();
9692 else
9693 scrollup_clamp();
9694 redraw_later(VALID);
9696 else
9697 #endif
9699 c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
9700 if (c != NUL)
9702 long tw_save;
9704 /* The character must be taken literally, insert like it
9705 * was typed after a CTRL-V, and pretend 'textwidth'
9706 * wasn't set. Digits, 'o' and 'x' are special after a
9707 * CTRL-V, don't use it for these. */
9708 if (c < 256 && !isalnum(c))
9709 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
9710 tw_save = curbuf->b_p_tw;
9711 curbuf->b_p_tw = -1;
9712 insert_special(c, TRUE, FALSE);
9713 curbuf->b_p_tw = tw_save;
9714 #ifdef FEAT_RIGHTLEFT
9715 revins_chars++;
9716 revins_legal++;
9717 #endif
9718 c = Ctrl_V; /* pretend CTRL-V is last character */
9719 auto_format(FALSE, TRUE);
9722 return c;
9725 #ifdef FEAT_SMARTINDENT
9727 * Try to do some very smart auto-indenting.
9728 * Used when inserting a "normal" character.
9730 static void
9731 ins_try_si(c)
9732 int c;
9734 pos_T *pos, old_pos;
9735 char_u *ptr;
9736 int i;
9737 int temp;
9740 * do some very smart indenting when entering '{' or '}'
9742 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
9745 * for '}' set indent equal to indent of line containing matching '{'
9747 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
9749 old_pos = curwin->w_cursor;
9751 * If the matching '{' has a ')' immediately before it (ignoring
9752 * white-space), then line up with the start of the line
9753 * containing the matching '(' if there is one. This handles the
9754 * case where an "if (..\n..) {" statement continues over multiple
9755 * lines -- webb
9757 ptr = ml_get(pos->lnum);
9758 i = pos->col;
9759 if (i > 0) /* skip blanks before '{' */
9760 while (--i > 0 && vim_iswhite(ptr[i]))
9762 curwin->w_cursor.lnum = pos->lnum;
9763 curwin->w_cursor.col = i;
9764 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
9765 curwin->w_cursor = *pos;
9766 i = get_indent();
9767 curwin->w_cursor = old_pos;
9768 #ifdef FEAT_VREPLACE
9769 if (State & VREPLACE_FLAG)
9770 change_indent(INDENT_SET, i, FALSE, NUL, TRUE);
9771 else
9772 #endif
9773 (void)set_indent(i, SIN_CHANGED);
9775 else if (curwin->w_cursor.col > 0)
9778 * when inserting '{' after "O" reduce indent, but not
9779 * more than indent of previous line
9781 temp = TRUE;
9782 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
9784 old_pos = curwin->w_cursor;
9785 i = get_indent();
9786 while (curwin->w_cursor.lnum > 1)
9788 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
9790 /* ignore empty lines and lines starting with '#'. */
9791 if (*ptr != '#' && *ptr != NUL)
9792 break;
9794 if (get_indent() >= i)
9795 temp = FALSE;
9796 curwin->w_cursor = old_pos;
9798 if (temp)
9799 shift_line(TRUE, FALSE, 1, TRUE);
9804 * set indent of '#' always to 0
9806 if (curwin->w_cursor.col > 0 && can_si && c == '#')
9808 /* remember current indent for next line */
9809 old_indent = get_indent();
9810 (void)set_indent(0, SIN_CHANGED);
9813 /* Adjust ai_col, the char at this position can be deleted. */
9814 if (ai_col > curwin->w_cursor.col)
9815 ai_col = curwin->w_cursor.col;
9817 #endif
9820 * Get the value that w_virtcol would have when 'list' is off.
9821 * Unless 'cpo' contains the 'L' flag.
9823 static colnr_T
9824 get_nolist_virtcol()
9826 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9827 return getvcol_nolist(&curwin->w_cursor);
9828 validate_virtcol();
9829 return curwin->w_virtcol;