Merge branch 'vim'
[MacVim.git] / src / edit.c
blob3bdd143a8eb3109e884365df0e6db27b24d916f5
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 *wca; /* Wide character array. */
2168 int has_lower = FALSE;
2169 int was_letter = FALSE;
2171 if (p_ic && curbuf->b_p_inf && len > 0)
2173 /* Infer case of completed part. */
2175 /* Find actual length of completion. */
2176 #ifdef FEAT_MBYTE
2177 if (has_mbyte)
2179 p = str;
2180 actual_len = 0;
2181 while (*p != NUL)
2183 mb_ptr_adv(p);
2184 ++actual_len;
2187 else
2188 #endif
2189 actual_len = len;
2191 /* Find actual length of original text. */
2192 #ifdef FEAT_MBYTE
2193 if (has_mbyte)
2195 p = compl_orig_text;
2196 actual_compl_length = 0;
2197 while (*p != NUL)
2199 mb_ptr_adv(p);
2200 ++actual_compl_length;
2203 else
2204 #endif
2205 actual_compl_length = compl_length;
2207 /* Allocate wide character array for the completion and fill it. */
2208 wca = (int *)alloc((unsigned)(actual_len * sizeof(int)));
2209 if (wca != NULL)
2211 p = str;
2212 for (i = 0; i < actual_len; ++i)
2213 #ifdef FEAT_MBYTE
2214 if (has_mbyte)
2215 wca[i] = mb_ptr2char_adv(&p);
2216 else
2217 #endif
2218 wca[i] = *(p++);
2220 /* Rule 1: Were any chars converted to lower? */
2221 p = compl_orig_text;
2222 for (i = 0; i < actual_compl_length; ++i)
2224 #ifdef FEAT_MBYTE
2225 if (has_mbyte)
2226 c = mb_ptr2char_adv(&p);
2227 else
2228 #endif
2229 c = *(p++);
2230 if (MB_ISLOWER(c))
2232 has_lower = TRUE;
2233 if (MB_ISUPPER(wca[i]))
2235 /* Rule 1 is satisfied. */
2236 for (i = actual_compl_length; i < actual_len; ++i)
2237 wca[i] = MB_TOLOWER(wca[i]);
2238 break;
2244 * Rule 2: No lower case, 2nd consecutive letter converted to
2245 * upper case.
2247 if (!has_lower)
2249 p = compl_orig_text;
2250 for (i = 0; i < actual_compl_length; ++i)
2252 #ifdef FEAT_MBYTE
2253 if (has_mbyte)
2254 c = mb_ptr2char_adv(&p);
2255 else
2256 #endif
2257 c = *(p++);
2258 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
2260 /* Rule 2 is satisfied. */
2261 for (i = actual_compl_length; i < actual_len; ++i)
2262 wca[i] = MB_TOUPPER(wca[i]);
2263 break;
2265 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
2269 /* Copy the original case of the part we typed. */
2270 p = compl_orig_text;
2271 for (i = 0; i < actual_compl_length; ++i)
2273 #ifdef FEAT_MBYTE
2274 if (has_mbyte)
2275 c = mb_ptr2char_adv(&p);
2276 else
2277 #endif
2278 c = *(p++);
2279 if (MB_ISLOWER(c))
2280 wca[i] = MB_TOLOWER(wca[i]);
2281 else if (MB_ISUPPER(c))
2282 wca[i] = MB_TOUPPER(wca[i]);
2286 * Generate encoding specific output from wide character array.
2287 * Multi-byte characters can occupy up to five bytes more than
2288 * ASCII characters, and we also need one byte for NUL, so stay
2289 * six bytes away from the edge of IObuff.
2291 p = IObuff;
2292 i = 0;
2293 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
2294 #ifdef FEAT_MBYTE
2295 if (has_mbyte)
2296 p += (*mb_char2bytes)(wca[i++], p);
2297 else
2298 #endif
2299 *(p++) = wca[i++];
2300 *p = NUL;
2302 vim_free(wca);
2305 return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2306 flags, FALSE);
2308 return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2312 * Add a match to the list of matches.
2313 * If the given string is already in the list of completions, then return
2314 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2315 * maybe because alloc() returns NULL, then FAIL is returned.
2317 static int
2318 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup)
2319 char_u *str;
2320 int len;
2321 int icase;
2322 char_u *fname;
2323 char_u **cptext; /* extra text for popup menu or NULL */
2324 int cdir;
2325 int flags;
2326 int adup; /* accept duplicate match */
2328 compl_T *match;
2329 int dir = (cdir == 0 ? compl_direction : cdir);
2331 ui_breakcheck();
2332 if (got_int)
2333 return FAIL;
2334 if (len < 0)
2335 len = (int)STRLEN(str);
2338 * If the same match is already present, don't add it.
2340 if (compl_first_match != NULL && !adup)
2342 match = compl_first_match;
2345 if ( !(match->cp_flags & ORIGINAL_TEXT)
2346 && STRNCMP(match->cp_str, str, len) == 0
2347 && match->cp_str[len] == NUL)
2348 return NOTDONE;
2349 match = match->cp_next;
2350 } while (match != NULL && match != compl_first_match);
2353 /* Remove any popup menu before changing the list of matches. */
2354 ins_compl_del_pum();
2357 * Allocate a new match structure.
2358 * Copy the values to the new match structure.
2360 match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2361 if (match == NULL)
2362 return FAIL;
2363 match->cp_number = -1;
2364 if (flags & ORIGINAL_TEXT)
2365 match->cp_number = 0;
2366 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2368 vim_free(match);
2369 return FAIL;
2371 match->cp_icase = icase;
2373 /* match-fname is:
2374 * - compl_curr_match->cp_fname if it is a string equal to fname.
2375 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2376 * - NULL otherwise. --Acevedo */
2377 if (fname != NULL
2378 && compl_curr_match != NULL
2379 && compl_curr_match->cp_fname != NULL
2380 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2381 match->cp_fname = compl_curr_match->cp_fname;
2382 else if (fname != NULL)
2384 match->cp_fname = vim_strsave(fname);
2385 flags |= FREE_FNAME;
2387 else
2388 match->cp_fname = NULL;
2389 match->cp_flags = flags;
2391 if (cptext != NULL)
2393 int i;
2395 for (i = 0; i < CPT_COUNT; ++i)
2396 if (cptext[i] != NULL && *cptext[i] != NUL)
2397 match->cp_text[i] = vim_strsave(cptext[i]);
2401 * Link the new match structure in the list of matches.
2403 if (compl_first_match == NULL)
2404 match->cp_next = match->cp_prev = NULL;
2405 else if (dir == FORWARD)
2407 match->cp_next = compl_curr_match->cp_next;
2408 match->cp_prev = compl_curr_match;
2410 else /* BACKWARD */
2412 match->cp_next = compl_curr_match;
2413 match->cp_prev = compl_curr_match->cp_prev;
2415 if (match->cp_next)
2416 match->cp_next->cp_prev = match;
2417 if (match->cp_prev)
2418 match->cp_prev->cp_next = match;
2419 else /* if there's nothing before, it is the first match */
2420 compl_first_match = match;
2421 compl_curr_match = match;
2424 * Find the longest common string if still doing that.
2426 if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2427 ins_compl_longest_match(match);
2429 return OK;
2433 * Return TRUE if "str[len]" matches with match->cp_str, considering
2434 * match->cp_icase.
2436 static int
2437 ins_compl_equal(match, str, len)
2438 compl_T *match;
2439 char_u *str;
2440 int len;
2442 if (match->cp_icase)
2443 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2444 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2448 * Reduce the longest common string for match "match".
2450 static void
2451 ins_compl_longest_match(match)
2452 compl_T *match;
2454 char_u *p, *s;
2455 int c1, c2;
2456 int had_match;
2458 if (compl_leader == NULL)
2460 /* First match, use it as a whole. */
2461 compl_leader = vim_strsave(match->cp_str);
2462 if (compl_leader != NULL)
2464 had_match = (curwin->w_cursor.col > compl_col);
2465 ins_compl_delete();
2466 ins_bytes(compl_leader + ins_compl_len());
2467 ins_redraw(FALSE);
2469 /* When the match isn't there (to avoid matching itself) remove it
2470 * again after redrawing. */
2471 if (!had_match)
2472 ins_compl_delete();
2473 compl_used_match = FALSE;
2476 else
2478 /* Reduce the text if this match differs from compl_leader. */
2479 p = compl_leader;
2480 s = match->cp_str;
2481 while (*p != NUL)
2483 #ifdef FEAT_MBYTE
2484 if (has_mbyte)
2486 c1 = mb_ptr2char(p);
2487 c2 = mb_ptr2char(s);
2489 else
2490 #endif
2492 c1 = *p;
2493 c2 = *s;
2495 if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2496 : (c1 != c2))
2497 break;
2498 #ifdef FEAT_MBYTE
2499 if (has_mbyte)
2501 mb_ptr_adv(p);
2502 mb_ptr_adv(s);
2504 else
2505 #endif
2507 ++p;
2508 ++s;
2512 if (*p != NUL)
2514 /* Leader was shortened, need to change the inserted text. */
2515 *p = NUL;
2516 had_match = (curwin->w_cursor.col > compl_col);
2517 ins_compl_delete();
2518 ins_bytes(compl_leader + ins_compl_len());
2519 ins_redraw(FALSE);
2521 /* When the match isn't there (to avoid matching itself) remove it
2522 * again after redrawing. */
2523 if (!had_match)
2524 ins_compl_delete();
2527 compl_used_match = FALSE;
2532 * Add an array of matches to the list of matches.
2533 * Frees matches[].
2535 static void
2536 ins_compl_add_matches(num_matches, matches, icase)
2537 int num_matches;
2538 char_u **matches;
2539 int icase;
2541 int i;
2542 int add_r = OK;
2543 int dir = compl_direction;
2545 for (i = 0; i < num_matches && add_r != FAIL; i++)
2546 if ((add_r = ins_compl_add(matches[i], -1, icase,
2547 NULL, NULL, dir, 0, FALSE)) == OK)
2548 /* if dir was BACKWARD then honor it just once */
2549 dir = FORWARD;
2550 FreeWild(num_matches, matches);
2553 /* Make the completion list cyclic.
2554 * Return the number of matches (excluding the original).
2556 static int
2557 ins_compl_make_cyclic()
2559 compl_T *match;
2560 int count = 0;
2562 if (compl_first_match != NULL)
2565 * Find the end of the list.
2567 match = compl_first_match;
2568 /* there's always an entry for the compl_orig_text, it doesn't count. */
2569 while (match->cp_next != NULL && match->cp_next != compl_first_match)
2571 match = match->cp_next;
2572 ++count;
2574 match->cp_next = compl_first_match;
2575 compl_first_match->cp_prev = match;
2577 return count;
2581 * Start completion for the complete() function.
2582 * "startcol" is where the matched text starts (1 is first column).
2583 * "list" is the list of matches.
2585 void
2586 set_completion(startcol, list)
2587 colnr_T startcol;
2588 list_T *list;
2590 /* If already doing completions stop it. */
2591 if (ctrl_x_mode != 0)
2592 ins_compl_prep(' ');
2593 ins_compl_clear();
2595 if (stop_arrow() == FAIL)
2596 return;
2598 if (startcol > curwin->w_cursor.col)
2599 startcol = curwin->w_cursor.col;
2600 compl_col = startcol;
2601 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2602 /* compl_pattern doesn't need to be set */
2603 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2604 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2605 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2606 return;
2608 /* Handle like dictionary completion. */
2609 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2611 ins_compl_add_list(list);
2612 compl_matches = ins_compl_make_cyclic();
2613 compl_started = TRUE;
2614 compl_used_match = TRUE;
2615 compl_cont_status = 0;
2617 compl_curr_match = compl_first_match;
2618 ins_complete(Ctrl_N);
2619 out_flush();
2623 /* "compl_match_array" points the currently displayed list of entries in the
2624 * popup menu. It is NULL when there is no popup menu. */
2625 static pumitem_T *compl_match_array = NULL;
2626 static int compl_match_arraysize;
2629 * Update the screen and when there is any scrolling remove the popup menu.
2631 static void
2632 ins_compl_upd_pum()
2634 int h;
2636 if (compl_match_array != NULL)
2638 h = curwin->w_cline_height;
2639 update_screen(0);
2640 if (h != curwin->w_cline_height)
2641 ins_compl_del_pum();
2646 * Remove any popup menu.
2648 static void
2649 ins_compl_del_pum()
2651 if (compl_match_array != NULL)
2653 pum_undisplay();
2654 vim_free(compl_match_array);
2655 compl_match_array = NULL;
2660 * Return TRUE if the popup menu should be displayed.
2662 static int
2663 pum_wanted()
2665 /* 'completeopt' must contain "menu" or "menuone" */
2666 if (vim_strchr(p_cot, 'm') == NULL)
2667 return FALSE;
2669 /* The display looks bad on a B&W display. */
2670 if (t_colors < 8
2671 #ifdef FEAT_GUI
2672 && !gui.in_use
2673 #endif
2675 return FALSE;
2676 return TRUE;
2680 * Return TRUE if there are two or more matches to be shown in the popup menu.
2681 * One if 'completopt' contains "menuone".
2683 static int
2684 pum_enough_matches()
2686 compl_T *compl;
2687 int i;
2689 /* Don't display the popup menu if there are no matches or there is only
2690 * one (ignoring the original text). */
2691 compl = compl_first_match;
2692 i = 0;
2695 if (compl == NULL
2696 || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2697 break;
2698 compl = compl->cp_next;
2699 } while (compl != compl_first_match);
2701 if (strstr((char *)p_cot, "menuone") != NULL)
2702 return (i >= 1);
2703 return (i >= 2);
2707 * Show the popup menu for the list of matches.
2708 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2710 void
2711 ins_compl_show_pum()
2713 compl_T *compl;
2714 compl_T *shown_compl = NULL;
2715 int did_find_shown_match = FALSE;
2716 int shown_match_ok = FALSE;
2717 int i;
2718 int cur = -1;
2719 colnr_T col;
2720 int lead_len = 0;
2722 if (!pum_wanted() || !pum_enough_matches())
2723 return;
2725 #if defined(FEAT_EVAL)
2726 /* Dirty hard-coded hack: remove any matchparen highlighting. */
2727 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2728 #endif
2730 /* Update the screen before drawing the popup menu over it. */
2731 update_screen(0);
2733 if (compl_match_array == NULL)
2735 /* Need to build the popup menu list. */
2736 compl_match_arraysize = 0;
2737 compl = compl_first_match;
2738 if (compl_leader != NULL)
2739 lead_len = (int)STRLEN(compl_leader);
2742 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2743 && (compl_leader == NULL
2744 || ins_compl_equal(compl, compl_leader, lead_len)))
2745 ++compl_match_arraysize;
2746 compl = compl->cp_next;
2747 } while (compl != NULL && compl != compl_first_match);
2748 if (compl_match_arraysize == 0)
2749 return;
2750 compl_match_array = (pumitem_T *)alloc_clear(
2751 (unsigned)(sizeof(pumitem_T)
2752 * compl_match_arraysize));
2753 if (compl_match_array != NULL)
2755 /* If the current match is the original text don't find the first
2756 * match after it, don't highlight anything. */
2757 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2758 shown_match_ok = TRUE;
2760 i = 0;
2761 compl = compl_first_match;
2764 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2765 && (compl_leader == NULL
2766 || ins_compl_equal(compl, compl_leader, lead_len)))
2768 if (!shown_match_ok)
2770 if (compl == compl_shown_match || did_find_shown_match)
2772 /* This item is the shown match or this is the
2773 * first displayed item after the shown match. */
2774 compl_shown_match = compl;
2775 did_find_shown_match = TRUE;
2776 shown_match_ok = TRUE;
2778 else
2779 /* Remember this displayed match for when the
2780 * shown match is just below it. */
2781 shown_compl = compl;
2782 cur = i;
2785 if (compl->cp_text[CPT_ABBR] != NULL)
2786 compl_match_array[i].pum_text =
2787 compl->cp_text[CPT_ABBR];
2788 else
2789 compl_match_array[i].pum_text = compl->cp_str;
2790 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2791 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2792 if (compl->cp_text[CPT_MENU] != NULL)
2793 compl_match_array[i++].pum_extra =
2794 compl->cp_text[CPT_MENU];
2795 else
2796 compl_match_array[i++].pum_extra = compl->cp_fname;
2799 if (compl == compl_shown_match)
2801 did_find_shown_match = TRUE;
2803 /* When the original text is the shown match don't set
2804 * compl_shown_match. */
2805 if (compl->cp_flags & ORIGINAL_TEXT)
2806 shown_match_ok = TRUE;
2808 if (!shown_match_ok && shown_compl != NULL)
2810 /* The shown match isn't displayed, set it to the
2811 * previously displayed match. */
2812 compl_shown_match = shown_compl;
2813 shown_match_ok = TRUE;
2816 compl = compl->cp_next;
2817 } while (compl != NULL && compl != compl_first_match);
2819 if (!shown_match_ok) /* no displayed match at all */
2820 cur = -1;
2823 else
2825 /* popup menu already exists, only need to find the current item.*/
2826 for (i = 0; i < compl_match_arraysize; ++i)
2827 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2828 || compl_match_array[i].pum_text
2829 == compl_shown_match->cp_text[CPT_ABBR])
2831 cur = i;
2832 break;
2836 if (compl_match_array != NULL)
2838 /* Compute the screen column of the start of the completed text.
2839 * Use the cursor to get all wrapping and other settings right. */
2840 col = curwin->w_cursor.col;
2841 curwin->w_cursor.col = compl_col;
2842 pum_display(compl_match_array, compl_match_arraysize, cur);
2843 curwin->w_cursor.col = col;
2847 #define DICT_FIRST (1) /* use just first element in "dict" */
2848 #define DICT_EXACT (2) /* "dict" is the exact name of a file */
2851 * Add any identifiers that match the given pattern in the list of dictionary
2852 * files "dict_start" to the list of completions.
2854 static void
2855 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2856 char_u *dict_start;
2857 char_u *pat;
2858 int flags; /* DICT_FIRST and/or DICT_EXACT */
2859 int thesaurus; /* Thesaurus completion */
2861 char_u *dict = dict_start;
2862 char_u *ptr;
2863 char_u *buf;
2864 regmatch_T regmatch;
2865 char_u **files;
2866 int count;
2867 int save_p_scs;
2868 int dir = compl_direction;
2870 if (*dict == NUL)
2872 #ifdef FEAT_SPELL
2873 /* When 'dictionary' is empty and spell checking is enabled use
2874 * "spell". */
2875 if (!thesaurus && curwin->w_p_spell)
2876 dict = (char_u *)"spell";
2877 else
2878 #endif
2879 return;
2882 buf = alloc(LSIZE);
2883 if (buf == NULL)
2884 return;
2885 regmatch.regprog = NULL; /* so that we can goto theend */
2887 /* If 'infercase' is set, don't use 'smartcase' here */
2888 save_p_scs = p_scs;
2889 if (curbuf->b_p_inf)
2890 p_scs = FALSE;
2892 /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
2893 * to only match at the start of a line. Otherwise just match the
2894 * pattern. Also need to double backslashes. */
2895 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2897 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
2898 size_t len;
2900 if (pat_esc == NULL)
2901 goto theend;
2902 len = STRLEN(pat_esc) + 10;
2903 ptr = alloc((unsigned)len);
2904 if (ptr == NULL)
2906 vim_free(pat_esc);
2907 goto theend;
2909 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
2910 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
2911 vim_free(pat_esc);
2912 vim_free(ptr);
2914 else
2916 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2917 if (regmatch.regprog == NULL)
2918 goto theend;
2921 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2922 regmatch.rm_ic = ignorecase(pat);
2923 while (*dict != NUL && !got_int && !compl_interrupted)
2925 /* copy one dictionary file name into buf */
2926 if (flags == DICT_EXACT)
2928 count = 1;
2929 files = &dict;
2931 else
2933 /* Expand wildcards in the dictionary name, but do not allow
2934 * backticks (for security, the 'dict' option may have been set in
2935 * a modeline). */
2936 copy_option_part(&dict, buf, LSIZE, ",");
2937 # ifdef FEAT_SPELL
2938 if (!thesaurus && STRCMP(buf, "spell") == 0)
2939 count = -1;
2940 else
2941 # endif
2942 if (vim_strchr(buf, '`') != NULL
2943 || expand_wildcards(1, &buf, &count, &files,
2944 EW_FILE|EW_SILENT) != OK)
2945 count = 0;
2948 # ifdef FEAT_SPELL
2949 if (count == -1)
2951 /* Complete from active spelling. Skip "\<" in the pattern, we
2952 * don't use it as a RE. */
2953 if (pat[0] == '\\' && pat[1] == '<')
2954 ptr = pat + 2;
2955 else
2956 ptr = pat;
2957 spell_dump_compl(curbuf, ptr, regmatch.rm_ic, &dir, 0);
2959 else
2960 # endif
2961 if (count > 0) /* avoid warning for using "files" uninit */
2963 ins_compl_files(count, files, thesaurus, flags,
2964 &regmatch, buf, &dir);
2965 if (flags != DICT_EXACT)
2966 FreeWild(count, files);
2968 if (flags != 0)
2969 break;
2972 theend:
2973 p_scs = save_p_scs;
2974 vim_free(regmatch.regprog);
2975 vim_free(buf);
2978 static void
2979 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
2980 int count;
2981 char_u **files;
2982 int thesaurus;
2983 int flags;
2984 regmatch_T *regmatch;
2985 char_u *buf;
2986 int *dir;
2988 char_u *ptr;
2989 int i;
2990 FILE *fp;
2991 int add_r;
2993 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
2995 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
2996 if (flags != DICT_EXACT)
2998 vim_snprintf((char *)IObuff, IOSIZE,
2999 _("Scanning dictionary: %s"), (char *)files[i]);
3000 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3003 if (fp != NULL)
3006 * Read dictionary file line by line.
3007 * Check each line for a match.
3009 while (!got_int && !compl_interrupted
3010 && !vim_fgets(buf, LSIZE, fp))
3012 ptr = buf;
3013 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
3015 ptr = regmatch->startp[0];
3016 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3017 ptr = find_line_end(ptr);
3018 else
3019 ptr = find_word_end(ptr);
3020 add_r = ins_compl_add_infercase(regmatch->startp[0],
3021 (int)(ptr - regmatch->startp[0]),
3022 p_ic, files[i], *dir, 0);
3023 if (thesaurus)
3025 char_u *wstart;
3028 * Add the other matches on the line
3030 ptr = buf;
3031 while (!got_int)
3033 /* Find start of the next word. Skip white
3034 * space and punctuation. */
3035 ptr = find_word_start(ptr);
3036 if (*ptr == NUL || *ptr == NL)
3037 break;
3038 wstart = ptr;
3040 /* Find end of the word. */
3041 #ifdef FEAT_MBYTE
3042 if (has_mbyte)
3043 /* Japanese words may have characters in
3044 * different classes, only separate words
3045 * with single-byte non-word characters. */
3046 while (*ptr != NUL)
3048 int l = (*mb_ptr2len)(ptr);
3050 if (l < 2 && !vim_iswordc(*ptr))
3051 break;
3052 ptr += l;
3054 else
3055 #endif
3056 ptr = find_word_end(ptr);
3058 /* Add the word. Skip the regexp match. */
3059 if (wstart != regmatch->startp[0])
3060 add_r = ins_compl_add_infercase(wstart,
3061 (int)(ptr - wstart),
3062 p_ic, files[i], *dir, 0);
3065 if (add_r == OK)
3066 /* if dir was BACKWARD then honor it just once */
3067 *dir = FORWARD;
3068 else if (add_r == FAIL)
3069 break;
3070 /* avoid expensive call to vim_regexec() when at end
3071 * of line */
3072 if (*ptr == '\n' || got_int)
3073 break;
3075 line_breakcheck();
3076 ins_compl_check_keys(50);
3078 fclose(fp);
3084 * Find the start of the next word.
3085 * Returns a pointer to the first char of the word. Also stops at a NUL.
3087 char_u *
3088 find_word_start(ptr)
3089 char_u *ptr;
3091 #ifdef FEAT_MBYTE
3092 if (has_mbyte)
3093 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
3094 ptr += (*mb_ptr2len)(ptr);
3095 else
3096 #endif
3097 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
3098 ++ptr;
3099 return ptr;
3103 * Find the end of the word. Assumes it starts inside a word.
3104 * Returns a pointer to just after the word.
3106 char_u *
3107 find_word_end(ptr)
3108 char_u *ptr;
3110 #ifdef FEAT_MBYTE
3111 int start_class;
3113 if (has_mbyte)
3115 start_class = mb_get_class(ptr);
3116 if (start_class > 1)
3117 while (*ptr != NUL)
3119 ptr += (*mb_ptr2len)(ptr);
3120 if (mb_get_class(ptr) != start_class)
3121 break;
3124 else
3125 #endif
3126 while (vim_iswordc(*ptr))
3127 ++ptr;
3128 return ptr;
3132 * Find the end of the line, omitting CR and NL at the end.
3133 * Returns a pointer to just after the line.
3135 static char_u *
3136 find_line_end(ptr)
3137 char_u *ptr;
3139 char_u *s;
3141 s = ptr + STRLEN(ptr);
3142 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
3143 --s;
3144 return s;
3148 * Free the list of completions
3150 static void
3151 ins_compl_free()
3153 compl_T *match;
3154 int i;
3156 vim_free(compl_pattern);
3157 compl_pattern = NULL;
3158 vim_free(compl_leader);
3159 compl_leader = NULL;
3161 if (compl_first_match == NULL)
3162 return;
3164 ins_compl_del_pum();
3165 pum_clear();
3167 compl_curr_match = compl_first_match;
3170 match = compl_curr_match;
3171 compl_curr_match = compl_curr_match->cp_next;
3172 vim_free(match->cp_str);
3173 /* several entries may use the same fname, free it just once. */
3174 if (match->cp_flags & FREE_FNAME)
3175 vim_free(match->cp_fname);
3176 for (i = 0; i < CPT_COUNT; ++i)
3177 vim_free(match->cp_text[i]);
3178 vim_free(match);
3179 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
3180 compl_first_match = compl_curr_match = NULL;
3181 compl_shown_match = NULL;
3184 static void
3185 ins_compl_clear()
3187 compl_cont_status = 0;
3188 compl_started = FALSE;
3189 compl_matches = 0;
3190 vim_free(compl_pattern);
3191 compl_pattern = NULL;
3192 vim_free(compl_leader);
3193 compl_leader = NULL;
3194 edit_submode_extra = NULL;
3195 vim_free(compl_orig_text);
3196 compl_orig_text = NULL;
3197 compl_enter_selects = FALSE;
3201 * Return TRUE when Insert completion is active.
3204 ins_compl_active()
3206 return compl_started;
3210 * Delete one character before the cursor and show the subset of the matches
3211 * that match the word that is now before the cursor.
3212 * Returns the character to be used, NUL if the work is done and another char
3213 * to be got from the user.
3215 static int
3216 ins_compl_bs()
3218 char_u *line;
3219 char_u *p;
3221 line = ml_get_curline();
3222 p = line + curwin->w_cursor.col;
3223 mb_ptr_back(line, p);
3225 /* Stop completion when the whole word was deleted. For Omni completion
3226 * allow the word to be deleted, we won't match everything. */
3227 if ((int)(p - line) - (int)compl_col < 0
3228 || ((int)(p - line) - (int)compl_col == 0
3229 && (ctrl_x_mode & CTRL_X_OMNI) == 0))
3230 return K_BS;
3232 /* Deleted more than what was used to find matches or didn't finish
3233 * finding all matches: need to look for matches all over again. */
3234 if (curwin->w_cursor.col <= compl_col + compl_length
3235 || compl_was_interrupted)
3236 ins_compl_restart();
3238 vim_free(compl_leader);
3239 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3240 if (compl_leader != NULL)
3242 ins_compl_new_leader();
3243 return NUL;
3245 return K_BS;
3249 * Called after changing "compl_leader".
3250 * Show the popup menu with a different set of matches.
3251 * May also search for matches again if the previous search was interrupted.
3253 static void
3254 ins_compl_new_leader()
3256 ins_compl_del_pum();
3257 ins_compl_delete();
3258 ins_bytes(compl_leader + ins_compl_len());
3259 compl_used_match = FALSE;
3261 if (compl_started)
3262 ins_compl_set_original_text(compl_leader);
3263 else
3265 #ifdef FEAT_SPELL
3266 spell_bad_len = 0; /* need to redetect bad word */
3267 #endif
3269 * Matches were cleared, need to search for them now. First display
3270 * the changed text before the cursor. Set "compl_restarting" to
3271 * avoid that the first match is inserted.
3273 update_screen(0);
3274 #ifdef FEAT_GUI
3275 if (gui.in_use)
3277 /* Show the cursor after the match, not after the redrawn text. */
3278 setcursor();
3279 out_flush();
3280 gui_update_cursor(FALSE, FALSE);
3282 #endif
3283 compl_restarting = TRUE;
3284 if (ins_complete(Ctrl_N) == FAIL)
3285 compl_cont_status = 0;
3286 compl_restarting = FALSE;
3289 #if 0 /* disabled, made CTRL-L, BS and typing char jump to original text. */
3290 if (!compl_used_match)
3292 /* Go to the original text, since none of the matches is inserted. */
3293 if (compl_first_match->cp_prev != NULL
3294 && (compl_first_match->cp_prev->cp_flags & ORIGINAL_TEXT))
3295 compl_shown_match = compl_first_match->cp_prev;
3296 else
3297 compl_shown_match = compl_first_match;
3298 compl_curr_match = compl_shown_match;
3299 compl_shows_dir = compl_direction;
3301 #endif
3302 compl_enter_selects = !compl_used_match;
3304 /* Show the popup menu with a different set of matches. */
3305 ins_compl_show_pum();
3307 /* Don't let Enter select the original text when there is no popup menu. */
3308 if (compl_match_array == NULL)
3309 compl_enter_selects = FALSE;
3313 * Return the length of the completion, from the completion start column to
3314 * the cursor column. Making sure it never goes below zero.
3316 static int
3317 ins_compl_len()
3319 int off = (int)curwin->w_cursor.col - (int)compl_col;
3321 if (off < 0)
3322 return 0;
3323 return off;
3327 * Append one character to the match leader. May reduce the number of
3328 * matches.
3330 static void
3331 ins_compl_addleader(c)
3332 int c;
3334 #ifdef FEAT_MBYTE
3335 int cc;
3337 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3339 char_u buf[MB_MAXBYTES + 1];
3341 (*mb_char2bytes)(c, buf);
3342 buf[cc] = NUL;
3343 ins_char_bytes(buf, cc);
3345 else
3346 #endif
3347 ins_char(c);
3349 /* If we didn't complete finding matches we must search again. */
3350 if (compl_was_interrupted)
3351 ins_compl_restart();
3353 vim_free(compl_leader);
3354 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3355 (int)(curwin->w_cursor.col - compl_col));
3356 if (compl_leader != NULL)
3357 ins_compl_new_leader();
3361 * Setup for finding completions again without leaving CTRL-X mode. Used when
3362 * BS or a key was typed while still searching for matches.
3364 static void
3365 ins_compl_restart()
3367 ins_compl_free();
3368 compl_started = FALSE;
3369 compl_matches = 0;
3370 compl_cont_status = 0;
3371 compl_cont_mode = 0;
3375 * Set the first match, the original text.
3377 static void
3378 ins_compl_set_original_text(str)
3379 char_u *str;
3381 char_u *p;
3383 /* Replace the original text entry. */
3384 if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */
3386 p = vim_strsave(str);
3387 if (p != NULL)
3389 vim_free(compl_first_match->cp_str);
3390 compl_first_match->cp_str = p;
3396 * Append one character to the match leader. May reduce the number of
3397 * matches.
3399 static void
3400 ins_compl_addfrommatch()
3402 char_u *p;
3403 int len = (int)curwin->w_cursor.col - (int)compl_col;
3404 int c;
3405 compl_T *cp;
3407 p = compl_shown_match->cp_str;
3408 if ((int)STRLEN(p) <= len) /* the match is too short */
3410 /* When still at the original match use the first entry that matches
3411 * the leader. */
3412 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
3414 p = NULL;
3415 for (cp = compl_shown_match->cp_next; cp != NULL
3416 && cp != compl_first_match; cp = cp->cp_next)
3418 if (compl_leader == NULL
3419 || ins_compl_equal(cp, compl_leader,
3420 (int)STRLEN(compl_leader)))
3422 p = cp->cp_str;
3423 break;
3426 if (p == NULL || (int)STRLEN(p) <= len)
3427 return;
3429 else
3430 return;
3432 p += len;
3433 #ifdef FEAT_MBYTE
3434 c = mb_ptr2char(p);
3435 #else
3436 c = *p;
3437 #endif
3438 ins_compl_addleader(c);
3442 * Prepare for Insert mode completion, or stop it.
3443 * Called just after typing a character in Insert mode.
3444 * Returns TRUE when the character is not to be inserted;
3446 static int
3447 ins_compl_prep(c)
3448 int c;
3450 char_u *ptr;
3451 int want_cindent;
3452 int retval = FALSE;
3454 /* Forget any previous 'special' messages if this is actually
3455 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3457 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3458 edit_submode_extra = NULL;
3460 /* Ignore end of Select mode mapping and mouse scroll buttons. */
3461 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP)
3462 return retval;
3464 /* Set "compl_get_longest" when finding the first matches. */
3465 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3466 || (ctrl_x_mode == 0 && !compl_started))
3468 compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3469 compl_used_match = TRUE;
3472 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3475 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3476 * it will be yet. Now we decide.
3478 switch (c)
3480 case Ctrl_E:
3481 case Ctrl_Y:
3482 ctrl_x_mode = CTRL_X_SCROLL;
3483 if (!(State & REPLACE_FLAG))
3484 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3485 else
3486 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3487 edit_submode_pre = NULL;
3488 showmode();
3489 break;
3490 case Ctrl_L:
3491 ctrl_x_mode = CTRL_X_WHOLE_LINE;
3492 break;
3493 case Ctrl_F:
3494 ctrl_x_mode = CTRL_X_FILES;
3495 break;
3496 case Ctrl_K:
3497 ctrl_x_mode = CTRL_X_DICTIONARY;
3498 break;
3499 case Ctrl_R:
3500 /* Simply allow ^R to happen without affecting ^X mode */
3501 break;
3502 case Ctrl_T:
3503 ctrl_x_mode = CTRL_X_THESAURUS;
3504 break;
3505 #ifdef FEAT_COMPL_FUNC
3506 case Ctrl_U:
3507 ctrl_x_mode = CTRL_X_FUNCTION;
3508 break;
3509 case Ctrl_O:
3510 ctrl_x_mode = CTRL_X_OMNI;
3511 break;
3512 #endif
3513 case 's':
3514 case Ctrl_S:
3515 ctrl_x_mode = CTRL_X_SPELL;
3516 #ifdef FEAT_SPELL
3517 ++emsg_off; /* Avoid getting the E756 error twice. */
3518 spell_back_to_badword();
3519 --emsg_off;
3520 #endif
3521 break;
3522 case Ctrl_RSB:
3523 ctrl_x_mode = CTRL_X_TAGS;
3524 break;
3525 #ifdef FEAT_FIND_ID
3526 case Ctrl_I:
3527 case K_S_TAB:
3528 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3529 break;
3530 case Ctrl_D:
3531 ctrl_x_mode = CTRL_X_PATH_DEFINES;
3532 break;
3533 #endif
3534 case Ctrl_V:
3535 case Ctrl_Q:
3536 ctrl_x_mode = CTRL_X_CMDLINE;
3537 break;
3538 case Ctrl_P:
3539 case Ctrl_N:
3540 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
3541 * just started ^X mode, or there were enough ^X's to cancel
3542 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3543 * do normal expansion when interrupting a different mode (say
3544 * ^X^F^X^P or ^P^X^X^P, see below)
3545 * nothing changes if interrupting mode 0, (eg, the flag
3546 * doesn't change when going to ADDING mode -- Acevedo */
3547 if (!(compl_cont_status & CONT_INTRPT))
3548 compl_cont_status |= CONT_LOCAL;
3549 else if (compl_cont_mode != 0)
3550 compl_cont_status &= ~CONT_LOCAL;
3551 /* FALLTHROUGH */
3552 default:
3553 /* If we have typed at least 2 ^X's... for modes != 0, we set
3554 * compl_cont_status = 0 (eg, as if we had just started ^X
3555 * mode).
3556 * For mode 0, we set "compl_cont_mode" to an impossible
3557 * value, in both cases ^X^X can be used to restart the same
3558 * mode (avoiding ADDING mode).
3559 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3560 * 'complete' and local ^P expansions respectively.
3561 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3562 * mode -- Acevedo */
3563 if (c == Ctrl_X)
3565 if (compl_cont_mode != 0)
3566 compl_cont_status = 0;
3567 else
3568 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3570 ctrl_x_mode = 0;
3571 edit_submode = NULL;
3572 showmode();
3573 break;
3576 else if (ctrl_x_mode != 0)
3578 /* We're already in CTRL-X mode, do we stay in it? */
3579 if (!vim_is_ctrl_x_key(c))
3581 if (ctrl_x_mode == CTRL_X_SCROLL)
3582 ctrl_x_mode = 0;
3583 else
3584 ctrl_x_mode = CTRL_X_FINISHED;
3585 edit_submode = NULL;
3587 showmode();
3590 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3592 /* Show error message from attempted keyword completion (probably
3593 * 'Pattern not found') until another key is hit, then go back to
3594 * showing what mode we are in. */
3595 showmode();
3596 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3597 && !ins_compl_pum_key(c))
3598 || ctrl_x_mode == CTRL_X_FINISHED)
3600 /* Get here when we have finished typing a sequence of ^N and
3601 * ^P or other completion characters in CTRL-X mode. Free up
3602 * memory that was used, and make sure we can redo the insert. */
3603 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3605 char_u *p;
3606 int temp = 0;
3609 * If any of the original typed text has been changed, eg when
3610 * ignorecase is set, we must add back-spaces to the redo
3611 * buffer. We add as few as necessary to delete just the part
3612 * of the original text that has changed.
3613 * When using the longest match, edited the match or used
3614 * CTRL-E then don't use the current match.
3616 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3617 ptr = compl_curr_match->cp_str;
3618 else if (compl_leader != NULL)
3619 ptr = compl_leader;
3620 else
3621 ptr = compl_orig_text;
3622 if (compl_orig_text != NULL)
3624 p = compl_orig_text;
3625 for (temp = 0; p[temp] != NUL && p[temp] == ptr[temp];
3626 ++temp)
3628 #ifdef FEAT_MBYTE
3629 if (temp > 0)
3630 temp -= (*mb_head_off)(compl_orig_text, p + temp);
3631 #endif
3632 for (p += temp; *p != NUL; mb_ptr_adv(p))
3633 AppendCharToRedobuff(K_BS);
3635 if (ptr != NULL)
3636 AppendToRedobuffLit(ptr + temp, -1);
3639 #ifdef FEAT_CINDENT
3640 want_cindent = (can_cindent && cindent_on());
3641 #endif
3643 * When completing whole lines: fix indent for 'cindent'.
3644 * Otherwise, break line if it's too long.
3646 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3648 #ifdef FEAT_CINDENT
3649 /* re-indent the current line */
3650 if (want_cindent)
3652 do_c_expr_indent();
3653 want_cindent = FALSE; /* don't do it again */
3655 #endif
3657 else
3659 int prev_col = curwin->w_cursor.col;
3661 /* put the cursor on the last char, for 'tw' formatting */
3662 if (prev_col > 0)
3663 dec_cursor();
3664 if (stop_arrow() == OK)
3665 insertchar(NUL, 0, -1);
3666 if (prev_col > 0
3667 && ml_get_curline()[curwin->w_cursor.col] != NUL)
3668 inc_cursor();
3671 /* If the popup menu is displayed pressing CTRL-Y means accepting
3672 * the selection without inserting anything. When
3673 * compl_enter_selects is set the Enter key does the same. */
3674 if ((c == Ctrl_Y || (compl_enter_selects
3675 && (c == CAR || c == K_KENTER || c == NL)))
3676 && pum_visible())
3677 retval = TRUE;
3679 /* CTRL-E means completion is Ended, go back to the typed text. */
3680 if (c == Ctrl_E)
3682 ins_compl_delete();
3683 if (compl_leader != NULL)
3684 ins_bytes(compl_leader + ins_compl_len());
3685 else if (compl_first_match != NULL)
3686 ins_bytes(compl_orig_text + ins_compl_len());
3687 retval = TRUE;
3690 auto_format(FALSE, TRUE);
3692 ins_compl_free();
3693 compl_started = FALSE;
3694 compl_matches = 0;
3695 msg_clr_cmdline(); /* necessary for "noshowmode" */
3696 ctrl_x_mode = 0;
3697 compl_enter_selects = FALSE;
3698 if (edit_submode != NULL)
3700 edit_submode = NULL;
3701 showmode();
3704 #ifdef FEAT_CINDENT
3706 * Indent now if a key was typed that is in 'cinkeys'.
3708 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3709 do_c_expr_indent();
3710 #endif
3714 /* reset continue_* if we left expansion-mode, if we stay they'll be
3715 * (re)set properly in ins_complete() */
3716 if (!vim_is_ctrl_x_key(c))
3718 compl_cont_status = 0;
3719 compl_cont_mode = 0;
3722 return retval;
3726 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3727 * (depending on flag) starting from buf and looking for a non-scanned
3728 * buffer (other than curbuf). curbuf is special, if it is called with
3729 * buf=curbuf then it has to be the first call for a given flag/expansion.
3731 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3733 static buf_T *
3734 ins_compl_next_buf(buf, flag)
3735 buf_T *buf;
3736 int flag;
3738 #ifdef FEAT_WINDOWS
3739 static win_T *wp;
3740 #endif
3742 if (flag == 'w') /* just windows */
3744 #ifdef FEAT_WINDOWS
3745 if (buf == curbuf) /* first call for this flag/expansion */
3746 wp = curwin;
3747 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3748 && wp->w_buffer->b_scanned)
3750 buf = wp->w_buffer;
3751 #else
3752 buf = curbuf;
3753 #endif
3755 else
3756 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3757 * (unlisted buffers)
3758 * When completing whole lines skip unloaded buffers. */
3759 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3760 && ((flag == 'U'
3761 ? buf->b_p_bl
3762 : (!buf->b_p_bl
3763 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3764 || buf->b_scanned))
3766 return buf;
3769 #ifdef FEAT_COMPL_FUNC
3770 static void expand_by_function __ARGS((int type, char_u *base));
3773 * Execute user defined complete function 'completefunc' or 'omnifunc', and
3774 * get matches in "matches".
3776 static void
3777 expand_by_function(type, base)
3778 int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3779 char_u *base;
3781 list_T *matchlist;
3782 char_u *args[2];
3783 char_u *funcname;
3784 pos_T pos;
3786 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3787 if (*funcname == NUL)
3788 return;
3790 /* Call 'completefunc' to obtain the list of matches. */
3791 args[0] = (char_u *)"0";
3792 args[1] = base;
3794 pos = curwin->w_cursor;
3795 matchlist = call_func_retlist(funcname, 2, args, FALSE);
3796 curwin->w_cursor = pos; /* restore the cursor position */
3797 if (matchlist == NULL)
3798 return;
3800 ins_compl_add_list(matchlist);
3801 list_unref(matchlist);
3803 #endif /* FEAT_COMPL_FUNC */
3805 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
3807 * Add completions from a list.
3809 static void
3810 ins_compl_add_list(list)
3811 list_T *list;
3813 listitem_T *li;
3814 int dir = compl_direction;
3816 /* Go through the List with matches and add each of them. */
3817 for (li = list->lv_first; li != NULL; li = li->li_next)
3819 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
3820 /* if dir was BACKWARD then honor it just once */
3821 dir = FORWARD;
3822 else if (did_emsg)
3823 break;
3828 * Add a match to the list of matches from a typeval_T.
3829 * If the given string is already in the list of completions, then return
3830 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3831 * maybe because alloc() returns NULL, then FAIL is returned.
3834 ins_compl_add_tv(tv, dir)
3835 typval_T *tv;
3836 int dir;
3838 char_u *word;
3839 int icase = FALSE;
3840 int adup = FALSE;
3841 char_u *(cptext[CPT_COUNT]);
3843 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3845 word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
3846 cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
3847 (char_u *)"abbr", FALSE);
3848 cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
3849 (char_u *)"menu", FALSE);
3850 cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
3851 (char_u *)"kind", FALSE);
3852 cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
3853 (char_u *)"info", FALSE);
3854 if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
3855 icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
3856 if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
3857 adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
3859 else
3861 word = get_tv_string_chk(tv);
3862 vim_memset(cptext, 0, sizeof(cptext));
3864 if (word == NULL || *word == NUL)
3865 return FAIL;
3866 return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup);
3868 #endif
3871 * Get the next expansion(s), using "compl_pattern".
3872 * The search starts at position "ini" in curbuf and in the direction
3873 * compl_direction.
3874 * When "compl_started" is FALSE start at that position, otherwise continue
3875 * where we stopped searching before.
3876 * This may return before finding all the matches.
3877 * Return the total number of matches or -1 if still unknown -- Acevedo
3879 static int
3880 ins_compl_get_exp(ini)
3881 pos_T *ini;
3883 static pos_T first_match_pos;
3884 static pos_T last_match_pos;
3885 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
3886 static int found_all = FALSE; /* Found all matches of a
3887 certain type. */
3888 static buf_T *ins_buf = NULL; /* buffer being scanned */
3890 pos_T *pos;
3891 char_u **matches;
3892 int save_p_scs;
3893 int save_p_ws;
3894 int save_p_ic;
3895 int i;
3896 int num_matches;
3897 int len;
3898 int found_new_match;
3899 int type = ctrl_x_mode;
3900 char_u *ptr;
3901 char_u *dict = NULL;
3902 int dict_f = 0;
3903 compl_T *old_match;
3905 if (!compl_started)
3907 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
3908 ins_buf->b_scanned = 0;
3909 found_all = FALSE;
3910 ins_buf = curbuf;
3911 e_cpt = (compl_cont_status & CONT_LOCAL)
3912 ? (char_u *)"." : curbuf->b_p_cpt;
3913 last_match_pos = first_match_pos = *ini;
3916 old_match = compl_curr_match; /* remember the last current match */
3917 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3918 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
3919 for (;;)
3921 found_new_match = FAIL;
3923 /* For ^N/^P pick a new entry from e_cpt if compl_started is off,
3924 * or if found_all says this entry is done. For ^X^L only use the
3925 * entries from 'complete' that look in loaded buffers. */
3926 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3927 && (!compl_started || found_all))
3929 found_all = FALSE;
3930 while (*e_cpt == ',' || *e_cpt == ' ')
3931 e_cpt++;
3932 if (*e_cpt == '.' && !curbuf->b_scanned)
3934 ins_buf = curbuf;
3935 first_match_pos = *ini;
3936 /* So that ^N can match word immediately after cursor */
3937 if (ctrl_x_mode == 0)
3938 dec(&first_match_pos);
3939 last_match_pos = first_match_pos;
3940 type = 0;
3942 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3943 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
3945 /* Scan a buffer, but not the current one. */
3946 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
3948 compl_started = TRUE;
3949 first_match_pos.col = last_match_pos.col = 0;
3950 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
3951 last_match_pos.lnum = 0;
3952 type = 0;
3954 else /* unloaded buffer, scan like dictionary */
3956 found_all = TRUE;
3957 if (ins_buf->b_fname == NULL)
3958 continue;
3959 type = CTRL_X_DICTIONARY;
3960 dict = ins_buf->b_fname;
3961 dict_f = DICT_EXACT;
3963 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3964 ins_buf->b_fname == NULL
3965 ? buf_spname(ins_buf)
3966 : ins_buf->b_sfname == NULL
3967 ? (char *)ins_buf->b_fname
3968 : (char *)ins_buf->b_sfname);
3969 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3971 else if (*e_cpt == NUL)
3972 break;
3973 else
3975 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3976 type = -1;
3977 else if (*e_cpt == 'k' || *e_cpt == 's')
3979 if (*e_cpt == 'k')
3980 type = CTRL_X_DICTIONARY;
3981 else
3982 type = CTRL_X_THESAURUS;
3983 if (*++e_cpt != ',' && *e_cpt != NUL)
3985 dict = e_cpt;
3986 dict_f = DICT_FIRST;
3989 #ifdef FEAT_FIND_ID
3990 else if (*e_cpt == 'i')
3991 type = CTRL_X_PATH_PATTERNS;
3992 else if (*e_cpt == 'd')
3993 type = CTRL_X_PATH_DEFINES;
3994 #endif
3995 else if (*e_cpt == ']' || *e_cpt == 't')
3997 type = CTRL_X_TAGS;
3998 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3999 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
4001 else
4002 type = -1;
4004 /* in any case e_cpt is advanced to the next entry */
4005 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
4007 found_all = TRUE;
4008 if (type == -1)
4009 continue;
4013 switch (type)
4015 case -1:
4016 break;
4017 #ifdef FEAT_FIND_ID
4018 case CTRL_X_PATH_PATTERNS:
4019 case CTRL_X_PATH_DEFINES:
4020 find_pattern_in_path(compl_pattern, compl_direction,
4021 (int)STRLEN(compl_pattern), FALSE, FALSE,
4022 (type == CTRL_X_PATH_DEFINES
4023 && !(compl_cont_status & CONT_SOL))
4024 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
4025 (linenr_T)1, (linenr_T)MAXLNUM);
4026 break;
4027 #endif
4029 case CTRL_X_DICTIONARY:
4030 case CTRL_X_THESAURUS:
4031 ins_compl_dictionaries(
4032 dict != NULL ? dict
4033 : (type == CTRL_X_THESAURUS
4034 ? (*curbuf->b_p_tsr == NUL
4035 ? p_tsr
4036 : curbuf->b_p_tsr)
4037 : (*curbuf->b_p_dict == NUL
4038 ? p_dict
4039 : curbuf->b_p_dict)),
4040 compl_pattern,
4041 dict != NULL ? dict_f
4042 : 0, type == CTRL_X_THESAURUS);
4043 dict = NULL;
4044 break;
4046 case CTRL_X_TAGS:
4047 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
4048 save_p_ic = p_ic;
4049 p_ic = ignorecase(compl_pattern);
4051 /* Find up to TAG_MANY matches. Avoids that an enourmous number
4052 * of matches is found when compl_pattern is empty */
4053 if (find_tags(compl_pattern, &num_matches, &matches,
4054 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
4055 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
4056 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4058 ins_compl_add_matches(num_matches, matches, p_ic);
4060 p_ic = save_p_ic;
4061 break;
4063 case CTRL_X_FILES:
4064 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
4065 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
4068 /* May change home directory back to "~". */
4069 tilde_replace(compl_pattern, num_matches, matches);
4070 ins_compl_add_matches(num_matches, matches,
4071 #ifdef CASE_INSENSITIVE_FILENAME
4072 TRUE
4073 #else
4074 FALSE
4075 #endif
4078 break;
4080 case CTRL_X_CMDLINE:
4081 if (expand_cmdline(&compl_xp, compl_pattern,
4082 (int)STRLEN(compl_pattern),
4083 &num_matches, &matches) == EXPAND_OK)
4084 ins_compl_add_matches(num_matches, matches, FALSE);
4085 break;
4087 #ifdef FEAT_COMPL_FUNC
4088 case CTRL_X_FUNCTION:
4089 case CTRL_X_OMNI:
4090 expand_by_function(type, compl_pattern);
4091 break;
4092 #endif
4094 case CTRL_X_SPELL:
4095 #ifdef FEAT_SPELL
4096 num_matches = expand_spelling(first_match_pos.lnum,
4097 compl_pattern, &matches);
4098 if (num_matches > 0)
4099 ins_compl_add_matches(num_matches, matches, p_ic);
4100 #endif
4101 break;
4103 default: /* normal ^P/^N and ^X^L */
4105 * If 'infercase' is set, don't use 'smartcase' here
4107 save_p_scs = p_scs;
4108 if (ins_buf->b_p_inf)
4109 p_scs = FALSE;
4111 /* buffers other than curbuf are scanned from the beginning or the
4112 * end but never from the middle, thus setting nowrapscan in this
4113 * buffers is a good idea, on the other hand, we always set
4114 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
4115 save_p_ws = p_ws;
4116 if (ins_buf != curbuf)
4117 p_ws = FALSE;
4118 else if (*e_cpt == '.')
4119 p_ws = TRUE;
4120 for (;;)
4122 int flags = 0;
4124 ++msg_silent; /* Don't want messages for wrapscan. */
4126 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
4127 * has added a word that was at the beginning of the line */
4128 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
4129 || (compl_cont_status & CONT_SOL))
4130 found_new_match = search_for_exact_line(ins_buf, pos,
4131 compl_direction, compl_pattern);
4132 else
4133 found_new_match = searchit(NULL, ins_buf, pos,
4134 compl_direction,
4135 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
4136 RE_LAST, (linenr_T)0, NULL);
4137 --msg_silent;
4138 if (!compl_started)
4140 /* set "compl_started" even on fail */
4141 compl_started = TRUE;
4142 first_match_pos = *pos;
4143 last_match_pos = *pos;
4145 else if (first_match_pos.lnum == last_match_pos.lnum
4146 && first_match_pos.col == last_match_pos.col)
4147 found_new_match = FAIL;
4148 if (found_new_match == FAIL)
4150 if (ins_buf == curbuf)
4151 found_all = TRUE;
4152 break;
4155 /* when ADDING, the text before the cursor matches, skip it */
4156 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
4157 && ini->lnum == pos->lnum
4158 && ini->col == pos->col)
4159 continue;
4160 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
4161 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4163 if (compl_cont_status & CONT_ADDING)
4165 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
4166 continue;
4167 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4168 if (!p_paste)
4169 ptr = skipwhite(ptr);
4171 len = (int)STRLEN(ptr);
4173 else
4175 char_u *tmp_ptr = ptr;
4177 if (compl_cont_status & CONT_ADDING)
4179 tmp_ptr += compl_length;
4180 /* Skip if already inside a word. */
4181 if (vim_iswordp(tmp_ptr))
4182 continue;
4183 /* Find start of next word. */
4184 tmp_ptr = find_word_start(tmp_ptr);
4186 /* Find end of this word. */
4187 tmp_ptr = find_word_end(tmp_ptr);
4188 len = (int)(tmp_ptr - ptr);
4190 if ((compl_cont_status & CONT_ADDING)
4191 && len == compl_length)
4193 if (pos->lnum < ins_buf->b_ml.ml_line_count)
4195 /* Try next line, if any. the new word will be
4196 * "join" as if the normal command "J" was used.
4197 * IOSIZE is always greater than
4198 * compl_length, so the next STRNCPY always
4199 * works -- Acevedo */
4200 STRNCPY(IObuff, ptr, len);
4201 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4202 tmp_ptr = ptr = skipwhite(ptr);
4203 /* Find start of next word. */
4204 tmp_ptr = find_word_start(tmp_ptr);
4205 /* Find end of next word. */
4206 tmp_ptr = find_word_end(tmp_ptr);
4207 if (tmp_ptr > ptr)
4209 if (*ptr != ')' && IObuff[len - 1] != TAB)
4211 if (IObuff[len - 1] != ' ')
4212 IObuff[len++] = ' ';
4213 /* IObuf =~ "\k.* ", thus len >= 2 */
4214 if (p_js
4215 && (IObuff[len - 2] == '.'
4216 || (vim_strchr(p_cpo, CPO_JOINSP)
4217 == NULL
4218 && (IObuff[len - 2] == '?'
4219 || IObuff[len - 2] == '!'))))
4220 IObuff[len++] = ' ';
4222 /* copy as much as posible of the new word */
4223 if (tmp_ptr - ptr >= IOSIZE - len)
4224 tmp_ptr = ptr + IOSIZE - len - 1;
4225 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4226 len += (int)(tmp_ptr - ptr);
4227 flags |= CONT_S_IPOS;
4229 IObuff[len] = NUL;
4230 ptr = IObuff;
4232 if (len == compl_length)
4233 continue;
4236 if (ins_compl_add_infercase(ptr, len, p_ic,
4237 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
4238 0, flags) != NOTDONE)
4240 found_new_match = OK;
4241 break;
4244 p_scs = save_p_scs;
4245 p_ws = save_p_ws;
4248 /* check if compl_curr_match has changed, (e.g. other type of
4249 * expansion added something) */
4250 if (type != 0 && compl_curr_match != old_match)
4251 found_new_match = OK;
4253 /* break the loop for specialized modes (use 'complete' just for the
4254 * generic ctrl_x_mode == 0) or when we've found a new match */
4255 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4256 || found_new_match != FAIL)
4258 if (got_int)
4259 break;
4260 /* Fill the popup menu as soon as possible. */
4261 if (type != -1)
4262 ins_compl_check_keys(0);
4264 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4265 || compl_interrupted)
4266 break;
4267 compl_started = TRUE;
4269 else
4271 /* Mark a buffer scanned when it has been scanned completely */
4272 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
4273 ins_buf->b_scanned = TRUE;
4275 compl_started = FALSE;
4278 compl_started = TRUE;
4280 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4281 && *e_cpt == NUL) /* Got to end of 'complete' */
4282 found_new_match = FAIL;
4284 i = -1; /* total of matches, unknown */
4285 if (found_new_match == FAIL
4286 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
4287 i = ins_compl_make_cyclic();
4289 /* If several matches were added (FORWARD) or the search failed and has
4290 * just been made cyclic then we have to move compl_curr_match to the next
4291 * or previous entry (if any) -- Acevedo */
4292 compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
4293 : old_match->cp_prev;
4294 if (compl_curr_match == NULL)
4295 compl_curr_match = old_match;
4296 return i;
4299 /* Delete the old text being completed. */
4300 static void
4301 ins_compl_delete()
4303 int i;
4306 * In insert mode: Delete the typed part.
4307 * In replace mode: Put the old characters back, if any.
4309 i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
4310 backspace_until_column(i);
4311 changed_cline_bef_curs();
4314 /* Insert the new text being completed. */
4315 static void
4316 ins_compl_insert()
4318 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
4319 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4320 compl_used_match = FALSE;
4321 else
4322 compl_used_match = TRUE;
4326 * Fill in the next completion in the current direction.
4327 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4328 * get more completions. If it is FALSE, then we just do nothing when there
4329 * are no more completions in a given direction. The latter case is used when
4330 * we are still in the middle of finding completions, to allow browsing
4331 * through the ones found so far.
4332 * Return the total number of matches, or -1 if still unknown -- webb.
4334 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4335 * compl_shown_match here.
4337 * Note that this function may be called recursively once only. First with
4338 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4339 * calls this function with "allow_get_expansion" FALSE.
4341 static int
4342 ins_compl_next(allow_get_expansion, count, insert_match)
4343 int allow_get_expansion;
4344 int count; /* repeat completion this many times; should
4345 be at least 1 */
4346 int insert_match; /* Insert the newly selected match */
4348 int num_matches = -1;
4349 int i;
4350 int todo = count;
4351 compl_T *found_compl = NULL;
4352 int found_end = FALSE;
4353 int advance;
4355 if (compl_leader != NULL
4356 && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4358 /* Set "compl_shown_match" to the actually shown match, it may differ
4359 * when "compl_leader" is used to omit some of the matches. */
4360 while (!ins_compl_equal(compl_shown_match,
4361 compl_leader, (int)STRLEN(compl_leader))
4362 && compl_shown_match->cp_next != NULL
4363 && compl_shown_match->cp_next != compl_first_match)
4364 compl_shown_match = compl_shown_match->cp_next;
4366 /* If we didn't find it searching forward, and compl_shows_dir is
4367 * backward, find the last match. */
4368 if (compl_shows_dir == BACKWARD
4369 && !ins_compl_equal(compl_shown_match,
4370 compl_leader, (int)STRLEN(compl_leader))
4371 && (compl_shown_match->cp_next == NULL
4372 || compl_shown_match->cp_next == compl_first_match))
4374 while (!ins_compl_equal(compl_shown_match,
4375 compl_leader, (int)STRLEN(compl_leader))
4376 && compl_shown_match->cp_prev != NULL
4377 && compl_shown_match->cp_prev != compl_first_match)
4378 compl_shown_match = compl_shown_match->cp_prev;
4382 if (allow_get_expansion && insert_match
4383 && (!(compl_get_longest || compl_restarting) || compl_used_match))
4384 /* Delete old text to be replaced */
4385 ins_compl_delete();
4387 /* When finding the longest common text we stick at the original text,
4388 * don't let CTRL-N or CTRL-P move to the first match. */
4389 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4391 /* When restarting the search don't insert the first match either. */
4392 if (compl_restarting)
4394 advance = FALSE;
4395 compl_restarting = FALSE;
4398 /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4399 * around. */
4400 while (--todo >= 0)
4402 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4404 compl_shown_match = compl_shown_match->cp_next;
4405 found_end = (compl_first_match != NULL
4406 && (compl_shown_match->cp_next == compl_first_match
4407 || compl_shown_match == compl_first_match));
4409 else if (compl_shows_dir == BACKWARD
4410 && compl_shown_match->cp_prev != NULL)
4412 found_end = (compl_shown_match == compl_first_match);
4413 compl_shown_match = compl_shown_match->cp_prev;
4414 found_end |= (compl_shown_match == compl_first_match);
4416 else
4418 if (!allow_get_expansion)
4420 if (advance)
4422 if (compl_shows_dir == BACKWARD)
4423 compl_pending -= todo + 1;
4424 else
4425 compl_pending += todo + 1;
4427 return -1;
4430 if (advance)
4432 if (compl_shows_dir == BACKWARD)
4433 --compl_pending;
4434 else
4435 ++compl_pending;
4438 /* Find matches. */
4439 num_matches = ins_compl_get_exp(&compl_startpos);
4441 /* handle any pending completions */
4442 while (compl_pending != 0 && compl_direction == compl_shows_dir
4443 && advance)
4445 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4447 compl_shown_match = compl_shown_match->cp_next;
4448 --compl_pending;
4450 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4452 compl_shown_match = compl_shown_match->cp_prev;
4453 ++compl_pending;
4455 else
4456 break;
4458 found_end = FALSE;
4460 if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4461 && compl_leader != NULL
4462 && !ins_compl_equal(compl_shown_match,
4463 compl_leader, (int)STRLEN(compl_leader)))
4464 ++todo;
4465 else
4466 /* Remember a matching item. */
4467 found_compl = compl_shown_match;
4469 /* Stop at the end of the list when we found a usable match. */
4470 if (found_end)
4472 if (found_compl != NULL)
4474 compl_shown_match = found_compl;
4475 break;
4477 todo = 1; /* use first usable match after wrapping around */
4481 /* Insert the text of the new completion, or the compl_leader. */
4482 if (insert_match)
4484 if (!compl_get_longest || compl_used_match)
4485 ins_compl_insert();
4486 else
4487 ins_bytes(compl_leader + ins_compl_len());
4489 else
4490 compl_used_match = FALSE;
4492 if (!allow_get_expansion)
4494 /* may undisplay the popup menu first */
4495 ins_compl_upd_pum();
4497 /* redraw to show the user what was inserted */
4498 update_screen(0);
4500 /* display the updated popup menu */
4501 ins_compl_show_pum();
4502 #ifdef FEAT_GUI
4503 if (gui.in_use)
4505 /* Show the cursor after the match, not after the redrawn text. */
4506 setcursor();
4507 out_flush();
4508 gui_update_cursor(FALSE, FALSE);
4510 #endif
4512 /* Delete old text to be replaced, since we're still searching and
4513 * don't want to match ourselves! */
4514 ins_compl_delete();
4517 /* Enter will select a match when the match wasn't inserted and the popup
4518 * menu is visible. */
4519 compl_enter_selects = !insert_match && compl_match_array != NULL;
4522 * Show the file name for the match (if any)
4523 * Truncate the file name to avoid a wait for return.
4525 if (compl_shown_match->cp_fname != NULL)
4527 STRCPY(IObuff, "match in file ");
4528 i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4529 if (i <= 0)
4530 i = 0;
4531 else
4532 STRCAT(IObuff, "<");
4533 STRCAT(IObuff, compl_shown_match->cp_fname + i);
4534 msg(IObuff);
4535 redraw_cmdline = FALSE; /* don't overwrite! */
4538 return num_matches;
4542 * Call this while finding completions, to check whether the user has hit a key
4543 * that should change the currently displayed completion, or exit completion
4544 * mode. Also, when compl_pending is not zero, show a completion as soon as
4545 * possible. -- webb
4546 * "frequency" specifies out of how many calls we actually check.
4548 void
4549 ins_compl_check_keys(frequency)
4550 int frequency;
4552 static int count = 0;
4554 int c;
4556 /* Don't check when reading keys from a script. That would break the test
4557 * scripts */
4558 if (using_script())
4559 return;
4561 /* Only do this at regular intervals */
4562 if (++count < frequency)
4563 return;
4564 count = 0;
4566 /* Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4567 * can't do its work correctly. */
4568 c = vpeekc_any();
4569 if (c != NUL)
4571 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4573 c = safe_vgetc(); /* Eat the character */
4574 compl_shows_dir = ins_compl_key2dir(c);
4575 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4576 c != K_UP && c != K_DOWN);
4578 else
4580 /* Need to get the character to have KeyTyped set. We'll put it
4581 * back with vungetc() below. But skip K_IGNORE. */
4582 c = safe_vgetc();
4583 if (c != K_IGNORE)
4585 /* Don't interrupt completion when the character wasn't typed,
4586 * e.g., when doing @q to replay keys. */
4587 if (c != Ctrl_R && KeyTyped)
4588 compl_interrupted = TRUE;
4590 vungetc(c);
4594 if (compl_pending != 0 && !got_int)
4596 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4598 compl_pending = 0;
4599 (void)ins_compl_next(FALSE, todo, TRUE);
4604 * Decide the direction of Insert mode complete from the key typed.
4605 * Returns BACKWARD or FORWARD.
4607 static int
4608 ins_compl_key2dir(c)
4609 int c;
4611 if (c == Ctrl_P || c == Ctrl_L
4612 || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4613 || c == K_S_UP || c == K_UP)))
4614 return BACKWARD;
4615 return FORWARD;
4619 * Return TRUE for keys that are used for completion only when the popup menu
4620 * is visible.
4622 static int
4623 ins_compl_pum_key(c)
4624 int c;
4626 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4627 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4628 || c == K_UP || c == K_DOWN);
4632 * Decide the number of completions to move forward.
4633 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4635 static int
4636 ins_compl_key2count(c)
4637 int c;
4639 int h;
4641 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4643 h = pum_get_height();
4644 if (h > 3)
4645 h -= 2; /* keep some context */
4646 return h;
4648 return 1;
4652 * Return TRUE if completion with "c" should insert the match, FALSE if only
4653 * to change the currently selected completion.
4655 static int
4656 ins_compl_use_match(c)
4657 int c;
4659 switch (c)
4661 case K_UP:
4662 case K_DOWN:
4663 case K_PAGEDOWN:
4664 case K_KPAGEDOWN:
4665 case K_S_DOWN:
4666 case K_PAGEUP:
4667 case K_KPAGEUP:
4668 case K_S_UP:
4669 return FALSE;
4671 return TRUE;
4675 * Do Insert mode completion.
4676 * Called when character "c" was typed, which has a meaning for completion.
4677 * Returns OK if completion was done, FAIL if something failed (out of mem).
4679 static int
4680 ins_complete(c)
4681 int c;
4683 char_u *line;
4684 int startcol = 0; /* column where searched text starts */
4685 colnr_T curs_col; /* cursor column */
4686 int n;
4688 compl_direction = ins_compl_key2dir(c);
4689 if (!compl_started)
4691 /* First time we hit ^N or ^P (in a row, I mean) */
4693 did_ai = FALSE;
4694 #ifdef FEAT_SMARTINDENT
4695 did_si = FALSE;
4696 can_si = FALSE;
4697 can_si_back = FALSE;
4698 #endif
4699 if (stop_arrow() == FAIL)
4700 return FAIL;
4702 line = ml_get(curwin->w_cursor.lnum);
4703 curs_col = curwin->w_cursor.col;
4704 compl_pending = 0;
4706 /* If this same ctrl_x_mode has been interrupted use the text from
4707 * "compl_startpos" to the cursor as a pattern to add a new word
4708 * instead of expand the one before the cursor, in word-wise if
4709 * "compl_startpos" is not in the same line as the cursor then fix it
4710 * (the line has been split because it was longer than 'tw'). if SOL
4711 * is set then skip the previous pattern, a word at the beginning of
4712 * the line has been inserted, we'll look for that -- Acevedo. */
4713 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4714 && compl_cont_mode == ctrl_x_mode)
4717 * it is a continued search
4719 compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */
4720 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4721 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4723 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4725 /* line (probably) wrapped, set compl_startpos to the
4726 * first non_blank in the line, if it is not a wordchar
4727 * include it to get a better pattern, but then we don't
4728 * want the "\\<" prefix, check it bellow */
4729 compl_col = (colnr_T)(skipwhite(line) - line);
4730 compl_startpos.col = compl_col;
4731 compl_startpos.lnum = curwin->w_cursor.lnum;
4732 compl_cont_status &= ~CONT_SOL; /* clear SOL if present */
4734 else
4736 /* S_IPOS was set when we inserted a word that was at the
4737 * beginning of the line, which means that we'll go to SOL
4738 * mode but first we need to redefine compl_startpos */
4739 if (compl_cont_status & CONT_S_IPOS)
4741 compl_cont_status |= CONT_SOL;
4742 compl_startpos.col = (colnr_T)(skipwhite(
4743 line + compl_length
4744 + compl_startpos.col) - line);
4746 compl_col = compl_startpos.col;
4748 compl_length = curwin->w_cursor.col - (int)compl_col;
4749 /* IObuff is used to add a "word from the next line" would we
4750 * have enough space? just being paranoid */
4751 #define MIN_SPACE 75
4752 if (compl_length > (IOSIZE - MIN_SPACE))
4754 compl_cont_status &= ~CONT_SOL;
4755 compl_length = (IOSIZE - MIN_SPACE);
4756 compl_col = curwin->w_cursor.col - compl_length;
4758 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4759 if (compl_length < 1)
4760 compl_cont_status &= CONT_LOCAL;
4762 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4763 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4764 else
4765 compl_cont_status = 0;
4767 else
4768 compl_cont_status &= CONT_LOCAL;
4770 if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */
4772 compl_cont_mode = ctrl_x_mode;
4773 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
4774 compl_cont_status = 0;
4775 compl_cont_status |= CONT_N_ADDS;
4776 compl_startpos = curwin->w_cursor;
4777 startcol = (int)curs_col;
4778 compl_col = 0;
4781 /* Work out completion pattern and original text -- webb */
4782 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
4784 if ((compl_cont_status & CONT_SOL)
4785 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4787 if (!(compl_cont_status & CONT_ADDING))
4789 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4791 compl_col += ++startcol;
4792 compl_length = curs_col - startcol;
4794 if (p_ic)
4795 compl_pattern = str_foldcase(line + compl_col,
4796 compl_length, NULL, 0);
4797 else
4798 compl_pattern = vim_strnsave(line + compl_col,
4799 compl_length);
4800 if (compl_pattern == NULL)
4801 return FAIL;
4803 else if (compl_cont_status & CONT_ADDING)
4805 char_u *prefix = (char_u *)"\\<";
4807 /* we need up to 2 extra chars for the prefix */
4808 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4809 compl_length) + 2);
4810 if (compl_pattern == NULL)
4811 return FAIL;
4812 if (!vim_iswordp(line + compl_col)
4813 || (compl_col > 0
4814 && (
4815 #ifdef FEAT_MBYTE
4816 vim_iswordp(mb_prevptr(line, line + compl_col))
4817 #else
4818 vim_iswordc(line[compl_col - 1])
4819 #endif
4821 prefix = (char_u *)"";
4822 STRCPY((char *)compl_pattern, prefix);
4823 (void)quote_meta(compl_pattern + STRLEN(prefix),
4824 line + compl_col, compl_length);
4826 else if (--startcol < 0 ||
4827 #ifdef FEAT_MBYTE
4828 !vim_iswordp(mb_prevptr(line, line + startcol + 1))
4829 #else
4830 !vim_iswordc(line[startcol])
4831 #endif
4834 /* Match any word of at least two chars */
4835 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4836 if (compl_pattern == NULL)
4837 return FAIL;
4838 compl_col += curs_col;
4839 compl_length = 0;
4841 else
4843 #ifdef FEAT_MBYTE
4844 /* Search the point of change class of multibyte character
4845 * or not a word single byte character backward. */
4846 if (has_mbyte)
4848 int base_class;
4849 int head_off;
4851 startcol -= (*mb_head_off)(line, line + startcol);
4852 base_class = mb_get_class(line + startcol);
4853 while (--startcol >= 0)
4855 head_off = (*mb_head_off)(line, line + startcol);
4856 if (base_class != mb_get_class(line + startcol
4857 - head_off))
4858 break;
4859 startcol -= head_off;
4862 else
4863 #endif
4864 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4866 compl_col += ++startcol;
4867 compl_length = (int)curs_col - startcol;
4868 if (compl_length == 1)
4870 /* Only match word with at least two chars -- webb
4871 * there's no need to call quote_meta,
4872 * alloc(7) is enough -- Acevedo
4874 compl_pattern = alloc(7);
4875 if (compl_pattern == NULL)
4876 return FAIL;
4877 STRCPY((char *)compl_pattern, "\\<");
4878 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4879 STRCAT((char *)compl_pattern, "\\k");
4881 else
4883 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4884 compl_length) + 2);
4885 if (compl_pattern == NULL)
4886 return FAIL;
4887 STRCPY((char *)compl_pattern, "\\<");
4888 (void)quote_meta(compl_pattern + 2, line + compl_col,
4889 compl_length);
4893 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4895 compl_col = (colnr_T)(skipwhite(line) - line);
4896 compl_length = (int)curs_col - (int)compl_col;
4897 if (compl_length < 0) /* cursor in indent: empty pattern */
4898 compl_length = 0;
4899 if (p_ic)
4900 compl_pattern = str_foldcase(line + compl_col, compl_length,
4901 NULL, 0);
4902 else
4903 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4904 if (compl_pattern == NULL)
4905 return FAIL;
4907 else if (ctrl_x_mode == CTRL_X_FILES)
4909 while (--startcol >= 0 && vim_isfilec(line[startcol]))
4911 compl_col += ++startcol;
4912 compl_length = (int)curs_col - startcol;
4913 compl_pattern = addstar(line + compl_col, compl_length,
4914 EXPAND_FILES);
4915 if (compl_pattern == NULL)
4916 return FAIL;
4918 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4920 compl_pattern = vim_strnsave(line, curs_col);
4921 if (compl_pattern == NULL)
4922 return FAIL;
4923 set_cmd_context(&compl_xp, compl_pattern,
4924 (int)STRLEN(compl_pattern), curs_col);
4925 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4926 || compl_xp.xp_context == EXPAND_NOTHING)
4927 /* No completion possible, use an empty pattern to get a
4928 * "pattern not found" message. */
4929 compl_col = curs_col;
4930 else
4931 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4932 compl_length = curs_col - compl_col;
4934 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
4936 #ifdef FEAT_COMPL_FUNC
4938 * Call user defined function 'completefunc' with "a:findstart"
4939 * set to 1 to obtain the length of text to use for completion.
4941 char_u *args[2];
4942 int col;
4943 char_u *funcname;
4944 pos_T pos;
4946 /* Call 'completefunc' or 'omnifunc' and get pattern length as a
4947 * string */
4948 funcname = ctrl_x_mode == CTRL_X_FUNCTION
4949 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
4950 if (*funcname == NUL)
4952 EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4953 ? "completefunc" : "omnifunc");
4954 return FAIL;
4957 args[0] = (char_u *)"1";
4958 args[1] = NULL;
4959 pos = curwin->w_cursor;
4960 col = call_func_retnr(funcname, 2, args, FALSE);
4961 curwin->w_cursor = pos; /* restore the cursor position */
4963 if (col < 0)
4964 col = curs_col;
4965 compl_col = col;
4966 if (compl_col > curs_col)
4967 compl_col = curs_col;
4969 /* Setup variables for completion. Need to obtain "line" again,
4970 * it may have become invalid. */
4971 line = ml_get(curwin->w_cursor.lnum);
4972 compl_length = curs_col - compl_col;
4973 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4974 if (compl_pattern == NULL)
4975 #endif
4976 return FAIL;
4978 else if (ctrl_x_mode == CTRL_X_SPELL)
4980 #ifdef FEAT_SPELL
4981 if (spell_bad_len > 0)
4982 compl_col = curs_col - spell_bad_len;
4983 else
4984 compl_col = spell_word_start(startcol);
4985 if (compl_col >= (colnr_T)startcol)
4987 compl_length = 0;
4988 compl_col = curs_col;
4990 else
4992 spell_expand_check_cap(compl_col);
4993 compl_length = (int)curs_col - compl_col;
4995 /* Need to obtain "line" again, it may have become invalid. */
4996 line = ml_get(curwin->w_cursor.lnum);
4997 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4998 if (compl_pattern == NULL)
4999 #endif
5000 return FAIL;
5002 else
5004 EMSG2(_(e_intern2), "ins_complete()");
5005 return FAIL;
5008 if (compl_cont_status & CONT_ADDING)
5010 edit_submode_pre = (char_u *)_(" Adding");
5011 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
5013 /* Insert a new line, keep indentation but ignore 'comments' */
5014 #ifdef FEAT_COMMENTS
5015 char_u *old = curbuf->b_p_com;
5017 curbuf->b_p_com = (char_u *)"";
5018 #endif
5019 compl_startpos.lnum = curwin->w_cursor.lnum;
5020 compl_startpos.col = compl_col;
5021 ins_eol('\r');
5022 #ifdef FEAT_COMMENTS
5023 curbuf->b_p_com = old;
5024 #endif
5025 compl_length = 0;
5026 compl_col = curwin->w_cursor.col;
5029 else
5031 edit_submode_pre = NULL;
5032 compl_startpos.col = compl_col;
5035 if (compl_cont_status & CONT_LOCAL)
5036 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5037 else
5038 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5040 /* Always add completion for the original text. */
5041 vim_free(compl_orig_text);
5042 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5043 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5044 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
5046 vim_free(compl_pattern);
5047 compl_pattern = NULL;
5048 vim_free(compl_orig_text);
5049 compl_orig_text = NULL;
5050 return FAIL;
5053 /* showmode might reset the internal line pointers, so it must
5054 * be called before line = ml_get(), or when this address is no
5055 * longer needed. -- Acevedo.
5057 edit_submode_extra = (char_u *)_("-- Searching...");
5058 edit_submode_highl = HLF_COUNT;
5059 showmode();
5060 edit_submode_extra = NULL;
5061 out_flush();
5064 compl_shown_match = compl_curr_match;
5065 compl_shows_dir = compl_direction;
5068 * Find next match (and following matches).
5070 n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
5072 /* may undisplay the popup menu */
5073 ins_compl_upd_pum();
5075 if (n > 1) /* all matches have been found */
5076 compl_matches = n;
5077 compl_curr_match = compl_shown_match;
5078 compl_direction = compl_shows_dir;
5080 /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5081 * mode. */
5082 if (got_int && !global_busy)
5084 (void)vgetc();
5085 got_int = FALSE;
5088 /* we found no match if the list has only the "compl_orig_text"-entry */
5089 if (compl_first_match == compl_first_match->cp_next)
5091 edit_submode_extra = (compl_cont_status & CONT_ADDING)
5092 && compl_length > 1
5093 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
5094 edit_submode_highl = HLF_E;
5095 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5096 * because we couldn't expand anything at first place, but if we used
5097 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5098 * (such as M in M'exico) if not tried already. -- Acevedo */
5099 if ( compl_length > 1
5100 || (compl_cont_status & CONT_ADDING)
5101 || (ctrl_x_mode != 0
5102 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
5103 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
5104 compl_cont_status &= ~CONT_N_ADDS;
5107 if (compl_curr_match->cp_flags & CONT_S_IPOS)
5108 compl_cont_status |= CONT_S_IPOS;
5109 else
5110 compl_cont_status &= ~CONT_S_IPOS;
5112 if (edit_submode_extra == NULL)
5114 if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
5116 edit_submode_extra = (char_u *)_("Back at original");
5117 edit_submode_highl = HLF_W;
5119 else if (compl_cont_status & CONT_S_IPOS)
5121 edit_submode_extra = (char_u *)_("Word from other line");
5122 edit_submode_highl = HLF_COUNT;
5124 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5126 edit_submode_extra = (char_u *)_("The only match");
5127 edit_submode_highl = HLF_COUNT;
5129 else
5131 /* Update completion sequence number when needed. */
5132 if (compl_curr_match->cp_number == -1)
5134 int number = 0;
5135 compl_T *match;
5137 if (compl_direction == FORWARD)
5139 /* search backwards for the first valid (!= -1) number.
5140 * This should normally succeed already at the first loop
5141 * cycle, so it's fast! */
5142 for (match = compl_curr_match->cp_prev; match != NULL
5143 && match != compl_first_match;
5144 match = match->cp_prev)
5145 if (match->cp_number != -1)
5147 number = match->cp_number;
5148 break;
5150 if (match != NULL)
5151 /* go up and assign all numbers which are not assigned
5152 * yet */
5153 for (match = match->cp_next;
5154 match != NULL && match->cp_number == -1;
5155 match = match->cp_next)
5156 match->cp_number = ++number;
5158 else /* BACKWARD */
5160 /* search forwards (upwards) for the first valid (!= -1)
5161 * number. This should normally succeed already at the
5162 * first loop cycle, so it's fast! */
5163 for (match = compl_curr_match->cp_next; match != NULL
5164 && match != compl_first_match;
5165 match = match->cp_next)
5166 if (match->cp_number != -1)
5168 number = match->cp_number;
5169 break;
5171 if (match != NULL)
5172 /* go down and assign all numbers which are not
5173 * assigned yet */
5174 for (match = match->cp_prev; match
5175 && match->cp_number == -1;
5176 match = match->cp_prev)
5177 match->cp_number = ++number;
5181 /* The match should always have a sequence number now, this is
5182 * just a safety check. */
5183 if (compl_curr_match->cp_number != -1)
5185 /* Space for 10 text chars. + 2x10-digit no.s = 31.
5186 * Translations may need more than twice that. */
5187 static char_u match_ref[81];
5189 if (compl_matches > 0)
5190 vim_snprintf((char *)match_ref, sizeof(match_ref),
5191 _("match %d of %d"),
5192 compl_curr_match->cp_number, compl_matches);
5193 else
5194 vim_snprintf((char *)match_ref, sizeof(match_ref),
5195 _("match %d"),
5196 compl_curr_match->cp_number);
5197 edit_submode_extra = match_ref;
5198 edit_submode_highl = HLF_R;
5199 if (dollar_vcol)
5200 curs_columns(FALSE);
5205 /* Show a message about what (completion) mode we're in. */
5206 showmode();
5207 if (edit_submode_extra != NULL)
5209 if (!p_smd)
5210 msg_attr(edit_submode_extra,
5211 edit_submode_highl < HLF_COUNT
5212 ? hl_attr(edit_submode_highl) : 0);
5214 else
5215 msg_clr_cmdline(); /* necessary for "noshowmode" */
5217 /* Show the popup menu, unless we got interrupted. */
5218 if (!compl_interrupted)
5220 /* RedrawingDisabled may be set when invoked through complete(). */
5221 n = RedrawingDisabled;
5222 RedrawingDisabled = 0;
5223 ins_compl_show_pum();
5224 setcursor();
5225 RedrawingDisabled = n;
5227 compl_was_interrupted = compl_interrupted;
5228 compl_interrupted = FALSE;
5230 return OK;
5234 * Looks in the first "len" chars. of "src" for search-metachars.
5235 * If dest is not NULL the chars. are copied there quoting (with
5236 * a backslash) the metachars, and dest would be NUL terminated.
5237 * Returns the length (needed) of dest
5239 static unsigned
5240 quote_meta(dest, src, len)
5241 char_u *dest;
5242 char_u *src;
5243 int len;
5245 unsigned m = (unsigned)len + 1; /* one extra for the NUL */
5247 for ( ; --len >= 0; src++)
5249 switch (*src)
5251 case '.':
5252 case '*':
5253 case '[':
5254 if (ctrl_x_mode == CTRL_X_DICTIONARY
5255 || ctrl_x_mode == CTRL_X_THESAURUS)
5256 break;
5257 case '~':
5258 if (!p_magic) /* quote these only if magic is set */
5259 break;
5260 case '\\':
5261 if (ctrl_x_mode == CTRL_X_DICTIONARY
5262 || ctrl_x_mode == CTRL_X_THESAURUS)
5263 break;
5264 case '^': /* currently it's not needed. */
5265 case '$':
5266 m++;
5267 if (dest != NULL)
5268 *dest++ = '\\';
5269 break;
5271 if (dest != NULL)
5272 *dest++ = *src;
5273 # ifdef FEAT_MBYTE
5274 /* Copy remaining bytes of a multibyte character. */
5275 if (has_mbyte)
5277 int i, mb_len;
5279 mb_len = (*mb_ptr2len)(src) - 1;
5280 if (mb_len > 0 && len >= mb_len)
5281 for (i = 0; i < mb_len; ++i)
5283 --len;
5284 ++src;
5285 if (dest != NULL)
5286 *dest++ = *src;
5289 # endif
5291 if (dest != NULL)
5292 *dest = NUL;
5294 return m;
5296 #endif /* FEAT_INS_EXPAND */
5299 * Next character is interpreted literally.
5300 * A one, two or three digit decimal number is interpreted as its byte value.
5301 * If one or two digits are entered, the next character is given to vungetc().
5302 * For Unicode a character > 255 may be returned.
5305 get_literal()
5307 int cc;
5308 int nc;
5309 int i;
5310 int hex = FALSE;
5311 int octal = FALSE;
5312 #ifdef FEAT_MBYTE
5313 int unicode = 0;
5314 #endif
5316 if (got_int)
5317 return Ctrl_C;
5319 #ifdef FEAT_GUI
5321 * In GUI there is no point inserting the internal code for a special key.
5322 * It is more useful to insert the string "<KEY>" instead. This would
5323 * probably be useful in a text window too, but it would not be
5324 * vi-compatible (maybe there should be an option for it?) -- webb
5326 if (gui.in_use)
5327 ++allow_keys;
5328 #endif
5329 #ifdef USE_ON_FLY_SCROLL
5330 dont_scroll = TRUE; /* disallow scrolling here */
5331 #endif
5332 ++no_mapping; /* don't map the next key hits */
5333 cc = 0;
5334 i = 0;
5335 for (;;)
5337 nc = plain_vgetc();
5338 #ifdef FEAT_CMDL_INFO
5339 if (!(State & CMDLINE)
5340 # ifdef FEAT_MBYTE
5341 && MB_BYTE2LEN_CHECK(nc) == 1
5342 # endif
5344 add_to_showcmd(nc);
5345 #endif
5346 if (nc == 'x' || nc == 'X')
5347 hex = TRUE;
5348 else if (nc == 'o' || nc == 'O')
5349 octal = TRUE;
5350 #ifdef FEAT_MBYTE
5351 else if (nc == 'u' || nc == 'U')
5352 unicode = nc;
5353 #endif
5354 else
5356 if (hex
5357 #ifdef FEAT_MBYTE
5358 || unicode != 0
5359 #endif
5362 if (!vim_isxdigit(nc))
5363 break;
5364 cc = cc * 16 + hex2nr(nc);
5366 else if (octal)
5368 if (nc < '0' || nc > '7')
5369 break;
5370 cc = cc * 8 + nc - '0';
5372 else
5374 if (!VIM_ISDIGIT(nc))
5375 break;
5376 cc = cc * 10 + nc - '0';
5379 ++i;
5382 if (cc > 255
5383 #ifdef FEAT_MBYTE
5384 && unicode == 0
5385 #endif
5387 cc = 255; /* limit range to 0-255 */
5388 nc = 0;
5390 if (hex) /* hex: up to two chars */
5392 if (i >= 2)
5393 break;
5395 #ifdef FEAT_MBYTE
5396 else if (unicode) /* Unicode: up to four or eight chars */
5398 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
5399 break;
5401 #endif
5402 else if (i >= 3) /* decimal or octal: up to three chars */
5403 break;
5405 if (i == 0) /* no number entered */
5407 if (nc == K_ZERO) /* NUL is stored as NL */
5409 cc = '\n';
5410 nc = 0;
5412 else
5414 cc = nc;
5415 nc = 0;
5419 if (cc == 0) /* NUL is stored as NL */
5420 cc = '\n';
5421 #ifdef FEAT_MBYTE
5422 if (enc_dbcs && (cc & 0xff) == 0)
5423 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
5424 second byte will cause trouble! */
5425 #endif
5427 --no_mapping;
5428 #ifdef FEAT_GUI
5429 if (gui.in_use)
5430 --allow_keys;
5431 #endif
5432 if (nc)
5433 vungetc(nc);
5434 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
5435 return cc;
5439 * Insert character, taking care of special keys and mod_mask
5441 static void
5442 insert_special(c, allow_modmask, ctrlv)
5443 int c;
5444 int allow_modmask;
5445 int ctrlv; /* c was typed after CTRL-V */
5447 char_u *p;
5448 int len;
5451 * Special function key, translate into "<Key>". Up to the last '>' is
5452 * inserted with ins_str(), so as not to replace characters in replace
5453 * mode.
5454 * Only use mod_mask for special keys, to avoid things like <S-Space>,
5455 * unless 'allow_modmask' is TRUE.
5457 #ifdef MACOS
5458 /* Command-key never produces a normal key */
5459 if (mod_mask & MOD_MASK_CMD)
5460 allow_modmask = TRUE;
5461 #endif
5462 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5464 p = get_special_key_name(c, mod_mask);
5465 len = (int)STRLEN(p);
5466 c = p[len - 1];
5467 if (len > 2)
5469 if (stop_arrow() == FAIL)
5470 return;
5471 p[len - 1] = NUL;
5472 ins_str(p);
5473 AppendToRedobuffLit(p, -1);
5474 ctrlv = FALSE;
5477 if (stop_arrow() == OK)
5478 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5482 * Special characters in this context are those that need processing other
5483 * than the simple insertion that can be performed here. This includes ESC
5484 * which terminates the insert, and CR/NL which need special processing to
5485 * open up a new line. This routine tries to optimize insertions performed by
5486 * the "redo", "undo" or "put" commands, so it needs to know when it should
5487 * stop and defer processing to the "normal" mechanism.
5488 * '0' and '^' are special, because they can be followed by CTRL-D.
5490 #ifdef EBCDIC
5491 # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
5492 #else
5493 # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5494 #endif
5496 #ifdef FEAT_MBYTE
5497 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5498 #else
5499 # define WHITECHAR(cc) vim_iswhite(cc)
5500 #endif
5502 void
5503 insertchar(c, flags, second_indent)
5504 int c; /* character to insert or NUL */
5505 int flags; /* INSCHAR_FORMAT, etc. */
5506 int second_indent; /* indent for second line if >= 0 */
5508 int textwidth;
5509 #ifdef FEAT_COMMENTS
5510 char_u *p;
5511 #endif
5512 int fo_ins_blank;
5514 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5515 fo_ins_blank = has_format_option(FO_INS_BLANK);
5518 * Try to break the line in two or more pieces when:
5519 * - Always do this if we have been called to do formatting only.
5520 * - Always do this when 'formatoptions' has the 'a' flag and the line
5521 * ends in white space.
5522 * - Otherwise:
5523 * - Don't do this if inserting a blank
5524 * - Don't do this if an existing character is being replaced, unless
5525 * we're in VREPLACE mode.
5526 * - Do this if the cursor is not on the line where insert started
5527 * or - 'formatoptions' doesn't have 'l' or the line was not too long
5528 * before the insert.
5529 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5530 * before 'textwidth'
5532 if (textwidth > 0
5533 && ((flags & INSCHAR_FORMAT)
5534 || (!vim_iswhite(c)
5535 && !((State & REPLACE_FLAG)
5536 #ifdef FEAT_VREPLACE
5537 && !(State & VREPLACE_FLAG)
5538 #endif
5539 && *ml_get_cursor() != NUL)
5540 && (curwin->w_cursor.lnum != Insstart.lnum
5541 || ((!has_format_option(FO_INS_LONG)
5542 || Insstart_textlen <= (colnr_T)textwidth)
5543 && (!fo_ins_blank
5544 || Insstart_blank_vcol <= (colnr_T)textwidth
5545 ))))))
5547 /* Format with 'formatexpr' when it's set. Use internal formatting
5548 * when 'formatexpr' isn't set or it returns non-zero. */
5549 #if defined(FEAT_EVAL)
5550 int do_internal = TRUE;
5552 if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0)
5554 do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0);
5555 /* It may be required to save for undo again, e.g. when setline()
5556 * was called. */
5557 ins_need_undo = TRUE;
5559 if (do_internal)
5560 #endif
5561 internal_format(textwidth, second_indent, flags, c == NUL, c);
5564 if (c == NUL) /* only formatting was wanted */
5565 return;
5567 #ifdef FEAT_COMMENTS
5568 /* Check whether this character should end a comment. */
5569 if (did_ai && (int)c == end_comment_pending)
5571 char_u *line;
5572 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5573 int middle_len, end_len;
5574 int i;
5577 * Need to remove existing (middle) comment leader and insert end
5578 * comment leader. First, check what comment leader we can find.
5580 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
5581 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
5583 /* Skip middle-comment string */
5584 while (*p && p[-1] != ':') /* find end of middle flags */
5585 ++p;
5586 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5587 /* Don't count trailing white space for middle_len */
5588 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5589 --middle_len;
5591 /* Find the end-comment string */
5592 while (*p && p[-1] != ':') /* find end of end flags */
5593 ++p;
5594 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5596 /* Skip white space before the cursor */
5597 i = curwin->w_cursor.col;
5598 while (--i >= 0 && vim_iswhite(line[i]))
5600 i++;
5602 /* Skip to before the middle leader */
5603 i -= middle_len;
5605 /* Check some expected things before we go on */
5606 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5608 /* Backspace over all the stuff we want to replace */
5609 backspace_until_column(i);
5612 * Insert the end-comment string, except for the last
5613 * character, which will get inserted as normal later.
5615 ins_bytes_len(lead_end, end_len - 1);
5619 end_comment_pending = NUL;
5620 #endif
5622 did_ai = FALSE;
5623 #ifdef FEAT_SMARTINDENT
5624 did_si = FALSE;
5625 can_si = FALSE;
5626 can_si_back = FALSE;
5627 #endif
5630 * If there's any pending input, grab up to INPUT_BUFLEN at once.
5631 * This speeds up normal text input considerably.
5632 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5633 * need to re-indent at a ':', or any other character (but not what
5634 * 'paste' is set)..
5636 #ifdef USE_ON_FLY_SCROLL
5637 dont_scroll = FALSE; /* allow scrolling here */
5638 #endif
5640 if ( !ISSPECIAL(c)
5641 #ifdef FEAT_MBYTE
5642 && (!has_mbyte || (*mb_char2len)(c) == 1)
5643 #endif
5644 && vpeekc() != NUL
5645 && !(State & REPLACE_FLAG)
5646 #ifdef FEAT_CINDENT
5647 && !cindent_on()
5648 #endif
5649 #ifdef FEAT_RIGHTLEFT
5650 && !p_ri
5651 #endif
5654 #define INPUT_BUFLEN 100
5655 char_u buf[INPUT_BUFLEN + 1];
5656 int i;
5657 colnr_T virtcol = 0;
5659 buf[0] = c;
5660 i = 1;
5661 if (textwidth > 0)
5662 virtcol = get_nolist_virtcol();
5664 * Stop the string when:
5665 * - no more chars available
5666 * - finding a special character (command key)
5667 * - buffer is full
5668 * - running into the 'textwidth' boundary
5669 * - need to check for abbreviation: A non-word char after a word-char
5671 while ( (c = vpeekc()) != NUL
5672 && !ISSPECIAL(c)
5673 #ifdef FEAT_MBYTE
5674 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5675 #endif
5676 && i < INPUT_BUFLEN
5677 && (textwidth == 0
5678 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5679 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5681 #ifdef FEAT_RIGHTLEFT
5682 c = vgetc();
5683 if (p_hkmap && KeyTyped)
5684 c = hkmap(c); /* Hebrew mode mapping */
5685 # ifdef FEAT_FKMAP
5686 if (p_fkmap && KeyTyped)
5687 c = fkmap(c); /* Farsi mode mapping */
5688 # endif
5689 buf[i++] = c;
5690 #else
5691 buf[i++] = vgetc();
5692 #endif
5695 #ifdef FEAT_DIGRAPHS
5696 do_digraph(-1); /* clear digraphs */
5697 do_digraph(buf[i-1]); /* may be the start of a digraph */
5698 #endif
5699 buf[i] = NUL;
5700 ins_str(buf);
5701 if (flags & INSCHAR_CTRLV)
5703 redo_literal(*buf);
5704 i = 1;
5706 else
5707 i = 0;
5708 if (buf[i] != NUL)
5709 AppendToRedobuffLit(buf + i, -1);
5711 else
5713 #ifdef FEAT_MBYTE
5714 int cc;
5716 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
5718 char_u buf[MB_MAXBYTES + 1];
5720 (*mb_char2bytes)(c, buf);
5721 buf[cc] = NUL;
5722 ins_char_bytes(buf, cc);
5723 AppendCharToRedobuff(c);
5725 else
5726 #endif
5728 ins_char(c);
5729 if (flags & INSCHAR_CTRLV)
5730 redo_literal(c);
5731 else
5732 AppendCharToRedobuff(c);
5738 * Format text at the current insert position.
5740 static void
5741 internal_format(textwidth, second_indent, flags, format_only, c)
5742 int textwidth;
5743 int second_indent;
5744 int flags;
5745 int format_only;
5746 int c; /* character to be inserted (can be NUL) */
5748 int cc;
5749 int save_char = NUL;
5750 int haveto_redraw = FALSE;
5751 int fo_ins_blank = has_format_option(FO_INS_BLANK);
5752 #ifdef FEAT_MBYTE
5753 int fo_multibyte = has_format_option(FO_MBYTE_BREAK);
5754 #endif
5755 int fo_white_par = has_format_option(FO_WHITE_PAR);
5756 int first_line = TRUE;
5757 #ifdef FEAT_COMMENTS
5758 colnr_T leader_len;
5759 int no_leader = FALSE;
5760 int do_comments = (flags & INSCHAR_DO_COM);
5761 #endif
5764 * When 'ai' is off we don't want a space under the cursor to be
5765 * deleted. Replace it with an 'x' temporarily.
5767 if (!curbuf->b_p_ai
5768 #ifdef FEAT_VREPLACE
5769 && !(State & VREPLACE_FLAG)
5770 #endif
5773 cc = gchar_cursor();
5774 if (vim_iswhite(cc))
5776 save_char = cc;
5777 pchar_cursor('x');
5782 * Repeat breaking lines, until the current line is not too long.
5784 while (!got_int)
5786 int startcol; /* Cursor column at entry */
5787 int wantcol; /* column at textwidth border */
5788 int foundcol; /* column for start of spaces */
5789 int end_foundcol = 0; /* column for start of word */
5790 colnr_T len;
5791 colnr_T virtcol;
5792 #ifdef FEAT_VREPLACE
5793 int orig_col = 0;
5794 char_u *saved_text = NULL;
5795 #endif
5796 colnr_T col;
5797 colnr_T end_col;
5799 virtcol = get_nolist_virtcol()
5800 + char2cells(c != NUL ? c : gchar_cursor());
5801 if (virtcol <= (colnr_T)textwidth)
5802 break;
5804 #ifdef FEAT_COMMENTS
5805 if (no_leader)
5806 do_comments = FALSE;
5807 else if (!(flags & INSCHAR_FORMAT)
5808 && has_format_option(FO_WRAP_COMS))
5809 do_comments = TRUE;
5811 /* Don't break until after the comment leader */
5812 if (do_comments)
5813 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
5814 else
5815 leader_len = 0;
5817 /* If the line doesn't start with a comment leader, then don't
5818 * start one in a following broken line. Avoids that a %word
5819 * moved to the start of the next line causes all following lines
5820 * to start with %. */
5821 if (leader_len == 0)
5822 no_leader = TRUE;
5823 #endif
5824 if (!(flags & INSCHAR_FORMAT)
5825 #ifdef FEAT_COMMENTS
5826 && leader_len == 0
5827 #endif
5828 && !has_format_option(FO_WRAP))
5831 textwidth = 0;
5832 break;
5834 if ((startcol = curwin->w_cursor.col) == 0)
5835 break;
5837 /* find column of textwidth border */
5838 coladvance((colnr_T)textwidth);
5839 wantcol = curwin->w_cursor.col;
5841 curwin->w_cursor.col = startcol;
5842 foundcol = 0;
5845 * Find position to break at.
5846 * Stop at first entered white when 'formatoptions' has 'v'
5848 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
5849 || curwin->w_cursor.lnum != Insstart.lnum
5850 || curwin->w_cursor.col >= Insstart.col)
5852 if (curwin->w_cursor.col == startcol && c != NUL)
5853 cc = c;
5854 else
5855 cc = gchar_cursor();
5856 if (WHITECHAR(cc))
5858 /* remember position of blank just before text */
5859 end_col = curwin->w_cursor.col;
5861 /* find start of sequence of blanks */
5862 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
5864 dec_cursor();
5865 cc = gchar_cursor();
5867 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
5868 break; /* only spaces in front of text */
5869 #ifdef FEAT_COMMENTS
5870 /* Don't break until after the comment leader */
5871 if (curwin->w_cursor.col < leader_len)
5872 break;
5873 #endif
5874 if (has_format_option(FO_ONE_LETTER))
5876 /* do not break after one-letter words */
5877 if (curwin->w_cursor.col == 0)
5878 break; /* one-letter word at begin */
5879 #ifdef FEAT_COMMENTS
5880 /* do not break "#a b" when 'tw' is 2 */
5881 if (curwin->w_cursor.col <= leader_len)
5882 break;
5883 #endif
5884 col = curwin->w_cursor.col;
5885 dec_cursor();
5886 cc = gchar_cursor();
5888 if (WHITECHAR(cc))
5889 continue; /* one-letter, continue */
5890 curwin->w_cursor.col = col;
5893 inc_cursor();
5895 end_foundcol = end_col + 1;
5896 foundcol = curwin->w_cursor.col;
5897 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5898 break;
5900 #ifdef FEAT_MBYTE
5901 else if (cc >= 0x100 && fo_multibyte)
5903 /* Break after or before a multi-byte character. */
5904 if (curwin->w_cursor.col != startcol)
5906 #ifdef FEAT_COMMENTS
5907 /* Don't break until after the comment leader */
5908 if (curwin->w_cursor.col < leader_len)
5909 break;
5910 #endif
5911 col = curwin->w_cursor.col;
5912 inc_cursor();
5913 /* Don't change end_foundcol if already set. */
5914 if (foundcol != curwin->w_cursor.col)
5916 foundcol = curwin->w_cursor.col;
5917 end_foundcol = foundcol;
5918 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5919 break;
5921 curwin->w_cursor.col = col;
5924 if (curwin->w_cursor.col == 0)
5925 break;
5927 col = curwin->w_cursor.col;
5929 dec_cursor();
5930 cc = gchar_cursor();
5932 if (WHITECHAR(cc))
5933 continue; /* break with space */
5934 #ifdef FEAT_COMMENTS
5935 /* Don't break until after the comment leader */
5936 if (curwin->w_cursor.col < leader_len)
5937 break;
5938 #endif
5940 curwin->w_cursor.col = col;
5942 foundcol = curwin->w_cursor.col;
5943 end_foundcol = foundcol;
5944 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5945 break;
5947 #endif
5948 if (curwin->w_cursor.col == 0)
5949 break;
5950 dec_cursor();
5953 if (foundcol == 0) /* no spaces, cannot break line */
5955 curwin->w_cursor.col = startcol;
5956 break;
5959 /* Going to break the line, remove any "$" now. */
5960 undisplay_dollar();
5963 * Offset between cursor position and line break is used by replace
5964 * stack functions. VREPLACE does not use this, and backspaces
5965 * over the text instead.
5967 #ifdef FEAT_VREPLACE
5968 if (State & VREPLACE_FLAG)
5969 orig_col = startcol; /* Will start backspacing from here */
5970 else
5971 #endif
5972 replace_offset = startcol - end_foundcol;
5975 * adjust startcol for spaces that will be deleted and
5976 * characters that will remain on top line
5978 curwin->w_cursor.col = foundcol;
5979 while ((cc = gchar_cursor(), WHITECHAR(cc))
5980 && (!fo_white_par || curwin->w_cursor.col < startcol))
5981 inc_cursor();
5982 startcol -= curwin->w_cursor.col;
5983 if (startcol < 0)
5984 startcol = 0;
5986 #ifdef FEAT_VREPLACE
5987 if (State & VREPLACE_FLAG)
5990 * In VREPLACE mode, we will backspace over the text to be
5991 * wrapped, so save a copy now to put on the next line.
5993 saved_text = vim_strsave(ml_get_cursor());
5994 curwin->w_cursor.col = orig_col;
5995 if (saved_text == NULL)
5996 break; /* Can't do it, out of memory */
5997 saved_text[startcol] = NUL;
5999 /* Backspace over characters that will move to the next line */
6000 if (!fo_white_par)
6001 backspace_until_column(foundcol);
6003 else
6004 #endif
6006 /* put cursor after pos. to break line */
6007 if (!fo_white_par)
6008 curwin->w_cursor.col = foundcol;
6012 * Split the line just before the margin.
6013 * Only insert/delete lines, but don't really redraw the window.
6015 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
6016 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
6017 #ifdef FEAT_COMMENTS
6018 + (do_comments ? OPENLINE_DO_COM : 0)
6019 #endif
6020 , old_indent);
6021 old_indent = 0;
6023 replace_offset = 0;
6024 if (first_line)
6026 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
6027 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
6028 if (second_indent >= 0)
6030 #ifdef FEAT_VREPLACE
6031 if (State & VREPLACE_FLAG)
6032 change_indent(INDENT_SET, second_indent, FALSE, NUL, TRUE);
6033 else
6034 #endif
6035 (void)set_indent(second_indent, SIN_CHANGED);
6037 first_line = FALSE;
6040 #ifdef FEAT_VREPLACE
6041 if (State & VREPLACE_FLAG)
6044 * In VREPLACE mode we have backspaced over the text to be
6045 * moved, now we re-insert it into the new line.
6047 ins_bytes(saved_text);
6048 vim_free(saved_text);
6050 else
6051 #endif
6054 * Check if cursor is not past the NUL off the line, cindent
6055 * may have added or removed indent.
6057 curwin->w_cursor.col += startcol;
6058 len = (colnr_T)STRLEN(ml_get_curline());
6059 if (curwin->w_cursor.col > len)
6060 curwin->w_cursor.col = len;
6063 haveto_redraw = TRUE;
6064 #ifdef FEAT_CINDENT
6065 can_cindent = TRUE;
6066 #endif
6067 /* moved the cursor, don't autoindent or cindent now */
6068 did_ai = FALSE;
6069 #ifdef FEAT_SMARTINDENT
6070 did_si = FALSE;
6071 can_si = FALSE;
6072 can_si_back = FALSE;
6073 #endif
6074 line_breakcheck();
6077 if (save_char != NUL) /* put back space after cursor */
6078 pchar_cursor(save_char);
6080 if (!format_only && haveto_redraw)
6082 update_topline();
6083 redraw_curbuf_later(VALID);
6088 * Called after inserting or deleting text: When 'formatoptions' includes the
6089 * 'a' flag format from the current line until the end of the paragraph.
6090 * Keep the cursor at the same position relative to the text.
6091 * The caller must have saved the cursor line for undo, following ones will be
6092 * saved here.
6094 void
6095 auto_format(trailblank, prev_line)
6096 int trailblank; /* when TRUE also format with trailing blank */
6097 int prev_line; /* may start in previous line */
6099 pos_T pos;
6100 colnr_T len;
6101 char_u *old;
6102 char_u *new, *pnew;
6103 int wasatend;
6104 int cc;
6106 if (!has_format_option(FO_AUTO))
6107 return;
6109 pos = curwin->w_cursor;
6110 old = ml_get_curline();
6112 /* may remove added space */
6113 check_auto_format(FALSE);
6115 /* Don't format in Insert mode when the cursor is on a trailing blank, the
6116 * user might insert normal text next. Also skip formatting when "1" is
6117 * in 'formatoptions' and there is a single character before the cursor.
6118 * Otherwise the line would be broken and when typing another non-white
6119 * next they are not joined back together. */
6120 wasatend = (pos.col == (colnr_T)STRLEN(old));
6121 if (*old != NUL && !trailblank && wasatend)
6123 dec_cursor();
6124 cc = gchar_cursor();
6125 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
6126 && has_format_option(FO_ONE_LETTER))
6127 dec_cursor();
6128 cc = gchar_cursor();
6129 if (WHITECHAR(cc))
6131 curwin->w_cursor = pos;
6132 return;
6134 curwin->w_cursor = pos;
6137 #ifdef FEAT_COMMENTS
6138 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
6139 * comments. */
6140 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
6141 && get_leader_len(old, NULL, FALSE) == 0)
6142 return;
6143 #endif
6146 * May start formatting in a previous line, so that after "x" a word is
6147 * moved to the previous line if it fits there now. Only when this is not
6148 * the start of a paragraph.
6150 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
6152 --curwin->w_cursor.lnum;
6153 if (u_save_cursor() == FAIL)
6154 return;
6158 * Do the formatting and restore the cursor position. "saved_cursor" will
6159 * be adjusted for the text formatting.
6161 saved_cursor = pos;
6162 format_lines((linenr_T)-1, FALSE);
6163 curwin->w_cursor = saved_cursor;
6164 saved_cursor.lnum = 0;
6166 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6168 /* "cannot happen" */
6169 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6170 coladvance((colnr_T)MAXCOL);
6172 else
6173 check_cursor_col();
6175 /* Insert mode: If the cursor is now after the end of the line while it
6176 * previously wasn't, the line was broken. Because of the rule above we
6177 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
6178 * formatted. */
6179 if (!wasatend && has_format_option(FO_WHITE_PAR))
6181 new = ml_get_curline();
6182 len = (colnr_T)STRLEN(new);
6183 if (curwin->w_cursor.col == len)
6185 pnew = vim_strnsave(new, len + 2);
6186 pnew[len] = ' ';
6187 pnew[len + 1] = NUL;
6188 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
6189 /* remove the space later */
6190 did_add_space = TRUE;
6192 else
6193 /* may remove added space */
6194 check_auto_format(FALSE);
6197 check_cursor();
6201 * When an extra space was added to continue a paragraph for auto-formatting,
6202 * delete it now. The space must be under the cursor, just after the insert
6203 * position.
6205 static void
6206 check_auto_format(end_insert)
6207 int end_insert; /* TRUE when ending Insert mode */
6209 int c = ' ';
6210 int cc;
6212 if (did_add_space)
6214 cc = gchar_cursor();
6215 if (!WHITECHAR(cc))
6216 /* Somehow the space was removed already. */
6217 did_add_space = FALSE;
6218 else
6220 if (!end_insert)
6222 inc_cursor();
6223 c = gchar_cursor();
6224 dec_cursor();
6226 if (c != NUL)
6228 /* The space is no longer at the end of the line, delete it. */
6229 del_char(FALSE);
6230 did_add_space = FALSE;
6237 * Find out textwidth to be used for formatting:
6238 * if 'textwidth' option is set, use it
6239 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
6240 * if invalid value, use 0.
6241 * Set default to window width (maximum 79) for "gq" operator.
6244 comp_textwidth(ff)
6245 int ff; /* force formatting (for "gq" command) */
6247 int textwidth;
6249 textwidth = curbuf->b_p_tw;
6250 if (textwidth == 0 && curbuf->b_p_wm)
6252 /* The width is the window width minus 'wrapmargin' minus all the
6253 * things that add to the margin. */
6254 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
6255 #ifdef FEAT_CMDWIN
6256 if (cmdwin_type != 0)
6257 textwidth -= 1;
6258 #endif
6259 #ifdef FEAT_FOLDING
6260 textwidth -= curwin->w_p_fdc;
6261 #endif
6262 #ifdef FEAT_SIGNS
6263 if (curwin->w_buffer->b_signlist != NULL
6264 # ifdef FEAT_NETBEANS_INTG
6265 || usingNetbeans
6266 # endif
6268 textwidth -= 1;
6269 #endif
6270 if (curwin->w_p_nu)
6271 textwidth -= 8;
6273 if (textwidth < 0)
6274 textwidth = 0;
6275 if (ff && textwidth == 0)
6277 textwidth = W_WIDTH(curwin) - 1;
6278 if (textwidth > 79)
6279 textwidth = 79;
6281 return textwidth;
6285 * Put a character in the redo buffer, for when just after a CTRL-V.
6287 static void
6288 redo_literal(c)
6289 int c;
6291 char_u buf[10];
6293 /* Only digits need special treatment. Translate them into a string of
6294 * three digits. */
6295 if (VIM_ISDIGIT(c))
6297 vim_snprintf((char *)buf, sizeof(buf), "%03d", c);
6298 AppendToRedobuff(buf);
6300 else
6301 AppendCharToRedobuff(c);
6305 * start_arrow() is called when an arrow key is used in insert mode.
6306 * For undo/redo it resembles hitting the <ESC> key.
6308 static void
6309 start_arrow(end_insert_pos)
6310 pos_T *end_insert_pos; /* can be NULL */
6312 if (!arrow_used) /* something has been inserted */
6314 AppendToRedobuff(ESC_STR);
6315 stop_insert(end_insert_pos, FALSE);
6316 arrow_used = TRUE; /* this means we stopped the current insert */
6318 #ifdef FEAT_SPELL
6319 check_spell_redraw();
6320 #endif
6323 #ifdef FEAT_SPELL
6325 * If we skipped highlighting word at cursor, do it now.
6326 * It may be skipped again, thus reset spell_redraw_lnum first.
6328 static void
6329 check_spell_redraw()
6331 if (spell_redraw_lnum != 0)
6333 linenr_T lnum = spell_redraw_lnum;
6335 spell_redraw_lnum = 0;
6336 redrawWinline(lnum, FALSE);
6341 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6342 * spelled word, if there is one.
6344 static void
6345 spell_back_to_badword()
6347 pos_T tpos = curwin->w_cursor;
6349 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
6350 if (curwin->w_cursor.col != tpos.col)
6351 start_arrow(&tpos);
6353 #endif
6356 * stop_arrow() is called before a change is made in insert mode.
6357 * If an arrow key has been used, start a new insertion.
6358 * Returns FAIL if undo is impossible, shouldn't insert then.
6361 stop_arrow()
6363 if (arrow_used)
6365 if (u_save_cursor() == OK)
6367 arrow_used = FALSE;
6368 ins_need_undo = FALSE;
6370 Insstart = curwin->w_cursor; /* new insertion starts here */
6371 Insstart_textlen = (colnr_T)linetabsize(ml_get_curline());
6372 ai_col = 0;
6373 #ifdef FEAT_VREPLACE
6374 if (State & VREPLACE_FLAG)
6376 orig_line_count = curbuf->b_ml.ml_line_count;
6377 vr_lines_changed = 1;
6379 #endif
6380 ResetRedobuff();
6381 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
6382 new_insert_skip = 2;
6384 else if (ins_need_undo)
6386 if (u_save_cursor() == OK)
6387 ins_need_undo = FALSE;
6390 #ifdef FEAT_FOLDING
6391 /* Always open fold at the cursor line when inserting something. */
6392 foldOpenCursor();
6393 #endif
6395 return (arrow_used || ins_need_undo ? FAIL : OK);
6399 * Do a few things to stop inserting.
6400 * "end_insert_pos" is where insert ended. It is NULL when we already jumped
6401 * to another window/buffer.
6403 static void
6404 stop_insert(end_insert_pos, esc)
6405 pos_T *end_insert_pos;
6406 int esc; /* called by ins_esc() */
6408 int cc;
6409 char_u *ptr;
6411 stop_redo_ins();
6412 replace_flush(); /* abandon replace stack */
6415 * Save the inserted text for later redo with ^@ and CTRL-A.
6416 * Don't do it when "restart_edit" was set and nothing was inserted,
6417 * otherwise CTRL-O w and then <Left> will clear "last_insert".
6419 ptr = get_inserted();
6420 if (did_restart_edit == 0 || (ptr != NULL
6421 && (int)STRLEN(ptr) > new_insert_skip))
6423 vim_free(last_insert);
6424 last_insert = ptr;
6425 last_insert_skip = new_insert_skip;
6427 else
6428 vim_free(ptr);
6430 if (!arrow_used && end_insert_pos != NULL)
6432 /* Auto-format now. It may seem strange to do this when stopping an
6433 * insertion (or moving the cursor), but it's required when appending
6434 * a line and having it end in a space. But only do it when something
6435 * was actually inserted, otherwise undo won't work. */
6436 if (!ins_need_undo && has_format_option(FO_AUTO))
6438 pos_T tpos = curwin->w_cursor;
6440 /* When the cursor is at the end of the line after a space the
6441 * formatting will move it to the following word. Avoid that by
6442 * moving the cursor onto the space. */
6443 cc = 'x';
6444 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
6446 dec_cursor();
6447 cc = gchar_cursor();
6448 if (!vim_iswhite(cc))
6449 curwin->w_cursor = tpos;
6452 auto_format(TRUE, FALSE);
6454 if (vim_iswhite(cc))
6456 if (gchar_cursor() != NUL)
6457 inc_cursor();
6458 #ifdef FEAT_VIRTUALEDIT
6459 /* If the cursor is still at the same character, also keep
6460 * the "coladd". */
6461 if (gchar_cursor() == NUL
6462 && curwin->w_cursor.lnum == tpos.lnum
6463 && curwin->w_cursor.col == tpos.col)
6464 curwin->w_cursor.coladd = tpos.coladd;
6465 #endif
6469 /* If a space was inserted for auto-formatting, remove it now. */
6470 check_auto_format(TRUE);
6472 /* If we just did an auto-indent, remove the white space from the end
6473 * of the line, and put the cursor back.
6474 * Do this when ESC was used or moving the cursor up/down.
6475 * Check for the old position still being valid, just in case the text
6476 * got changed unexpectedly. */
6477 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6478 && curwin->w_cursor.lnum != end_insert_pos->lnum))
6479 && end_insert_pos->lnum <= curbuf->b_ml.ml_line_count)
6481 pos_T tpos = curwin->w_cursor;
6483 curwin->w_cursor = *end_insert_pos;
6484 check_cursor_col(); /* make sure it is not past the line */
6485 for (;;)
6487 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6488 --curwin->w_cursor.col;
6489 cc = gchar_cursor();
6490 if (!vim_iswhite(cc))
6491 break;
6492 if (del_char(TRUE) == FAIL)
6493 break; /* should not happen */
6495 if (curwin->w_cursor.lnum != tpos.lnum)
6496 curwin->w_cursor = tpos;
6497 else if (cc != NUL)
6498 ++curwin->w_cursor.col; /* put cursor back on the NUL */
6500 #ifdef FEAT_VISUAL
6501 /* <C-S-Right> may have started Visual mode, adjust the position for
6502 * deleted characters. */
6503 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6505 int len = (int)STRLEN(ml_get_curline());
6507 if (VIsual.col > len)
6509 VIsual.col = len;
6510 # ifdef FEAT_VIRTUALEDIT
6511 VIsual.coladd = 0;
6512 # endif
6515 #endif
6518 did_ai = FALSE;
6519 #ifdef FEAT_SMARTINDENT
6520 did_si = FALSE;
6521 can_si = FALSE;
6522 can_si_back = FALSE;
6523 #endif
6525 /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are
6526 * now in a different buffer. */
6527 if (end_insert_pos != NULL)
6529 curbuf->b_op_start = Insstart;
6530 curbuf->b_op_end = *end_insert_pos;
6535 * Set the last inserted text to a single character.
6536 * Used for the replace command.
6538 void
6539 set_last_insert(c)
6540 int c;
6542 char_u *s;
6544 vim_free(last_insert);
6545 #ifdef FEAT_MBYTE
6546 last_insert = alloc(MB_MAXBYTES * 3 + 5);
6547 #else
6548 last_insert = alloc(6);
6549 #endif
6550 if (last_insert != NULL)
6552 s = last_insert;
6553 /* Use the CTRL-V only when entering a special char */
6554 if (c < ' ' || c == DEL)
6555 *s++ = Ctrl_V;
6556 s = add_char2buf(c, s);
6557 *s++ = ESC;
6558 *s++ = NUL;
6559 last_insert_skip = 0;
6563 #if defined(EXITFREE) || defined(PROTO)
6564 void
6565 free_last_insert()
6567 vim_free(last_insert);
6568 last_insert = NULL;
6569 # ifdef FEAT_INS_EXPAND
6570 vim_free(compl_orig_text);
6571 compl_orig_text = NULL;
6572 # endif
6574 #endif
6577 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
6578 * and CSI. Handle multi-byte characters.
6579 * Returns a pointer to after the added bytes.
6581 char_u *
6582 add_char2buf(c, s)
6583 int c;
6584 char_u *s;
6586 #ifdef FEAT_MBYTE
6587 char_u temp[MB_MAXBYTES];
6588 int i;
6589 int len;
6591 len = (*mb_char2bytes)(c, temp);
6592 for (i = 0; i < len; ++i)
6594 c = temp[i];
6595 #endif
6596 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6597 if (c == K_SPECIAL)
6599 *s++ = K_SPECIAL;
6600 *s++ = KS_SPECIAL;
6601 *s++ = KE_FILLER;
6603 #ifdef FEAT_GUI
6604 else if (c == CSI)
6606 *s++ = CSI;
6607 *s++ = KS_EXTRA;
6608 *s++ = (int)KE_CSI;
6610 #endif
6611 else
6612 *s++ = c;
6613 #ifdef FEAT_MBYTE
6615 #endif
6616 return s;
6620 * move cursor to start of line
6621 * if flags & BL_WHITE move to first non-white
6622 * if flags & BL_SOL move to first non-white if startofline is set,
6623 * otherwise keep "curswant" column
6624 * if flags & BL_FIX don't leave the cursor on a NUL.
6626 void
6627 beginline(flags)
6628 int flags;
6630 if ((flags & BL_SOL) && !p_sol)
6631 coladvance(curwin->w_curswant);
6632 else
6634 curwin->w_cursor.col = 0;
6635 #ifdef FEAT_VIRTUALEDIT
6636 curwin->w_cursor.coladd = 0;
6637 #endif
6639 if (flags & (BL_WHITE | BL_SOL))
6641 char_u *ptr;
6643 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6644 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6645 ++curwin->w_cursor.col;
6647 curwin->w_set_curswant = TRUE;
6652 * oneright oneleft cursor_down cursor_up
6654 * Move one char {right,left,down,up}.
6655 * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6656 * Return OK when successful, FAIL when we hit a line of file boundary.
6660 oneright()
6662 char_u *ptr;
6663 int l;
6665 #ifdef FEAT_VIRTUALEDIT
6666 if (virtual_active())
6668 pos_T prevpos = curwin->w_cursor;
6670 /* Adjust for multi-wide char (excluding TAB) */
6671 ptr = ml_get_cursor();
6672 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
6673 # ifdef FEAT_MBYTE
6674 (*mb_ptr2char)(ptr)
6675 # else
6676 *ptr
6677 # endif
6679 ? ptr2cells(ptr) : 1));
6680 curwin->w_set_curswant = TRUE;
6681 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
6682 return (prevpos.col != curwin->w_cursor.col
6683 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
6685 #endif
6687 ptr = ml_get_cursor();
6688 if (*ptr == NUL)
6689 return FAIL; /* already at the very end */
6691 #ifdef FEAT_MBYTE
6692 if (has_mbyte)
6693 l = (*mb_ptr2len)(ptr);
6694 else
6695 #endif
6696 l = 1;
6698 /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
6699 * contains "onemore". */
6700 if (ptr[l] == NUL
6701 #ifdef FEAT_VIRTUALEDIT
6702 && (ve_flags & VE_ONEMORE) == 0
6703 #endif
6705 return FAIL;
6706 curwin->w_cursor.col += l;
6708 curwin->w_set_curswant = TRUE;
6709 return OK;
6713 oneleft()
6715 #ifdef FEAT_VIRTUALEDIT
6716 if (virtual_active())
6718 int width;
6719 int v = getviscol();
6721 if (v == 0)
6722 return FAIL;
6724 # ifdef FEAT_LINEBREAK
6725 /* We might get stuck on 'showbreak', skip over it. */
6726 width = 1;
6727 for (;;)
6729 coladvance(v - width);
6730 /* getviscol() is slow, skip it when 'showbreak' is empty and
6731 * there are no multi-byte characters */
6732 if ((*p_sbr == NUL
6733 # ifdef FEAT_MBYTE
6734 && !has_mbyte
6735 # endif
6736 ) || getviscol() < v)
6737 break;
6738 ++width;
6740 # else
6741 coladvance(v - 1);
6742 # endif
6744 if (curwin->w_cursor.coladd == 1)
6746 char_u *ptr;
6748 /* Adjust for multi-wide char (not a TAB) */
6749 ptr = ml_get_cursor();
6750 if (*ptr != TAB && vim_isprintc(
6751 # ifdef FEAT_MBYTE
6752 (*mb_ptr2char)(ptr)
6753 # else
6754 *ptr
6755 # endif
6756 ) && ptr2cells(ptr) > 1)
6757 curwin->w_cursor.coladd = 0;
6760 curwin->w_set_curswant = TRUE;
6761 return OK;
6763 #endif
6765 if (curwin->w_cursor.col == 0)
6766 return FAIL;
6768 curwin->w_set_curswant = TRUE;
6769 --curwin->w_cursor.col;
6771 #ifdef FEAT_MBYTE
6772 /* if the character on the left of the current cursor is a multi-byte
6773 * character, move to its first byte */
6774 if (has_mbyte)
6775 mb_adjust_cursor();
6776 #endif
6777 return OK;
6781 cursor_up(n, upd_topline)
6782 long n;
6783 int upd_topline; /* When TRUE: update topline */
6785 linenr_T lnum;
6787 if (n > 0)
6789 lnum = curwin->w_cursor.lnum;
6790 /* This fails if the cursor is already in the first line or the count
6791 * is larger than the line number and '-' is in 'cpoptions' */
6792 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6793 return FAIL;
6794 if (n >= lnum)
6795 lnum = 1;
6796 else
6797 #ifdef FEAT_FOLDING
6798 if (hasAnyFolding(curwin))
6801 * Count each sequence of folded lines as one logical line.
6803 /* go to the the start of the current fold */
6804 (void)hasFolding(lnum, &lnum, NULL);
6806 while (n--)
6808 /* move up one line */
6809 --lnum;
6810 if (lnum <= 1)
6811 break;
6812 /* If we entered a fold, move to the beginning, unless in
6813 * Insert mode or when 'foldopen' contains "all": it will open
6814 * in a moment. */
6815 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
6816 (void)hasFolding(lnum, &lnum, NULL);
6818 if (lnum < 1)
6819 lnum = 1;
6821 else
6822 #endif
6823 lnum -= n;
6824 curwin->w_cursor.lnum = lnum;
6827 /* try to advance to the column we want to be at */
6828 coladvance(curwin->w_curswant);
6830 if (upd_topline)
6831 update_topline(); /* make sure curwin->w_topline is valid */
6833 return OK;
6837 * Cursor down a number of logical lines.
6840 cursor_down(n, upd_topline)
6841 long n;
6842 int upd_topline; /* When TRUE: update topline */
6844 linenr_T lnum;
6846 if (n > 0)
6848 lnum = curwin->w_cursor.lnum;
6849 #ifdef FEAT_FOLDING
6850 /* Move to last line of fold, will fail if it's the end-of-file. */
6851 (void)hasFolding(lnum, NULL, &lnum);
6852 #endif
6853 /* This fails if the cursor is already in the last line or would move
6854 * beyound the last line and '-' is in 'cpoptions' */
6855 if (lnum >= curbuf->b_ml.ml_line_count
6856 || (lnum + n > curbuf->b_ml.ml_line_count
6857 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6858 return FAIL;
6859 if (lnum + n >= curbuf->b_ml.ml_line_count)
6860 lnum = curbuf->b_ml.ml_line_count;
6861 else
6862 #ifdef FEAT_FOLDING
6863 if (hasAnyFolding(curwin))
6865 linenr_T last;
6867 /* count each sequence of folded lines as one logical line */
6868 while (n--)
6870 if (hasFolding(lnum, NULL, &last))
6871 lnum = last + 1;
6872 else
6873 ++lnum;
6874 if (lnum >= curbuf->b_ml.ml_line_count)
6875 break;
6877 if (lnum > curbuf->b_ml.ml_line_count)
6878 lnum = curbuf->b_ml.ml_line_count;
6880 else
6881 #endif
6882 lnum += n;
6883 curwin->w_cursor.lnum = lnum;
6886 /* try to advance to the column we want to be at */
6887 coladvance(curwin->w_curswant);
6889 if (upd_topline)
6890 update_topline(); /* make sure curwin->w_topline is valid */
6892 return OK;
6896 * Stuff the last inserted text in the read buffer.
6897 * Last_insert actually is a copy of the redo buffer, so we
6898 * first have to remove the command.
6901 stuff_inserted(c, count, no_esc)
6902 int c; /* Command character to be inserted */
6903 long count; /* Repeat this many times */
6904 int no_esc; /* Don't add an ESC at the end */
6906 char_u *esc_ptr;
6907 char_u *ptr;
6908 char_u *last_ptr;
6909 char_u last = NUL;
6911 ptr = get_last_insert();
6912 if (ptr == NULL)
6914 EMSG(_(e_noinstext));
6915 return FAIL;
6918 /* may want to stuff the command character, to start Insert mode */
6919 if (c != NUL)
6920 stuffcharReadbuff(c);
6921 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
6922 *esc_ptr = NUL; /* remove the ESC */
6924 /* when the last char is either "0" or "^" it will be quoted if no ESC
6925 * comes after it OR if it will inserted more than once and "ptr"
6926 * starts with ^D. -- Acevedo
6928 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
6929 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
6930 && (no_esc || (*ptr == Ctrl_D && count > 1)))
6932 last = *last_ptr;
6933 *last_ptr = NUL;
6938 stuffReadbuff(ptr);
6939 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
6940 if (last)
6941 stuffReadbuff((char_u *)(last == '0'
6942 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
6943 : IF_EB("\026^", CTRL_V_STR "^")));
6945 while (--count > 0);
6947 if (last)
6948 *last_ptr = last;
6950 if (esc_ptr != NULL)
6951 *esc_ptr = ESC; /* put the ESC back */
6953 /* may want to stuff a trailing ESC, to get out of Insert mode */
6954 if (!no_esc)
6955 stuffcharReadbuff(ESC);
6957 return OK;
6960 char_u *
6961 get_last_insert()
6963 if (last_insert == NULL)
6964 return NULL;
6965 return last_insert + last_insert_skip;
6969 * Get last inserted string, and remove trailing <Esc>.
6970 * Returns pointer to allocated memory (must be freed) or NULL.
6972 char_u *
6973 get_last_insert_save()
6975 char_u *s;
6976 int len;
6978 if (last_insert == NULL)
6979 return NULL;
6980 s = vim_strsave(last_insert + last_insert_skip);
6981 if (s != NULL)
6983 len = (int)STRLEN(s);
6984 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
6985 s[len - 1] = NUL;
6987 return s;
6991 * Check the word in front of the cursor for an abbreviation.
6992 * Called when the non-id character "c" has been entered.
6993 * When an abbreviation is recognized it is removed from the text and
6994 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
6996 static int
6997 echeck_abbr(c)
6998 int c;
7000 /* Don't check for abbreviation in paste mode, when disabled and just
7001 * after moving around with cursor keys. */
7002 if (p_paste || no_abbr || arrow_used)
7003 return FALSE;
7005 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
7006 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
7010 * replace-stack functions
7012 * When replacing characters, the replaced characters are remembered for each
7013 * new character. This is used to re-insert the old text when backspacing.
7015 * There is a NUL headed list of characters for each character that is
7016 * currently in the file after the insertion point. When BS is used, one NUL
7017 * headed list is put back for the deleted character.
7019 * For a newline, there are two NUL headed lists. One contains the characters
7020 * that the NL replaced. The extra one stores the characters after the cursor
7021 * that were deleted (always white space).
7023 * Replace_offset is normally 0, in which case replace_push will add a new
7024 * character at the end of the stack. If replace_offset is not 0, that many
7025 * characters will be left on the stack above the newly inserted character.
7028 static char_u *replace_stack = NULL;
7029 static long replace_stack_nr = 0; /* next entry in replace stack */
7030 static long replace_stack_len = 0; /* max. number of entries */
7032 void
7033 replace_push(c)
7034 int c; /* character that is replaced (NUL is none) */
7036 char_u *p;
7038 if (replace_stack_nr < replace_offset) /* nothing to do */
7039 return;
7040 if (replace_stack_len <= replace_stack_nr)
7042 replace_stack_len += 50;
7043 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
7044 if (p == NULL) /* out of memory */
7046 replace_stack_len -= 50;
7047 return;
7049 if (replace_stack != NULL)
7051 mch_memmove(p, replace_stack,
7052 (size_t)(replace_stack_nr * sizeof(char_u)));
7053 vim_free(replace_stack);
7055 replace_stack = p;
7057 p = replace_stack + replace_stack_nr - replace_offset;
7058 if (replace_offset)
7059 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
7060 *p = c;
7061 ++replace_stack_nr;
7064 #if defined(FEAT_MBYTE) || defined(PROTO)
7066 * Push a character onto the replace stack. Handles a multi-byte character in
7067 * reverse byte order, so that the first byte is popped off first.
7068 * Return the number of bytes done (includes composing characters).
7071 replace_push_mb(p)
7072 char_u *p;
7074 int l = (*mb_ptr2len)(p);
7075 int j;
7077 for (j = l - 1; j >= 0; --j)
7078 replace_push(p[j]);
7079 return l;
7081 #endif
7083 #if 0
7085 * call replace_push(c) with replace_offset set to the first NUL.
7087 static void
7088 replace_push_off(c)
7089 int c;
7091 char_u *p;
7093 p = replace_stack + replace_stack_nr;
7094 for (replace_offset = 1; replace_offset < replace_stack_nr;
7095 ++replace_offset)
7096 if (*--p == NUL)
7097 break;
7098 replace_push(c);
7099 replace_offset = 0;
7101 #endif
7104 * Pop one item from the replace stack.
7105 * return -1 if stack empty
7106 * return replaced character or NUL otherwise
7108 static int
7109 replace_pop()
7111 if (replace_stack_nr == 0)
7112 return -1;
7113 return (int)replace_stack[--replace_stack_nr];
7117 * Join the top two items on the replace stack. This removes to "off"'th NUL
7118 * encountered.
7120 static void
7121 replace_join(off)
7122 int off; /* offset for which NUL to remove */
7124 int i;
7126 for (i = replace_stack_nr; --i >= 0; )
7127 if (replace_stack[i] == NUL && off-- <= 0)
7129 --replace_stack_nr;
7130 mch_memmove(replace_stack + i, replace_stack + i + 1,
7131 (size_t)(replace_stack_nr - i));
7132 return;
7137 * Pop bytes from the replace stack until a NUL is found, and insert them
7138 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
7140 static void
7141 replace_pop_ins()
7143 int cc;
7144 int oldState = State;
7146 State = NORMAL; /* don't want REPLACE here */
7147 while ((cc = replace_pop()) > 0)
7149 #ifdef FEAT_MBYTE
7150 mb_replace_pop_ins(cc);
7151 #else
7152 ins_char(cc);
7153 #endif
7154 dec_cursor();
7156 State = oldState;
7159 #ifdef FEAT_MBYTE
7161 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
7162 * indicates a multi-byte char, pop the other bytes too.
7164 static void
7165 mb_replace_pop_ins(cc)
7166 int cc;
7168 int n;
7169 char_u buf[MB_MAXBYTES];
7170 int i;
7171 int c;
7173 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
7175 buf[0] = cc;
7176 for (i = 1; i < n; ++i)
7177 buf[i] = replace_pop();
7178 ins_bytes_len(buf, n);
7180 else
7181 ins_char(cc);
7183 if (enc_utf8)
7184 /* Handle composing chars. */
7185 for (;;)
7187 c = replace_pop();
7188 if (c == -1) /* stack empty */
7189 break;
7190 if ((n = MB_BYTE2LEN(c)) == 1)
7192 /* Not a multi-byte char, put it back. */
7193 replace_push(c);
7194 break;
7196 else
7198 buf[0] = c;
7199 for (i = 1; i < n; ++i)
7200 buf[i] = replace_pop();
7201 if (utf_iscomposing(utf_ptr2char(buf)))
7202 ins_bytes_len(buf, n);
7203 else
7205 /* Not a composing char, put it back. */
7206 for (i = n - 1; i >= 0; --i)
7207 replace_push(buf[i]);
7208 break;
7213 #endif
7216 * make the replace stack empty
7217 * (called when exiting replace mode)
7219 static void
7220 replace_flush()
7222 vim_free(replace_stack);
7223 replace_stack = NULL;
7224 replace_stack_len = 0;
7225 replace_stack_nr = 0;
7229 * Handle doing a BS for one character.
7230 * cc < 0: replace stack empty, just move cursor
7231 * cc == 0: character was inserted, delete it
7232 * cc > 0: character was replaced, put cc (first byte of original char) back
7233 * and check for more characters to be put back
7234 * When "limit_col" is >= 0, don't delete before this column. Matters when
7235 * using composing characters, use del_char_after_col() instead of del_char().
7237 static void
7238 replace_do_bs(limit_col)
7239 int limit_col;
7241 int cc;
7242 #ifdef FEAT_VREPLACE
7243 int orig_len = 0;
7244 int ins_len;
7245 int orig_vcols = 0;
7246 colnr_T start_vcol;
7247 char_u *p;
7248 int i;
7249 int vcol;
7250 #endif
7252 cc = replace_pop();
7253 if (cc > 0)
7255 #ifdef FEAT_VREPLACE
7256 if (State & VREPLACE_FLAG)
7258 /* Get the number of screen cells used by the character we are
7259 * going to delete. */
7260 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
7261 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
7263 #endif
7264 #ifdef FEAT_MBYTE
7265 if (has_mbyte)
7267 (void)del_char_after_col(limit_col);
7268 # ifdef FEAT_VREPLACE
7269 if (State & VREPLACE_FLAG)
7270 orig_len = (int)STRLEN(ml_get_cursor());
7271 # endif
7272 replace_push(cc);
7274 else
7275 #endif
7277 pchar_cursor(cc);
7278 #ifdef FEAT_VREPLACE
7279 if (State & VREPLACE_FLAG)
7280 orig_len = (int)STRLEN(ml_get_cursor()) - 1;
7281 #endif
7283 replace_pop_ins();
7285 #ifdef FEAT_VREPLACE
7286 if (State & VREPLACE_FLAG)
7288 /* Get the number of screen cells used by the inserted characters */
7289 p = ml_get_cursor();
7290 ins_len = (int)STRLEN(p) - orig_len;
7291 vcol = start_vcol;
7292 for (i = 0; i < ins_len; ++i)
7294 vcol += chartabsize(p + i, vcol);
7295 #ifdef FEAT_MBYTE
7296 i += (*mb_ptr2len)(p) - 1;
7297 #endif
7299 vcol -= start_vcol;
7301 /* Delete spaces that were inserted after the cursor to keep the
7302 * text aligned. */
7303 curwin->w_cursor.col += ins_len;
7304 while (vcol > orig_vcols && gchar_cursor() == ' ')
7306 del_char(FALSE);
7307 ++orig_vcols;
7309 curwin->w_cursor.col -= ins_len;
7311 #endif
7313 /* mark the buffer as changed and prepare for displaying */
7314 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
7316 else if (cc == 0)
7317 (void)del_char_after_col(limit_col);
7320 #ifdef FEAT_CINDENT
7322 * Return TRUE if C-indenting is on.
7324 static int
7325 cindent_on()
7327 return (!p_paste && (curbuf->b_p_cin
7328 # ifdef FEAT_EVAL
7329 || *curbuf->b_p_inde != NUL
7330 # endif
7333 #endif
7335 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
7337 * Re-indent the current line, based on the current contents of it and the
7338 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
7339 * confused what all the part that handles Control-T is doing that I'm not.
7340 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
7343 void
7344 fixthisline(get_the_indent)
7345 int (*get_the_indent) __ARGS((void));
7347 change_indent(INDENT_SET, get_the_indent(), FALSE, 0, TRUE);
7348 if (linewhite(curwin->w_cursor.lnum))
7349 did_ai = TRUE; /* delete the indent if the line stays empty */
7352 void
7353 fix_indent()
7355 if (p_paste)
7356 return;
7357 # ifdef FEAT_LISP
7358 if (curbuf->b_p_lisp && curbuf->b_p_ai)
7359 fixthisline(get_lisp_indent);
7360 # endif
7361 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
7362 else
7363 # endif
7364 # ifdef FEAT_CINDENT
7365 if (cindent_on())
7366 do_c_expr_indent();
7367 # endif
7370 #endif
7372 #ifdef FEAT_CINDENT
7374 * return TRUE if 'cinkeys' contains the key "keytyped",
7375 * when == '*': Only if key is preceded with '*' (indent before insert)
7376 * when == '!': Only if key is prededed with '!' (don't insert)
7377 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
7379 * "keytyped" can have a few special values:
7380 * KEY_OPEN_FORW
7381 * KEY_OPEN_BACK
7382 * KEY_COMPLETE just finished completion.
7384 * If line_is_empty is TRUE accept keys with '0' before them.
7387 in_cinkeys(keytyped, when, line_is_empty)
7388 int keytyped;
7389 int when;
7390 int line_is_empty;
7392 char_u *look;
7393 int try_match;
7394 int try_match_word;
7395 char_u *p;
7396 char_u *line;
7397 int icase;
7398 int i;
7400 #ifdef FEAT_EVAL
7401 if (*curbuf->b_p_inde != NUL)
7402 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
7403 else
7404 #endif
7405 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
7406 while (*look)
7409 * Find out if we want to try a match with this key, depending on
7410 * 'when' and a '*' or '!' before the key.
7412 switch (when)
7414 case '*': try_match = (*look == '*'); break;
7415 case '!': try_match = (*look == '!'); break;
7416 default: try_match = (*look != '*'); break;
7418 if (*look == '*' || *look == '!')
7419 ++look;
7422 * If there is a '0', only accept a match if the line is empty.
7423 * But may still match when typing last char of a word.
7425 if (*look == '0')
7427 try_match_word = try_match;
7428 if (!line_is_empty)
7429 try_match = FALSE;
7430 ++look;
7432 else
7433 try_match_word = FALSE;
7436 * does it look like a control character?
7438 if (*look == '^'
7439 #ifdef EBCDIC
7440 && (Ctrl_chr(look[1]) != 0)
7441 #else
7442 && look[1] >= '?' && look[1] <= '_'
7443 #endif
7446 if (try_match && keytyped == Ctrl_chr(look[1]))
7447 return TRUE;
7448 look += 2;
7451 * 'o' means "o" command, open forward.
7452 * 'O' means "O" command, open backward.
7454 else if (*look == 'o')
7456 if (try_match && keytyped == KEY_OPEN_FORW)
7457 return TRUE;
7458 ++look;
7460 else if (*look == 'O')
7462 if (try_match && keytyped == KEY_OPEN_BACK)
7463 return TRUE;
7464 ++look;
7468 * 'e' means to check for "else" at start of line and just before the
7469 * cursor.
7471 else if (*look == 'e')
7473 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
7475 p = ml_get_curline();
7476 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
7477 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
7478 return TRUE;
7480 ++look;
7484 * ':' only causes an indent if it is at the end of a label or case
7485 * statement, or when it was before typing the ':' (to fix
7486 * class::method for C++).
7488 else if (*look == ':')
7490 if (try_match && keytyped == ':')
7492 p = ml_get_curline();
7493 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
7494 return TRUE;
7495 /* Need to get the line again after cin_islabel(). */
7496 p = ml_get_curline();
7497 if (curwin->w_cursor.col > 2
7498 && p[curwin->w_cursor.col - 1] == ':'
7499 && p[curwin->w_cursor.col - 2] == ':')
7501 p[curwin->w_cursor.col - 1] = ' ';
7502 i = (cin_iscase(p) || cin_isscopedecl(p)
7503 || cin_islabel(30));
7504 p = ml_get_curline();
7505 p[curwin->w_cursor.col - 1] = ':';
7506 if (i)
7507 return TRUE;
7510 ++look;
7515 * Is it a key in <>, maybe?
7517 else if (*look == '<')
7519 if (try_match)
7522 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7523 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7524 * >, *, : and ! keys if they really really want to.
7526 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7527 && keytyped == look[1])
7528 return TRUE;
7530 if (keytyped == get_special_key_code(look + 1))
7531 return TRUE;
7533 while (*look && *look != '>')
7534 look++;
7535 while (*look == '>')
7536 look++;
7540 * Is it a word: "=word"?
7542 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7544 ++look;
7545 if (*look == '~')
7547 icase = TRUE;
7548 ++look;
7550 else
7551 icase = FALSE;
7552 p = vim_strchr(look, ',');
7553 if (p == NULL)
7554 p = look + STRLEN(look);
7555 if ((try_match || try_match_word)
7556 && curwin->w_cursor.col >= (colnr_T)(p - look))
7558 int match = FALSE;
7560 #ifdef FEAT_INS_EXPAND
7561 if (keytyped == KEY_COMPLETE)
7563 char_u *s;
7565 /* Just completed a word, check if it starts with "look".
7566 * search back for the start of a word. */
7567 line = ml_get_curline();
7568 # ifdef FEAT_MBYTE
7569 if (has_mbyte)
7571 char_u *n;
7573 for (s = line + curwin->w_cursor.col; s > line; s = n)
7575 n = mb_prevptr(line, s);
7576 if (!vim_iswordp(n))
7577 break;
7580 else
7581 # endif
7582 for (s = line + curwin->w_cursor.col; s > line; --s)
7583 if (!vim_iswordc(s[-1]))
7584 break;
7585 if (s + (p - look) <= line + curwin->w_cursor.col
7586 && (icase
7587 ? MB_STRNICMP(s, look, p - look)
7588 : STRNCMP(s, look, p - look)) == 0)
7589 match = TRUE;
7591 else
7592 #endif
7593 /* TODO: multi-byte */
7594 if (keytyped == (int)p[-1] || (icase && keytyped < 256
7595 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7597 line = ml_get_cursor();
7598 if ((curwin->w_cursor.col == (colnr_T)(p - look)
7599 || !vim_iswordc(line[-(p - look) - 1]))
7600 && (icase
7601 ? MB_STRNICMP(line - (p - look), look, p - look)
7602 : STRNCMP(line - (p - look), look, p - look))
7603 == 0)
7604 match = TRUE;
7606 if (match && try_match_word && !try_match)
7608 /* "0=word": Check if there are only blanks before the
7609 * word. */
7610 line = ml_get_curline();
7611 if ((int)(skipwhite(line) - line) !=
7612 (int)(curwin->w_cursor.col - (p - look)))
7613 match = FALSE;
7615 if (match)
7616 return TRUE;
7618 look = p;
7622 * ok, it's a boring generic character.
7624 else
7626 if (try_match && *look == keytyped)
7627 return TRUE;
7628 ++look;
7632 * Skip over ", ".
7634 look = skip_to_option_part(look);
7636 return FALSE;
7638 #endif /* FEAT_CINDENT */
7640 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7642 * Map Hebrew keyboard when in hkmap mode.
7645 hkmap(c)
7646 int c;
7648 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
7650 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7651 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7652 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7653 static char_u map[26] =
7654 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
7655 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
7656 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
7657 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
7658 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
7659 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
7660 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
7661 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
7662 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
7664 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7665 return (int)(map[CharOrd(c)] - 1 + p_aleph);
7666 /* '-1'='sofit' */
7667 else if (c == 'x')
7668 return 'X';
7669 else if (c == 'q')
7670 return '\''; /* {geresh}={'} */
7671 else if (c == 246)
7672 return ' '; /* \"o --> ' ' for a german keyboard */
7673 else if (c == 228)
7674 return ' '; /* \"a --> ' ' -- / -- */
7675 else if (c == 252)
7676 return ' '; /* \"u --> ' ' -- / -- */
7677 #ifdef EBCDIC
7678 else if (islower(c))
7679 #else
7680 /* NOTE: islower() does not do the right thing for us on Linux so we
7681 * do this the same was as 5.7 and previous, so it works correctly on
7682 * all systems. Specifically, the e.g. Delete and Arrow keys are
7683 * munged and won't work if e.g. searching for Hebrew text.
7685 else if (c >= 'a' && c <= 'z')
7686 #endif
7687 return (int)(map[CharOrdLow(c)] + p_aleph);
7688 else
7689 return c;
7691 else
7693 switch (c)
7695 case '`': return ';';
7696 case '/': return '.';
7697 case '\'': return ',';
7698 case 'q': return '/';
7699 case 'w': return '\'';
7701 /* Hebrew letters - set offset from 'a' */
7702 case ',': c = '{'; break;
7703 case '.': c = 'v'; break;
7704 case ';': c = 't'; break;
7705 default: {
7706 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
7708 #ifdef EBCDIC
7709 /* see note about islower() above */
7710 if (!islower(c))
7711 #else
7712 if (c < 'a' || c > 'z')
7713 #endif
7714 return c;
7715 c = str[CharOrdLow(c)];
7716 break;
7720 return (int)(CharOrdLow(c) + p_aleph);
7723 #endif
7725 static void
7726 ins_reg()
7728 int need_redraw = FALSE;
7729 int regname;
7730 int literally = 0;
7731 #ifdef FEAT_VISUAL
7732 int vis_active = VIsual_active;
7733 #endif
7736 * If we are going to wait for a character, show a '"'.
7738 pc_status = PC_STATUS_UNSET;
7739 if (redrawing() && !char_avail())
7741 /* may need to redraw when no more chars available now */
7742 ins_redraw(FALSE);
7744 edit_putchar('"', TRUE);
7745 #ifdef FEAT_CMDL_INFO
7746 add_to_showcmd_c(Ctrl_R);
7747 #endif
7750 #ifdef USE_ON_FLY_SCROLL
7751 dont_scroll = TRUE; /* disallow scrolling here */
7752 #endif
7755 * Don't map the register name. This also prevents the mode message to be
7756 * deleted when ESC is hit.
7758 ++no_mapping;
7759 regname = plain_vgetc();
7760 LANGMAP_ADJUST(regname, TRUE);
7761 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
7763 /* Get a third key for literal register insertion */
7764 literally = regname;
7765 #ifdef FEAT_CMDL_INFO
7766 add_to_showcmd_c(literally);
7767 #endif
7768 regname = plain_vgetc();
7769 LANGMAP_ADJUST(regname, TRUE);
7771 --no_mapping;
7773 #ifdef FEAT_EVAL
7775 * Don't call u_sync() while getting the expression,
7776 * evaluating it or giving an error message for it!
7778 ++no_u_sync;
7779 if (regname == '=')
7781 # ifdef USE_IM_CONTROL
7782 int im_on = im_get_status();
7783 # endif
7784 regname = get_expr_register();
7785 # ifdef USE_IM_CONTROL
7786 /* Restore the Input Method. */
7787 if (im_on)
7788 im_set_active(TRUE);
7789 # endif
7791 if (regname == NUL || !valid_yank_reg(regname, FALSE))
7793 vim_beep();
7794 need_redraw = TRUE; /* remove the '"' */
7796 else
7798 #endif
7799 if (literally == Ctrl_O || literally == Ctrl_P)
7801 /* Append the command to the redo buffer. */
7802 AppendCharToRedobuff(Ctrl_R);
7803 AppendCharToRedobuff(literally);
7804 AppendCharToRedobuff(regname);
7806 do_put(regname, BACKWARD, 1L,
7807 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
7809 else if (insert_reg(regname, literally) == FAIL)
7811 vim_beep();
7812 need_redraw = TRUE; /* remove the '"' */
7814 else if (stop_insert_mode)
7815 /* When the '=' register was used and a function was invoked that
7816 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
7817 * insert anything, need to remove the '"' */
7818 need_redraw = TRUE;
7820 #ifdef FEAT_EVAL
7822 --no_u_sync;
7823 #endif
7824 #ifdef FEAT_CMDL_INFO
7825 clear_showcmd();
7826 #endif
7828 /* If the inserted register is empty, we need to remove the '"' */
7829 if (need_redraw || stuff_empty())
7830 edit_unputchar();
7832 #ifdef FEAT_VISUAL
7833 /* Disallow starting Visual mode here, would get a weird mode. */
7834 if (!vis_active && VIsual_active)
7835 end_visual_mode();
7836 #endif
7840 * CTRL-G commands in Insert mode.
7842 static void
7843 ins_ctrl_g()
7845 int c;
7847 #ifdef FEAT_INS_EXPAND
7848 /* Right after CTRL-X the cursor will be after the ruler. */
7849 setcursor();
7850 #endif
7853 * Don't map the second key. This also prevents the mode message to be
7854 * deleted when ESC is hit.
7856 ++no_mapping;
7857 c = plain_vgetc();
7858 --no_mapping;
7859 switch (c)
7861 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
7862 case K_UP:
7863 case Ctrl_K:
7864 case 'k': ins_up(TRUE);
7865 break;
7867 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
7868 case K_DOWN:
7869 case Ctrl_J:
7870 case 'j': ins_down(TRUE);
7871 break;
7873 /* CTRL-G u: start new undoable edit */
7874 case 'u': u_sync(TRUE);
7875 ins_need_undo = TRUE;
7877 /* Need to reset Insstart, esp. because a BS that joins
7878 * a line to the previous one must save for undo. */
7879 Insstart = curwin->w_cursor;
7880 break;
7882 /* Unknown CTRL-G command, reserved for future expansion. */
7883 default: vim_beep();
7888 * CTRL-^ in Insert mode.
7890 static void
7891 ins_ctrl_hat()
7893 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
7895 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
7896 if (State & LANGMAP)
7898 curbuf->b_p_iminsert = B_IMODE_NONE;
7899 State &= ~LANGMAP;
7901 else
7903 curbuf->b_p_iminsert = B_IMODE_LMAP;
7904 State |= LANGMAP;
7905 #ifdef USE_IM_CONTROL
7906 im_set_active(FALSE);
7907 #endif
7910 #ifdef USE_IM_CONTROL
7911 else
7913 /* There are no ":lmap" mappings, toggle IM */
7914 if (im_get_status())
7916 curbuf->b_p_iminsert = B_IMODE_NONE;
7917 im_set_active(FALSE);
7919 else
7921 curbuf->b_p_iminsert = B_IMODE_IM;
7922 State &= ~LANGMAP;
7923 im_set_active(TRUE);
7926 #endif
7927 set_iminsert_global();
7928 showmode();
7929 #ifdef FEAT_GUI
7930 /* may show different cursor shape or color */
7931 if (gui.in_use)
7932 gui_update_cursor(TRUE, FALSE);
7933 #endif
7934 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
7935 /* Show/unshow value of 'keymap' in status lines. */
7936 status_redraw_curbuf();
7937 #endif
7941 * Handle ESC in insert mode.
7942 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
7943 * insert.
7945 static int
7946 ins_esc(count, cmdchar, nomove)
7947 long *count;
7948 int cmdchar;
7949 int nomove; /* don't move cursor */
7951 int temp;
7952 static int disabled_redraw = FALSE;
7954 #ifdef FEAT_SPELL
7955 check_spell_redraw();
7956 #endif
7957 #if defined(FEAT_HANGULIN)
7958 # if defined(ESC_CHG_TO_ENG_MODE)
7959 hangul_input_state_set(0);
7960 # endif
7961 if (composing_hangul)
7963 push_raw_key(composing_hangul_buffer, 2);
7964 composing_hangul = 0;
7966 #endif
7968 temp = curwin->w_cursor.col;
7969 if (disabled_redraw)
7971 --RedrawingDisabled;
7972 disabled_redraw = FALSE;
7974 if (!arrow_used)
7977 * Don't append the ESC for "r<CR>" and "grx".
7978 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
7979 * when "count" is non-zero.
7981 if (cmdchar != 'r' && cmdchar != 'v')
7982 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
7985 * Repeating insert may take a long time. Check for
7986 * interrupt now and then.
7988 if (*count > 0)
7990 line_breakcheck();
7991 if (got_int)
7992 *count = 0;
7995 if (--*count > 0) /* repeat what was typed */
7997 /* Vi repeats the insert without replacing characters. */
7998 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
7999 State &= ~REPLACE_FLAG;
8001 (void)start_redo_ins();
8002 if (cmdchar == 'r' || cmdchar == 'v')
8003 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
8004 ++RedrawingDisabled;
8005 disabled_redraw = TRUE;
8006 return FALSE; /* repeat the insert */
8008 stop_insert(&curwin->w_cursor, TRUE);
8009 undisplay_dollar();
8012 /* When an autoindent was removed, curswant stays after the
8013 * indent */
8014 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
8015 curwin->w_set_curswant = TRUE;
8017 /* Remember the last Insert position in the '^ mark. */
8018 if (!cmdmod.keepjumps)
8019 curbuf->b_last_insert = curwin->w_cursor;
8022 * The cursor should end up on the last inserted character.
8023 * Don't do it for CTRL-O, unless past the end of the line.
8025 if (!nomove
8026 && (curwin->w_cursor.col != 0
8027 #ifdef FEAT_VIRTUALEDIT
8028 || curwin->w_cursor.coladd > 0
8029 #endif
8031 && (restart_edit == NUL
8032 || (gchar_cursor() == NUL
8033 #ifdef FEAT_VISUAL
8034 && !VIsual_active
8035 #endif
8037 #ifdef FEAT_RIGHTLEFT
8038 && !revins_on
8039 #endif
8042 #ifdef FEAT_VIRTUALEDIT
8043 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
8045 oneleft();
8046 if (restart_edit != NUL)
8047 ++curwin->w_cursor.coladd;
8049 else
8050 #endif
8052 --curwin->w_cursor.col;
8053 #ifdef FEAT_MBYTE
8054 /* Correct cursor for multi-byte character. */
8055 if (has_mbyte)
8056 mb_adjust_cursor();
8057 #endif
8061 #ifdef USE_IM_CONTROL
8062 /* Disable IM to allow typing English directly for Normal mode commands.
8063 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
8064 * well). */
8065 if (!(State & LANGMAP))
8066 im_save_status(&curbuf->b_p_iminsert);
8067 im_set_active(FALSE);
8068 #endif
8070 State = NORMAL;
8071 /* need to position cursor again (e.g. when on a TAB ) */
8072 changed_cline_bef_curs();
8074 #ifdef FEAT_MOUSE
8075 setmouse();
8076 #endif
8077 #ifdef CURSOR_SHAPE
8078 ui_cursor_shape(); /* may show different cursor shape */
8079 #endif
8082 * When recording or for CTRL-O, need to display the new mode.
8083 * Otherwise remove the mode message.
8085 if (Recording || restart_edit != NUL)
8086 showmode();
8087 else if (p_smd)
8088 MSG("");
8090 return TRUE; /* exit Insert mode */
8093 #ifdef FEAT_RIGHTLEFT
8095 * Toggle language: hkmap and revins_on.
8096 * Move to end of reverse inserted text.
8098 static void
8099 ins_ctrl_()
8101 if (revins_on && revins_chars && revins_scol >= 0)
8103 while (gchar_cursor() != NUL && revins_chars--)
8104 ++curwin->w_cursor.col;
8106 p_ri = !p_ri;
8107 revins_on = (State == INSERT && p_ri);
8108 if (revins_on)
8110 revins_scol = curwin->w_cursor.col;
8111 revins_legal++;
8112 revins_chars = 0;
8113 undisplay_dollar();
8115 else
8116 revins_scol = -1;
8117 #ifdef FEAT_FKMAP
8118 if (p_altkeymap)
8121 * to be consistent also for redo command, using '.'
8122 * set arrow_used to true and stop it - causing to redo
8123 * characters entered in one mode (normal/reverse insert).
8125 arrow_used = TRUE;
8126 (void)stop_arrow();
8127 p_fkmap = curwin->w_p_rl ^ p_ri;
8128 if (p_fkmap && p_ri)
8129 State = INSERT;
8131 else
8132 #endif
8133 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
8134 showmode();
8136 #endif
8138 #ifdef FEAT_VISUAL
8140 * If 'keymodel' contains "startsel", may start selection.
8141 * Returns TRUE when a CTRL-O and other keys stuffed.
8143 static int
8144 ins_start_select(c)
8145 int c;
8147 if (km_startsel)
8148 switch (c)
8150 case K_KHOME:
8151 case K_KEND:
8152 case K_PAGEUP:
8153 case K_KPAGEUP:
8154 case K_PAGEDOWN:
8155 case K_KPAGEDOWN:
8156 # ifdef MACOS
8157 case K_LEFT:
8158 case K_RIGHT:
8159 case K_UP:
8160 case K_DOWN:
8161 case K_END:
8162 case K_HOME:
8163 # endif
8164 if (!(mod_mask & MOD_MASK_SHIFT))
8165 break;
8166 /* FALLTHROUGH */
8167 case K_S_LEFT:
8168 case K_S_RIGHT:
8169 case K_S_UP:
8170 case K_S_DOWN:
8171 case K_S_END:
8172 case K_S_HOME:
8173 /* Start selection right away, the cursor can move with
8174 * CTRL-O when beyond the end of the line. */
8175 start_selection();
8177 /* Execute the key in (insert) Select mode. */
8178 stuffcharReadbuff(Ctrl_O);
8179 if (mod_mask)
8181 char_u buf[4];
8183 buf[0] = K_SPECIAL;
8184 buf[1] = KS_MODIFIER;
8185 buf[2] = mod_mask;
8186 buf[3] = NUL;
8187 stuffReadbuff(buf);
8189 stuffcharReadbuff(c);
8190 return TRUE;
8192 return FALSE;
8194 #endif
8197 * <Insert> key in Insert mode: toggle insert/remplace mode.
8199 static void
8200 ins_insert(replaceState)
8201 int replaceState;
8203 #ifdef FEAT_FKMAP
8204 if (p_fkmap && p_ri)
8206 beep_flush();
8207 EMSG(farsi_text_3); /* encoded in Farsi */
8208 return;
8210 #endif
8212 #ifdef FEAT_AUTOCMD
8213 # ifdef FEAT_EVAL
8214 set_vim_var_string(VV_INSERTMODE,
8215 (char_u *)((State & REPLACE_FLAG) ? "i" :
8216 # ifdef FEAT_VREPLACE
8217 replaceState == VREPLACE ? "v" :
8218 # endif
8219 "r"), 1);
8220 # endif
8221 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
8222 #endif
8223 if (State & REPLACE_FLAG)
8224 State = INSERT | (State & LANGMAP);
8225 else
8226 State = replaceState | (State & LANGMAP);
8227 AppendCharToRedobuff(K_INS);
8228 showmode();
8229 #ifdef CURSOR_SHAPE
8230 ui_cursor_shape(); /* may show different cursor shape */
8231 #endif
8235 * Pressed CTRL-O in Insert mode.
8237 static void
8238 ins_ctrl_o()
8240 #ifdef FEAT_VREPLACE
8241 if (State & VREPLACE_FLAG)
8242 restart_edit = 'V';
8243 else
8244 #endif
8245 if (State & REPLACE_FLAG)
8246 restart_edit = 'R';
8247 else
8248 restart_edit = 'I';
8249 #ifdef FEAT_VIRTUALEDIT
8250 if (virtual_active())
8251 ins_at_eol = FALSE; /* cursor always keeps its column */
8252 else
8253 #endif
8254 ins_at_eol = (gchar_cursor() == NUL);
8258 * If the cursor is on an indent, ^T/^D insert/delete one
8259 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
8260 * Always round the indent to 'shiftwidth', this is compatible
8261 * with vi. But vi only supports ^T and ^D after an
8262 * autoindent, we support it everywhere.
8264 static void
8265 ins_shift(c, lastc)
8266 int c;
8267 int lastc;
8269 if (stop_arrow() == FAIL)
8270 return;
8271 AppendCharToRedobuff(c);
8274 * 0^D and ^^D: remove all indent.
8276 if (c == Ctrl_D && (lastc == '0' || lastc == '^')
8277 && curwin->w_cursor.col > 0)
8279 --curwin->w_cursor.col;
8280 (void)del_char(FALSE); /* delete the '^' or '0' */
8281 /* In Replace mode, restore the characters that '^' or '0' replaced. */
8282 if (State & REPLACE_FLAG)
8283 replace_pop_ins();
8284 if (lastc == '^')
8285 old_indent = get_indent(); /* remember curr. indent */
8286 change_indent(INDENT_SET, 0, TRUE, 0, TRUE);
8288 else
8289 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE);
8291 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
8292 did_ai = FALSE;
8293 #ifdef FEAT_SMARTINDENT
8294 did_si = FALSE;
8295 can_si = FALSE;
8296 can_si_back = FALSE;
8297 #endif
8298 #ifdef FEAT_CINDENT
8299 can_cindent = FALSE; /* no cindenting after ^D or ^T */
8300 #endif
8303 static void
8304 ins_del()
8306 int temp;
8308 if (stop_arrow() == FAIL)
8309 return;
8310 if (gchar_cursor() == NUL) /* delete newline */
8312 temp = curwin->w_cursor.col;
8313 if (!can_bs(BS_EOL) /* only if "eol" included */
8314 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
8315 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
8316 || do_join(FALSE) == FAIL)
8317 vim_beep();
8318 else
8319 curwin->w_cursor.col = temp;
8321 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
8322 vim_beep();
8323 did_ai = FALSE;
8324 #ifdef FEAT_SMARTINDENT
8325 did_si = FALSE;
8326 can_si = FALSE;
8327 can_si_back = FALSE;
8328 #endif
8329 AppendCharToRedobuff(K_DEL);
8332 static void ins_bs_one __ARGS((colnr_T *vcolp));
8335 * Delete one character for ins_bs().
8337 static void
8338 ins_bs_one(vcolp)
8339 colnr_T *vcolp;
8341 dec_cursor();
8342 getvcol(curwin, &curwin->w_cursor, vcolp, NULL, NULL);
8343 if (State & REPLACE_FLAG)
8345 /* Don't delete characters before the insert point when in
8346 * Replace mode */
8347 if (curwin->w_cursor.lnum != Insstart.lnum
8348 || curwin->w_cursor.col >= Insstart.col)
8349 replace_do_bs(-1);
8351 else
8352 (void)del_char(FALSE);
8356 * Handle Backspace, delete-word and delete-line in Insert mode.
8357 * Return TRUE when backspace was actually used.
8359 static int
8360 ins_bs(c, mode, inserted_space_p)
8361 int c;
8362 int mode;
8363 int *inserted_space_p;
8365 linenr_T lnum;
8366 int cc;
8367 int temp = 0; /* init for GCC */
8368 colnr_T save_col;
8369 colnr_T mincol;
8370 int did_backspace = FALSE;
8371 int in_indent;
8372 int oldState;
8373 #ifdef FEAT_MBYTE
8374 int cpc[MAX_MCO]; /* composing characters */
8375 #endif
8378 * can't delete anything in an empty file
8379 * can't backup past first character in buffer
8380 * can't backup past starting point unless 'backspace' > 1
8381 * can backup to a previous line if 'backspace' == 0
8383 if ( bufempty()
8384 || (
8385 #ifdef FEAT_RIGHTLEFT
8386 !revins_on &&
8387 #endif
8388 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
8389 || (!can_bs(BS_START)
8390 && (arrow_used
8391 || (curwin->w_cursor.lnum == Insstart.lnum
8392 && curwin->w_cursor.col <= Insstart.col)))
8393 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
8394 && curwin->w_cursor.col <= ai_col)
8395 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
8397 vim_beep();
8398 return FALSE;
8401 if (stop_arrow() == FAIL)
8402 return FALSE;
8403 in_indent = inindent(0);
8404 #ifdef FEAT_CINDENT
8405 if (in_indent)
8406 can_cindent = FALSE;
8407 #endif
8408 #ifdef FEAT_COMMENTS
8409 end_comment_pending = NUL; /* After BS, don't auto-end comment */
8410 #endif
8411 #ifdef FEAT_RIGHTLEFT
8412 if (revins_on) /* put cursor after last inserted char */
8413 inc_cursor();
8414 #endif
8416 #ifdef FEAT_VIRTUALEDIT
8417 /* Virtualedit:
8418 * BACKSPACE_CHAR eats a virtual space
8419 * BACKSPACE_WORD eats all coladd
8420 * BACKSPACE_LINE eats all coladd and keeps going
8422 if (curwin->w_cursor.coladd > 0)
8424 if (mode == BACKSPACE_CHAR)
8426 --curwin->w_cursor.coladd;
8427 return TRUE;
8429 if (mode == BACKSPACE_WORD)
8431 curwin->w_cursor.coladd = 0;
8432 return TRUE;
8434 curwin->w_cursor.coladd = 0;
8436 #endif
8439 * delete newline!
8441 if (curwin->w_cursor.col == 0)
8443 lnum = Insstart.lnum;
8444 if (curwin->w_cursor.lnum == Insstart.lnum
8445 #ifdef FEAT_RIGHTLEFT
8446 || revins_on
8447 #endif
8450 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
8451 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
8452 return FALSE;
8453 --Insstart.lnum;
8454 Insstart.col = MAXCOL;
8457 * In replace mode:
8458 * cc < 0: NL was inserted, delete it
8459 * cc >= 0: NL was replaced, put original characters back
8461 cc = -1;
8462 if (State & REPLACE_FLAG)
8463 cc = replace_pop(); /* returns -1 if NL was inserted */
8465 * In replace mode, in the line we started replacing, we only move the
8466 * cursor.
8468 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
8470 dec_cursor();
8472 else
8474 #ifdef FEAT_VREPLACE
8475 if (!(State & VREPLACE_FLAG)
8476 || curwin->w_cursor.lnum > orig_line_count)
8477 #endif
8479 temp = gchar_cursor(); /* remember current char */
8480 --curwin->w_cursor.lnum;
8482 /* When "aw" is in 'formatoptions' we must delete the space at
8483 * the end of the line, otherwise the line will be broken
8484 * again when auto-formatting. */
8485 if (has_format_option(FO_AUTO)
8486 && has_format_option(FO_WHITE_PAR))
8488 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
8489 TRUE);
8490 int len;
8492 len = (int)STRLEN(ptr);
8493 if (len > 0 && ptr[len - 1] == ' ')
8494 ptr[len - 1] = NUL;
8497 (void)do_join(FALSE);
8498 if (temp == NUL && gchar_cursor() != NUL)
8499 inc_cursor();
8501 #ifdef FEAT_VREPLACE
8502 else
8503 dec_cursor();
8504 #endif
8507 * In REPLACE mode we have to put back the text that was replaced
8508 * by the NL. On the replace stack is first a NUL-terminated
8509 * sequence of characters that were deleted and then the
8510 * characters that NL replaced.
8512 if (State & REPLACE_FLAG)
8515 * Do the next ins_char() in NORMAL state, to
8516 * prevent ins_char() from replacing characters and
8517 * avoiding showmatch().
8519 oldState = State;
8520 State = NORMAL;
8522 * restore characters (blanks) deleted after cursor
8524 while (cc > 0)
8526 save_col = curwin->w_cursor.col;
8527 #ifdef FEAT_MBYTE
8528 mb_replace_pop_ins(cc);
8529 #else
8530 ins_char(cc);
8531 #endif
8532 curwin->w_cursor.col = save_col;
8533 cc = replace_pop();
8535 /* restore the characters that NL replaced */
8536 replace_pop_ins();
8537 State = oldState;
8540 did_ai = FALSE;
8542 else
8545 * Delete character(s) before the cursor.
8547 #ifdef FEAT_RIGHTLEFT
8548 if (revins_on) /* put cursor on last inserted char */
8549 dec_cursor();
8550 #endif
8551 mincol = 0;
8552 /* keep indent */
8553 if (mode == BACKSPACE_LINE
8554 && (curbuf->b_p_ai
8555 #ifdef FEAT_CINDENT
8556 || cindent_on()
8557 #endif
8559 #ifdef FEAT_RIGHTLEFT
8560 && !revins_on
8561 #endif
8564 save_col = curwin->w_cursor.col;
8565 beginline(BL_WHITE);
8566 if (curwin->w_cursor.col < save_col)
8567 mincol = curwin->w_cursor.col;
8568 curwin->w_cursor.col = save_col;
8572 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8574 if ( mode == BACKSPACE_CHAR
8575 && ((p_sta && in_indent)
8576 || (curbuf->b_p_sts != 0
8577 && curwin->w_cursor.col > 0
8578 && (*(ml_get_cursor() - 1) == TAB
8579 || (*(ml_get_cursor() - 1) == ' '
8580 && (!*inserted_space_p
8581 || arrow_used))))))
8583 int ts;
8584 colnr_T vcol;
8585 colnr_T want_vcol;
8586 colnr_T start_vcol;
8588 *inserted_space_p = FALSE;
8589 if (p_sta && in_indent)
8590 ts = curbuf->b_p_sw;
8591 else
8592 ts = curbuf->b_p_sts;
8593 /* Compute the virtual column where we want to be. Since
8594 * 'showbreak' may get in the way, need to get the last column of
8595 * the previous character. */
8596 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8597 start_vcol = vcol;
8598 dec_cursor();
8599 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8600 inc_cursor();
8601 want_vcol = (want_vcol / ts) * ts;
8603 /* delete characters until we are at or before want_vcol */
8604 while (vcol > want_vcol
8605 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8606 ins_bs_one(&vcol);
8608 /* insert extra spaces until we are at want_vcol */
8609 while (vcol < want_vcol)
8611 /* Remember the first char we inserted */
8612 if (curwin->w_cursor.lnum == Insstart.lnum
8613 && curwin->w_cursor.col < Insstart.col)
8614 Insstart.col = curwin->w_cursor.col;
8616 #ifdef FEAT_VREPLACE
8617 if (State & VREPLACE_FLAG)
8618 ins_char(' ');
8619 else
8620 #endif
8622 ins_str((char_u *)" ");
8623 if ((State & REPLACE_FLAG))
8624 replace_push(NUL);
8626 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8629 /* If we are now back where we started delete one character. Can
8630 * happen when using 'sts' and 'linebreak'. */
8631 if (vcol >= start_vcol)
8632 ins_bs_one(&vcol);
8636 * Delete upto starting point, start of line or previous word.
8638 else do
8640 #ifdef FEAT_RIGHTLEFT
8641 if (!revins_on) /* put cursor on char to be deleted */
8642 #endif
8643 dec_cursor();
8645 /* start of word? */
8646 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8648 mode = BACKSPACE_WORD_NOT_SPACE;
8649 temp = vim_iswordc(gchar_cursor());
8651 /* end of word? */
8652 else if (mode == BACKSPACE_WORD_NOT_SPACE
8653 && (vim_isspace(cc = gchar_cursor())
8654 || vim_iswordc(cc) != temp))
8656 #ifdef FEAT_RIGHTLEFT
8657 if (!revins_on)
8658 #endif
8659 inc_cursor();
8660 #ifdef FEAT_RIGHTLEFT
8661 else if (State & REPLACE_FLAG)
8662 dec_cursor();
8663 #endif
8664 break;
8666 if (State & REPLACE_FLAG)
8667 replace_do_bs(-1);
8668 else
8670 #ifdef FEAT_MBYTE
8671 if (enc_utf8 && p_deco)
8672 (void)utfc_ptr2char(ml_get_cursor(), cpc);
8673 #endif
8674 (void)del_char(FALSE);
8675 #ifdef FEAT_MBYTE
8677 * If there are combining characters and 'delcombine' is set
8678 * move the cursor back. Don't back up before the base
8679 * character.
8681 if (enc_utf8 && p_deco && cpc[0] != NUL)
8682 inc_cursor();
8683 #endif
8684 #ifdef FEAT_RIGHTLEFT
8685 if (revins_chars)
8687 revins_chars--;
8688 revins_legal++;
8690 if (revins_on && gchar_cursor() == NUL)
8691 break;
8692 #endif
8694 /* Just a single backspace?: */
8695 if (mode == BACKSPACE_CHAR)
8696 break;
8697 } while (
8698 #ifdef FEAT_RIGHTLEFT
8699 revins_on ||
8700 #endif
8701 (curwin->w_cursor.col > mincol
8702 && (curwin->w_cursor.lnum != Insstart.lnum
8703 || curwin->w_cursor.col != Insstart.col)));
8704 did_backspace = TRUE;
8706 #ifdef FEAT_SMARTINDENT
8707 did_si = FALSE;
8708 can_si = FALSE;
8709 can_si_back = FALSE;
8710 #endif
8711 if (curwin->w_cursor.col <= 1)
8712 did_ai = FALSE;
8714 * It's a little strange to put backspaces into the redo
8715 * buffer, but it makes auto-indent a lot easier to deal
8716 * with.
8718 AppendCharToRedobuff(c);
8720 /* If deleted before the insertion point, adjust it */
8721 if (curwin->w_cursor.lnum == Insstart.lnum
8722 && curwin->w_cursor.col < Insstart.col)
8723 Insstart.col = curwin->w_cursor.col;
8725 /* vi behaviour: the cursor moves backward but the character that
8726 * was there remains visible
8727 * Vim behaviour: the cursor moves backward and the character that
8728 * was there is erased from the screen.
8729 * We can emulate the vi behaviour by pretending there is a dollar
8730 * displayed even when there isn't.
8731 * --pkv Sun Jan 19 01:56:40 EST 2003 */
8732 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
8733 dollar_vcol = curwin->w_virtcol;
8735 #ifdef FEAT_FOLDING
8736 /* When deleting a char the cursor line must never be in a closed fold.
8737 * E.g., when 'foldmethod' is indent and deleting the first non-white
8738 * char before a Tab. */
8739 if (did_backspace)
8740 foldOpenCursor();
8741 #endif
8743 return did_backspace;
8746 #ifdef FEAT_MOUSE
8747 static void
8748 ins_mouse(c)
8749 int c;
8751 pos_T tpos;
8752 win_T *old_curwin = curwin;
8754 # ifdef FEAT_GUI
8755 /* When GUI is active, also move/paste when 'mouse' is empty */
8756 if (!gui.in_use)
8757 # endif
8758 if (!mouse_has(MOUSE_INSERT))
8759 return;
8761 undisplay_dollar();
8762 tpos = curwin->w_cursor;
8763 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
8765 #ifdef FEAT_WINDOWS
8766 win_T *new_curwin = curwin;
8768 if (curwin != old_curwin && win_valid(old_curwin))
8770 /* Mouse took us to another window. We need to go back to the
8771 * previous one to stop insert there properly. */
8772 curwin = old_curwin;
8773 curbuf = curwin->w_buffer;
8775 #endif
8776 start_arrow(curwin == old_curwin ? &tpos : NULL);
8777 #ifdef FEAT_WINDOWS
8778 if (curwin != new_curwin && win_valid(new_curwin))
8780 curwin = new_curwin;
8781 curbuf = curwin->w_buffer;
8783 #endif
8784 # ifdef FEAT_CINDENT
8785 can_cindent = TRUE;
8786 # endif
8789 #ifdef FEAT_WINDOWS
8790 /* redraw status lines (in case another window became active) */
8791 redraw_statuslines();
8792 #endif
8795 static void
8796 ins_mousescroll(up)
8797 int up;
8799 pos_T tpos;
8800 # if defined(FEAT_WINDOWS)
8801 win_T *old_curwin = curwin;
8802 # endif
8803 # ifdef FEAT_INS_EXPAND
8804 int did_scroll = FALSE;
8805 # endif
8807 tpos = curwin->w_cursor;
8809 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8810 /* Currently the mouse coordinates are only known in the GUI. */
8811 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
8813 int row, col;
8815 row = mouse_row;
8816 col = mouse_col;
8818 /* find the window at the pointer coordinates */
8819 curwin = mouse_find_win(&row, &col);
8820 curbuf = curwin->w_buffer;
8822 if (curwin == old_curwin)
8823 # endif
8824 undisplay_dollar();
8826 # ifdef FEAT_INS_EXPAND
8827 /* Don't scroll the window in which completion is being done. */
8828 if (!pum_visible()
8829 # if defined(FEAT_WINDOWS)
8830 || curwin != old_curwin
8831 # endif
8833 # endif
8835 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
8836 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
8837 else
8838 scroll_redraw(up, 3L);
8839 # ifdef FEAT_INS_EXPAND
8840 did_scroll = TRUE;
8841 # endif
8844 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8845 curwin->w_redr_status = TRUE;
8847 curwin = old_curwin;
8848 curbuf = curwin->w_buffer;
8849 # endif
8851 # ifdef FEAT_INS_EXPAND
8852 /* The popup menu may overlay the window, need to redraw it.
8853 * TODO: Would be more efficient to only redraw the windows that are
8854 * overlapped by the popup menu. */
8855 if (pum_visible() && did_scroll)
8857 redraw_all_later(NOT_VALID);
8858 ins_compl_show_pum();
8860 # endif
8862 if (!equalpos(curwin->w_cursor, tpos))
8864 start_arrow(&tpos);
8865 # ifdef FEAT_CINDENT
8866 can_cindent = TRUE;
8867 # endif
8870 #endif
8872 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
8873 static void
8874 ins_tabline(c)
8875 int c;
8877 /* We will be leaving the current window, unless closing another tab. */
8878 if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
8879 || (current_tab != 0 && current_tab != tabpage_index(curtab)))
8881 undisplay_dollar();
8882 start_arrow(&curwin->w_cursor);
8883 # ifdef FEAT_CINDENT
8884 can_cindent = TRUE;
8885 # endif
8888 if (c == K_TABLINE)
8889 goto_tabpage(current_tab);
8890 else
8892 handle_tabmenu();
8893 redraw_statuslines(); /* will redraw the tabline when needed */
8896 #endif
8898 #if defined(FEAT_GUI) || defined(PROTO)
8899 void
8900 ins_scroll()
8902 pos_T tpos;
8904 undisplay_dollar();
8905 tpos = curwin->w_cursor;
8906 if (gui_do_scroll())
8908 start_arrow(&tpos);
8909 # ifdef FEAT_CINDENT
8910 can_cindent = TRUE;
8911 # endif
8915 void
8916 ins_horscroll()
8918 pos_T tpos;
8920 undisplay_dollar();
8921 tpos = curwin->w_cursor;
8922 if (gui_do_horiz_scroll())
8924 start_arrow(&tpos);
8925 # ifdef FEAT_CINDENT
8926 can_cindent = TRUE;
8927 # endif
8930 #endif
8932 static void
8933 ins_left()
8935 pos_T tpos;
8937 #ifdef FEAT_FOLDING
8938 if ((fdo_flags & FDO_HOR) && KeyTyped)
8939 foldOpenCursor();
8940 #endif
8941 undisplay_dollar();
8942 tpos = curwin->w_cursor;
8943 if (oneleft() == OK)
8945 #if defined(FEAT_XIM) && (defined(FEAT_GUI_GTK) || defined(FEAT_GUI_MACVIM))
8946 /* Only call start_arrow() when not busy with preediting, it will
8947 * break undo. K_LEFT is inserted in im_correct_cursor(). */
8948 if (!im_is_preediting())
8949 #endif
8950 start_arrow(&tpos);
8951 #ifdef FEAT_RIGHTLEFT
8952 /* If exit reversed string, position is fixed */
8953 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
8954 revins_legal++;
8955 revins_chars++;
8956 #endif
8960 * if 'whichwrap' set for cursor in insert mode may go to
8961 * previous line
8963 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
8965 start_arrow(&tpos);
8966 --(curwin->w_cursor.lnum);
8967 coladvance((colnr_T)MAXCOL);
8968 curwin->w_set_curswant = TRUE; /* so we stay at the end */
8970 else
8971 vim_beep();
8974 static void
8975 ins_home(c)
8976 int c;
8978 pos_T tpos;
8980 #ifdef FEAT_FOLDING
8981 if ((fdo_flags & FDO_HOR) && KeyTyped)
8982 foldOpenCursor();
8983 #endif
8984 undisplay_dollar();
8985 tpos = curwin->w_cursor;
8986 if (c == K_C_HOME)
8987 curwin->w_cursor.lnum = 1;
8988 curwin->w_cursor.col = 0;
8989 #ifdef FEAT_VIRTUALEDIT
8990 curwin->w_cursor.coladd = 0;
8991 #endif
8992 curwin->w_curswant = 0;
8993 start_arrow(&tpos);
8996 static void
8997 ins_end(c)
8998 int c;
9000 pos_T tpos;
9002 #ifdef FEAT_FOLDING
9003 if ((fdo_flags & FDO_HOR) && KeyTyped)
9004 foldOpenCursor();
9005 #endif
9006 undisplay_dollar();
9007 tpos = curwin->w_cursor;
9008 if (c == K_C_END)
9009 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9010 coladvance((colnr_T)MAXCOL);
9011 curwin->w_curswant = MAXCOL;
9013 start_arrow(&tpos);
9016 static void
9017 ins_s_left()
9019 #ifdef FEAT_FOLDING
9020 if ((fdo_flags & FDO_HOR) && KeyTyped)
9021 foldOpenCursor();
9022 #endif
9023 undisplay_dollar();
9024 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
9026 start_arrow(&curwin->w_cursor);
9027 (void)bck_word(1L, FALSE, FALSE);
9028 curwin->w_set_curswant = TRUE;
9030 else
9031 vim_beep();
9034 static void
9035 ins_right()
9037 #ifdef FEAT_FOLDING
9038 if ((fdo_flags & FDO_HOR) && KeyTyped)
9039 foldOpenCursor();
9040 #endif
9041 undisplay_dollar();
9042 if (gchar_cursor() != NUL
9043 #ifdef FEAT_VIRTUALEDIT
9044 || virtual_active()
9045 #endif
9048 start_arrow(&curwin->w_cursor);
9049 curwin->w_set_curswant = TRUE;
9050 #ifdef FEAT_VIRTUALEDIT
9051 if (virtual_active())
9052 oneright();
9053 else
9054 #endif
9056 #ifdef FEAT_MBYTE
9057 if (has_mbyte)
9058 curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
9059 else
9060 #endif
9061 ++curwin->w_cursor.col;
9064 #ifdef FEAT_RIGHTLEFT
9065 revins_legal++;
9066 if (revins_chars)
9067 revins_chars--;
9068 #endif
9070 /* if 'whichwrap' set for cursor in insert mode, may move the
9071 * cursor to the next line */
9072 else if (vim_strchr(p_ww, ']') != NULL
9073 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
9075 start_arrow(&curwin->w_cursor);
9076 curwin->w_set_curswant = TRUE;
9077 ++curwin->w_cursor.lnum;
9078 curwin->w_cursor.col = 0;
9080 else
9081 vim_beep();
9084 static void
9085 ins_s_right()
9087 #ifdef FEAT_FOLDING
9088 if ((fdo_flags & FDO_HOR) && KeyTyped)
9089 foldOpenCursor();
9090 #endif
9091 undisplay_dollar();
9092 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
9093 || gchar_cursor() != NUL)
9095 start_arrow(&curwin->w_cursor);
9096 (void)fwd_word(1L, FALSE, 0);
9097 curwin->w_set_curswant = TRUE;
9099 else
9100 vim_beep();
9103 static void
9104 ins_up(startcol)
9105 int startcol; /* when TRUE move to Insstart.col */
9107 pos_T tpos;
9108 linenr_T old_topline = curwin->w_topline;
9109 #ifdef FEAT_DIFF
9110 int old_topfill = curwin->w_topfill;
9111 #endif
9113 undisplay_dollar();
9114 tpos = curwin->w_cursor;
9115 if (cursor_up(1L, TRUE) == OK)
9117 if (startcol)
9118 coladvance(getvcol_nolist(&Insstart));
9119 if (old_topline != curwin->w_topline
9120 #ifdef FEAT_DIFF
9121 || old_topfill != curwin->w_topfill
9122 #endif
9124 redraw_later(VALID);
9125 start_arrow(&tpos);
9126 #ifdef FEAT_CINDENT
9127 can_cindent = TRUE;
9128 #endif
9130 else
9131 vim_beep();
9134 static void
9135 ins_pageup()
9137 pos_T tpos;
9139 undisplay_dollar();
9141 #ifdef FEAT_WINDOWS
9142 if (mod_mask & MOD_MASK_CTRL)
9144 /* <C-PageUp>: tab page back */
9145 if (first_tabpage->tp_next != NULL)
9147 start_arrow(&curwin->w_cursor);
9148 goto_tabpage(-1);
9150 return;
9152 #endif
9154 tpos = curwin->w_cursor;
9155 if (onepage(BACKWARD, 1L) == OK)
9157 start_arrow(&tpos);
9158 #ifdef FEAT_CINDENT
9159 can_cindent = TRUE;
9160 #endif
9162 else
9163 vim_beep();
9166 static void
9167 ins_down(startcol)
9168 int startcol; /* when TRUE move to Insstart.col */
9170 pos_T tpos;
9171 linenr_T old_topline = curwin->w_topline;
9172 #ifdef FEAT_DIFF
9173 int old_topfill = curwin->w_topfill;
9174 #endif
9176 undisplay_dollar();
9177 tpos = curwin->w_cursor;
9178 if (cursor_down(1L, TRUE) == OK)
9180 if (startcol)
9181 coladvance(getvcol_nolist(&Insstart));
9182 if (old_topline != curwin->w_topline
9183 #ifdef FEAT_DIFF
9184 || old_topfill != curwin->w_topfill
9185 #endif
9187 redraw_later(VALID);
9188 start_arrow(&tpos);
9189 #ifdef FEAT_CINDENT
9190 can_cindent = TRUE;
9191 #endif
9193 else
9194 vim_beep();
9197 static void
9198 ins_pagedown()
9200 pos_T tpos;
9202 undisplay_dollar();
9204 #ifdef FEAT_WINDOWS
9205 if (mod_mask & MOD_MASK_CTRL)
9207 /* <C-PageDown>: tab page forward */
9208 if (first_tabpage->tp_next != NULL)
9210 start_arrow(&curwin->w_cursor);
9211 goto_tabpage(0);
9213 return;
9215 #endif
9217 tpos = curwin->w_cursor;
9218 if (onepage(FORWARD, 1L) == OK)
9220 start_arrow(&tpos);
9221 #ifdef FEAT_CINDENT
9222 can_cindent = TRUE;
9223 #endif
9225 else
9226 vim_beep();
9229 #ifdef FEAT_DND
9230 static void
9231 ins_drop()
9233 do_put('~', BACKWARD, 1L, PUT_CURSEND);
9235 #endif
9238 * Handle TAB in Insert or Replace mode.
9239 * Return TRUE when the TAB needs to be inserted like a normal character.
9241 static int
9242 ins_tab()
9244 int ind;
9245 int i;
9246 int temp;
9248 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
9249 Insstart_blank_vcol = get_nolist_virtcol();
9250 if (echeck_abbr(TAB + ABBR_OFF))
9251 return FALSE;
9253 ind = inindent(0);
9254 #ifdef FEAT_CINDENT
9255 if (ind)
9256 can_cindent = FALSE;
9257 #endif
9260 * When nothing special, insert TAB like a normal character
9262 if (!curbuf->b_p_et
9263 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
9264 && curbuf->b_p_sts == 0)
9265 return TRUE;
9267 if (stop_arrow() == FAIL)
9268 return TRUE;
9270 did_ai = FALSE;
9271 #ifdef FEAT_SMARTINDENT
9272 did_si = FALSE;
9273 can_si = FALSE;
9274 can_si_back = FALSE;
9275 #endif
9276 AppendToRedobuff((char_u *)"\t");
9278 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9279 temp = (int)curbuf->b_p_sw;
9280 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
9281 temp = (int)curbuf->b_p_sts;
9282 else /* otherwise use 'tabstop' */
9283 temp = (int)curbuf->b_p_ts;
9284 temp -= get_nolist_virtcol() % temp;
9287 * Insert the first space with ins_char(). It will delete one char in
9288 * replace mode. Insert the rest with ins_str(); it will not delete any
9289 * chars. For VREPLACE mode, we use ins_char() for all characters.
9291 ins_char(' ');
9292 while (--temp > 0)
9294 #ifdef FEAT_VREPLACE
9295 if (State & VREPLACE_FLAG)
9296 ins_char(' ');
9297 else
9298 #endif
9300 ins_str((char_u *)" ");
9301 if (State & REPLACE_FLAG) /* no char replaced */
9302 replace_push(NUL);
9307 * When 'expandtab' not set: Replace spaces by TABs where possible.
9309 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
9311 char_u *ptr;
9312 #ifdef FEAT_VREPLACE
9313 char_u *saved_line = NULL; /* init for GCC */
9314 pos_T pos;
9315 #endif
9316 pos_T fpos;
9317 pos_T *cursor;
9318 colnr_T want_vcol, vcol;
9319 int change_col = -1;
9320 int save_list = curwin->w_p_list;
9323 * Get the current line. For VREPLACE mode, don't make real changes
9324 * yet, just work on a copy of the line.
9326 #ifdef FEAT_VREPLACE
9327 if (State & VREPLACE_FLAG)
9329 pos = curwin->w_cursor;
9330 cursor = &pos;
9331 saved_line = vim_strsave(ml_get_curline());
9332 if (saved_line == NULL)
9333 return FALSE;
9334 ptr = saved_line + pos.col;
9336 else
9337 #endif
9339 ptr = ml_get_cursor();
9340 cursor = &curwin->w_cursor;
9343 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
9344 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9345 curwin->w_p_list = FALSE;
9347 /* Find first white before the cursor */
9348 fpos = curwin->w_cursor;
9349 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
9351 --fpos.col;
9352 --ptr;
9355 /* In Replace mode, don't change characters before the insert point. */
9356 if ((State & REPLACE_FLAG)
9357 && fpos.lnum == Insstart.lnum
9358 && fpos.col < Insstart.col)
9360 ptr += Insstart.col - fpos.col;
9361 fpos.col = Insstart.col;
9364 /* compute virtual column numbers of first white and cursor */
9365 getvcol(curwin, &fpos, &vcol, NULL, NULL);
9366 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
9368 /* Use as many TABs as possible. Beware of 'showbreak' and
9369 * 'linebreak' adding extra virtual columns. */
9370 while (vim_iswhite(*ptr))
9372 i = lbr_chartabsize((char_u *)"\t", vcol);
9373 if (vcol + i > want_vcol)
9374 break;
9375 if (*ptr != TAB)
9377 *ptr = TAB;
9378 if (change_col < 0)
9380 change_col = fpos.col; /* Column of first change */
9381 /* May have to adjust Insstart */
9382 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
9383 Insstart.col = fpos.col;
9386 ++fpos.col;
9387 ++ptr;
9388 vcol += i;
9391 if (change_col >= 0)
9393 int repl_off = 0;
9395 /* Skip over the spaces we need. */
9396 while (vcol < want_vcol && *ptr == ' ')
9398 vcol += lbr_chartabsize(ptr, vcol);
9399 ++ptr;
9400 ++repl_off;
9402 if (vcol > want_vcol)
9404 /* Must have a char with 'showbreak' just before it. */
9405 --ptr;
9406 --repl_off;
9408 fpos.col += repl_off;
9410 /* Delete following spaces. */
9411 i = cursor->col - fpos.col;
9412 if (i > 0)
9414 STRMOVE(ptr, ptr + i);
9415 /* correct replace stack. */
9416 if ((State & REPLACE_FLAG)
9417 #ifdef FEAT_VREPLACE
9418 && !(State & VREPLACE_FLAG)
9419 #endif
9421 for (temp = i; --temp >= 0; )
9422 replace_join(repl_off);
9424 #ifdef FEAT_NETBEANS_INTG
9425 if (usingNetbeans)
9427 netbeans_removed(curbuf, fpos.lnum, cursor->col,
9428 (long)(i + 1));
9429 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
9430 (char_u *)"\t", 1);
9432 #endif
9433 cursor->col -= i;
9435 #ifdef FEAT_VREPLACE
9437 * In VREPLACE mode, we haven't changed anything yet. Do it now by
9438 * backspacing over the changed spacing and then inserting the new
9439 * spacing.
9441 if (State & VREPLACE_FLAG)
9443 /* Backspace from real cursor to change_col */
9444 backspace_until_column(change_col);
9446 /* Insert each char in saved_line from changed_col to
9447 * ptr-cursor */
9448 ins_bytes_len(saved_line + change_col,
9449 cursor->col - change_col);
9451 #endif
9454 #ifdef FEAT_VREPLACE
9455 if (State & VREPLACE_FLAG)
9456 vim_free(saved_line);
9457 #endif
9458 curwin->w_p_list = save_list;
9461 return FALSE;
9465 * Handle CR or NL in insert mode.
9466 * Return TRUE when out of memory or can't undo.
9468 static int
9469 ins_eol(c)
9470 int c;
9472 int i;
9474 if (echeck_abbr(c + ABBR_OFF))
9475 return FALSE;
9476 if (stop_arrow() == FAIL)
9477 return TRUE;
9478 undisplay_dollar();
9481 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
9482 * character under the cursor. Only push a NUL on the replace stack,
9483 * nothing to put back when the NL is deleted.
9485 if ((State & REPLACE_FLAG)
9486 #ifdef FEAT_VREPLACE
9487 && !(State & VREPLACE_FLAG)
9488 #endif
9490 replace_push(NUL);
9493 * In VREPLACE mode, a NL replaces the rest of the line, and starts
9494 * replacing the next line, so we push all of the characters left on the
9495 * line onto the replace stack. This is not done here though, it is done
9496 * in open_line().
9499 #ifdef FEAT_VIRTUALEDIT
9500 /* Put cursor on NUL if on the last char and coladd is 1 (happens after
9501 * CTRL-O). */
9502 if (virtual_active() && curwin->w_cursor.coladd > 0)
9503 coladvance(getviscol());
9504 #endif
9506 #ifdef FEAT_RIGHTLEFT
9507 # ifdef FEAT_FKMAP
9508 if (p_altkeymap && p_fkmap)
9509 fkmap(NL);
9510 # endif
9511 /* NL in reverse insert will always start in the end of
9512 * current line. */
9513 if (revins_on)
9514 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9515 #endif
9517 AppendToRedobuff(NL_STR);
9518 i = open_line(FORWARD,
9519 #ifdef FEAT_COMMENTS
9520 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
9521 #endif
9522 0, old_indent);
9523 old_indent = 0;
9524 #ifdef FEAT_CINDENT
9525 can_cindent = TRUE;
9526 #endif
9527 #ifdef FEAT_FOLDING
9528 /* When inserting a line the cursor line must never be in a closed fold. */
9529 foldOpenCursor();
9530 #endif
9532 return (!i);
9535 #ifdef FEAT_DIGRAPHS
9537 * Handle digraph in insert mode.
9538 * Returns character still to be inserted, or NUL when nothing remaining to be
9539 * done.
9541 static int
9542 ins_digraph()
9544 int c;
9545 int cc;
9547 pc_status = PC_STATUS_UNSET;
9548 if (redrawing() && !char_avail())
9550 /* may need to redraw when no more chars available now */
9551 ins_redraw(FALSE);
9553 edit_putchar('?', TRUE);
9554 #ifdef FEAT_CMDL_INFO
9555 add_to_showcmd_c(Ctrl_K);
9556 #endif
9559 #ifdef USE_ON_FLY_SCROLL
9560 dont_scroll = TRUE; /* disallow scrolling here */
9561 #endif
9563 /* don't map the digraph chars. This also prevents the
9564 * mode message to be deleted when ESC is hit */
9565 ++no_mapping;
9566 ++allow_keys;
9567 c = plain_vgetc();
9568 --no_mapping;
9569 --allow_keys;
9570 if (IS_SPECIAL(c) || mod_mask) /* special key */
9572 #ifdef FEAT_CMDL_INFO
9573 clear_showcmd();
9574 #endif
9575 insert_special(c, TRUE, FALSE);
9576 return NUL;
9578 if (c != ESC)
9580 if (redrawing() && !char_avail())
9582 /* may need to redraw when no more chars available now */
9583 ins_redraw(FALSE);
9585 if (char2cells(c) == 1)
9587 /* first remove the '?', otherwise it's restored when typing
9588 * an ESC next */
9589 edit_unputchar();
9590 ins_redraw(FALSE);
9591 edit_putchar(c, TRUE);
9593 #ifdef FEAT_CMDL_INFO
9594 add_to_showcmd_c(c);
9595 #endif
9597 ++no_mapping;
9598 ++allow_keys;
9599 cc = plain_vgetc();
9600 --no_mapping;
9601 --allow_keys;
9602 if (cc != ESC)
9604 AppendToRedobuff((char_u *)CTRL_V_STR);
9605 c = getdigraph(c, cc, TRUE);
9606 #ifdef FEAT_CMDL_INFO
9607 clear_showcmd();
9608 #endif
9609 return c;
9612 edit_unputchar();
9613 #ifdef FEAT_CMDL_INFO
9614 clear_showcmd();
9615 #endif
9616 return NUL;
9618 #endif
9621 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9622 * Returns the char to be inserted, or NUL if none found.
9624 static int
9625 ins_copychar(lnum)
9626 linenr_T lnum;
9628 int c;
9629 int temp;
9630 char_u *ptr, *prev_ptr;
9632 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9634 vim_beep();
9635 return NUL;
9638 /* try to advance to the cursor column */
9639 temp = 0;
9640 ptr = ml_get(lnum);
9641 prev_ptr = ptr;
9642 validate_virtcol();
9643 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9645 prev_ptr = ptr;
9646 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
9648 if ((colnr_T)temp > curwin->w_virtcol)
9649 ptr = prev_ptr;
9651 #ifdef FEAT_MBYTE
9652 c = (*mb_ptr2char)(ptr);
9653 #else
9654 c = *ptr;
9655 #endif
9656 if (c == NUL)
9657 vim_beep();
9658 return c;
9662 * CTRL-Y or CTRL-E typed in Insert mode.
9664 static int
9665 ins_ctrl_ey(tc)
9666 int tc;
9668 int c = tc;
9670 #ifdef FEAT_INS_EXPAND
9671 if (ctrl_x_mode == CTRL_X_SCROLL)
9673 if (c == Ctrl_Y)
9674 scrolldown_clamp();
9675 else
9676 scrollup_clamp();
9677 redraw_later(VALID);
9679 else
9680 #endif
9682 c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
9683 if (c != NUL)
9685 long tw_save;
9687 /* The character must be taken literally, insert like it
9688 * was typed after a CTRL-V, and pretend 'textwidth'
9689 * wasn't set. Digits, 'o' and 'x' are special after a
9690 * CTRL-V, don't use it for these. */
9691 if (c < 256 && !isalnum(c))
9692 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
9693 tw_save = curbuf->b_p_tw;
9694 curbuf->b_p_tw = -1;
9695 insert_special(c, TRUE, FALSE);
9696 curbuf->b_p_tw = tw_save;
9697 #ifdef FEAT_RIGHTLEFT
9698 revins_chars++;
9699 revins_legal++;
9700 #endif
9701 c = Ctrl_V; /* pretend CTRL-V is last character */
9702 auto_format(FALSE, TRUE);
9705 return c;
9708 #ifdef FEAT_SMARTINDENT
9710 * Try to do some very smart auto-indenting.
9711 * Used when inserting a "normal" character.
9713 static void
9714 ins_try_si(c)
9715 int c;
9717 pos_T *pos, old_pos;
9718 char_u *ptr;
9719 int i;
9720 int temp;
9723 * do some very smart indenting when entering '{' or '}'
9725 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
9728 * for '}' set indent equal to indent of line containing matching '{'
9730 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
9732 old_pos = curwin->w_cursor;
9734 * If the matching '{' has a ')' immediately before it (ignoring
9735 * white-space), then line up with the start of the line
9736 * containing the matching '(' if there is one. This handles the
9737 * case where an "if (..\n..) {" statement continues over multiple
9738 * lines -- webb
9740 ptr = ml_get(pos->lnum);
9741 i = pos->col;
9742 if (i > 0) /* skip blanks before '{' */
9743 while (--i > 0 && vim_iswhite(ptr[i]))
9745 curwin->w_cursor.lnum = pos->lnum;
9746 curwin->w_cursor.col = i;
9747 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
9748 curwin->w_cursor = *pos;
9749 i = get_indent();
9750 curwin->w_cursor = old_pos;
9751 #ifdef FEAT_VREPLACE
9752 if (State & VREPLACE_FLAG)
9753 change_indent(INDENT_SET, i, FALSE, NUL, TRUE);
9754 else
9755 #endif
9756 (void)set_indent(i, SIN_CHANGED);
9758 else if (curwin->w_cursor.col > 0)
9761 * when inserting '{' after "O" reduce indent, but not
9762 * more than indent of previous line
9764 temp = TRUE;
9765 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
9767 old_pos = curwin->w_cursor;
9768 i = get_indent();
9769 while (curwin->w_cursor.lnum > 1)
9771 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
9773 /* ignore empty lines and lines starting with '#'. */
9774 if (*ptr != '#' && *ptr != NUL)
9775 break;
9777 if (get_indent() >= i)
9778 temp = FALSE;
9779 curwin->w_cursor = old_pos;
9781 if (temp)
9782 shift_line(TRUE, FALSE, 1, TRUE);
9787 * set indent of '#' always to 0
9789 if (curwin->w_cursor.col > 0 && can_si && c == '#')
9791 /* remember current indent for next line */
9792 old_indent = get_indent();
9793 (void)set_indent(0, SIN_CHANGED);
9796 /* Adjust ai_col, the char at this position can be deleted. */
9797 if (ai_col > curwin->w_cursor.col)
9798 ai_col = curwin->w_cursor.col;
9800 #endif
9803 * Get the value that w_virtcol would have when 'list' is off.
9804 * Unless 'cpo' contains the 'L' flag.
9806 static colnr_T
9807 get_nolist_virtcol()
9809 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9810 return getvcol_nolist(&curwin->w_cursor);
9811 validate_virtcol();
9812 return curwin->w_virtcol;