Merge branch 'vim-with-runtime' into feat/var-tabstops
[vim_extended.git] / src / edit.c
bloba3bc5998ef77501cfe0d5feeea5587e77d19e7bd
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 (
661 #ifdef FEAT_VARTABS
662 (int)curwin->w_wcol < mincol
663 - tabstop_at(get_nolist_virtcol(), curbuf->b_p_ts, curbuf->b_p_vts_ary)
664 #else
665 (int)curwin->w_wcol < mincol - curbuf->b_p_ts
666 #endif
667 && curwin->w_wrow == W_WINROW(curwin)
668 + curwin->w_height - 1 - p_so
669 && (curwin->w_cursor.lnum != curwin->w_topline
670 #ifdef FEAT_DIFF
671 || curwin->w_topfill > 0
672 #endif
675 #ifdef FEAT_DIFF
676 if (curwin->w_topfill > 0)
677 --curwin->w_topfill;
678 else
679 #endif
680 #ifdef FEAT_FOLDING
681 if (hasFolding(curwin->w_topline, NULL, &old_topline))
682 set_topline(curwin, old_topline + 1);
683 else
684 #endif
685 set_topline(curwin, curwin->w_topline + 1);
689 /* May need to adjust w_topline to show the cursor. */
690 update_topline();
692 did_backspace = FALSE;
694 validate_cursor(); /* may set must_redraw */
697 * Redraw the display when no characters are waiting.
698 * Also shows mode, ruler and positions cursor.
700 ins_redraw(TRUE);
702 #ifdef FEAT_SCROLLBIND
703 if (curwin->w_p_scb)
704 do_check_scrollbind(TRUE);
705 #endif
707 update_curswant();
708 old_topline = curwin->w_topline;
709 #ifdef FEAT_DIFF
710 old_topfill = curwin->w_topfill;
711 #endif
713 #ifdef USE_ON_FLY_SCROLL
714 dont_scroll = FALSE; /* allow scrolling here */
715 #endif
718 * Get a character for Insert mode. Ignore K_IGNORE.
720 lastc = c; /* remember previous char for CTRL-D */
723 c = safe_vgetc();
724 } while (c == K_IGNORE);
726 #ifdef FEAT_AUTOCMD
727 /* Don't want K_CURSORHOLD for the second key, e.g., after CTRL-V. */
728 did_cursorhold = TRUE;
729 #endif
731 #ifdef FEAT_RIGHTLEFT
732 if (p_hkmap && KeyTyped)
733 c = hkmap(c); /* Hebrew mode mapping */
734 #endif
735 #ifdef FEAT_FKMAP
736 if (p_fkmap && KeyTyped)
737 c = fkmap(c); /* Farsi mode mapping */
738 #endif
740 #ifdef FEAT_INS_EXPAND
742 * Special handling of keys while the popup menu is visible or wanted
743 * and the cursor is still in the completed word. Only when there is
744 * a match, skip this when no matches were found.
746 if (compl_started
747 && pum_wanted()
748 && curwin->w_cursor.col >= compl_col
749 && (compl_shown_match == NULL
750 || compl_shown_match != compl_shown_match->cp_next))
752 /* BS: Delete one character from "compl_leader". */
753 if ((c == K_BS || c == Ctrl_H)
754 && curwin->w_cursor.col > compl_col
755 && (c = ins_compl_bs()) == NUL)
756 continue;
758 /* When no match was selected or it was edited. */
759 if (!compl_used_match)
761 /* CTRL-L: Add one character from the current match to
762 * "compl_leader". Except when at the original match and
763 * there is nothing to add, CTRL-L works like CTRL-P then. */
764 if (c == Ctrl_L
765 && (ctrl_x_mode != CTRL_X_WHOLE_LINE
766 || (int)STRLEN(compl_shown_match->cp_str)
767 > curwin->w_cursor.col - compl_col))
769 ins_compl_addfrommatch();
770 continue;
773 /* A non-white character that fits in with the current
774 * completion: Add to "compl_leader". */
775 if (ins_compl_accept_char(c))
777 ins_compl_addleader(c);
778 continue;
781 /* Pressing CTRL-Y selects the current match. When
782 * compl_enter_selects is set the Enter key does the same. */
783 if (c == Ctrl_Y || (compl_enter_selects
784 && (c == CAR || c == K_KENTER || c == NL)))
786 ins_compl_delete();
787 ins_compl_insert();
792 /* Prepare for or stop CTRL-X mode. This doesn't do completion, but
793 * it does fix up the text when finishing completion. */
794 compl_get_longest = FALSE;
795 if (ins_compl_prep(c))
796 continue;
797 #endif
799 /* CTRL-\ CTRL-N goes to Normal mode,
800 * CTRL-\ CTRL-G goes to mode selected with 'insertmode',
801 * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor. */
802 if (c == Ctrl_BSL)
804 /* may need to redraw when no more chars available now */
805 ins_redraw(FALSE);
806 ++no_mapping;
807 ++allow_keys;
808 c = plain_vgetc();
809 --no_mapping;
810 --allow_keys;
811 if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O)
813 /* it's something else */
814 vungetc(c);
815 c = Ctrl_BSL;
817 else if (c == Ctrl_G && p_im)
818 continue;
819 else
821 if (c == Ctrl_O)
823 ins_ctrl_o();
824 ins_at_eol = FALSE; /* cursor keeps its column */
825 nomove = TRUE;
827 count = 0;
828 goto doESCkey;
832 #ifdef FEAT_DIGRAPHS
833 c = do_digraph(c);
834 #endif
836 #ifdef FEAT_INS_EXPAND
837 if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
838 goto docomplete;
839 #endif
840 if (c == Ctrl_V || c == Ctrl_Q)
842 ins_ctrl_v();
843 c = Ctrl_V; /* pretend CTRL-V is last typed character */
844 continue;
847 #ifdef FEAT_CINDENT
848 if (cindent_on()
849 # ifdef FEAT_INS_EXPAND
850 && ctrl_x_mode == 0
851 # endif
854 /* A key name preceded by a bang means this key is not to be
855 * inserted. Skip ahead to the re-indenting below.
856 * A key name preceded by a star means that indenting has to be
857 * done before inserting the key. */
858 line_is_white = inindent(0);
859 if (in_cinkeys(c, '!', line_is_white))
860 goto force_cindent;
861 if (can_cindent && in_cinkeys(c, '*', line_is_white)
862 && stop_arrow() == OK)
863 do_c_expr_indent();
865 #endif
867 #ifdef FEAT_RIGHTLEFT
868 if (curwin->w_p_rl)
869 switch (c)
871 case K_LEFT: c = K_RIGHT; break;
872 case K_S_LEFT: c = K_S_RIGHT; break;
873 case K_C_LEFT: c = K_C_RIGHT; break;
874 case K_RIGHT: c = K_LEFT; break;
875 case K_S_RIGHT: c = K_S_LEFT; break;
876 case K_C_RIGHT: c = K_C_LEFT; break;
878 #endif
880 #ifdef FEAT_VISUAL
882 * If 'keymodel' contains "startsel", may start selection. If it
883 * does, a CTRL-O and c will be stuffed, we need to get these
884 * characters.
886 if (ins_start_select(c))
887 continue;
888 #endif
891 * The big switch to handle a character in insert mode.
893 switch (c)
895 case ESC: /* End input mode */
896 if (echeck_abbr(ESC + ABBR_OFF))
897 break;
898 /*FALLTHROUGH*/
900 case Ctrl_C: /* End input mode */
901 #ifdef FEAT_CMDWIN
902 if (c == Ctrl_C && cmdwin_type != 0)
904 /* Close the cmdline window. */
905 cmdwin_result = K_IGNORE;
906 got_int = FALSE; /* don't stop executing autocommands et al. */
907 nomove = TRUE;
908 goto doESCkey;
910 #endif
912 #ifdef UNIX
913 do_intr:
914 #endif
915 /* when 'insertmode' set, and not halfway a mapping, don't leave
916 * Insert mode */
917 if (goto_im())
919 if (got_int)
921 (void)vgetc(); /* flush all buffers */
922 got_int = FALSE;
924 else
925 vim_beep();
926 break;
928 doESCkey:
930 * This is the ONLY return from edit()!
932 /* Always update o_lnum, so that a "CTRL-O ." that adds a line
933 * still puts the cursor back after the inserted text. */
934 if (ins_at_eol && gchar_cursor() == NUL)
935 o_lnum = curwin->w_cursor.lnum;
937 if (ins_esc(&count, cmdchar, nomove))
939 #ifdef FEAT_AUTOCMD
940 if (cmdchar != 'r' && cmdchar != 'v')
941 apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
942 FALSE, curbuf);
943 did_cursorhold = FALSE;
944 #endif
945 return (c == Ctrl_O);
947 continue;
949 case Ctrl_Z: /* suspend when 'insertmode' set */
950 if (!p_im)
951 goto normalchar; /* insert CTRL-Z as normal char */
952 stuffReadbuff((char_u *)":st\r");
953 c = Ctrl_O;
954 /*FALLTHROUGH*/
956 case Ctrl_O: /* execute one command */
957 #ifdef FEAT_COMPL_FUNC
958 if (ctrl_x_mode == CTRL_X_OMNI)
959 goto docomplete;
960 #endif
961 if (echeck_abbr(Ctrl_O + ABBR_OFF))
962 break;
963 ins_ctrl_o();
965 #ifdef FEAT_VIRTUALEDIT
966 /* don't move the cursor left when 'virtualedit' has "onemore". */
967 if (ve_flags & VE_ONEMORE)
969 ins_at_eol = FALSE;
970 nomove = TRUE;
972 #endif
973 count = 0;
974 goto doESCkey;
976 case K_INS: /* toggle insert/replace mode */
977 case K_KINS:
978 ins_insert(replaceState);
979 break;
981 case K_SELECT: /* end of Select mode mapping - ignore */
982 break;
984 #ifdef FEAT_SNIFF
985 case K_SNIFF: /* Sniff command received */
986 stuffcharReadbuff(K_SNIFF);
987 goto doESCkey;
988 #endif
990 case K_HELP: /* Help key works like <ESC> <Help> */
991 case K_F1:
992 case K_XF1:
993 stuffcharReadbuff(K_HELP);
994 if (p_im)
995 need_start_insertmode = TRUE;
996 goto doESCkey;
998 #ifdef FEAT_NETBEANS_INTG
999 case K_F21: /* NetBeans command */
1000 ++no_mapping; /* don't map the next key hits */
1001 i = plain_vgetc();
1002 --no_mapping;
1003 netbeans_keycommand(i);
1004 break;
1005 #endif
1007 case K_ZERO: /* Insert the previously inserted text. */
1008 case NUL:
1009 case Ctrl_A:
1010 /* For ^@ the trailing ESC will end the insert, unless there is an
1011 * error. */
1012 if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
1013 && c != Ctrl_A && !p_im)
1014 goto doESCkey; /* quit insert mode */
1015 inserted_space = FALSE;
1016 break;
1018 case Ctrl_R: /* insert the contents of a register */
1019 ins_reg();
1020 auto_format(FALSE, TRUE);
1021 inserted_space = FALSE;
1022 break;
1024 case Ctrl_G: /* commands starting with CTRL-G */
1025 ins_ctrl_g();
1026 break;
1028 case Ctrl_HAT: /* switch input mode and/or langmap */
1029 ins_ctrl_hat();
1030 break;
1032 #ifdef FEAT_RIGHTLEFT
1033 case Ctrl__: /* switch between languages */
1034 if (!p_ari)
1035 goto normalchar;
1036 ins_ctrl_();
1037 break;
1038 #endif
1040 case Ctrl_D: /* Make indent one shiftwidth smaller. */
1041 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1042 if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
1043 goto docomplete;
1044 #endif
1045 /* FALLTHROUGH */
1047 case Ctrl_T: /* Make indent one shiftwidth greater. */
1048 # ifdef FEAT_INS_EXPAND
1049 if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
1051 if (has_compl_option(FALSE))
1052 goto docomplete;
1053 break;
1055 # endif
1056 ins_shift(c, lastc);
1057 auto_format(FALSE, TRUE);
1058 inserted_space = FALSE;
1059 break;
1061 case K_DEL: /* delete character under the cursor */
1062 case K_KDEL:
1063 ins_del();
1064 auto_format(FALSE, TRUE);
1065 break;
1067 case K_BS: /* delete character before the cursor */
1068 case Ctrl_H:
1069 did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1070 auto_format(FALSE, TRUE);
1071 break;
1073 case Ctrl_W: /* delete word before the cursor */
1074 did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1075 auto_format(FALSE, TRUE);
1076 break;
1078 case Ctrl_U: /* delete all inserted text in current line */
1079 # ifdef FEAT_COMPL_FUNC
1080 /* CTRL-X CTRL-U completes with 'completefunc'. */
1081 if (ctrl_x_mode == CTRL_X_FUNCTION)
1082 goto docomplete;
1083 # endif
1084 did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1085 auto_format(FALSE, TRUE);
1086 inserted_space = FALSE;
1087 break;
1089 #ifdef FEAT_MOUSE
1090 case K_LEFTMOUSE: /* mouse keys */
1091 case K_LEFTMOUSE_NM:
1092 case K_LEFTDRAG:
1093 case K_LEFTRELEASE:
1094 case K_LEFTRELEASE_NM:
1095 case K_MIDDLEMOUSE:
1096 case K_MIDDLEDRAG:
1097 case K_MIDDLERELEASE:
1098 case K_RIGHTMOUSE:
1099 case K_RIGHTDRAG:
1100 case K_RIGHTRELEASE:
1101 case K_X1MOUSE:
1102 case K_X1DRAG:
1103 case K_X1RELEASE:
1104 case K_X2MOUSE:
1105 case K_X2DRAG:
1106 case K_X2RELEASE:
1107 ins_mouse(c);
1108 break;
1110 case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */
1111 ins_mousescroll(FALSE);
1112 break;
1114 case K_MOUSEUP: /* Default action for scroll wheel down: scroll down */
1115 ins_mousescroll(TRUE);
1116 break;
1117 #endif
1118 #ifdef FEAT_GUI_TABLINE
1119 case K_TABLINE:
1120 case K_TABMENU:
1121 ins_tabline(c);
1122 break;
1123 #endif
1125 case K_IGNORE: /* Something mapped to nothing */
1126 break;
1128 #ifdef FEAT_AUTOCMD
1129 case K_CURSORHOLD: /* Didn't type something for a while. */
1130 apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf);
1131 did_cursorhold = TRUE;
1132 break;
1133 #endif
1135 #ifdef FEAT_GUI_W32
1136 /* On Win32 ignore <M-F4>, we get it when closing the window was
1137 * cancelled. */
1138 case K_F4:
1139 if (mod_mask != MOD_MASK_ALT)
1140 goto normalchar;
1141 break;
1142 #endif
1144 #ifdef FEAT_GUI
1145 case K_VER_SCROLLBAR:
1146 ins_scroll();
1147 break;
1149 case K_HOR_SCROLLBAR:
1150 ins_horscroll();
1151 break;
1152 #endif
1154 case K_HOME: /* <Home> */
1155 case K_KHOME:
1156 case K_S_HOME:
1157 case K_C_HOME:
1158 ins_home(c);
1159 break;
1161 case K_END: /* <End> */
1162 case K_KEND:
1163 case K_S_END:
1164 case K_C_END:
1165 ins_end(c);
1166 break;
1168 case K_LEFT: /* <Left> */
1169 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1170 ins_s_left();
1171 else
1172 ins_left();
1173 break;
1175 case K_S_LEFT: /* <S-Left> */
1176 case K_C_LEFT:
1177 ins_s_left();
1178 break;
1180 case K_RIGHT: /* <Right> */
1181 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1182 ins_s_right();
1183 else
1184 ins_right();
1185 break;
1187 case K_S_RIGHT: /* <S-Right> */
1188 case K_C_RIGHT:
1189 ins_s_right();
1190 break;
1192 case K_UP: /* <Up> */
1193 #ifdef FEAT_INS_EXPAND
1194 if (pum_visible())
1195 goto docomplete;
1196 #endif
1197 if (mod_mask & MOD_MASK_SHIFT)
1198 ins_pageup();
1199 else
1200 ins_up(FALSE);
1201 break;
1203 case K_S_UP: /* <S-Up> */
1204 case K_PAGEUP:
1205 case K_KPAGEUP:
1206 #ifdef FEAT_INS_EXPAND
1207 if (pum_visible())
1208 goto docomplete;
1209 #endif
1210 ins_pageup();
1211 break;
1213 case K_DOWN: /* <Down> */
1214 #ifdef FEAT_INS_EXPAND
1215 if (pum_visible())
1216 goto docomplete;
1217 #endif
1218 if (mod_mask & MOD_MASK_SHIFT)
1219 ins_pagedown();
1220 else
1221 ins_down(FALSE);
1222 break;
1224 case K_S_DOWN: /* <S-Down> */
1225 case K_PAGEDOWN:
1226 case K_KPAGEDOWN:
1227 #ifdef FEAT_INS_EXPAND
1228 if (pum_visible())
1229 goto docomplete;
1230 #endif
1231 ins_pagedown();
1232 break;
1234 #ifdef FEAT_DND
1235 case K_DROP: /* drag-n-drop event */
1236 ins_drop();
1237 break;
1238 #endif
1240 case K_S_TAB: /* When not mapped, use like a normal TAB */
1241 c = TAB;
1242 /* FALLTHROUGH */
1244 case TAB: /* TAB or Complete patterns along path */
1245 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1246 if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1247 goto docomplete;
1248 #endif
1249 inserted_space = FALSE;
1250 if (ins_tab())
1251 goto normalchar; /* insert TAB as a normal char */
1252 auto_format(FALSE, TRUE);
1253 break;
1255 case K_KENTER: /* <Enter> */
1256 c = CAR;
1257 /* FALLTHROUGH */
1258 case CAR:
1259 case NL:
1260 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1261 /* In a quickfix window a <CR> jumps to the error under the
1262 * cursor. */
1263 if (bt_quickfix(curbuf) && c == CAR)
1265 if (curwin->w_llist_ref == NULL) /* quickfix window */
1266 do_cmdline_cmd((char_u *)".cc");
1267 else /* location list window */
1268 do_cmdline_cmd((char_u *)".ll");
1269 break;
1271 #endif
1272 #ifdef FEAT_CMDWIN
1273 if (cmdwin_type != 0)
1275 /* Execute the command in the cmdline window. */
1276 cmdwin_result = CAR;
1277 goto doESCkey;
1279 #endif
1280 if (ins_eol(c) && !p_im)
1281 goto doESCkey; /* out of memory */
1282 auto_format(FALSE, FALSE);
1283 inserted_space = FALSE;
1284 break;
1286 #if defined(FEAT_DIGRAPHS) || defined (FEAT_INS_EXPAND)
1287 case Ctrl_K: /* digraph or keyword completion */
1288 # ifdef FEAT_INS_EXPAND
1289 if (ctrl_x_mode == CTRL_X_DICTIONARY)
1291 if (has_compl_option(TRUE))
1292 goto docomplete;
1293 break;
1295 # endif
1296 # ifdef FEAT_DIGRAPHS
1297 c = ins_digraph();
1298 if (c == NUL)
1299 break;
1300 # endif
1301 goto normalchar;
1302 #endif
1304 #ifdef FEAT_INS_EXPAND
1305 case Ctrl_X: /* Enter CTRL-X mode */
1306 ins_ctrl_x();
1307 break;
1309 case Ctrl_RSB: /* Tag name completion after ^X */
1310 if (ctrl_x_mode != CTRL_X_TAGS)
1311 goto normalchar;
1312 goto docomplete;
1314 case Ctrl_F: /* File name completion after ^X */
1315 if (ctrl_x_mode != CTRL_X_FILES)
1316 goto normalchar;
1317 goto docomplete;
1319 case 's': /* Spelling completion after ^X */
1320 case Ctrl_S:
1321 if (ctrl_x_mode != CTRL_X_SPELL)
1322 goto normalchar;
1323 goto docomplete;
1324 #endif
1326 case Ctrl_L: /* Whole line completion after ^X */
1327 #ifdef FEAT_INS_EXPAND
1328 if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1329 #endif
1331 /* CTRL-L with 'insertmode' set: Leave Insert mode */
1332 if (p_im)
1334 if (echeck_abbr(Ctrl_L + ABBR_OFF))
1335 break;
1336 goto doESCkey;
1338 goto normalchar;
1340 #ifdef FEAT_INS_EXPAND
1341 /* FALLTHROUGH */
1343 case Ctrl_P: /* Do previous/next pattern completion */
1344 case Ctrl_N:
1345 /* if 'complete' is empty then plain ^P is no longer special,
1346 * but it is under other ^X modes */
1347 if (*curbuf->b_p_cpt == NUL
1348 && ctrl_x_mode != 0
1349 && !(compl_cont_status & CONT_LOCAL))
1350 goto normalchar;
1352 docomplete:
1353 compl_busy = TRUE;
1354 if (ins_complete(c) == FAIL)
1355 compl_cont_status = 0;
1356 compl_busy = FALSE;
1357 break;
1358 #endif /* FEAT_INS_EXPAND */
1360 case Ctrl_Y: /* copy from previous line or scroll down */
1361 case Ctrl_E: /* copy from next line or scroll up */
1362 c = ins_ctrl_ey(c);
1363 break;
1365 default:
1366 #ifdef UNIX
1367 if (c == intr_char) /* special interrupt char */
1368 goto do_intr;
1369 #endif
1372 * Insert a nomal character.
1374 normalchar:
1375 #ifdef FEAT_SMARTINDENT
1376 /* Try to perform smart-indenting. */
1377 ins_try_si(c);
1378 #endif
1380 if (c == ' ')
1382 inserted_space = TRUE;
1383 #ifdef FEAT_CINDENT
1384 if (inindent(0))
1385 can_cindent = FALSE;
1386 #endif
1387 if (Insstart_blank_vcol == MAXCOL
1388 && curwin->w_cursor.lnum == Insstart.lnum)
1389 Insstart_blank_vcol = get_nolist_virtcol();
1392 if (vim_iswordc(c) || !echeck_abbr(
1393 #ifdef FEAT_MBYTE
1394 /* Add ABBR_OFF for characters above 0x100, this is
1395 * what check_abbr() expects. */
1396 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1397 #endif
1400 insert_special(c, FALSE, FALSE);
1401 #ifdef FEAT_RIGHTLEFT
1402 revins_legal++;
1403 revins_chars++;
1404 #endif
1407 auto_format(FALSE, TRUE);
1409 #ifdef FEAT_FOLDING
1410 /* When inserting a character the cursor line must never be in a
1411 * closed fold. */
1412 foldOpenCursor();
1413 #endif
1414 break;
1415 } /* end of switch (c) */
1417 #ifdef FEAT_AUTOCMD
1418 /* If typed something may trigger CursorHoldI again. */
1419 if (c != K_CURSORHOLD)
1420 did_cursorhold = FALSE;
1421 #endif
1423 /* If the cursor was moved we didn't just insert a space */
1424 if (arrow_used)
1425 inserted_space = FALSE;
1427 #ifdef FEAT_CINDENT
1428 if (can_cindent && cindent_on()
1429 # ifdef FEAT_INS_EXPAND
1430 && ctrl_x_mode == 0
1431 # endif
1434 force_cindent:
1436 * Indent now if a key was typed that is in 'cinkeys'.
1438 if (in_cinkeys(c, ' ', line_is_white))
1440 if (stop_arrow() == OK)
1441 /* re-indent the current line */
1442 do_c_expr_indent();
1445 #endif /* FEAT_CINDENT */
1447 } /* for (;;) */
1448 /* NOTREACHED */
1452 * Redraw for Insert mode.
1453 * This is postponed until getting the next character to make '$' in the 'cpo'
1454 * option work correctly.
1455 * Only redraw when there are no characters available. This speeds up
1456 * inserting sequences of characters (e.g., for CTRL-R).
1458 static void
1459 ins_redraw(ready)
1460 int ready UNUSED; /* not busy with something */
1462 if (!char_avail())
1464 #ifdef FEAT_AUTOCMD
1465 /* Trigger CursorMoved if the cursor moved. Not when the popup menu is
1466 * visible, the command might delete it. */
1467 if (ready && has_cursormovedI()
1468 && !equalpos(last_cursormoved, curwin->w_cursor)
1469 # ifdef FEAT_INS_EXPAND
1470 && !pum_visible()
1471 # endif
1474 # ifdef FEAT_SYN_HL
1475 /* Need to update the screen first, to make sure syntax
1476 * highlighting is correct after making a change (e.g., inserting
1477 * a "(". The autocommand may also require a redraw, so it's done
1478 * again below, unfortunately. */
1479 if (syntax_present(curbuf) && must_redraw)
1480 update_screen(0);
1481 # endif
1482 apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf);
1483 last_cursormoved = curwin->w_cursor;
1485 #endif
1486 if (must_redraw)
1487 update_screen(0);
1488 else if (clear_cmdline || redraw_cmdline)
1489 showmode(); /* clear cmdline and show mode */
1490 showruler(FALSE);
1491 setcursor();
1492 emsg_on_display = FALSE; /* may remove error message now */
1497 * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1499 static void
1500 ins_ctrl_v()
1502 int c;
1504 /* may need to redraw when no more chars available now */
1505 ins_redraw(FALSE);
1507 if (redrawing() && !char_avail())
1508 edit_putchar('^', TRUE);
1509 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1511 #ifdef FEAT_CMDL_INFO
1512 add_to_showcmd_c(Ctrl_V);
1513 #endif
1515 c = get_literal();
1516 #ifdef FEAT_CMDL_INFO
1517 clear_showcmd();
1518 #endif
1519 insert_special(c, FALSE, TRUE);
1520 #ifdef FEAT_RIGHTLEFT
1521 revins_chars++;
1522 revins_legal++;
1523 #endif
1527 * Put a character directly onto the screen. It's not stored in a buffer.
1528 * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1530 static int pc_status;
1531 #define PC_STATUS_UNSET 0 /* pc_bytes was not set */
1532 #define PC_STATUS_RIGHT 1 /* right halve of double-wide char */
1533 #define PC_STATUS_LEFT 2 /* left halve of double-wide char */
1534 #define PC_STATUS_SET 3 /* pc_bytes was filled */
1535 #ifdef FEAT_MBYTE
1536 static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1537 #else
1538 static char_u pc_bytes[2]; /* saved bytes */
1539 #endif
1540 static int pc_attr;
1541 static int pc_row;
1542 static int pc_col;
1544 void
1545 edit_putchar(c, highlight)
1546 int c;
1547 int highlight;
1549 int attr;
1551 if (ScreenLines != NULL)
1553 update_topline(); /* just in case w_topline isn't valid */
1554 validate_cursor();
1555 if (highlight)
1556 attr = hl_attr(HLF_8);
1557 else
1558 attr = 0;
1559 pc_row = W_WINROW(curwin) + curwin->w_wrow;
1560 pc_col = W_WINCOL(curwin);
1561 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1562 pc_status = PC_STATUS_UNSET;
1563 #endif
1564 #ifdef FEAT_RIGHTLEFT
1565 if (curwin->w_p_rl)
1567 pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1568 # ifdef FEAT_MBYTE
1569 if (has_mbyte)
1571 int fix_col = mb_fix_col(pc_col, pc_row);
1573 if (fix_col != pc_col)
1575 screen_putchar(' ', pc_row, fix_col, attr);
1576 --curwin->w_wcol;
1577 pc_status = PC_STATUS_RIGHT;
1580 # endif
1582 else
1583 #endif
1585 pc_col += curwin->w_wcol;
1586 #ifdef FEAT_MBYTE
1587 if (mb_lefthalve(pc_row, pc_col))
1588 pc_status = PC_STATUS_LEFT;
1589 #endif
1592 /* save the character to be able to put it back */
1593 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1594 if (pc_status == PC_STATUS_UNSET)
1595 #endif
1597 screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1598 pc_status = PC_STATUS_SET;
1600 screen_putchar(c, pc_row, pc_col, attr);
1605 * Undo the previous edit_putchar().
1607 void
1608 edit_unputchar()
1610 if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1612 #if defined(FEAT_MBYTE)
1613 if (pc_status == PC_STATUS_RIGHT)
1614 ++curwin->w_wcol;
1615 if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1616 redrawWinline(curwin->w_cursor.lnum, FALSE);
1617 else
1618 #endif
1619 screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1624 * Called when p_dollar is set: display a '$' at the end of the changed text
1625 * Only works when cursor is in the line that changes.
1627 void
1628 display_dollar(col)
1629 colnr_T col;
1631 colnr_T save_col;
1633 if (!redrawing())
1634 return;
1636 cursor_off();
1637 save_col = curwin->w_cursor.col;
1638 curwin->w_cursor.col = col;
1639 #ifdef FEAT_MBYTE
1640 if (has_mbyte)
1642 char_u *p;
1644 /* If on the last byte of a multi-byte move to the first byte. */
1645 p = ml_get_curline();
1646 curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1648 #endif
1649 curs_columns(FALSE); /* recompute w_wrow and w_wcol */
1650 if (curwin->w_wcol < W_WIDTH(curwin))
1652 edit_putchar('$', FALSE);
1653 dollar_vcol = curwin->w_virtcol;
1655 curwin->w_cursor.col = save_col;
1659 * Call this function before moving the cursor from the normal insert position
1660 * in insert mode.
1662 static void
1663 undisplay_dollar()
1665 if (dollar_vcol)
1667 dollar_vcol = 0;
1668 redrawWinline(curwin->w_cursor.lnum, FALSE);
1673 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1674 * Keep the cursor on the same character.
1675 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1676 * type == INDENT_DEC decrease indent (for CTRL-D)
1677 * type == INDENT_SET set indent to "amount"
1678 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1680 void
1681 change_indent(type, amount, round, replaced, call_changed_bytes)
1682 int type;
1683 int amount;
1684 int round;
1685 int replaced; /* replaced character, put on replace stack */
1686 int call_changed_bytes; /* call changed_bytes() */
1688 int vcol;
1689 int last_vcol;
1690 int insstart_less; /* reduction for Insstart.col */
1691 int new_cursor_col;
1692 int i;
1693 char_u *ptr;
1694 int save_p_list;
1695 int start_col;
1696 colnr_T vc;
1697 #ifdef FEAT_VREPLACE
1698 colnr_T orig_col = 0; /* init for GCC */
1699 char_u *new_line, *orig_line = NULL; /* init for GCC */
1701 /* VREPLACE mode needs to know what the line was like before changing */
1702 if (State & VREPLACE_FLAG)
1704 orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */
1705 orig_col = curwin->w_cursor.col;
1707 #endif
1709 /* for the following tricks we don't want list mode */
1710 save_p_list = curwin->w_p_list;
1711 curwin->w_p_list = FALSE;
1712 vc = getvcol_nolist(&curwin->w_cursor);
1713 vcol = vc;
1716 * For Replace mode we need to fix the replace stack later, which is only
1717 * possible when the cursor is in the indent. Remember the number of
1718 * characters before the cursor if it's possible.
1720 start_col = curwin->w_cursor.col;
1722 /* determine offset from first non-blank */
1723 new_cursor_col = curwin->w_cursor.col;
1724 beginline(BL_WHITE);
1725 new_cursor_col -= curwin->w_cursor.col;
1727 insstart_less = curwin->w_cursor.col;
1730 * If the cursor is in the indent, compute how many screen columns the
1731 * cursor is to the left of the first non-blank.
1733 if (new_cursor_col < 0)
1734 vcol = get_indent() - vcol;
1736 if (new_cursor_col > 0) /* can't fix replace stack */
1737 start_col = -1;
1740 * Set the new indent. The cursor will be put on the first non-blank.
1742 if (type == INDENT_SET)
1743 (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
1744 else
1746 #ifdef FEAT_VREPLACE
1747 int save_State = State;
1749 /* Avoid being called recursively. */
1750 if (State & VREPLACE_FLAG)
1751 State = INSERT;
1752 #endif
1753 shift_line(type == INDENT_DEC, round, 1, call_changed_bytes);
1754 #ifdef FEAT_VREPLACE
1755 State = save_State;
1756 #endif
1758 insstart_less -= curwin->w_cursor.col;
1761 * Try to put cursor on same character.
1762 * If the cursor is at or after the first non-blank in the line,
1763 * compute the cursor column relative to the column of the first
1764 * non-blank character.
1765 * If we are not in insert mode, leave the cursor on the first non-blank.
1766 * If the cursor is before the first non-blank, position it relative
1767 * to the first non-blank, counted in screen columns.
1769 if (new_cursor_col >= 0)
1772 * When changing the indent while the cursor is touching it, reset
1773 * Insstart_col to 0.
1775 if (new_cursor_col == 0)
1776 insstart_less = MAXCOL;
1777 new_cursor_col += curwin->w_cursor.col;
1779 else if (!(State & INSERT))
1780 new_cursor_col = curwin->w_cursor.col;
1781 else
1784 * Compute the screen column where the cursor should be.
1786 vcol = get_indent() - vcol;
1787 curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);
1790 * Advance the cursor until we reach the right screen column.
1792 vcol = last_vcol = 0;
1793 new_cursor_col = -1;
1794 ptr = ml_get_curline();
1795 while (vcol <= (int)curwin->w_virtcol)
1797 last_vcol = vcol;
1798 #ifdef FEAT_MBYTE
1799 if (has_mbyte && new_cursor_col >= 0)
1800 new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1801 else
1802 #endif
1803 ++new_cursor_col;
1804 vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol);
1806 vcol = last_vcol;
1809 * May need to insert spaces to be able to position the cursor on
1810 * the right screen column.
1812 if (vcol != (int)curwin->w_virtcol)
1814 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1815 i = (int)curwin->w_virtcol - vcol;
1816 ptr = alloc((unsigned)(i + 1));
1817 if (ptr != NULL)
1819 new_cursor_col += i;
1820 ptr[i] = NUL;
1821 while (--i >= 0)
1822 ptr[i] = ' ';
1823 ins_str(ptr);
1824 vim_free(ptr);
1829 * When changing the indent while the cursor is in it, reset
1830 * Insstart_col to 0.
1832 insstart_less = MAXCOL;
1835 curwin->w_p_list = save_p_list;
1837 if (new_cursor_col <= 0)
1838 curwin->w_cursor.col = 0;
1839 else
1840 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1841 curwin->w_set_curswant = TRUE;
1842 changed_cline_bef_curs();
1845 * May have to adjust the start of the insert.
1847 if (State & INSERT)
1849 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1851 if ((int)Insstart.col <= insstart_less)
1852 Insstart.col = 0;
1853 else
1854 Insstart.col -= insstart_less;
1856 if ((int)ai_col <= insstart_less)
1857 ai_col = 0;
1858 else
1859 ai_col -= insstart_less;
1863 * For REPLACE mode, may have to fix the replace stack, if it's possible.
1864 * If the number of characters before the cursor decreased, need to pop a
1865 * few characters from the replace stack.
1866 * If the number of characters before the cursor increased, need to push a
1867 * few NULs onto the replace stack.
1869 if (REPLACE_NORMAL(State) && start_col >= 0)
1871 while (start_col > (int)curwin->w_cursor.col)
1873 replace_join(0); /* remove a NUL from the replace stack */
1874 --start_col;
1876 while (start_col < (int)curwin->w_cursor.col || replaced)
1878 replace_push(NUL);
1879 if (replaced)
1881 replace_push(replaced);
1882 replaced = NUL;
1884 ++start_col;
1888 #ifdef FEAT_VREPLACE
1890 * For VREPLACE mode, we also have to fix the replace stack. In this case
1891 * it is always possible because we backspace over the whole line and then
1892 * put it back again the way we wanted it.
1894 if (State & VREPLACE_FLAG)
1896 /* If orig_line didn't allocate, just return. At least we did the job,
1897 * even if you can't backspace. */
1898 if (orig_line == NULL)
1899 return;
1901 /* Save new line */
1902 new_line = vim_strsave(ml_get_curline());
1903 if (new_line == NULL)
1904 return;
1906 /* We only put back the new line up to the cursor */
1907 new_line[curwin->w_cursor.col] = NUL;
1909 /* Put back original line */
1910 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1911 curwin->w_cursor.col = orig_col;
1913 /* Backspace from cursor to start of line */
1914 backspace_until_column(0);
1916 /* Insert new stuff into line again */
1917 ins_bytes(new_line);
1919 vim_free(new_line);
1921 #endif
1925 * Truncate the space at the end of a line. This is to be used only in an
1926 * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE
1927 * modes.
1929 void
1930 truncate_spaces(line)
1931 char_u *line;
1933 int i;
1935 /* find start of trailing white space */
1936 for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
1938 if (State & REPLACE_FLAG)
1939 replace_join(0); /* remove a NUL from the replace stack */
1941 line[i + 1] = NUL;
1944 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1945 || defined(FEAT_COMMENTS) || defined(PROTO)
1947 * Backspace the cursor until the given column. Handles REPLACE and VREPLACE
1948 * modes correctly. May also be used when not in insert mode at all.
1949 * Will attempt not to go before "col" even when there is a composing
1950 * character.
1952 void
1953 backspace_until_column(col)
1954 int col;
1956 while ((int)curwin->w_cursor.col > col)
1958 curwin->w_cursor.col--;
1959 if (State & REPLACE_FLAG)
1960 replace_do_bs(col);
1961 else if (!del_char_after_col(col))
1962 break;
1965 #endif
1968 * Like del_char(), but make sure not to go before column "limit_col".
1969 * Only matters when there are composing characters.
1970 * Return TRUE when something was deleted.
1972 static int
1973 del_char_after_col(limit_col)
1974 int limit_col UNUSED;
1976 #ifdef FEAT_MBYTE
1977 if (enc_utf8 && limit_col >= 0)
1979 colnr_T ecol = curwin->w_cursor.col + 1;
1981 /* Make sure the cursor is at the start of a character, but
1982 * skip forward again when going too far back because of a
1983 * composing character. */
1984 mb_adjust_cursor();
1985 while (curwin->w_cursor.col < (colnr_T)limit_col)
1987 int l = utf_ptr2len(ml_get_cursor());
1989 if (l == 0) /* end of line */
1990 break;
1991 curwin->w_cursor.col += l;
1993 if (*ml_get_cursor() == NUL || curwin->w_cursor.col == ecol)
1994 return FALSE;
1995 del_bytes((long)((int)ecol - curwin->w_cursor.col), FALSE, TRUE);
1997 else
1998 #endif
1999 (void)del_char(FALSE);
2000 return TRUE;
2003 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
2005 * CTRL-X pressed in Insert mode.
2007 static void
2008 ins_ctrl_x()
2010 /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
2011 * CTRL-V works like CTRL-N */
2012 if (ctrl_x_mode != CTRL_X_CMDLINE)
2014 /* if the next ^X<> won't ADD nothing, then reset
2015 * compl_cont_status */
2016 if (compl_cont_status & CONT_N_ADDS)
2017 compl_cont_status |= CONT_INTRPT;
2018 else
2019 compl_cont_status = 0;
2020 /* We're not sure which CTRL-X mode it will be yet */
2021 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2022 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
2023 edit_submode_pre = NULL;
2024 showmode();
2029 * Return TRUE if the 'dict' or 'tsr' option can be used.
2031 static int
2032 has_compl_option(dict_opt)
2033 int dict_opt;
2035 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
2036 # ifdef FEAT_SPELL
2037 && !curwin->w_p_spell
2038 # endif
2040 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
2042 ctrl_x_mode = 0;
2043 edit_submode = NULL;
2044 msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty")
2045 : (char_u *)_("'thesaurus' option is empty"),
2046 hl_attr(HLF_E));
2047 if (emsg_silent == 0)
2049 vim_beep();
2050 setcursor();
2051 out_flush();
2052 ui_delay(2000L, FALSE);
2054 return FALSE;
2056 return TRUE;
2060 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
2061 * This depends on the current mode.
2064 vim_is_ctrl_x_key(c)
2065 int c;
2067 /* Always allow ^R - let it's results then be checked */
2068 if (c == Ctrl_R)
2069 return TRUE;
2071 /* Accept <PageUp> and <PageDown> if the popup menu is visible. */
2072 if (ins_compl_pum_key(c))
2073 return TRUE;
2075 switch (ctrl_x_mode)
2077 case 0: /* Not in any CTRL-X mode */
2078 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
2079 case CTRL_X_NOT_DEFINED_YET:
2080 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
2081 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
2082 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
2083 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
2084 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
2085 || c == Ctrl_S || c == 's');
2086 case CTRL_X_SCROLL:
2087 return (c == Ctrl_Y || c == Ctrl_E);
2088 case CTRL_X_WHOLE_LINE:
2089 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
2090 case CTRL_X_FILES:
2091 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
2092 case CTRL_X_DICTIONARY:
2093 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
2094 case CTRL_X_THESAURUS:
2095 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
2096 case CTRL_X_TAGS:
2097 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
2098 #ifdef FEAT_FIND_ID
2099 case CTRL_X_PATH_PATTERNS:
2100 return (c == Ctrl_P || c == Ctrl_N);
2101 case CTRL_X_PATH_DEFINES:
2102 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
2103 #endif
2104 case CTRL_X_CMDLINE:
2105 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
2106 || c == Ctrl_X);
2107 #ifdef FEAT_COMPL_FUNC
2108 case CTRL_X_FUNCTION:
2109 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
2110 case CTRL_X_OMNI:
2111 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
2112 #endif
2113 case CTRL_X_SPELL:
2114 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
2116 EMSG(_(e_internal));
2117 return FALSE;
2121 * Return TRUE when character "c" is part of the item currently being
2122 * completed. Used to decide whether to abandon complete mode when the menu
2123 * is visible.
2125 static int
2126 ins_compl_accept_char(c)
2127 int c;
2129 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
2130 /* When expanding an identifier only accept identifier chars. */
2131 return vim_isIDc(c);
2133 switch (ctrl_x_mode)
2135 case CTRL_X_FILES:
2136 /* When expanding file name only accept file name chars. But not
2137 * path separators, so that "proto/<Tab>" expands files in
2138 * "proto", not "proto/" as a whole */
2139 return vim_isfilec(c) && !vim_ispathsep(c);
2141 case CTRL_X_CMDLINE:
2142 case CTRL_X_OMNI:
2143 /* Command line and Omni completion can work with just about any
2144 * printable character, but do stop at white space. */
2145 return vim_isprintc(c) && !vim_iswhite(c);
2147 case CTRL_X_WHOLE_LINE:
2148 /* For while line completion a space can be part of the line. */
2149 return vim_isprintc(c);
2151 return vim_iswordc(c);
2155 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
2156 * case of the originally typed text is used, and the case of the completed
2157 * text is inferred, ie this tries to work out what case you probably wanted
2158 * the rest of the word to be in -- webb
2161 ins_compl_add_infercase(str, len, icase, fname, dir, flags)
2162 char_u *str;
2163 int len;
2164 int icase;
2165 char_u *fname;
2166 int dir;
2167 int flags;
2169 char_u *p;
2170 int i, c;
2171 int actual_len; /* Take multi-byte characters */
2172 int actual_compl_length; /* into account. */
2173 int min_len;
2174 int *wca; /* Wide character array. */
2175 int has_lower = FALSE;
2176 int was_letter = FALSE;
2178 if (p_ic && curbuf->b_p_inf && len > 0)
2180 /* Infer case of completed part. */
2182 /* Find actual length of completion. */
2183 #ifdef FEAT_MBYTE
2184 if (has_mbyte)
2186 p = str;
2187 actual_len = 0;
2188 while (*p != NUL)
2190 mb_ptr_adv(p);
2191 ++actual_len;
2194 else
2195 #endif
2196 actual_len = len;
2198 /* Find actual length of original text. */
2199 #ifdef FEAT_MBYTE
2200 if (has_mbyte)
2202 p = compl_orig_text;
2203 actual_compl_length = 0;
2204 while (*p != NUL)
2206 mb_ptr_adv(p);
2207 ++actual_compl_length;
2210 else
2211 #endif
2212 actual_compl_length = compl_length;
2214 /* "actual_len" may be smaller than "actual_compl_length" when using
2215 * thesaurus, only use the minimum when comparing. */
2216 min_len = actual_len < actual_compl_length
2217 ? actual_len : actual_compl_length;
2219 /* Allocate wide character array for the completion and fill it. */
2220 wca = (int *)alloc((unsigned)(actual_len * sizeof(int)));
2221 if (wca != NULL)
2223 p = str;
2224 for (i = 0; i < actual_len; ++i)
2225 #ifdef FEAT_MBYTE
2226 if (has_mbyte)
2227 wca[i] = mb_ptr2char_adv(&p);
2228 else
2229 #endif
2230 wca[i] = *(p++);
2232 /* Rule 1: Were any chars converted to lower? */
2233 p = compl_orig_text;
2234 for (i = 0; i < min_len; ++i)
2236 #ifdef FEAT_MBYTE
2237 if (has_mbyte)
2238 c = mb_ptr2char_adv(&p);
2239 else
2240 #endif
2241 c = *(p++);
2242 if (MB_ISLOWER(c))
2244 has_lower = TRUE;
2245 if (MB_ISUPPER(wca[i]))
2247 /* Rule 1 is satisfied. */
2248 for (i = actual_compl_length; i < actual_len; ++i)
2249 wca[i] = MB_TOLOWER(wca[i]);
2250 break;
2256 * Rule 2: No lower case, 2nd consecutive letter converted to
2257 * upper case.
2259 if (!has_lower)
2261 p = compl_orig_text;
2262 for (i = 0; i < min_len; ++i)
2264 #ifdef FEAT_MBYTE
2265 if (has_mbyte)
2266 c = mb_ptr2char_adv(&p);
2267 else
2268 #endif
2269 c = *(p++);
2270 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
2272 /* Rule 2 is satisfied. */
2273 for (i = actual_compl_length; i < actual_len; ++i)
2274 wca[i] = MB_TOUPPER(wca[i]);
2275 break;
2277 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
2281 /* Copy the original case of the part we typed. */
2282 p = compl_orig_text;
2283 for (i = 0; i < min_len; ++i)
2285 #ifdef FEAT_MBYTE
2286 if (has_mbyte)
2287 c = mb_ptr2char_adv(&p);
2288 else
2289 #endif
2290 c = *(p++);
2291 if (MB_ISLOWER(c))
2292 wca[i] = MB_TOLOWER(wca[i]);
2293 else if (MB_ISUPPER(c))
2294 wca[i] = MB_TOUPPER(wca[i]);
2298 * Generate encoding specific output from wide character array.
2299 * Multi-byte characters can occupy up to five bytes more than
2300 * ASCII characters, and we also need one byte for NUL, so stay
2301 * six bytes away from the edge of IObuff.
2303 p = IObuff;
2304 i = 0;
2305 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
2306 #ifdef FEAT_MBYTE
2307 if (has_mbyte)
2308 p += (*mb_char2bytes)(wca[i++], p);
2309 else
2310 #endif
2311 *(p++) = wca[i++];
2312 *p = NUL;
2314 vim_free(wca);
2317 return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2318 flags, FALSE);
2320 return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2324 * Add a match to the list of matches.
2325 * If the given string is already in the list of completions, then return
2326 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2327 * maybe because alloc() returns NULL, then FAIL is returned.
2329 static int
2330 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup)
2331 char_u *str;
2332 int len;
2333 int icase;
2334 char_u *fname;
2335 char_u **cptext; /* extra text for popup menu or NULL */
2336 int cdir;
2337 int flags;
2338 int adup; /* accept duplicate match */
2340 compl_T *match;
2341 int dir = (cdir == 0 ? compl_direction : cdir);
2343 ui_breakcheck();
2344 if (got_int)
2345 return FAIL;
2346 if (len < 0)
2347 len = (int)STRLEN(str);
2350 * If the same match is already present, don't add it.
2352 if (compl_first_match != NULL && !adup)
2354 match = compl_first_match;
2357 if ( !(match->cp_flags & ORIGINAL_TEXT)
2358 && STRNCMP(match->cp_str, str, len) == 0
2359 && match->cp_str[len] == NUL)
2360 return NOTDONE;
2361 match = match->cp_next;
2362 } while (match != NULL && match != compl_first_match);
2365 /* Remove any popup menu before changing the list of matches. */
2366 ins_compl_del_pum();
2369 * Allocate a new match structure.
2370 * Copy the values to the new match structure.
2372 match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2373 if (match == NULL)
2374 return FAIL;
2375 match->cp_number = -1;
2376 if (flags & ORIGINAL_TEXT)
2377 match->cp_number = 0;
2378 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2380 vim_free(match);
2381 return FAIL;
2383 match->cp_icase = icase;
2385 /* match-fname is:
2386 * - compl_curr_match->cp_fname if it is a string equal to fname.
2387 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2388 * - NULL otherwise. --Acevedo */
2389 if (fname != NULL
2390 && compl_curr_match != NULL
2391 && compl_curr_match->cp_fname != NULL
2392 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2393 match->cp_fname = compl_curr_match->cp_fname;
2394 else if (fname != NULL)
2396 match->cp_fname = vim_strsave(fname);
2397 flags |= FREE_FNAME;
2399 else
2400 match->cp_fname = NULL;
2401 match->cp_flags = flags;
2403 if (cptext != NULL)
2405 int i;
2407 for (i = 0; i < CPT_COUNT; ++i)
2408 if (cptext[i] != NULL && *cptext[i] != NUL)
2409 match->cp_text[i] = vim_strsave(cptext[i]);
2413 * Link the new match structure in the list of matches.
2415 if (compl_first_match == NULL)
2416 match->cp_next = match->cp_prev = NULL;
2417 else if (dir == FORWARD)
2419 match->cp_next = compl_curr_match->cp_next;
2420 match->cp_prev = compl_curr_match;
2422 else /* BACKWARD */
2424 match->cp_next = compl_curr_match;
2425 match->cp_prev = compl_curr_match->cp_prev;
2427 if (match->cp_next)
2428 match->cp_next->cp_prev = match;
2429 if (match->cp_prev)
2430 match->cp_prev->cp_next = match;
2431 else /* if there's nothing before, it is the first match */
2432 compl_first_match = match;
2433 compl_curr_match = match;
2436 * Find the longest common string if still doing that.
2438 if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2439 ins_compl_longest_match(match);
2441 return OK;
2445 * Return TRUE if "str[len]" matches with match->cp_str, considering
2446 * match->cp_icase.
2448 static int
2449 ins_compl_equal(match, str, len)
2450 compl_T *match;
2451 char_u *str;
2452 int len;
2454 if (match->cp_icase)
2455 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2456 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2460 * Reduce the longest common string for match "match".
2462 static void
2463 ins_compl_longest_match(match)
2464 compl_T *match;
2466 char_u *p, *s;
2467 int c1, c2;
2468 int had_match;
2470 if (compl_leader == NULL)
2472 /* First match, use it as a whole. */
2473 compl_leader = vim_strsave(match->cp_str);
2474 if (compl_leader != NULL)
2476 had_match = (curwin->w_cursor.col > compl_col);
2477 ins_compl_delete();
2478 ins_bytes(compl_leader + ins_compl_len());
2479 ins_redraw(FALSE);
2481 /* When the match isn't there (to avoid matching itself) remove it
2482 * again after redrawing. */
2483 if (!had_match)
2484 ins_compl_delete();
2485 compl_used_match = FALSE;
2488 else
2490 /* Reduce the text if this match differs from compl_leader. */
2491 p = compl_leader;
2492 s = match->cp_str;
2493 while (*p != NUL)
2495 #ifdef FEAT_MBYTE
2496 if (has_mbyte)
2498 c1 = mb_ptr2char(p);
2499 c2 = mb_ptr2char(s);
2501 else
2502 #endif
2504 c1 = *p;
2505 c2 = *s;
2507 if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2508 : (c1 != c2))
2509 break;
2510 #ifdef FEAT_MBYTE
2511 if (has_mbyte)
2513 mb_ptr_adv(p);
2514 mb_ptr_adv(s);
2516 else
2517 #endif
2519 ++p;
2520 ++s;
2524 if (*p != NUL)
2526 /* Leader was shortened, need to change the inserted text. */
2527 *p = NUL;
2528 had_match = (curwin->w_cursor.col > compl_col);
2529 ins_compl_delete();
2530 ins_bytes(compl_leader + ins_compl_len());
2531 ins_redraw(FALSE);
2533 /* When the match isn't there (to avoid matching itself) remove it
2534 * again after redrawing. */
2535 if (!had_match)
2536 ins_compl_delete();
2539 compl_used_match = FALSE;
2544 * Add an array of matches to the list of matches.
2545 * Frees matches[].
2547 static void
2548 ins_compl_add_matches(num_matches, matches, icase)
2549 int num_matches;
2550 char_u **matches;
2551 int icase;
2553 int i;
2554 int add_r = OK;
2555 int dir = compl_direction;
2557 for (i = 0; i < num_matches && add_r != FAIL; i++)
2558 if ((add_r = ins_compl_add(matches[i], -1, icase,
2559 NULL, NULL, dir, 0, FALSE)) == OK)
2560 /* if dir was BACKWARD then honor it just once */
2561 dir = FORWARD;
2562 FreeWild(num_matches, matches);
2565 /* Make the completion list cyclic.
2566 * Return the number of matches (excluding the original).
2568 static int
2569 ins_compl_make_cyclic()
2571 compl_T *match;
2572 int count = 0;
2574 if (compl_first_match != NULL)
2577 * Find the end of the list.
2579 match = compl_first_match;
2580 /* there's always an entry for the compl_orig_text, it doesn't count. */
2581 while (match->cp_next != NULL && match->cp_next != compl_first_match)
2583 match = match->cp_next;
2584 ++count;
2586 match->cp_next = compl_first_match;
2587 compl_first_match->cp_prev = match;
2589 return count;
2593 * Start completion for the complete() function.
2594 * "startcol" is where the matched text starts (1 is first column).
2595 * "list" is the list of matches.
2597 void
2598 set_completion(startcol, list)
2599 colnr_T startcol;
2600 list_T *list;
2602 /* If already doing completions stop it. */
2603 if (ctrl_x_mode != 0)
2604 ins_compl_prep(' ');
2605 ins_compl_clear();
2607 if (stop_arrow() == FAIL)
2608 return;
2610 if (startcol > curwin->w_cursor.col)
2611 startcol = curwin->w_cursor.col;
2612 compl_col = startcol;
2613 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2614 /* compl_pattern doesn't need to be set */
2615 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2616 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2617 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2618 return;
2620 /* Handle like dictionary completion. */
2621 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2623 ins_compl_add_list(list);
2624 compl_matches = ins_compl_make_cyclic();
2625 compl_started = TRUE;
2626 compl_used_match = TRUE;
2627 compl_cont_status = 0;
2629 compl_curr_match = compl_first_match;
2630 ins_complete(Ctrl_N);
2631 out_flush();
2635 /* "compl_match_array" points the currently displayed list of entries in the
2636 * popup menu. It is NULL when there is no popup menu. */
2637 static pumitem_T *compl_match_array = NULL;
2638 static int compl_match_arraysize;
2641 * Update the screen and when there is any scrolling remove the popup menu.
2643 static void
2644 ins_compl_upd_pum()
2646 int h;
2648 if (compl_match_array != NULL)
2650 h = curwin->w_cline_height;
2651 update_screen(0);
2652 if (h != curwin->w_cline_height)
2653 ins_compl_del_pum();
2658 * Remove any popup menu.
2660 static void
2661 ins_compl_del_pum()
2663 if (compl_match_array != NULL)
2665 pum_undisplay();
2666 vim_free(compl_match_array);
2667 compl_match_array = NULL;
2672 * Return TRUE if the popup menu should be displayed.
2674 static int
2675 pum_wanted()
2677 /* 'completeopt' must contain "menu" or "menuone" */
2678 if (vim_strchr(p_cot, 'm') == NULL)
2679 return FALSE;
2681 /* The display looks bad on a B&W display. */
2682 if (t_colors < 8
2683 #ifdef FEAT_GUI
2684 && !gui.in_use
2685 #endif
2687 return FALSE;
2688 return TRUE;
2692 * Return TRUE if there are two or more matches to be shown in the popup menu.
2693 * One if 'completopt' contains "menuone".
2695 static int
2696 pum_enough_matches()
2698 compl_T *compl;
2699 int i;
2701 /* Don't display the popup menu if there are no matches or there is only
2702 * one (ignoring the original text). */
2703 compl = compl_first_match;
2704 i = 0;
2707 if (compl == NULL
2708 || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2709 break;
2710 compl = compl->cp_next;
2711 } while (compl != compl_first_match);
2713 if (strstr((char *)p_cot, "menuone") != NULL)
2714 return (i >= 1);
2715 return (i >= 2);
2719 * Show the popup menu for the list of matches.
2720 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2722 void
2723 ins_compl_show_pum()
2725 compl_T *compl;
2726 compl_T *shown_compl = NULL;
2727 int did_find_shown_match = FALSE;
2728 int shown_match_ok = FALSE;
2729 int i;
2730 int cur = -1;
2731 colnr_T col;
2732 int lead_len = 0;
2734 if (!pum_wanted() || !pum_enough_matches())
2735 return;
2737 #if defined(FEAT_EVAL)
2738 /* Dirty hard-coded hack: remove any matchparen highlighting. */
2739 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2740 #endif
2742 /* Update the screen before drawing the popup menu over it. */
2743 update_screen(0);
2745 if (compl_match_array == NULL)
2747 /* Need to build the popup menu list. */
2748 compl_match_arraysize = 0;
2749 compl = compl_first_match;
2750 if (compl_leader != NULL)
2751 lead_len = (int)STRLEN(compl_leader);
2754 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2755 && (compl_leader == NULL
2756 || ins_compl_equal(compl, compl_leader, lead_len)))
2757 ++compl_match_arraysize;
2758 compl = compl->cp_next;
2759 } while (compl != NULL && compl != compl_first_match);
2760 if (compl_match_arraysize == 0)
2761 return;
2762 compl_match_array = (pumitem_T *)alloc_clear(
2763 (unsigned)(sizeof(pumitem_T)
2764 * compl_match_arraysize));
2765 if (compl_match_array != NULL)
2767 /* If the current match is the original text don't find the first
2768 * match after it, don't highlight anything. */
2769 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2770 shown_match_ok = TRUE;
2772 i = 0;
2773 compl = compl_first_match;
2776 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2777 && (compl_leader == NULL
2778 || ins_compl_equal(compl, compl_leader, lead_len)))
2780 if (!shown_match_ok)
2782 if (compl == compl_shown_match || did_find_shown_match)
2784 /* This item is the shown match or this is the
2785 * first displayed item after the shown match. */
2786 compl_shown_match = compl;
2787 did_find_shown_match = TRUE;
2788 shown_match_ok = TRUE;
2790 else
2791 /* Remember this displayed match for when the
2792 * shown match is just below it. */
2793 shown_compl = compl;
2794 cur = i;
2797 if (compl->cp_text[CPT_ABBR] != NULL)
2798 compl_match_array[i].pum_text =
2799 compl->cp_text[CPT_ABBR];
2800 else
2801 compl_match_array[i].pum_text = compl->cp_str;
2802 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2803 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2804 if (compl->cp_text[CPT_MENU] != NULL)
2805 compl_match_array[i++].pum_extra =
2806 compl->cp_text[CPT_MENU];
2807 else
2808 compl_match_array[i++].pum_extra = compl->cp_fname;
2811 if (compl == compl_shown_match)
2813 did_find_shown_match = TRUE;
2815 /* When the original text is the shown match don't set
2816 * compl_shown_match. */
2817 if (compl->cp_flags & ORIGINAL_TEXT)
2818 shown_match_ok = TRUE;
2820 if (!shown_match_ok && shown_compl != NULL)
2822 /* The shown match isn't displayed, set it to the
2823 * previously displayed match. */
2824 compl_shown_match = shown_compl;
2825 shown_match_ok = TRUE;
2828 compl = compl->cp_next;
2829 } while (compl != NULL && compl != compl_first_match);
2831 if (!shown_match_ok) /* no displayed match at all */
2832 cur = -1;
2835 else
2837 /* popup menu already exists, only need to find the current item.*/
2838 for (i = 0; i < compl_match_arraysize; ++i)
2839 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2840 || compl_match_array[i].pum_text
2841 == compl_shown_match->cp_text[CPT_ABBR])
2843 cur = i;
2844 break;
2848 if (compl_match_array != NULL)
2850 /* Compute the screen column of the start of the completed text.
2851 * Use the cursor to get all wrapping and other settings right. */
2852 col = curwin->w_cursor.col;
2853 curwin->w_cursor.col = compl_col;
2854 pum_display(compl_match_array, compl_match_arraysize, cur);
2855 curwin->w_cursor.col = col;
2859 #define DICT_FIRST (1) /* use just first element in "dict" */
2860 #define DICT_EXACT (2) /* "dict" is the exact name of a file */
2863 * Add any identifiers that match the given pattern in the list of dictionary
2864 * files "dict_start" to the list of completions.
2866 static void
2867 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2868 char_u *dict_start;
2869 char_u *pat;
2870 int flags; /* DICT_FIRST and/or DICT_EXACT */
2871 int thesaurus; /* Thesaurus completion */
2873 char_u *dict = dict_start;
2874 char_u *ptr;
2875 char_u *buf;
2876 regmatch_T regmatch;
2877 char_u **files;
2878 int count;
2879 int save_p_scs;
2880 int dir = compl_direction;
2882 if (*dict == NUL)
2884 #ifdef FEAT_SPELL
2885 /* When 'dictionary' is empty and spell checking is enabled use
2886 * "spell". */
2887 if (!thesaurus && curwin->w_p_spell)
2888 dict = (char_u *)"spell";
2889 else
2890 #endif
2891 return;
2894 buf = alloc(LSIZE);
2895 if (buf == NULL)
2896 return;
2897 regmatch.regprog = NULL; /* so that we can goto theend */
2899 /* If 'infercase' is set, don't use 'smartcase' here */
2900 save_p_scs = p_scs;
2901 if (curbuf->b_p_inf)
2902 p_scs = FALSE;
2904 /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
2905 * to only match at the start of a line. Otherwise just match the
2906 * pattern. Also need to double backslashes. */
2907 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2909 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
2910 size_t len;
2912 if (pat_esc == NULL)
2913 goto theend;
2914 len = STRLEN(pat_esc) + 10;
2915 ptr = alloc((unsigned)len);
2916 if (ptr == NULL)
2918 vim_free(pat_esc);
2919 goto theend;
2921 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
2922 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
2923 vim_free(pat_esc);
2924 vim_free(ptr);
2926 else
2928 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2929 if (regmatch.regprog == NULL)
2930 goto theend;
2933 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2934 regmatch.rm_ic = ignorecase(pat);
2935 while (*dict != NUL && !got_int && !compl_interrupted)
2937 /* copy one dictionary file name into buf */
2938 if (flags == DICT_EXACT)
2940 count = 1;
2941 files = &dict;
2943 else
2945 /* Expand wildcards in the dictionary name, but do not allow
2946 * backticks (for security, the 'dict' option may have been set in
2947 * a modeline). */
2948 copy_option_part(&dict, buf, LSIZE, ",");
2949 # ifdef FEAT_SPELL
2950 if (!thesaurus && STRCMP(buf, "spell") == 0)
2951 count = -1;
2952 else
2953 # endif
2954 if (vim_strchr(buf, '`') != NULL
2955 || expand_wildcards(1, &buf, &count, &files,
2956 EW_FILE|EW_SILENT) != OK)
2957 count = 0;
2960 # ifdef FEAT_SPELL
2961 if (count == -1)
2963 /* Complete from active spelling. Skip "\<" in the pattern, we
2964 * don't use it as a RE. */
2965 if (pat[0] == '\\' && pat[1] == '<')
2966 ptr = pat + 2;
2967 else
2968 ptr = pat;
2969 spell_dump_compl(curbuf, ptr, regmatch.rm_ic, &dir, 0);
2971 else
2972 # endif
2973 if (count > 0) /* avoid warning for using "files" uninit */
2975 ins_compl_files(count, files, thesaurus, flags,
2976 &regmatch, buf, &dir);
2977 if (flags != DICT_EXACT)
2978 FreeWild(count, files);
2980 if (flags != 0)
2981 break;
2984 theend:
2985 p_scs = save_p_scs;
2986 vim_free(regmatch.regprog);
2987 vim_free(buf);
2990 static void
2991 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
2992 int count;
2993 char_u **files;
2994 int thesaurus;
2995 int flags;
2996 regmatch_T *regmatch;
2997 char_u *buf;
2998 int *dir;
3000 char_u *ptr;
3001 int i;
3002 FILE *fp;
3003 int add_r;
3005 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
3007 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
3008 if (flags != DICT_EXACT)
3010 vim_snprintf((char *)IObuff, IOSIZE,
3011 _("Scanning dictionary: %s"), (char *)files[i]);
3012 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3015 if (fp != NULL)
3018 * Read dictionary file line by line.
3019 * Check each line for a match.
3021 while (!got_int && !compl_interrupted
3022 && !vim_fgets(buf, LSIZE, fp))
3024 ptr = buf;
3025 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
3027 ptr = regmatch->startp[0];
3028 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3029 ptr = find_line_end(ptr);
3030 else
3031 ptr = find_word_end(ptr);
3032 add_r = ins_compl_add_infercase(regmatch->startp[0],
3033 (int)(ptr - regmatch->startp[0]),
3034 p_ic, files[i], *dir, 0);
3035 if (thesaurus)
3037 char_u *wstart;
3040 * Add the other matches on the line
3042 ptr = buf;
3043 while (!got_int)
3045 /* Find start of the next word. Skip white
3046 * space and punctuation. */
3047 ptr = find_word_start(ptr);
3048 if (*ptr == NUL || *ptr == NL)
3049 break;
3050 wstart = ptr;
3052 /* Find end of the word. */
3053 #ifdef FEAT_MBYTE
3054 if (has_mbyte)
3055 /* Japanese words may have characters in
3056 * different classes, only separate words
3057 * with single-byte non-word characters. */
3058 while (*ptr != NUL)
3060 int l = (*mb_ptr2len)(ptr);
3062 if (l < 2 && !vim_iswordc(*ptr))
3063 break;
3064 ptr += l;
3066 else
3067 #endif
3068 ptr = find_word_end(ptr);
3070 /* Add the word. Skip the regexp match. */
3071 if (wstart != regmatch->startp[0])
3072 add_r = ins_compl_add_infercase(wstart,
3073 (int)(ptr - wstart),
3074 p_ic, files[i], *dir, 0);
3077 if (add_r == OK)
3078 /* if dir was BACKWARD then honor it just once */
3079 *dir = FORWARD;
3080 else if (add_r == FAIL)
3081 break;
3082 /* avoid expensive call to vim_regexec() when at end
3083 * of line */
3084 if (*ptr == '\n' || got_int)
3085 break;
3087 line_breakcheck();
3088 ins_compl_check_keys(50);
3090 fclose(fp);
3096 * Find the start of the next word.
3097 * Returns a pointer to the first char of the word. Also stops at a NUL.
3099 char_u *
3100 find_word_start(ptr)
3101 char_u *ptr;
3103 #ifdef FEAT_MBYTE
3104 if (has_mbyte)
3105 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
3106 ptr += (*mb_ptr2len)(ptr);
3107 else
3108 #endif
3109 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
3110 ++ptr;
3111 return ptr;
3115 * Find the end of the word. Assumes it starts inside a word.
3116 * Returns a pointer to just after the word.
3118 char_u *
3119 find_word_end(ptr)
3120 char_u *ptr;
3122 #ifdef FEAT_MBYTE
3123 int start_class;
3125 if (has_mbyte)
3127 start_class = mb_get_class(ptr);
3128 if (start_class > 1)
3129 while (*ptr != NUL)
3131 ptr += (*mb_ptr2len)(ptr);
3132 if (mb_get_class(ptr) != start_class)
3133 break;
3136 else
3137 #endif
3138 while (vim_iswordc(*ptr))
3139 ++ptr;
3140 return ptr;
3144 * Find the end of the line, omitting CR and NL at the end.
3145 * Returns a pointer to just after the line.
3147 static char_u *
3148 find_line_end(ptr)
3149 char_u *ptr;
3151 char_u *s;
3153 s = ptr + STRLEN(ptr);
3154 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
3155 --s;
3156 return s;
3160 * Free the list of completions
3162 static void
3163 ins_compl_free()
3165 compl_T *match;
3166 int i;
3168 vim_free(compl_pattern);
3169 compl_pattern = NULL;
3170 vim_free(compl_leader);
3171 compl_leader = NULL;
3173 if (compl_first_match == NULL)
3174 return;
3176 ins_compl_del_pum();
3177 pum_clear();
3179 compl_curr_match = compl_first_match;
3182 match = compl_curr_match;
3183 compl_curr_match = compl_curr_match->cp_next;
3184 vim_free(match->cp_str);
3185 /* several entries may use the same fname, free it just once. */
3186 if (match->cp_flags & FREE_FNAME)
3187 vim_free(match->cp_fname);
3188 for (i = 0; i < CPT_COUNT; ++i)
3189 vim_free(match->cp_text[i]);
3190 vim_free(match);
3191 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
3192 compl_first_match = compl_curr_match = NULL;
3193 compl_shown_match = NULL;
3196 static void
3197 ins_compl_clear()
3199 compl_cont_status = 0;
3200 compl_started = FALSE;
3201 compl_matches = 0;
3202 vim_free(compl_pattern);
3203 compl_pattern = NULL;
3204 vim_free(compl_leader);
3205 compl_leader = NULL;
3206 edit_submode_extra = NULL;
3207 vim_free(compl_orig_text);
3208 compl_orig_text = NULL;
3209 compl_enter_selects = FALSE;
3213 * Return TRUE when Insert completion is active.
3216 ins_compl_active()
3218 return compl_started;
3222 * Delete one character before the cursor and show the subset of the matches
3223 * that match the word that is now before the cursor.
3224 * Returns the character to be used, NUL if the work is done and another char
3225 * to be got from the user.
3227 static int
3228 ins_compl_bs()
3230 char_u *line;
3231 char_u *p;
3233 line = ml_get_curline();
3234 p = line + curwin->w_cursor.col;
3235 mb_ptr_back(line, p);
3237 /* Stop completion when the whole word was deleted. For Omni completion
3238 * allow the word to be deleted, we won't match everything. */
3239 if ((int)(p - line) - (int)compl_col < 0
3240 || ((int)(p - line) - (int)compl_col == 0
3241 && (ctrl_x_mode & CTRL_X_OMNI) == 0))
3242 return K_BS;
3244 /* Deleted more than what was used to find matches or didn't finish
3245 * finding all matches: need to look for matches all over again. */
3246 if (curwin->w_cursor.col <= compl_col + compl_length
3247 || compl_was_interrupted)
3248 ins_compl_restart();
3250 vim_free(compl_leader);
3251 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3252 if (compl_leader != NULL)
3254 ins_compl_new_leader();
3255 return NUL;
3257 return K_BS;
3261 * Called after changing "compl_leader".
3262 * Show the popup menu with a different set of matches.
3263 * May also search for matches again if the previous search was interrupted.
3265 static void
3266 ins_compl_new_leader()
3268 ins_compl_del_pum();
3269 ins_compl_delete();
3270 ins_bytes(compl_leader + ins_compl_len());
3271 compl_used_match = FALSE;
3273 if (compl_started)
3274 ins_compl_set_original_text(compl_leader);
3275 else
3277 #ifdef FEAT_SPELL
3278 spell_bad_len = 0; /* need to redetect bad word */
3279 #endif
3281 * Matches were cleared, need to search for them now. First display
3282 * the changed text before the cursor. Set "compl_restarting" to
3283 * avoid that the first match is inserted.
3285 update_screen(0);
3286 #ifdef FEAT_GUI
3287 if (gui.in_use)
3289 /* Show the cursor after the match, not after the redrawn text. */
3290 setcursor();
3291 out_flush();
3292 gui_update_cursor(FALSE, FALSE);
3294 #endif
3295 compl_restarting = TRUE;
3296 if (ins_complete(Ctrl_N) == FAIL)
3297 compl_cont_status = 0;
3298 compl_restarting = FALSE;
3301 #if 0 /* disabled, made CTRL-L, BS and typing char jump to original text. */
3302 if (!compl_used_match)
3304 /* Go to the original text, since none of the matches is inserted. */
3305 if (compl_first_match->cp_prev != NULL
3306 && (compl_first_match->cp_prev->cp_flags & ORIGINAL_TEXT))
3307 compl_shown_match = compl_first_match->cp_prev;
3308 else
3309 compl_shown_match = compl_first_match;
3310 compl_curr_match = compl_shown_match;
3311 compl_shows_dir = compl_direction;
3313 #endif
3314 compl_enter_selects = !compl_used_match;
3316 /* Show the popup menu with a different set of matches. */
3317 ins_compl_show_pum();
3319 /* Don't let Enter select the original text when there is no popup menu. */
3320 if (compl_match_array == NULL)
3321 compl_enter_selects = FALSE;
3325 * Return the length of the completion, from the completion start column to
3326 * the cursor column. Making sure it never goes below zero.
3328 static int
3329 ins_compl_len()
3331 int off = (int)curwin->w_cursor.col - (int)compl_col;
3333 if (off < 0)
3334 return 0;
3335 return off;
3339 * Append one character to the match leader. May reduce the number of
3340 * matches.
3342 static void
3343 ins_compl_addleader(c)
3344 int c;
3346 #ifdef FEAT_MBYTE
3347 int cc;
3349 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3351 char_u buf[MB_MAXBYTES + 1];
3353 (*mb_char2bytes)(c, buf);
3354 buf[cc] = NUL;
3355 ins_char_bytes(buf, cc);
3357 else
3358 #endif
3359 ins_char(c);
3361 /* If we didn't complete finding matches we must search again. */
3362 if (compl_was_interrupted)
3363 ins_compl_restart();
3365 vim_free(compl_leader);
3366 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3367 (int)(curwin->w_cursor.col - compl_col));
3368 if (compl_leader != NULL)
3369 ins_compl_new_leader();
3373 * Setup for finding completions again without leaving CTRL-X mode. Used when
3374 * BS or a key was typed while still searching for matches.
3376 static void
3377 ins_compl_restart()
3379 ins_compl_free();
3380 compl_started = FALSE;
3381 compl_matches = 0;
3382 compl_cont_status = 0;
3383 compl_cont_mode = 0;
3387 * Set the first match, the original text.
3389 static void
3390 ins_compl_set_original_text(str)
3391 char_u *str;
3393 char_u *p;
3395 /* Replace the original text entry. */
3396 if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */
3398 p = vim_strsave(str);
3399 if (p != NULL)
3401 vim_free(compl_first_match->cp_str);
3402 compl_first_match->cp_str = p;
3408 * Append one character to the match leader. May reduce the number of
3409 * matches.
3411 static void
3412 ins_compl_addfrommatch()
3414 char_u *p;
3415 int len = (int)curwin->w_cursor.col - (int)compl_col;
3416 int c;
3417 compl_T *cp;
3419 p = compl_shown_match->cp_str;
3420 if ((int)STRLEN(p) <= len) /* the match is too short */
3422 /* When still at the original match use the first entry that matches
3423 * the leader. */
3424 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
3426 p = NULL;
3427 for (cp = compl_shown_match->cp_next; cp != NULL
3428 && cp != compl_first_match; cp = cp->cp_next)
3430 if (compl_leader == NULL
3431 || ins_compl_equal(cp, compl_leader,
3432 (int)STRLEN(compl_leader)))
3434 p = cp->cp_str;
3435 break;
3438 if (p == NULL || (int)STRLEN(p) <= len)
3439 return;
3441 else
3442 return;
3444 p += len;
3445 #ifdef FEAT_MBYTE
3446 c = mb_ptr2char(p);
3447 #else
3448 c = *p;
3449 #endif
3450 ins_compl_addleader(c);
3454 * Prepare for Insert mode completion, or stop it.
3455 * Called just after typing a character in Insert mode.
3456 * Returns TRUE when the character is not to be inserted;
3458 static int
3459 ins_compl_prep(c)
3460 int c;
3462 char_u *ptr;
3463 int want_cindent;
3464 int retval = FALSE;
3466 /* Forget any previous 'special' messages if this is actually
3467 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3469 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3470 edit_submode_extra = NULL;
3472 /* Ignore end of Select mode mapping and mouse scroll buttons. */
3473 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP)
3474 return retval;
3476 /* Set "compl_get_longest" when finding the first matches. */
3477 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3478 || (ctrl_x_mode == 0 && !compl_started))
3480 compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3481 compl_used_match = TRUE;
3484 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3487 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3488 * it will be yet. Now we decide.
3490 switch (c)
3492 case Ctrl_E:
3493 case Ctrl_Y:
3494 ctrl_x_mode = CTRL_X_SCROLL;
3495 if (!(State & REPLACE_FLAG))
3496 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3497 else
3498 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3499 edit_submode_pre = NULL;
3500 showmode();
3501 break;
3502 case Ctrl_L:
3503 ctrl_x_mode = CTRL_X_WHOLE_LINE;
3504 break;
3505 case Ctrl_F:
3506 ctrl_x_mode = CTRL_X_FILES;
3507 break;
3508 case Ctrl_K:
3509 ctrl_x_mode = CTRL_X_DICTIONARY;
3510 break;
3511 case Ctrl_R:
3512 /* Simply allow ^R to happen without affecting ^X mode */
3513 break;
3514 case Ctrl_T:
3515 ctrl_x_mode = CTRL_X_THESAURUS;
3516 break;
3517 #ifdef FEAT_COMPL_FUNC
3518 case Ctrl_U:
3519 ctrl_x_mode = CTRL_X_FUNCTION;
3520 break;
3521 case Ctrl_O:
3522 ctrl_x_mode = CTRL_X_OMNI;
3523 break;
3524 #endif
3525 case 's':
3526 case Ctrl_S:
3527 ctrl_x_mode = CTRL_X_SPELL;
3528 #ifdef FEAT_SPELL
3529 ++emsg_off; /* Avoid getting the E756 error twice. */
3530 spell_back_to_badword();
3531 --emsg_off;
3532 #endif
3533 break;
3534 case Ctrl_RSB:
3535 ctrl_x_mode = CTRL_X_TAGS;
3536 break;
3537 #ifdef FEAT_FIND_ID
3538 case Ctrl_I:
3539 case K_S_TAB:
3540 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3541 break;
3542 case Ctrl_D:
3543 ctrl_x_mode = CTRL_X_PATH_DEFINES;
3544 break;
3545 #endif
3546 case Ctrl_V:
3547 case Ctrl_Q:
3548 ctrl_x_mode = CTRL_X_CMDLINE;
3549 break;
3550 case Ctrl_P:
3551 case Ctrl_N:
3552 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
3553 * just started ^X mode, or there were enough ^X's to cancel
3554 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3555 * do normal expansion when interrupting a different mode (say
3556 * ^X^F^X^P or ^P^X^X^P, see below)
3557 * nothing changes if interrupting mode 0, (eg, the flag
3558 * doesn't change when going to ADDING mode -- Acevedo */
3559 if (!(compl_cont_status & CONT_INTRPT))
3560 compl_cont_status |= CONT_LOCAL;
3561 else if (compl_cont_mode != 0)
3562 compl_cont_status &= ~CONT_LOCAL;
3563 /* FALLTHROUGH */
3564 default:
3565 /* If we have typed at least 2 ^X's... for modes != 0, we set
3566 * compl_cont_status = 0 (eg, as if we had just started ^X
3567 * mode).
3568 * For mode 0, we set "compl_cont_mode" to an impossible
3569 * value, in both cases ^X^X can be used to restart the same
3570 * mode (avoiding ADDING mode).
3571 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3572 * 'complete' and local ^P expansions respectively.
3573 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3574 * mode -- Acevedo */
3575 if (c == Ctrl_X)
3577 if (compl_cont_mode != 0)
3578 compl_cont_status = 0;
3579 else
3580 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3582 ctrl_x_mode = 0;
3583 edit_submode = NULL;
3584 showmode();
3585 break;
3588 else if (ctrl_x_mode != 0)
3590 /* We're already in CTRL-X mode, do we stay in it? */
3591 if (!vim_is_ctrl_x_key(c))
3593 if (ctrl_x_mode == CTRL_X_SCROLL)
3594 ctrl_x_mode = 0;
3595 else
3596 ctrl_x_mode = CTRL_X_FINISHED;
3597 edit_submode = NULL;
3599 showmode();
3602 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3604 /* Show error message from attempted keyword completion (probably
3605 * 'Pattern not found') until another key is hit, then go back to
3606 * showing what mode we are in. */
3607 showmode();
3608 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3609 && !ins_compl_pum_key(c))
3610 || ctrl_x_mode == CTRL_X_FINISHED)
3612 /* Get here when we have finished typing a sequence of ^N and
3613 * ^P or other completion characters in CTRL-X mode. Free up
3614 * memory that was used, and make sure we can redo the insert. */
3615 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3617 char_u *p;
3618 int temp = 0;
3621 * If any of the original typed text has been changed, eg when
3622 * ignorecase is set, we must add back-spaces to the redo
3623 * buffer. We add as few as necessary to delete just the part
3624 * of the original text that has changed.
3625 * When using the longest match, edited the match or used
3626 * CTRL-E then don't use the current match.
3628 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3629 ptr = compl_curr_match->cp_str;
3630 else if (compl_leader != NULL)
3631 ptr = compl_leader;
3632 else
3633 ptr = compl_orig_text;
3634 if (compl_orig_text != NULL)
3636 p = compl_orig_text;
3637 for (temp = 0; p[temp] != NUL && p[temp] == ptr[temp];
3638 ++temp)
3640 #ifdef FEAT_MBYTE
3641 if (temp > 0)
3642 temp -= (*mb_head_off)(compl_orig_text, p + temp);
3643 #endif
3644 for (p += temp; *p != NUL; mb_ptr_adv(p))
3645 AppendCharToRedobuff(K_BS);
3647 if (ptr != NULL)
3648 AppendToRedobuffLit(ptr + temp, -1);
3651 #ifdef FEAT_CINDENT
3652 want_cindent = (can_cindent && cindent_on());
3653 #endif
3655 * When completing whole lines: fix indent for 'cindent'.
3656 * Otherwise, break line if it's too long.
3658 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3660 #ifdef FEAT_CINDENT
3661 /* re-indent the current line */
3662 if (want_cindent)
3664 do_c_expr_indent();
3665 want_cindent = FALSE; /* don't do it again */
3667 #endif
3669 else
3671 int prev_col = curwin->w_cursor.col;
3673 /* put the cursor on the last char, for 'tw' formatting */
3674 if (prev_col > 0)
3675 dec_cursor();
3676 if (stop_arrow() == OK)
3677 insertchar(NUL, 0, -1);
3678 if (prev_col > 0
3679 && ml_get_curline()[curwin->w_cursor.col] != NUL)
3680 inc_cursor();
3683 /* If the popup menu is displayed pressing CTRL-Y means accepting
3684 * the selection without inserting anything. When
3685 * compl_enter_selects is set the Enter key does the same. */
3686 if ((c == Ctrl_Y || (compl_enter_selects
3687 && (c == CAR || c == K_KENTER || c == NL)))
3688 && pum_visible())
3689 retval = TRUE;
3691 /* CTRL-E means completion is Ended, go back to the typed text. */
3692 if (c == Ctrl_E)
3694 ins_compl_delete();
3695 if (compl_leader != NULL)
3696 ins_bytes(compl_leader + ins_compl_len());
3697 else if (compl_first_match != NULL)
3698 ins_bytes(compl_orig_text + ins_compl_len());
3699 retval = TRUE;
3702 auto_format(FALSE, TRUE);
3704 ins_compl_free();
3705 compl_started = FALSE;
3706 compl_matches = 0;
3707 msg_clr_cmdline(); /* necessary for "noshowmode" */
3708 ctrl_x_mode = 0;
3709 compl_enter_selects = FALSE;
3710 if (edit_submode != NULL)
3712 edit_submode = NULL;
3713 showmode();
3716 #ifdef FEAT_CINDENT
3718 * Indent now if a key was typed that is in 'cinkeys'.
3720 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3721 do_c_expr_indent();
3722 #endif
3726 /* reset continue_* if we left expansion-mode, if we stay they'll be
3727 * (re)set properly in ins_complete() */
3728 if (!vim_is_ctrl_x_key(c))
3730 compl_cont_status = 0;
3731 compl_cont_mode = 0;
3734 return retval;
3738 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3739 * (depending on flag) starting from buf and looking for a non-scanned
3740 * buffer (other than curbuf). curbuf is special, if it is called with
3741 * buf=curbuf then it has to be the first call for a given flag/expansion.
3743 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3745 static buf_T *
3746 ins_compl_next_buf(buf, flag)
3747 buf_T *buf;
3748 int flag;
3750 #ifdef FEAT_WINDOWS
3751 static win_T *wp;
3752 #endif
3754 if (flag == 'w') /* just windows */
3756 #ifdef FEAT_WINDOWS
3757 if (buf == curbuf) /* first call for this flag/expansion */
3758 wp = curwin;
3759 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3760 && wp->w_buffer->b_scanned)
3762 buf = wp->w_buffer;
3763 #else
3764 buf = curbuf;
3765 #endif
3767 else
3768 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3769 * (unlisted buffers)
3770 * When completing whole lines skip unloaded buffers. */
3771 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3772 && ((flag == 'U'
3773 ? buf->b_p_bl
3774 : (!buf->b_p_bl
3775 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3776 || buf->b_scanned))
3778 return buf;
3781 #ifdef FEAT_COMPL_FUNC
3782 static void expand_by_function __ARGS((int type, char_u *base));
3785 * Execute user defined complete function 'completefunc' or 'omnifunc', and
3786 * get matches in "matches".
3788 static void
3789 expand_by_function(type, base)
3790 int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3791 char_u *base;
3793 list_T *matchlist;
3794 char_u *args[2];
3795 char_u *funcname;
3796 pos_T pos;
3798 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3799 if (*funcname == NUL)
3800 return;
3802 /* Call 'completefunc' to obtain the list of matches. */
3803 args[0] = (char_u *)"0";
3804 args[1] = base;
3806 pos = curwin->w_cursor;
3807 matchlist = call_func_retlist(funcname, 2, args, FALSE);
3808 curwin->w_cursor = pos; /* restore the cursor position */
3809 if (matchlist == NULL)
3810 return;
3812 ins_compl_add_list(matchlist);
3813 list_unref(matchlist);
3815 #endif /* FEAT_COMPL_FUNC */
3817 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
3819 * Add completions from a list.
3821 static void
3822 ins_compl_add_list(list)
3823 list_T *list;
3825 listitem_T *li;
3826 int dir = compl_direction;
3828 /* Go through the List with matches and add each of them. */
3829 for (li = list->lv_first; li != NULL; li = li->li_next)
3831 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
3832 /* if dir was BACKWARD then honor it just once */
3833 dir = FORWARD;
3834 else if (did_emsg)
3835 break;
3840 * Add a match to the list of matches from a typeval_T.
3841 * If the given string is already in the list of completions, then return
3842 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3843 * maybe because alloc() returns NULL, then FAIL is returned.
3846 ins_compl_add_tv(tv, dir)
3847 typval_T *tv;
3848 int dir;
3850 char_u *word;
3851 int icase = FALSE;
3852 int adup = FALSE;
3853 char_u *(cptext[CPT_COUNT]);
3855 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3857 word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
3858 cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
3859 (char_u *)"abbr", FALSE);
3860 cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
3861 (char_u *)"menu", FALSE);
3862 cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
3863 (char_u *)"kind", FALSE);
3864 cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
3865 (char_u *)"info", FALSE);
3866 if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
3867 icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
3868 if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
3869 adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
3871 else
3873 word = get_tv_string_chk(tv);
3874 vim_memset(cptext, 0, sizeof(cptext));
3876 if (word == NULL || *word == NUL)
3877 return FAIL;
3878 return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup);
3880 #endif
3883 * Get the next expansion(s), using "compl_pattern".
3884 * The search starts at position "ini" in curbuf and in the direction
3885 * compl_direction.
3886 * When "compl_started" is FALSE start at that position, otherwise continue
3887 * where we stopped searching before.
3888 * This may return before finding all the matches.
3889 * Return the total number of matches or -1 if still unknown -- Acevedo
3891 static int
3892 ins_compl_get_exp(ini)
3893 pos_T *ini;
3895 static pos_T first_match_pos;
3896 static pos_T last_match_pos;
3897 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
3898 static int found_all = FALSE; /* Found all matches of a
3899 certain type. */
3900 static buf_T *ins_buf = NULL; /* buffer being scanned */
3902 pos_T *pos;
3903 char_u **matches;
3904 int save_p_scs;
3905 int save_p_ws;
3906 int save_p_ic;
3907 int i;
3908 int num_matches;
3909 int len;
3910 int found_new_match;
3911 int type = ctrl_x_mode;
3912 char_u *ptr;
3913 char_u *dict = NULL;
3914 int dict_f = 0;
3915 compl_T *old_match;
3917 if (!compl_started)
3919 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
3920 ins_buf->b_scanned = 0;
3921 found_all = FALSE;
3922 ins_buf = curbuf;
3923 e_cpt = (compl_cont_status & CONT_LOCAL)
3924 ? (char_u *)"." : curbuf->b_p_cpt;
3925 last_match_pos = first_match_pos = *ini;
3928 old_match = compl_curr_match; /* remember the last current match */
3929 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3930 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
3931 for (;;)
3933 found_new_match = FAIL;
3935 /* For ^N/^P pick a new entry from e_cpt if compl_started is off,
3936 * or if found_all says this entry is done. For ^X^L only use the
3937 * entries from 'complete' that look in loaded buffers. */
3938 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3939 && (!compl_started || found_all))
3941 found_all = FALSE;
3942 while (*e_cpt == ',' || *e_cpt == ' ')
3943 e_cpt++;
3944 if (*e_cpt == '.' && !curbuf->b_scanned)
3946 ins_buf = curbuf;
3947 first_match_pos = *ini;
3948 /* So that ^N can match word immediately after cursor */
3949 if (ctrl_x_mode == 0)
3950 dec(&first_match_pos);
3951 last_match_pos = first_match_pos;
3952 type = 0;
3954 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3955 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
3957 /* Scan a buffer, but not the current one. */
3958 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
3960 compl_started = TRUE;
3961 first_match_pos.col = last_match_pos.col = 0;
3962 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
3963 last_match_pos.lnum = 0;
3964 type = 0;
3966 else /* unloaded buffer, scan like dictionary */
3968 found_all = TRUE;
3969 if (ins_buf->b_fname == NULL)
3970 continue;
3971 type = CTRL_X_DICTIONARY;
3972 dict = ins_buf->b_fname;
3973 dict_f = DICT_EXACT;
3975 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3976 ins_buf->b_fname == NULL
3977 ? buf_spname(ins_buf)
3978 : ins_buf->b_sfname == NULL
3979 ? (char *)ins_buf->b_fname
3980 : (char *)ins_buf->b_sfname);
3981 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3983 else if (*e_cpt == NUL)
3984 break;
3985 else
3987 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3988 type = -1;
3989 else if (*e_cpt == 'k' || *e_cpt == 's')
3991 if (*e_cpt == 'k')
3992 type = CTRL_X_DICTIONARY;
3993 else
3994 type = CTRL_X_THESAURUS;
3995 if (*++e_cpt != ',' && *e_cpt != NUL)
3997 dict = e_cpt;
3998 dict_f = DICT_FIRST;
4001 #ifdef FEAT_FIND_ID
4002 else if (*e_cpt == 'i')
4003 type = CTRL_X_PATH_PATTERNS;
4004 else if (*e_cpt == 'd')
4005 type = CTRL_X_PATH_DEFINES;
4006 #endif
4007 else if (*e_cpt == ']' || *e_cpt == 't')
4009 type = CTRL_X_TAGS;
4010 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4011 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
4013 else
4014 type = -1;
4016 /* in any case e_cpt is advanced to the next entry */
4017 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
4019 found_all = TRUE;
4020 if (type == -1)
4021 continue;
4025 switch (type)
4027 case -1:
4028 break;
4029 #ifdef FEAT_FIND_ID
4030 case CTRL_X_PATH_PATTERNS:
4031 case CTRL_X_PATH_DEFINES:
4032 find_pattern_in_path(compl_pattern, compl_direction,
4033 (int)STRLEN(compl_pattern), FALSE, FALSE,
4034 (type == CTRL_X_PATH_DEFINES
4035 && !(compl_cont_status & CONT_SOL))
4036 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
4037 (linenr_T)1, (linenr_T)MAXLNUM);
4038 break;
4039 #endif
4041 case CTRL_X_DICTIONARY:
4042 case CTRL_X_THESAURUS:
4043 ins_compl_dictionaries(
4044 dict != NULL ? dict
4045 : (type == CTRL_X_THESAURUS
4046 ? (*curbuf->b_p_tsr == NUL
4047 ? p_tsr
4048 : curbuf->b_p_tsr)
4049 : (*curbuf->b_p_dict == NUL
4050 ? p_dict
4051 : curbuf->b_p_dict)),
4052 compl_pattern,
4053 dict != NULL ? dict_f
4054 : 0, type == CTRL_X_THESAURUS);
4055 dict = NULL;
4056 break;
4058 case CTRL_X_TAGS:
4059 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
4060 save_p_ic = p_ic;
4061 p_ic = ignorecase(compl_pattern);
4063 /* Find up to TAG_MANY matches. Avoids that an enormous number
4064 * of matches is found when compl_pattern is empty */
4065 if (find_tags(compl_pattern, &num_matches, &matches,
4066 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
4067 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
4068 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4070 ins_compl_add_matches(num_matches, matches, p_ic);
4072 p_ic = save_p_ic;
4073 break;
4075 case CTRL_X_FILES:
4076 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
4077 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
4080 /* May change home directory back to "~". */
4081 tilde_replace(compl_pattern, num_matches, matches);
4082 ins_compl_add_matches(num_matches, matches,
4083 #ifdef CASE_INSENSITIVE_FILENAME
4084 TRUE
4085 #else
4086 FALSE
4087 #endif
4090 break;
4092 case CTRL_X_CMDLINE:
4093 if (expand_cmdline(&compl_xp, compl_pattern,
4094 (int)STRLEN(compl_pattern),
4095 &num_matches, &matches) == EXPAND_OK)
4096 ins_compl_add_matches(num_matches, matches, FALSE);
4097 break;
4099 #ifdef FEAT_COMPL_FUNC
4100 case CTRL_X_FUNCTION:
4101 case CTRL_X_OMNI:
4102 expand_by_function(type, compl_pattern);
4103 break;
4104 #endif
4106 case CTRL_X_SPELL:
4107 #ifdef FEAT_SPELL
4108 num_matches = expand_spelling(first_match_pos.lnum,
4109 compl_pattern, &matches);
4110 if (num_matches > 0)
4111 ins_compl_add_matches(num_matches, matches, p_ic);
4112 #endif
4113 break;
4115 default: /* normal ^P/^N and ^X^L */
4117 * If 'infercase' is set, don't use 'smartcase' here
4119 save_p_scs = p_scs;
4120 if (ins_buf->b_p_inf)
4121 p_scs = FALSE;
4123 /* buffers other than curbuf are scanned from the beginning or the
4124 * end but never from the middle, thus setting nowrapscan in this
4125 * buffers is a good idea, on the other hand, we always set
4126 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
4127 save_p_ws = p_ws;
4128 if (ins_buf != curbuf)
4129 p_ws = FALSE;
4130 else if (*e_cpt == '.')
4131 p_ws = TRUE;
4132 for (;;)
4134 int flags = 0;
4136 ++msg_silent; /* Don't want messages for wrapscan. */
4138 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
4139 * has added a word that was at the beginning of the line */
4140 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
4141 || (compl_cont_status & CONT_SOL))
4142 found_new_match = search_for_exact_line(ins_buf, pos,
4143 compl_direction, compl_pattern);
4144 else
4145 found_new_match = searchit(NULL, ins_buf, pos,
4146 compl_direction,
4147 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
4148 RE_LAST, (linenr_T)0, NULL);
4149 --msg_silent;
4150 if (!compl_started)
4152 /* set "compl_started" even on fail */
4153 compl_started = TRUE;
4154 first_match_pos = *pos;
4155 last_match_pos = *pos;
4157 else if (first_match_pos.lnum == last_match_pos.lnum
4158 && first_match_pos.col == last_match_pos.col)
4159 found_new_match = FAIL;
4160 if (found_new_match == FAIL)
4162 if (ins_buf == curbuf)
4163 found_all = TRUE;
4164 break;
4167 /* when ADDING, the text before the cursor matches, skip it */
4168 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
4169 && ini->lnum == pos->lnum
4170 && ini->col == pos->col)
4171 continue;
4172 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
4173 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4175 if (compl_cont_status & CONT_ADDING)
4177 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
4178 continue;
4179 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4180 if (!p_paste)
4181 ptr = skipwhite(ptr);
4183 len = (int)STRLEN(ptr);
4185 else
4187 char_u *tmp_ptr = ptr;
4189 if (compl_cont_status & CONT_ADDING)
4191 tmp_ptr += compl_length;
4192 /* Skip if already inside a word. */
4193 if (vim_iswordp(tmp_ptr))
4194 continue;
4195 /* Find start of next word. */
4196 tmp_ptr = find_word_start(tmp_ptr);
4198 /* Find end of this word. */
4199 tmp_ptr = find_word_end(tmp_ptr);
4200 len = (int)(tmp_ptr - ptr);
4202 if ((compl_cont_status & CONT_ADDING)
4203 && len == compl_length)
4205 if (pos->lnum < ins_buf->b_ml.ml_line_count)
4207 /* Try next line, if any. the new word will be
4208 * "join" as if the normal command "J" was used.
4209 * IOSIZE is always greater than
4210 * compl_length, so the next STRNCPY always
4211 * works -- Acevedo */
4212 STRNCPY(IObuff, ptr, len);
4213 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4214 tmp_ptr = ptr = skipwhite(ptr);
4215 /* Find start of next word. */
4216 tmp_ptr = find_word_start(tmp_ptr);
4217 /* Find end of next word. */
4218 tmp_ptr = find_word_end(tmp_ptr);
4219 if (tmp_ptr > ptr)
4221 if (*ptr != ')' && IObuff[len - 1] != TAB)
4223 if (IObuff[len - 1] != ' ')
4224 IObuff[len++] = ' ';
4225 /* IObuf =~ "\k.* ", thus len >= 2 */
4226 if (p_js
4227 && (IObuff[len - 2] == '.'
4228 || (vim_strchr(p_cpo, CPO_JOINSP)
4229 == NULL
4230 && (IObuff[len - 2] == '?'
4231 || IObuff[len - 2] == '!'))))
4232 IObuff[len++] = ' ';
4234 /* copy as much as possible of the new word */
4235 if (tmp_ptr - ptr >= IOSIZE - len)
4236 tmp_ptr = ptr + IOSIZE - len - 1;
4237 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4238 len += (int)(tmp_ptr - ptr);
4239 flags |= CONT_S_IPOS;
4241 IObuff[len] = NUL;
4242 ptr = IObuff;
4244 if (len == compl_length)
4245 continue;
4248 if (ins_compl_add_infercase(ptr, len, p_ic,
4249 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
4250 0, flags) != NOTDONE)
4252 found_new_match = OK;
4253 break;
4256 p_scs = save_p_scs;
4257 p_ws = save_p_ws;
4260 /* check if compl_curr_match has changed, (e.g. other type of
4261 * expansion added something) */
4262 if (type != 0 && compl_curr_match != old_match)
4263 found_new_match = OK;
4265 /* break the loop for specialized modes (use 'complete' just for the
4266 * generic ctrl_x_mode == 0) or when we've found a new match */
4267 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4268 || found_new_match != FAIL)
4270 if (got_int)
4271 break;
4272 /* Fill the popup menu as soon as possible. */
4273 if (type != -1)
4274 ins_compl_check_keys(0);
4276 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4277 || compl_interrupted)
4278 break;
4279 compl_started = TRUE;
4281 else
4283 /* Mark a buffer scanned when it has been scanned completely */
4284 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
4285 ins_buf->b_scanned = TRUE;
4287 compl_started = FALSE;
4290 compl_started = TRUE;
4292 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4293 && *e_cpt == NUL) /* Got to end of 'complete' */
4294 found_new_match = FAIL;
4296 i = -1; /* total of matches, unknown */
4297 if (found_new_match == FAIL
4298 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
4299 i = ins_compl_make_cyclic();
4301 /* If several matches were added (FORWARD) or the search failed and has
4302 * just been made cyclic then we have to move compl_curr_match to the next
4303 * or previous entry (if any) -- Acevedo */
4304 compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
4305 : old_match->cp_prev;
4306 if (compl_curr_match == NULL)
4307 compl_curr_match = old_match;
4308 return i;
4311 /* Delete the old text being completed. */
4312 static void
4313 ins_compl_delete()
4315 int i;
4318 * In insert mode: Delete the typed part.
4319 * In replace mode: Put the old characters back, if any.
4321 i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
4322 backspace_until_column(i);
4323 changed_cline_bef_curs();
4326 /* Insert the new text being completed. */
4327 static void
4328 ins_compl_insert()
4330 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
4331 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4332 compl_used_match = FALSE;
4333 else
4334 compl_used_match = TRUE;
4338 * Fill in the next completion in the current direction.
4339 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4340 * get more completions. If it is FALSE, then we just do nothing when there
4341 * are no more completions in a given direction. The latter case is used when
4342 * we are still in the middle of finding completions, to allow browsing
4343 * through the ones found so far.
4344 * Return the total number of matches, or -1 if still unknown -- webb.
4346 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4347 * compl_shown_match here.
4349 * Note that this function may be called recursively once only. First with
4350 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4351 * calls this function with "allow_get_expansion" FALSE.
4353 static int
4354 ins_compl_next(allow_get_expansion, count, insert_match)
4355 int allow_get_expansion;
4356 int count; /* repeat completion this many times; should
4357 be at least 1 */
4358 int insert_match; /* Insert the newly selected match */
4360 int num_matches = -1;
4361 int i;
4362 int todo = count;
4363 compl_T *found_compl = NULL;
4364 int found_end = FALSE;
4365 int advance;
4367 if (compl_leader != NULL
4368 && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4370 /* Set "compl_shown_match" to the actually shown match, it may differ
4371 * when "compl_leader" is used to omit some of the matches. */
4372 while (!ins_compl_equal(compl_shown_match,
4373 compl_leader, (int)STRLEN(compl_leader))
4374 && compl_shown_match->cp_next != NULL
4375 && compl_shown_match->cp_next != compl_first_match)
4376 compl_shown_match = compl_shown_match->cp_next;
4378 /* If we didn't find it searching forward, and compl_shows_dir is
4379 * backward, find the last match. */
4380 if (compl_shows_dir == BACKWARD
4381 && !ins_compl_equal(compl_shown_match,
4382 compl_leader, (int)STRLEN(compl_leader))
4383 && (compl_shown_match->cp_next == NULL
4384 || compl_shown_match->cp_next == compl_first_match))
4386 while (!ins_compl_equal(compl_shown_match,
4387 compl_leader, (int)STRLEN(compl_leader))
4388 && compl_shown_match->cp_prev != NULL
4389 && compl_shown_match->cp_prev != compl_first_match)
4390 compl_shown_match = compl_shown_match->cp_prev;
4394 if (allow_get_expansion && insert_match
4395 && (!(compl_get_longest || compl_restarting) || compl_used_match))
4396 /* Delete old text to be replaced */
4397 ins_compl_delete();
4399 /* When finding the longest common text we stick at the original text,
4400 * don't let CTRL-N or CTRL-P move to the first match. */
4401 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4403 /* When restarting the search don't insert the first match either. */
4404 if (compl_restarting)
4406 advance = FALSE;
4407 compl_restarting = FALSE;
4410 /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4411 * around. */
4412 while (--todo >= 0)
4414 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4416 compl_shown_match = compl_shown_match->cp_next;
4417 found_end = (compl_first_match != NULL
4418 && (compl_shown_match->cp_next == compl_first_match
4419 || compl_shown_match == compl_first_match));
4421 else if (compl_shows_dir == BACKWARD
4422 && compl_shown_match->cp_prev != NULL)
4424 found_end = (compl_shown_match == compl_first_match);
4425 compl_shown_match = compl_shown_match->cp_prev;
4426 found_end |= (compl_shown_match == compl_first_match);
4428 else
4430 if (!allow_get_expansion)
4432 if (advance)
4434 if (compl_shows_dir == BACKWARD)
4435 compl_pending -= todo + 1;
4436 else
4437 compl_pending += todo + 1;
4439 return -1;
4442 if (advance)
4444 if (compl_shows_dir == BACKWARD)
4445 --compl_pending;
4446 else
4447 ++compl_pending;
4450 /* Find matches. */
4451 num_matches = ins_compl_get_exp(&compl_startpos);
4453 /* handle any pending completions */
4454 while (compl_pending != 0 && compl_direction == compl_shows_dir
4455 && advance)
4457 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4459 compl_shown_match = compl_shown_match->cp_next;
4460 --compl_pending;
4462 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4464 compl_shown_match = compl_shown_match->cp_prev;
4465 ++compl_pending;
4467 else
4468 break;
4470 found_end = FALSE;
4472 if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4473 && compl_leader != NULL
4474 && !ins_compl_equal(compl_shown_match,
4475 compl_leader, (int)STRLEN(compl_leader)))
4476 ++todo;
4477 else
4478 /* Remember a matching item. */
4479 found_compl = compl_shown_match;
4481 /* Stop at the end of the list when we found a usable match. */
4482 if (found_end)
4484 if (found_compl != NULL)
4486 compl_shown_match = found_compl;
4487 break;
4489 todo = 1; /* use first usable match after wrapping around */
4493 /* Insert the text of the new completion, or the compl_leader. */
4494 if (insert_match)
4496 if (!compl_get_longest || compl_used_match)
4497 ins_compl_insert();
4498 else
4499 ins_bytes(compl_leader + ins_compl_len());
4501 else
4502 compl_used_match = FALSE;
4504 if (!allow_get_expansion)
4506 /* may undisplay the popup menu first */
4507 ins_compl_upd_pum();
4509 /* redraw to show the user what was inserted */
4510 update_screen(0);
4512 /* display the updated popup menu */
4513 ins_compl_show_pum();
4514 #ifdef FEAT_GUI
4515 if (gui.in_use)
4517 /* Show the cursor after the match, not after the redrawn text. */
4518 setcursor();
4519 out_flush();
4520 gui_update_cursor(FALSE, FALSE);
4522 #endif
4524 /* Delete old text to be replaced, since we're still searching and
4525 * don't want to match ourselves! */
4526 ins_compl_delete();
4529 /* Enter will select a match when the match wasn't inserted and the popup
4530 * menu is visible. */
4531 compl_enter_selects = !insert_match && compl_match_array != NULL;
4534 * Show the file name for the match (if any)
4535 * Truncate the file name to avoid a wait for return.
4537 if (compl_shown_match->cp_fname != NULL)
4539 STRCPY(IObuff, "match in file ");
4540 i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4541 if (i <= 0)
4542 i = 0;
4543 else
4544 STRCAT(IObuff, "<");
4545 STRCAT(IObuff, compl_shown_match->cp_fname + i);
4546 msg(IObuff);
4547 redraw_cmdline = FALSE; /* don't overwrite! */
4550 return num_matches;
4554 * Call this while finding completions, to check whether the user has hit a key
4555 * that should change the currently displayed completion, or exit completion
4556 * mode. Also, when compl_pending is not zero, show a completion as soon as
4557 * possible. -- webb
4558 * "frequency" specifies out of how many calls we actually check.
4560 void
4561 ins_compl_check_keys(frequency)
4562 int frequency;
4564 static int count = 0;
4566 int c;
4568 /* Don't check when reading keys from a script. That would break the test
4569 * scripts */
4570 if (using_script())
4571 return;
4573 /* Only do this at regular intervals */
4574 if (++count < frequency)
4575 return;
4576 count = 0;
4578 /* Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4579 * can't do its work correctly. */
4580 c = vpeekc_any();
4581 if (c != NUL)
4583 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4585 c = safe_vgetc(); /* Eat the character */
4586 compl_shows_dir = ins_compl_key2dir(c);
4587 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4588 c != K_UP && c != K_DOWN);
4590 else
4592 /* Need to get the character to have KeyTyped set. We'll put it
4593 * back with vungetc() below. But skip K_IGNORE. */
4594 c = safe_vgetc();
4595 if (c != K_IGNORE)
4597 /* Don't interrupt completion when the character wasn't typed,
4598 * e.g., when doing @q to replay keys. */
4599 if (c != Ctrl_R && KeyTyped)
4600 compl_interrupted = TRUE;
4602 vungetc(c);
4606 if (compl_pending != 0 && !got_int)
4608 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4610 compl_pending = 0;
4611 (void)ins_compl_next(FALSE, todo, TRUE);
4616 * Decide the direction of Insert mode complete from the key typed.
4617 * Returns BACKWARD or FORWARD.
4619 static int
4620 ins_compl_key2dir(c)
4621 int c;
4623 if (c == Ctrl_P || c == Ctrl_L
4624 || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4625 || c == K_S_UP || c == K_UP)))
4626 return BACKWARD;
4627 return FORWARD;
4631 * Return TRUE for keys that are used for completion only when the popup menu
4632 * is visible.
4634 static int
4635 ins_compl_pum_key(c)
4636 int c;
4638 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4639 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4640 || c == K_UP || c == K_DOWN);
4644 * Decide the number of completions to move forward.
4645 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4647 static int
4648 ins_compl_key2count(c)
4649 int c;
4651 int h;
4653 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4655 h = pum_get_height();
4656 if (h > 3)
4657 h -= 2; /* keep some context */
4658 return h;
4660 return 1;
4664 * Return TRUE if completion with "c" should insert the match, FALSE if only
4665 * to change the currently selected completion.
4667 static int
4668 ins_compl_use_match(c)
4669 int c;
4671 switch (c)
4673 case K_UP:
4674 case K_DOWN:
4675 case K_PAGEDOWN:
4676 case K_KPAGEDOWN:
4677 case K_S_DOWN:
4678 case K_PAGEUP:
4679 case K_KPAGEUP:
4680 case K_S_UP:
4681 return FALSE;
4683 return TRUE;
4687 * Do Insert mode completion.
4688 * Called when character "c" was typed, which has a meaning for completion.
4689 * Returns OK if completion was done, FAIL if something failed (out of mem).
4691 static int
4692 ins_complete(c)
4693 int c;
4695 char_u *line;
4696 int startcol = 0; /* column where searched text starts */
4697 colnr_T curs_col; /* cursor column */
4698 int n;
4699 int save_w_wrow;
4701 compl_direction = ins_compl_key2dir(c);
4702 if (!compl_started)
4704 /* First time we hit ^N or ^P (in a row, I mean) */
4706 did_ai = FALSE;
4707 #ifdef FEAT_SMARTINDENT
4708 did_si = FALSE;
4709 can_si = FALSE;
4710 can_si_back = FALSE;
4711 #endif
4712 if (stop_arrow() == FAIL)
4713 return FAIL;
4715 line = ml_get(curwin->w_cursor.lnum);
4716 curs_col = curwin->w_cursor.col;
4717 compl_pending = 0;
4719 /* If this same ctrl_x_mode has been interrupted use the text from
4720 * "compl_startpos" to the cursor as a pattern to add a new word
4721 * instead of expand the one before the cursor, in word-wise if
4722 * "compl_startpos" is not in the same line as the cursor then fix it
4723 * (the line has been split because it was longer than 'tw'). if SOL
4724 * is set then skip the previous pattern, a word at the beginning of
4725 * the line has been inserted, we'll look for that -- Acevedo. */
4726 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4727 && compl_cont_mode == ctrl_x_mode)
4730 * it is a continued search
4732 compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */
4733 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4734 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4736 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4738 /* line (probably) wrapped, set compl_startpos to the
4739 * first non_blank in the line, if it is not a wordchar
4740 * include it to get a better pattern, but then we don't
4741 * want the "\\<" prefix, check it bellow */
4742 compl_col = (colnr_T)(skipwhite(line) - line);
4743 compl_startpos.col = compl_col;
4744 compl_startpos.lnum = curwin->w_cursor.lnum;
4745 compl_cont_status &= ~CONT_SOL; /* clear SOL if present */
4747 else
4749 /* S_IPOS was set when we inserted a word that was at the
4750 * beginning of the line, which means that we'll go to SOL
4751 * mode but first we need to redefine compl_startpos */
4752 if (compl_cont_status & CONT_S_IPOS)
4754 compl_cont_status |= CONT_SOL;
4755 compl_startpos.col = (colnr_T)(skipwhite(
4756 line + compl_length
4757 + compl_startpos.col) - line);
4759 compl_col = compl_startpos.col;
4761 compl_length = curwin->w_cursor.col - (int)compl_col;
4762 /* IObuff is used to add a "word from the next line" would we
4763 * have enough space? just being paranoid */
4764 #define MIN_SPACE 75
4765 if (compl_length > (IOSIZE - MIN_SPACE))
4767 compl_cont_status &= ~CONT_SOL;
4768 compl_length = (IOSIZE - MIN_SPACE);
4769 compl_col = curwin->w_cursor.col - compl_length;
4771 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4772 if (compl_length < 1)
4773 compl_cont_status &= CONT_LOCAL;
4775 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4776 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4777 else
4778 compl_cont_status = 0;
4780 else
4781 compl_cont_status &= CONT_LOCAL;
4783 if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */
4785 compl_cont_mode = ctrl_x_mode;
4786 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
4787 compl_cont_status = 0;
4788 compl_cont_status |= CONT_N_ADDS;
4789 compl_startpos = curwin->w_cursor;
4790 startcol = (int)curs_col;
4791 compl_col = 0;
4794 /* Work out completion pattern and original text -- webb */
4795 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
4797 if ((compl_cont_status & CONT_SOL)
4798 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4800 if (!(compl_cont_status & CONT_ADDING))
4802 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4804 compl_col += ++startcol;
4805 compl_length = curs_col - startcol;
4807 if (p_ic)
4808 compl_pattern = str_foldcase(line + compl_col,
4809 compl_length, NULL, 0);
4810 else
4811 compl_pattern = vim_strnsave(line + compl_col,
4812 compl_length);
4813 if (compl_pattern == NULL)
4814 return FAIL;
4816 else if (compl_cont_status & CONT_ADDING)
4818 char_u *prefix = (char_u *)"\\<";
4820 /* we need up to 2 extra chars for the prefix */
4821 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4822 compl_length) + 2);
4823 if (compl_pattern == NULL)
4824 return FAIL;
4825 if (!vim_iswordp(line + compl_col)
4826 || (compl_col > 0
4827 && (
4828 #ifdef FEAT_MBYTE
4829 vim_iswordp(mb_prevptr(line, line + compl_col))
4830 #else
4831 vim_iswordc(line[compl_col - 1])
4832 #endif
4834 prefix = (char_u *)"";
4835 STRCPY((char *)compl_pattern, prefix);
4836 (void)quote_meta(compl_pattern + STRLEN(prefix),
4837 line + compl_col, compl_length);
4839 else if (--startcol < 0 ||
4840 #ifdef FEAT_MBYTE
4841 !vim_iswordp(mb_prevptr(line, line + startcol + 1))
4842 #else
4843 !vim_iswordc(line[startcol])
4844 #endif
4847 /* Match any word of at least two chars */
4848 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4849 if (compl_pattern == NULL)
4850 return FAIL;
4851 compl_col += curs_col;
4852 compl_length = 0;
4854 else
4856 #ifdef FEAT_MBYTE
4857 /* Search the point of change class of multibyte character
4858 * or not a word single byte character backward. */
4859 if (has_mbyte)
4861 int base_class;
4862 int head_off;
4864 startcol -= (*mb_head_off)(line, line + startcol);
4865 base_class = mb_get_class(line + startcol);
4866 while (--startcol >= 0)
4868 head_off = (*mb_head_off)(line, line + startcol);
4869 if (base_class != mb_get_class(line + startcol
4870 - head_off))
4871 break;
4872 startcol -= head_off;
4875 else
4876 #endif
4877 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4879 compl_col += ++startcol;
4880 compl_length = (int)curs_col - startcol;
4881 if (compl_length == 1)
4883 /* Only match word with at least two chars -- webb
4884 * there's no need to call quote_meta,
4885 * alloc(7) is enough -- Acevedo
4887 compl_pattern = alloc(7);
4888 if (compl_pattern == NULL)
4889 return FAIL;
4890 STRCPY((char *)compl_pattern, "\\<");
4891 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4892 STRCAT((char *)compl_pattern, "\\k");
4894 else
4896 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4897 compl_length) + 2);
4898 if (compl_pattern == NULL)
4899 return FAIL;
4900 STRCPY((char *)compl_pattern, "\\<");
4901 (void)quote_meta(compl_pattern + 2, line + compl_col,
4902 compl_length);
4906 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4908 compl_col = (colnr_T)(skipwhite(line) - line);
4909 compl_length = (int)curs_col - (int)compl_col;
4910 if (compl_length < 0) /* cursor in indent: empty pattern */
4911 compl_length = 0;
4912 if (p_ic)
4913 compl_pattern = str_foldcase(line + compl_col, compl_length,
4914 NULL, 0);
4915 else
4916 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4917 if (compl_pattern == NULL)
4918 return FAIL;
4920 else if (ctrl_x_mode == CTRL_X_FILES)
4922 while (--startcol >= 0 && vim_isfilec(line[startcol]))
4924 compl_col += ++startcol;
4925 compl_length = (int)curs_col - startcol;
4926 compl_pattern = addstar(line + compl_col, compl_length,
4927 EXPAND_FILES);
4928 if (compl_pattern == NULL)
4929 return FAIL;
4931 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4933 compl_pattern = vim_strnsave(line, curs_col);
4934 if (compl_pattern == NULL)
4935 return FAIL;
4936 set_cmd_context(&compl_xp, compl_pattern,
4937 (int)STRLEN(compl_pattern), curs_col);
4938 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4939 || compl_xp.xp_context == EXPAND_NOTHING)
4940 /* No completion possible, use an empty pattern to get a
4941 * "pattern not found" message. */
4942 compl_col = curs_col;
4943 else
4944 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4945 compl_length = curs_col - compl_col;
4947 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
4949 #ifdef FEAT_COMPL_FUNC
4951 * Call user defined function 'completefunc' with "a:findstart"
4952 * set to 1 to obtain the length of text to use for completion.
4954 char_u *args[2];
4955 int col;
4956 char_u *funcname;
4957 pos_T pos;
4959 /* Call 'completefunc' or 'omnifunc' and get pattern length as a
4960 * string */
4961 funcname = ctrl_x_mode == CTRL_X_FUNCTION
4962 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
4963 if (*funcname == NUL)
4965 EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4966 ? "completefunc" : "omnifunc");
4967 return FAIL;
4970 args[0] = (char_u *)"1";
4971 args[1] = NULL;
4972 pos = curwin->w_cursor;
4973 col = call_func_retnr(funcname, 2, args, FALSE);
4974 curwin->w_cursor = pos; /* restore the cursor position */
4976 if (col < 0)
4977 col = curs_col;
4978 compl_col = col;
4979 if (compl_col > curs_col)
4980 compl_col = curs_col;
4982 /* Setup variables for completion. Need to obtain "line" again,
4983 * it may have become invalid. */
4984 line = ml_get(curwin->w_cursor.lnum);
4985 compl_length = curs_col - compl_col;
4986 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4987 if (compl_pattern == NULL)
4988 #endif
4989 return FAIL;
4991 else if (ctrl_x_mode == CTRL_X_SPELL)
4993 #ifdef FEAT_SPELL
4994 if (spell_bad_len > 0)
4995 compl_col = curs_col - spell_bad_len;
4996 else
4997 compl_col = spell_word_start(startcol);
4998 if (compl_col >= (colnr_T)startcol)
5000 compl_length = 0;
5001 compl_col = curs_col;
5003 else
5005 spell_expand_check_cap(compl_col);
5006 compl_length = (int)curs_col - compl_col;
5008 /* Need to obtain "line" again, it may have become invalid. */
5009 line = ml_get(curwin->w_cursor.lnum);
5010 compl_pattern = vim_strnsave(line + compl_col, compl_length);
5011 if (compl_pattern == NULL)
5012 #endif
5013 return FAIL;
5015 else
5017 EMSG2(_(e_intern2), "ins_complete()");
5018 return FAIL;
5021 if (compl_cont_status & CONT_ADDING)
5023 edit_submode_pre = (char_u *)_(" Adding");
5024 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
5026 /* Insert a new line, keep indentation but ignore 'comments' */
5027 #ifdef FEAT_COMMENTS
5028 char_u *old = curbuf->b_p_com;
5030 curbuf->b_p_com = (char_u *)"";
5031 #endif
5032 compl_startpos.lnum = curwin->w_cursor.lnum;
5033 compl_startpos.col = compl_col;
5034 ins_eol('\r');
5035 #ifdef FEAT_COMMENTS
5036 curbuf->b_p_com = old;
5037 #endif
5038 compl_length = 0;
5039 compl_col = curwin->w_cursor.col;
5042 else
5044 edit_submode_pre = NULL;
5045 compl_startpos.col = compl_col;
5048 if (compl_cont_status & CONT_LOCAL)
5049 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5050 else
5051 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5053 /* Always add completion for the original text. */
5054 vim_free(compl_orig_text);
5055 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5056 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5057 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
5059 vim_free(compl_pattern);
5060 compl_pattern = NULL;
5061 vim_free(compl_orig_text);
5062 compl_orig_text = NULL;
5063 return FAIL;
5066 /* showmode might reset the internal line pointers, so it must
5067 * be called before line = ml_get(), or when this address is no
5068 * longer needed. -- Acevedo.
5070 edit_submode_extra = (char_u *)_("-- Searching...");
5071 edit_submode_highl = HLF_COUNT;
5072 showmode();
5073 edit_submode_extra = NULL;
5074 out_flush();
5077 compl_shown_match = compl_curr_match;
5078 compl_shows_dir = compl_direction;
5081 * Find next match (and following matches).
5083 save_w_wrow = curwin->w_wrow;
5084 n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
5086 /* may undisplay the popup menu */
5087 ins_compl_upd_pum();
5089 if (n > 1) /* all matches have been found */
5090 compl_matches = n;
5091 compl_curr_match = compl_shown_match;
5092 compl_direction = compl_shows_dir;
5094 /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5095 * mode. */
5096 if (got_int && !global_busy)
5098 (void)vgetc();
5099 got_int = FALSE;
5102 /* we found no match if the list has only the "compl_orig_text"-entry */
5103 if (compl_first_match == compl_first_match->cp_next)
5105 edit_submode_extra = (compl_cont_status & CONT_ADDING)
5106 && compl_length > 1
5107 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
5108 edit_submode_highl = HLF_E;
5109 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5110 * because we couldn't expand anything at first place, but if we used
5111 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5112 * (such as M in M'exico) if not tried already. -- Acevedo */
5113 if ( compl_length > 1
5114 || (compl_cont_status & CONT_ADDING)
5115 || (ctrl_x_mode != 0
5116 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
5117 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
5118 compl_cont_status &= ~CONT_N_ADDS;
5121 if (compl_curr_match->cp_flags & CONT_S_IPOS)
5122 compl_cont_status |= CONT_S_IPOS;
5123 else
5124 compl_cont_status &= ~CONT_S_IPOS;
5126 if (edit_submode_extra == NULL)
5128 if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
5130 edit_submode_extra = (char_u *)_("Back at original");
5131 edit_submode_highl = HLF_W;
5133 else if (compl_cont_status & CONT_S_IPOS)
5135 edit_submode_extra = (char_u *)_("Word from other line");
5136 edit_submode_highl = HLF_COUNT;
5138 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5140 edit_submode_extra = (char_u *)_("The only match");
5141 edit_submode_highl = HLF_COUNT;
5143 else
5145 /* Update completion sequence number when needed. */
5146 if (compl_curr_match->cp_number == -1)
5148 int number = 0;
5149 compl_T *match;
5151 if (compl_direction == FORWARD)
5153 /* search backwards for the first valid (!= -1) number.
5154 * This should normally succeed already at the first loop
5155 * cycle, so it's fast! */
5156 for (match = compl_curr_match->cp_prev; match != NULL
5157 && match != compl_first_match;
5158 match = match->cp_prev)
5159 if (match->cp_number != -1)
5161 number = match->cp_number;
5162 break;
5164 if (match != NULL)
5165 /* go up and assign all numbers which are not assigned
5166 * yet */
5167 for (match = match->cp_next;
5168 match != NULL && match->cp_number == -1;
5169 match = match->cp_next)
5170 match->cp_number = ++number;
5172 else /* BACKWARD */
5174 /* search forwards (upwards) for the first valid (!= -1)
5175 * number. This should normally succeed already at the
5176 * first loop cycle, so it's fast! */
5177 for (match = compl_curr_match->cp_next; match != NULL
5178 && match != compl_first_match;
5179 match = match->cp_next)
5180 if (match->cp_number != -1)
5182 number = match->cp_number;
5183 break;
5185 if (match != NULL)
5186 /* go down and assign all numbers which are not
5187 * assigned yet */
5188 for (match = match->cp_prev; match
5189 && match->cp_number == -1;
5190 match = match->cp_prev)
5191 match->cp_number = ++number;
5195 /* The match should always have a sequence number now, this is
5196 * just a safety check. */
5197 if (compl_curr_match->cp_number != -1)
5199 /* Space for 10 text chars. + 2x10-digit no.s = 31.
5200 * Translations may need more than twice that. */
5201 static char_u match_ref[81];
5203 if (compl_matches > 0)
5204 vim_snprintf((char *)match_ref, sizeof(match_ref),
5205 _("match %d of %d"),
5206 compl_curr_match->cp_number, compl_matches);
5207 else
5208 vim_snprintf((char *)match_ref, sizeof(match_ref),
5209 _("match %d"),
5210 compl_curr_match->cp_number);
5211 edit_submode_extra = match_ref;
5212 edit_submode_highl = HLF_R;
5213 if (dollar_vcol)
5214 curs_columns(FALSE);
5219 /* Show a message about what (completion) mode we're in. */
5220 showmode();
5221 if (edit_submode_extra != NULL)
5223 if (!p_smd)
5224 msg_attr(edit_submode_extra,
5225 edit_submode_highl < HLF_COUNT
5226 ? hl_attr(edit_submode_highl) : 0);
5228 else
5229 msg_clr_cmdline(); /* necessary for "noshowmode" */
5231 /* Show the popup menu, unless we got interrupted. */
5232 if (!compl_interrupted)
5234 /* RedrawingDisabled may be set when invoked through complete(). */
5235 n = RedrawingDisabled;
5236 RedrawingDisabled = 0;
5238 /* If the cursor moved we need to remove the pum first. */
5239 setcursor();
5240 if (save_w_wrow != curwin->w_wrow)
5241 ins_compl_del_pum();
5243 ins_compl_show_pum();
5244 setcursor();
5245 RedrawingDisabled = n;
5247 compl_was_interrupted = compl_interrupted;
5248 compl_interrupted = FALSE;
5250 return OK;
5254 * Looks in the first "len" chars. of "src" for search-metachars.
5255 * If dest is not NULL the chars. are copied there quoting (with
5256 * a backslash) the metachars, and dest would be NUL terminated.
5257 * Returns the length (needed) of dest
5259 static unsigned
5260 quote_meta(dest, src, len)
5261 char_u *dest;
5262 char_u *src;
5263 int len;
5265 unsigned m = (unsigned)len + 1; /* one extra for the NUL */
5267 for ( ; --len >= 0; src++)
5269 switch (*src)
5271 case '.':
5272 case '*':
5273 case '[':
5274 if (ctrl_x_mode == CTRL_X_DICTIONARY
5275 || ctrl_x_mode == CTRL_X_THESAURUS)
5276 break;
5277 case '~':
5278 if (!p_magic) /* quote these only if magic is set */
5279 break;
5280 case '\\':
5281 if (ctrl_x_mode == CTRL_X_DICTIONARY
5282 || ctrl_x_mode == CTRL_X_THESAURUS)
5283 break;
5284 case '^': /* currently it's not needed. */
5285 case '$':
5286 m++;
5287 if (dest != NULL)
5288 *dest++ = '\\';
5289 break;
5291 if (dest != NULL)
5292 *dest++ = *src;
5293 # ifdef FEAT_MBYTE
5294 /* Copy remaining bytes of a multibyte character. */
5295 if (has_mbyte)
5297 int i, mb_len;
5299 mb_len = (*mb_ptr2len)(src) - 1;
5300 if (mb_len > 0 && len >= mb_len)
5301 for (i = 0; i < mb_len; ++i)
5303 --len;
5304 ++src;
5305 if (dest != NULL)
5306 *dest++ = *src;
5309 # endif
5311 if (dest != NULL)
5312 *dest = NUL;
5314 return m;
5316 #endif /* FEAT_INS_EXPAND */
5319 * Next character is interpreted literally.
5320 * A one, two or three digit decimal number is interpreted as its byte value.
5321 * If one or two digits are entered, the next character is given to vungetc().
5322 * For Unicode a character > 255 may be returned.
5325 get_literal()
5327 int cc;
5328 int nc;
5329 int i;
5330 int hex = FALSE;
5331 int octal = FALSE;
5332 #ifdef FEAT_MBYTE
5333 int unicode = 0;
5334 #endif
5336 if (got_int)
5337 return Ctrl_C;
5339 #ifdef FEAT_GUI
5341 * In GUI there is no point inserting the internal code for a special key.
5342 * It is more useful to insert the string "<KEY>" instead. This would
5343 * probably be useful in a text window too, but it would not be
5344 * vi-compatible (maybe there should be an option for it?) -- webb
5346 if (gui.in_use)
5347 ++allow_keys;
5348 #endif
5349 #ifdef USE_ON_FLY_SCROLL
5350 dont_scroll = TRUE; /* disallow scrolling here */
5351 #endif
5352 ++no_mapping; /* don't map the next key hits */
5353 cc = 0;
5354 i = 0;
5355 for (;;)
5357 nc = plain_vgetc();
5358 #ifdef FEAT_CMDL_INFO
5359 if (!(State & CMDLINE)
5360 # ifdef FEAT_MBYTE
5361 && MB_BYTE2LEN_CHECK(nc) == 1
5362 # endif
5364 add_to_showcmd(nc);
5365 #endif
5366 if (nc == 'x' || nc == 'X')
5367 hex = TRUE;
5368 else if (nc == 'o' || nc == 'O')
5369 octal = TRUE;
5370 #ifdef FEAT_MBYTE
5371 else if (nc == 'u' || nc == 'U')
5372 unicode = nc;
5373 #endif
5374 else
5376 if (hex
5377 #ifdef FEAT_MBYTE
5378 || unicode != 0
5379 #endif
5382 if (!vim_isxdigit(nc))
5383 break;
5384 cc = cc * 16 + hex2nr(nc);
5386 else if (octal)
5388 if (nc < '0' || nc > '7')
5389 break;
5390 cc = cc * 8 + nc - '0';
5392 else
5394 if (!VIM_ISDIGIT(nc))
5395 break;
5396 cc = cc * 10 + nc - '0';
5399 ++i;
5402 if (cc > 255
5403 #ifdef FEAT_MBYTE
5404 && unicode == 0
5405 #endif
5407 cc = 255; /* limit range to 0-255 */
5408 nc = 0;
5410 if (hex) /* hex: up to two chars */
5412 if (i >= 2)
5413 break;
5415 #ifdef FEAT_MBYTE
5416 else if (unicode) /* Unicode: up to four or eight chars */
5418 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
5419 break;
5421 #endif
5422 else if (i >= 3) /* decimal or octal: up to three chars */
5423 break;
5425 if (i == 0) /* no number entered */
5427 if (nc == K_ZERO) /* NUL is stored as NL */
5429 cc = '\n';
5430 nc = 0;
5432 else
5434 cc = nc;
5435 nc = 0;
5439 if (cc == 0) /* NUL is stored as NL */
5440 cc = '\n';
5441 #ifdef FEAT_MBYTE
5442 if (enc_dbcs && (cc & 0xff) == 0)
5443 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
5444 second byte will cause trouble! */
5445 #endif
5447 --no_mapping;
5448 #ifdef FEAT_GUI
5449 if (gui.in_use)
5450 --allow_keys;
5451 #endif
5452 if (nc)
5453 vungetc(nc);
5454 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
5455 return cc;
5459 * Insert character, taking care of special keys and mod_mask
5461 static void
5462 insert_special(c, allow_modmask, ctrlv)
5463 int c;
5464 int allow_modmask;
5465 int ctrlv; /* c was typed after CTRL-V */
5467 char_u *p;
5468 int len;
5471 * Special function key, translate into "<Key>". Up to the last '>' is
5472 * inserted with ins_str(), so as not to replace characters in replace
5473 * mode.
5474 * Only use mod_mask for special keys, to avoid things like <S-Space>,
5475 * unless 'allow_modmask' is TRUE.
5477 #ifdef MACOS
5478 /* Command-key never produces a normal key */
5479 if (mod_mask & MOD_MASK_CMD)
5480 allow_modmask = TRUE;
5481 #endif
5482 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5484 p = get_special_key_name(c, mod_mask);
5485 len = (int)STRLEN(p);
5486 c = p[len - 1];
5487 if (len > 2)
5489 if (stop_arrow() == FAIL)
5490 return;
5491 p[len - 1] = NUL;
5492 ins_str(p);
5493 AppendToRedobuffLit(p, -1);
5494 ctrlv = FALSE;
5497 if (stop_arrow() == OK)
5498 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5502 * Special characters in this context are those that need processing other
5503 * than the simple insertion that can be performed here. This includes ESC
5504 * which terminates the insert, and CR/NL which need special processing to
5505 * open up a new line. This routine tries to optimize insertions performed by
5506 * the "redo", "undo" or "put" commands, so it needs to know when it should
5507 * stop and defer processing to the "normal" mechanism.
5508 * '0' and '^' are special, because they can be followed by CTRL-D.
5510 #ifdef EBCDIC
5511 # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
5512 #else
5513 # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5514 #endif
5516 #ifdef FEAT_MBYTE
5517 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5518 #else
5519 # define WHITECHAR(cc) vim_iswhite(cc)
5520 #endif
5522 void
5523 insertchar(c, flags, second_indent)
5524 int c; /* character to insert or NUL */
5525 int flags; /* INSCHAR_FORMAT, etc. */
5526 int second_indent; /* indent for second line if >= 0 */
5528 int textwidth;
5529 #ifdef FEAT_COMMENTS
5530 char_u *p;
5531 #endif
5532 int fo_ins_blank;
5534 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5535 fo_ins_blank = has_format_option(FO_INS_BLANK);
5538 * Try to break the line in two or more pieces when:
5539 * - Always do this if we have been called to do formatting only.
5540 * - Always do this when 'formatoptions' has the 'a' flag and the line
5541 * ends in white space.
5542 * - Otherwise:
5543 * - Don't do this if inserting a blank
5544 * - Don't do this if an existing character is being replaced, unless
5545 * we're in VREPLACE mode.
5546 * - Do this if the cursor is not on the line where insert started
5547 * or - 'formatoptions' doesn't have 'l' or the line was not too long
5548 * before the insert.
5549 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5550 * before 'textwidth'
5552 if (textwidth > 0
5553 && ((flags & INSCHAR_FORMAT)
5554 || (!vim_iswhite(c)
5555 && !((State & REPLACE_FLAG)
5556 #ifdef FEAT_VREPLACE
5557 && !(State & VREPLACE_FLAG)
5558 #endif
5559 && *ml_get_cursor() != NUL)
5560 && (curwin->w_cursor.lnum != Insstart.lnum
5561 || ((!has_format_option(FO_INS_LONG)
5562 || Insstart_textlen <= (colnr_T)textwidth)
5563 && (!fo_ins_blank
5564 || Insstart_blank_vcol <= (colnr_T)textwidth
5565 ))))))
5567 /* Format with 'formatexpr' when it's set. Use internal formatting
5568 * when 'formatexpr' isn't set or it returns non-zero. */
5569 #if defined(FEAT_EVAL)
5570 int do_internal = TRUE;
5572 if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0)
5574 do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0);
5575 /* It may be required to save for undo again, e.g. when setline()
5576 * was called. */
5577 ins_need_undo = TRUE;
5579 if (do_internal)
5580 #endif
5581 internal_format(textwidth, second_indent, flags, c == NUL, c);
5584 if (c == NUL) /* only formatting was wanted */
5585 return;
5587 #ifdef FEAT_COMMENTS
5588 /* Check whether this character should end a comment. */
5589 if (did_ai && (int)c == end_comment_pending)
5591 char_u *line;
5592 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5593 int middle_len, end_len;
5594 int i;
5597 * Need to remove existing (middle) comment leader and insert end
5598 * comment leader. First, check what comment leader we can find.
5600 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
5601 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
5603 /* Skip middle-comment string */
5604 while (*p && p[-1] != ':') /* find end of middle flags */
5605 ++p;
5606 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5607 /* Don't count trailing white space for middle_len */
5608 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5609 --middle_len;
5611 /* Find the end-comment string */
5612 while (*p && p[-1] != ':') /* find end of end flags */
5613 ++p;
5614 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5616 /* Skip white space before the cursor */
5617 i = curwin->w_cursor.col;
5618 while (--i >= 0 && vim_iswhite(line[i]))
5620 i++;
5622 /* Skip to before the middle leader */
5623 i -= middle_len;
5625 /* Check some expected things before we go on */
5626 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5628 /* Backspace over all the stuff we want to replace */
5629 backspace_until_column(i);
5632 * Insert the end-comment string, except for the last
5633 * character, which will get inserted as normal later.
5635 ins_bytes_len(lead_end, end_len - 1);
5639 end_comment_pending = NUL;
5640 #endif
5642 did_ai = FALSE;
5643 #ifdef FEAT_SMARTINDENT
5644 did_si = FALSE;
5645 can_si = FALSE;
5646 can_si_back = FALSE;
5647 #endif
5650 * If there's any pending input, grab up to INPUT_BUFLEN at once.
5651 * This speeds up normal text input considerably.
5652 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5653 * need to re-indent at a ':', or any other character (but not what
5654 * 'paste' is set)..
5656 #ifdef USE_ON_FLY_SCROLL
5657 dont_scroll = FALSE; /* allow scrolling here */
5658 #endif
5660 if ( !ISSPECIAL(c)
5661 #ifdef FEAT_MBYTE
5662 && (!has_mbyte || (*mb_char2len)(c) == 1)
5663 #endif
5664 && vpeekc() != NUL
5665 && !(State & REPLACE_FLAG)
5666 #ifdef FEAT_CINDENT
5667 && !cindent_on()
5668 #endif
5669 #ifdef FEAT_RIGHTLEFT
5670 && !p_ri
5671 #endif
5674 #define INPUT_BUFLEN 100
5675 char_u buf[INPUT_BUFLEN + 1];
5676 int i;
5677 colnr_T virtcol = 0;
5679 buf[0] = c;
5680 i = 1;
5681 if (textwidth > 0)
5682 virtcol = get_nolist_virtcol();
5684 * Stop the string when:
5685 * - no more chars available
5686 * - finding a special character (command key)
5687 * - buffer is full
5688 * - running into the 'textwidth' boundary
5689 * - need to check for abbreviation: A non-word char after a word-char
5691 while ( (c = vpeekc()) != NUL
5692 && !ISSPECIAL(c)
5693 #ifdef FEAT_MBYTE
5694 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5695 #endif
5696 && i < INPUT_BUFLEN
5697 && (textwidth == 0
5698 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5699 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5701 #ifdef FEAT_RIGHTLEFT
5702 c = vgetc();
5703 if (p_hkmap && KeyTyped)
5704 c = hkmap(c); /* Hebrew mode mapping */
5705 # ifdef FEAT_FKMAP
5706 if (p_fkmap && KeyTyped)
5707 c = fkmap(c); /* Farsi mode mapping */
5708 # endif
5709 buf[i++] = c;
5710 #else
5711 buf[i++] = vgetc();
5712 #endif
5715 #ifdef FEAT_DIGRAPHS
5716 do_digraph(-1); /* clear digraphs */
5717 do_digraph(buf[i-1]); /* may be the start of a digraph */
5718 #endif
5719 buf[i] = NUL;
5720 ins_str(buf);
5721 if (flags & INSCHAR_CTRLV)
5723 redo_literal(*buf);
5724 i = 1;
5726 else
5727 i = 0;
5728 if (buf[i] != NUL)
5729 AppendToRedobuffLit(buf + i, -1);
5731 else
5733 #ifdef FEAT_MBYTE
5734 int cc;
5736 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
5738 char_u buf[MB_MAXBYTES + 1];
5740 (*mb_char2bytes)(c, buf);
5741 buf[cc] = NUL;
5742 ins_char_bytes(buf, cc);
5743 AppendCharToRedobuff(c);
5745 else
5746 #endif
5748 ins_char(c);
5749 if (flags & INSCHAR_CTRLV)
5750 redo_literal(c);
5751 else
5752 AppendCharToRedobuff(c);
5758 * Format text at the current insert position.
5760 static void
5761 internal_format(textwidth, second_indent, flags, format_only, c)
5762 int textwidth;
5763 int second_indent;
5764 int flags;
5765 int format_only;
5766 int c; /* character to be inserted (can be NUL) */
5768 int cc;
5769 int save_char = NUL;
5770 int haveto_redraw = FALSE;
5771 int fo_ins_blank = has_format_option(FO_INS_BLANK);
5772 #ifdef FEAT_MBYTE
5773 int fo_multibyte = has_format_option(FO_MBYTE_BREAK);
5774 #endif
5775 int fo_white_par = has_format_option(FO_WHITE_PAR);
5776 int first_line = TRUE;
5777 #ifdef FEAT_COMMENTS
5778 colnr_T leader_len;
5779 int no_leader = FALSE;
5780 int do_comments = (flags & INSCHAR_DO_COM);
5781 #endif
5784 * When 'ai' is off we don't want a space under the cursor to be
5785 * deleted. Replace it with an 'x' temporarily.
5787 if (!curbuf->b_p_ai
5788 #ifdef FEAT_VREPLACE
5789 && !(State & VREPLACE_FLAG)
5790 #endif
5793 cc = gchar_cursor();
5794 if (vim_iswhite(cc))
5796 save_char = cc;
5797 pchar_cursor('x');
5802 * Repeat breaking lines, until the current line is not too long.
5804 while (!got_int)
5806 int startcol; /* Cursor column at entry */
5807 int wantcol; /* column at textwidth border */
5808 int foundcol; /* column for start of spaces */
5809 int end_foundcol = 0; /* column for start of word */
5810 colnr_T len;
5811 colnr_T virtcol;
5812 #ifdef FEAT_VREPLACE
5813 int orig_col = 0;
5814 char_u *saved_text = NULL;
5815 #endif
5816 colnr_T col;
5817 colnr_T end_col;
5819 virtcol = get_nolist_virtcol()
5820 + char2cells(c != NUL ? c : gchar_cursor());
5821 if (virtcol <= (colnr_T)textwidth)
5822 break;
5824 #ifdef FEAT_COMMENTS
5825 if (no_leader)
5826 do_comments = FALSE;
5827 else if (!(flags & INSCHAR_FORMAT)
5828 && has_format_option(FO_WRAP_COMS))
5829 do_comments = TRUE;
5831 /* Don't break until after the comment leader */
5832 if (do_comments)
5833 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
5834 else
5835 leader_len = 0;
5837 /* If the line doesn't start with a comment leader, then don't
5838 * start one in a following broken line. Avoids that a %word
5839 * moved to the start of the next line causes all following lines
5840 * to start with %. */
5841 if (leader_len == 0)
5842 no_leader = TRUE;
5843 #endif
5844 if (!(flags & INSCHAR_FORMAT)
5845 #ifdef FEAT_COMMENTS
5846 && leader_len == 0
5847 #endif
5848 && !has_format_option(FO_WRAP))
5850 break;
5851 if ((startcol = curwin->w_cursor.col) == 0)
5852 break;
5854 /* find column of textwidth border */
5855 coladvance((colnr_T)textwidth);
5856 wantcol = curwin->w_cursor.col;
5858 curwin->w_cursor.col = startcol;
5859 foundcol = 0;
5862 * Find position to break at.
5863 * Stop at first entered white when 'formatoptions' has 'v'
5865 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
5866 || curwin->w_cursor.lnum != Insstart.lnum
5867 || curwin->w_cursor.col >= Insstart.col)
5869 if (curwin->w_cursor.col == startcol && c != NUL)
5870 cc = c;
5871 else
5872 cc = gchar_cursor();
5873 if (WHITECHAR(cc))
5875 /* remember position of blank just before text */
5876 end_col = curwin->w_cursor.col;
5878 /* find start of sequence of blanks */
5879 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
5881 dec_cursor();
5882 cc = gchar_cursor();
5884 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
5885 break; /* only spaces in front of text */
5886 #ifdef FEAT_COMMENTS
5887 /* Don't break until after the comment leader */
5888 if (curwin->w_cursor.col < leader_len)
5889 break;
5890 #endif
5891 if (has_format_option(FO_ONE_LETTER))
5893 /* do not break after one-letter words */
5894 if (curwin->w_cursor.col == 0)
5895 break; /* one-letter word at begin */
5896 #ifdef FEAT_COMMENTS
5897 /* do not break "#a b" when 'tw' is 2 */
5898 if (curwin->w_cursor.col <= leader_len)
5899 break;
5900 #endif
5901 col = curwin->w_cursor.col;
5902 dec_cursor();
5903 cc = gchar_cursor();
5905 if (WHITECHAR(cc))
5906 continue; /* one-letter, continue */
5907 curwin->w_cursor.col = col;
5910 inc_cursor();
5912 end_foundcol = end_col + 1;
5913 foundcol = curwin->w_cursor.col;
5914 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5915 break;
5917 #ifdef FEAT_MBYTE
5918 else if (cc >= 0x100 && fo_multibyte)
5920 /* Break after or before a multi-byte character. */
5921 if (curwin->w_cursor.col != startcol)
5923 #ifdef FEAT_COMMENTS
5924 /* Don't break until after the comment leader */
5925 if (curwin->w_cursor.col < leader_len)
5926 break;
5927 #endif
5928 col = curwin->w_cursor.col;
5929 inc_cursor();
5930 /* Don't change end_foundcol if already set. */
5931 if (foundcol != curwin->w_cursor.col)
5933 foundcol = curwin->w_cursor.col;
5934 end_foundcol = foundcol;
5935 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5936 break;
5938 curwin->w_cursor.col = col;
5941 if (curwin->w_cursor.col == 0)
5942 break;
5944 col = curwin->w_cursor.col;
5946 dec_cursor();
5947 cc = gchar_cursor();
5949 if (WHITECHAR(cc))
5950 continue; /* break with space */
5951 #ifdef FEAT_COMMENTS
5952 /* Don't break until after the comment leader */
5953 if (curwin->w_cursor.col < leader_len)
5954 break;
5955 #endif
5957 curwin->w_cursor.col = col;
5959 foundcol = curwin->w_cursor.col;
5960 end_foundcol = foundcol;
5961 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5962 break;
5964 #endif
5965 if (curwin->w_cursor.col == 0)
5966 break;
5967 dec_cursor();
5970 if (foundcol == 0) /* no spaces, cannot break line */
5972 curwin->w_cursor.col = startcol;
5973 break;
5976 /* Going to break the line, remove any "$" now. */
5977 undisplay_dollar();
5980 * Offset between cursor position and line break is used by replace
5981 * stack functions. VREPLACE does not use this, and backspaces
5982 * over the text instead.
5984 #ifdef FEAT_VREPLACE
5985 if (State & VREPLACE_FLAG)
5986 orig_col = startcol; /* Will start backspacing from here */
5987 else
5988 #endif
5989 replace_offset = startcol - end_foundcol;
5992 * adjust startcol for spaces that will be deleted and
5993 * characters that will remain on top line
5995 curwin->w_cursor.col = foundcol;
5996 while ((cc = gchar_cursor(), WHITECHAR(cc))
5997 && (!fo_white_par || curwin->w_cursor.col < startcol))
5998 inc_cursor();
5999 startcol -= curwin->w_cursor.col;
6000 if (startcol < 0)
6001 startcol = 0;
6003 #ifdef FEAT_VREPLACE
6004 if (State & VREPLACE_FLAG)
6007 * In VREPLACE mode, we will backspace over the text to be
6008 * wrapped, so save a copy now to put on the next line.
6010 saved_text = vim_strsave(ml_get_cursor());
6011 curwin->w_cursor.col = orig_col;
6012 if (saved_text == NULL)
6013 break; /* Can't do it, out of memory */
6014 saved_text[startcol] = NUL;
6016 /* Backspace over characters that will move to the next line */
6017 if (!fo_white_par)
6018 backspace_until_column(foundcol);
6020 else
6021 #endif
6023 /* put cursor after pos. to break line */
6024 if (!fo_white_par)
6025 curwin->w_cursor.col = foundcol;
6029 * Split the line just before the margin.
6030 * Only insert/delete lines, but don't really redraw the window.
6032 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
6033 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
6034 #ifdef FEAT_COMMENTS
6035 + (do_comments ? OPENLINE_DO_COM : 0)
6036 #endif
6037 , old_indent);
6038 old_indent = 0;
6040 replace_offset = 0;
6041 if (first_line)
6043 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
6044 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
6045 if (second_indent >= 0)
6047 #ifdef FEAT_VREPLACE
6048 if (State & VREPLACE_FLAG)
6049 change_indent(INDENT_SET, second_indent, FALSE, NUL, TRUE);
6050 else
6051 #endif
6052 (void)set_indent(second_indent, SIN_CHANGED);
6054 first_line = FALSE;
6057 #ifdef FEAT_VREPLACE
6058 if (State & VREPLACE_FLAG)
6061 * In VREPLACE mode we have backspaced over the text to be
6062 * moved, now we re-insert it into the new line.
6064 ins_bytes(saved_text);
6065 vim_free(saved_text);
6067 else
6068 #endif
6071 * Check if cursor is not past the NUL off the line, cindent
6072 * may have added or removed indent.
6074 curwin->w_cursor.col += startcol;
6075 len = (colnr_T)STRLEN(ml_get_curline());
6076 if (curwin->w_cursor.col > len)
6077 curwin->w_cursor.col = len;
6080 haveto_redraw = TRUE;
6081 #ifdef FEAT_CINDENT
6082 can_cindent = TRUE;
6083 #endif
6084 /* moved the cursor, don't autoindent or cindent now */
6085 did_ai = FALSE;
6086 #ifdef FEAT_SMARTINDENT
6087 did_si = FALSE;
6088 can_si = FALSE;
6089 can_si_back = FALSE;
6090 #endif
6091 line_breakcheck();
6094 if (save_char != NUL) /* put back space after cursor */
6095 pchar_cursor(save_char);
6097 if (!format_only && haveto_redraw)
6099 update_topline();
6100 redraw_curbuf_later(VALID);
6105 * Called after inserting or deleting text: When 'formatoptions' includes the
6106 * 'a' flag format from the current line until the end of the paragraph.
6107 * Keep the cursor at the same position relative to the text.
6108 * The caller must have saved the cursor line for undo, following ones will be
6109 * saved here.
6111 void
6112 auto_format(trailblank, prev_line)
6113 int trailblank; /* when TRUE also format with trailing blank */
6114 int prev_line; /* may start in previous line */
6116 pos_T pos;
6117 colnr_T len;
6118 char_u *old;
6119 char_u *new, *pnew;
6120 int wasatend;
6121 int cc;
6123 if (!has_format_option(FO_AUTO))
6124 return;
6126 pos = curwin->w_cursor;
6127 old = ml_get_curline();
6129 /* may remove added space */
6130 check_auto_format(FALSE);
6132 /* Don't format in Insert mode when the cursor is on a trailing blank, the
6133 * user might insert normal text next. Also skip formatting when "1" is
6134 * in 'formatoptions' and there is a single character before the cursor.
6135 * Otherwise the line would be broken and when typing another non-white
6136 * next they are not joined back together. */
6137 wasatend = (pos.col == (colnr_T)STRLEN(old));
6138 if (*old != NUL && !trailblank && wasatend)
6140 dec_cursor();
6141 cc = gchar_cursor();
6142 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
6143 && has_format_option(FO_ONE_LETTER))
6144 dec_cursor();
6145 cc = gchar_cursor();
6146 if (WHITECHAR(cc))
6148 curwin->w_cursor = pos;
6149 return;
6151 curwin->w_cursor = pos;
6154 #ifdef FEAT_COMMENTS
6155 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
6156 * comments. */
6157 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
6158 && get_leader_len(old, NULL, FALSE) == 0)
6159 return;
6160 #endif
6163 * May start formatting in a previous line, so that after "x" a word is
6164 * moved to the previous line if it fits there now. Only when this is not
6165 * the start of a paragraph.
6167 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
6169 --curwin->w_cursor.lnum;
6170 if (u_save_cursor() == FAIL)
6171 return;
6175 * Do the formatting and restore the cursor position. "saved_cursor" will
6176 * be adjusted for the text formatting.
6178 saved_cursor = pos;
6179 format_lines((linenr_T)-1, FALSE);
6180 curwin->w_cursor = saved_cursor;
6181 saved_cursor.lnum = 0;
6183 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6185 /* "cannot happen" */
6186 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6187 coladvance((colnr_T)MAXCOL);
6189 else
6190 check_cursor_col();
6192 /* Insert mode: If the cursor is now after the end of the line while it
6193 * previously wasn't, the line was broken. Because of the rule above we
6194 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
6195 * formatted. */
6196 if (!wasatend && has_format_option(FO_WHITE_PAR))
6198 new = ml_get_curline();
6199 len = (colnr_T)STRLEN(new);
6200 if (curwin->w_cursor.col == len)
6202 pnew = vim_strnsave(new, len + 2);
6203 pnew[len] = ' ';
6204 pnew[len + 1] = NUL;
6205 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
6206 /* remove the space later */
6207 did_add_space = TRUE;
6209 else
6210 /* may remove added space */
6211 check_auto_format(FALSE);
6214 check_cursor();
6218 * When an extra space was added to continue a paragraph for auto-formatting,
6219 * delete it now. The space must be under the cursor, just after the insert
6220 * position.
6222 static void
6223 check_auto_format(end_insert)
6224 int end_insert; /* TRUE when ending Insert mode */
6226 int c = ' ';
6227 int cc;
6229 if (did_add_space)
6231 cc = gchar_cursor();
6232 if (!WHITECHAR(cc))
6233 /* Somehow the space was removed already. */
6234 did_add_space = FALSE;
6235 else
6237 if (!end_insert)
6239 inc_cursor();
6240 c = gchar_cursor();
6241 dec_cursor();
6243 if (c != NUL)
6245 /* The space is no longer at the end of the line, delete it. */
6246 del_char(FALSE);
6247 did_add_space = FALSE;
6254 * Find out textwidth to be used for formatting:
6255 * if 'textwidth' option is set, use it
6256 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
6257 * if invalid value, use 0.
6258 * Set default to window width (maximum 79) for "gq" operator.
6261 comp_textwidth(ff)
6262 int ff; /* force formatting (for "gq" command) */
6264 int textwidth;
6266 textwidth = curbuf->b_p_tw;
6267 if (textwidth == 0 && curbuf->b_p_wm)
6269 /* The width is the window width minus 'wrapmargin' minus all the
6270 * things that add to the margin. */
6271 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
6272 #ifdef FEAT_CMDWIN
6273 if (cmdwin_type != 0)
6274 textwidth -= 1;
6275 #endif
6276 #ifdef FEAT_FOLDING
6277 textwidth -= curwin->w_p_fdc;
6278 #endif
6279 #ifdef FEAT_SIGNS
6280 if (curwin->w_buffer->b_signlist != NULL
6281 # ifdef FEAT_NETBEANS_INTG
6282 || usingNetbeans
6283 # endif
6285 textwidth -= 1;
6286 #endif
6287 if (curwin->w_p_nu)
6288 textwidth -= 8;
6290 if (textwidth < 0)
6291 textwidth = 0;
6292 if (ff && textwidth == 0)
6294 textwidth = W_WIDTH(curwin) - 1;
6295 if (textwidth > 79)
6296 textwidth = 79;
6298 return textwidth;
6302 * Put a character in the redo buffer, for when just after a CTRL-V.
6304 static void
6305 redo_literal(c)
6306 int c;
6308 char_u buf[10];
6310 /* Only digits need special treatment. Translate them into a string of
6311 * three digits. */
6312 if (VIM_ISDIGIT(c))
6314 vim_snprintf((char *)buf, sizeof(buf), "%03d", c);
6315 AppendToRedobuff(buf);
6317 else
6318 AppendCharToRedobuff(c);
6322 * start_arrow() is called when an arrow key is used in insert mode.
6323 * For undo/redo it resembles hitting the <ESC> key.
6325 static void
6326 start_arrow(end_insert_pos)
6327 pos_T *end_insert_pos; /* can be NULL */
6329 if (!arrow_used) /* something has been inserted */
6331 AppendToRedobuff(ESC_STR);
6332 stop_insert(end_insert_pos, FALSE);
6333 arrow_used = TRUE; /* this means we stopped the current insert */
6335 #ifdef FEAT_SPELL
6336 check_spell_redraw();
6337 #endif
6340 #ifdef FEAT_SPELL
6342 * If we skipped highlighting word at cursor, do it now.
6343 * It may be skipped again, thus reset spell_redraw_lnum first.
6345 static void
6346 check_spell_redraw()
6348 if (spell_redraw_lnum != 0)
6350 linenr_T lnum = spell_redraw_lnum;
6352 spell_redraw_lnum = 0;
6353 redrawWinline(lnum, FALSE);
6358 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6359 * spelled word, if there is one.
6361 static void
6362 spell_back_to_badword()
6364 pos_T tpos = curwin->w_cursor;
6366 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
6367 if (curwin->w_cursor.col != tpos.col)
6368 start_arrow(&tpos);
6370 #endif
6373 * stop_arrow() is called before a change is made in insert mode.
6374 * If an arrow key has been used, start a new insertion.
6375 * Returns FAIL if undo is impossible, shouldn't insert then.
6378 stop_arrow()
6380 if (arrow_used)
6382 if (u_save_cursor() == OK)
6384 arrow_used = FALSE;
6385 ins_need_undo = FALSE;
6387 Insstart = curwin->w_cursor; /* new insertion starts here */
6388 Insstart_textlen = (colnr_T)linetabsize(ml_get_curline());
6389 ai_col = 0;
6390 #ifdef FEAT_VREPLACE
6391 if (State & VREPLACE_FLAG)
6393 orig_line_count = curbuf->b_ml.ml_line_count;
6394 vr_lines_changed = 1;
6396 #endif
6397 ResetRedobuff();
6398 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
6399 new_insert_skip = 2;
6401 else if (ins_need_undo)
6403 if (u_save_cursor() == OK)
6404 ins_need_undo = FALSE;
6407 #ifdef FEAT_FOLDING
6408 /* Always open fold at the cursor line when inserting something. */
6409 foldOpenCursor();
6410 #endif
6412 return (arrow_used || ins_need_undo ? FAIL : OK);
6416 * Do a few things to stop inserting.
6417 * "end_insert_pos" is where insert ended. It is NULL when we already jumped
6418 * to another window/buffer.
6420 static void
6421 stop_insert(end_insert_pos, esc)
6422 pos_T *end_insert_pos;
6423 int esc; /* called by ins_esc() */
6425 int cc;
6426 char_u *ptr;
6428 stop_redo_ins();
6429 replace_flush(); /* abandon replace stack */
6432 * Save the inserted text for later redo with ^@ and CTRL-A.
6433 * Don't do it when "restart_edit" was set and nothing was inserted,
6434 * otherwise CTRL-O w and then <Left> will clear "last_insert".
6436 ptr = get_inserted();
6437 if (did_restart_edit == 0 || (ptr != NULL
6438 && (int)STRLEN(ptr) > new_insert_skip))
6440 vim_free(last_insert);
6441 last_insert = ptr;
6442 last_insert_skip = new_insert_skip;
6444 else
6445 vim_free(ptr);
6447 if (!arrow_used && end_insert_pos != NULL)
6449 /* Auto-format now. It may seem strange to do this when stopping an
6450 * insertion (or moving the cursor), but it's required when appending
6451 * a line and having it end in a space. But only do it when something
6452 * was actually inserted, otherwise undo won't work. */
6453 if (!ins_need_undo && has_format_option(FO_AUTO))
6455 pos_T tpos = curwin->w_cursor;
6457 /* When the cursor is at the end of the line after a space the
6458 * formatting will move it to the following word. Avoid that by
6459 * moving the cursor onto the space. */
6460 cc = 'x';
6461 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
6463 dec_cursor();
6464 cc = gchar_cursor();
6465 if (!vim_iswhite(cc))
6466 curwin->w_cursor = tpos;
6469 auto_format(TRUE, FALSE);
6471 if (vim_iswhite(cc))
6473 if (gchar_cursor() != NUL)
6474 inc_cursor();
6475 #ifdef FEAT_VIRTUALEDIT
6476 /* If the cursor is still at the same character, also keep
6477 * the "coladd". */
6478 if (gchar_cursor() == NUL
6479 && curwin->w_cursor.lnum == tpos.lnum
6480 && curwin->w_cursor.col == tpos.col)
6481 curwin->w_cursor.coladd = tpos.coladd;
6482 #endif
6486 /* If a space was inserted for auto-formatting, remove it now. */
6487 check_auto_format(TRUE);
6489 /* If we just did an auto-indent, remove the white space from the end
6490 * of the line, and put the cursor back.
6491 * Do this when ESC was used or moving the cursor up/down.
6492 * Check for the old position still being valid, just in case the text
6493 * got changed unexpectedly. */
6494 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6495 && curwin->w_cursor.lnum != end_insert_pos->lnum))
6496 && end_insert_pos->lnum <= curbuf->b_ml.ml_line_count)
6498 pos_T tpos = curwin->w_cursor;
6500 curwin->w_cursor = *end_insert_pos;
6501 check_cursor_col(); /* make sure it is not past the line */
6502 for (;;)
6504 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6505 --curwin->w_cursor.col;
6506 cc = gchar_cursor();
6507 if (!vim_iswhite(cc))
6508 break;
6509 if (del_char(TRUE) == FAIL)
6510 break; /* should not happen */
6512 if (curwin->w_cursor.lnum != tpos.lnum)
6513 curwin->w_cursor = tpos;
6514 else if (cc != NUL)
6515 ++curwin->w_cursor.col; /* put cursor back on the NUL */
6517 #ifdef FEAT_VISUAL
6518 /* <C-S-Right> may have started Visual mode, adjust the position for
6519 * deleted characters. */
6520 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6522 int len = (int)STRLEN(ml_get_curline());
6524 if (VIsual.col > len)
6526 VIsual.col = len;
6527 # ifdef FEAT_VIRTUALEDIT
6528 VIsual.coladd = 0;
6529 # endif
6532 #endif
6535 did_ai = FALSE;
6536 #ifdef FEAT_SMARTINDENT
6537 did_si = FALSE;
6538 can_si = FALSE;
6539 can_si_back = FALSE;
6540 #endif
6542 /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are
6543 * now in a different buffer. */
6544 if (end_insert_pos != NULL)
6546 curbuf->b_op_start = Insstart;
6547 curbuf->b_op_end = *end_insert_pos;
6552 * Set the last inserted text to a single character.
6553 * Used for the replace command.
6555 void
6556 set_last_insert(c)
6557 int c;
6559 char_u *s;
6561 vim_free(last_insert);
6562 #ifdef FEAT_MBYTE
6563 last_insert = alloc(MB_MAXBYTES * 3 + 5);
6564 #else
6565 last_insert = alloc(6);
6566 #endif
6567 if (last_insert != NULL)
6569 s = last_insert;
6570 /* Use the CTRL-V only when entering a special char */
6571 if (c < ' ' || c == DEL)
6572 *s++ = Ctrl_V;
6573 s = add_char2buf(c, s);
6574 *s++ = ESC;
6575 *s++ = NUL;
6576 last_insert_skip = 0;
6580 #if defined(EXITFREE) || defined(PROTO)
6581 void
6582 free_last_insert()
6584 vim_free(last_insert);
6585 last_insert = NULL;
6586 # ifdef FEAT_INS_EXPAND
6587 vim_free(compl_orig_text);
6588 compl_orig_text = NULL;
6589 # endif
6591 #endif
6594 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
6595 * and CSI. Handle multi-byte characters.
6596 * Returns a pointer to after the added bytes.
6598 char_u *
6599 add_char2buf(c, s)
6600 int c;
6601 char_u *s;
6603 #ifdef FEAT_MBYTE
6604 char_u temp[MB_MAXBYTES];
6605 int i;
6606 int len;
6608 len = (*mb_char2bytes)(c, temp);
6609 for (i = 0; i < len; ++i)
6611 c = temp[i];
6612 #endif
6613 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6614 if (c == K_SPECIAL)
6616 *s++ = K_SPECIAL;
6617 *s++ = KS_SPECIAL;
6618 *s++ = KE_FILLER;
6620 #ifdef FEAT_GUI
6621 else if (c == CSI)
6623 *s++ = CSI;
6624 *s++ = KS_EXTRA;
6625 *s++ = (int)KE_CSI;
6627 #endif
6628 else
6629 *s++ = c;
6630 #ifdef FEAT_MBYTE
6632 #endif
6633 return s;
6637 * move cursor to start of line
6638 * if flags & BL_WHITE move to first non-white
6639 * if flags & BL_SOL move to first non-white if startofline is set,
6640 * otherwise keep "curswant" column
6641 * if flags & BL_FIX don't leave the cursor on a NUL.
6643 void
6644 beginline(flags)
6645 int flags;
6647 if ((flags & BL_SOL) && !p_sol)
6648 coladvance(curwin->w_curswant);
6649 else
6651 curwin->w_cursor.col = 0;
6652 #ifdef FEAT_VIRTUALEDIT
6653 curwin->w_cursor.coladd = 0;
6654 #endif
6656 if (flags & (BL_WHITE | BL_SOL))
6658 char_u *ptr;
6660 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6661 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6662 ++curwin->w_cursor.col;
6664 curwin->w_set_curswant = TRUE;
6669 * oneright oneleft cursor_down cursor_up
6671 * Move one char {right,left,down,up}.
6672 * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6673 * Return OK when successful, FAIL when we hit a line of file boundary.
6677 oneright()
6679 char_u *ptr;
6680 int l;
6682 #ifdef FEAT_VIRTUALEDIT
6683 if (virtual_active())
6685 pos_T prevpos = curwin->w_cursor;
6687 /* Adjust for multi-wide char (excluding TAB) */
6688 ptr = ml_get_cursor();
6689 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
6690 # ifdef FEAT_MBYTE
6691 (*mb_ptr2char)(ptr)
6692 # else
6693 *ptr
6694 # endif
6696 ? ptr2cells(ptr) : 1));
6697 curwin->w_set_curswant = TRUE;
6698 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
6699 return (prevpos.col != curwin->w_cursor.col
6700 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
6702 #endif
6704 ptr = ml_get_cursor();
6705 if (*ptr == NUL)
6706 return FAIL; /* already at the very end */
6708 #ifdef FEAT_MBYTE
6709 if (has_mbyte)
6710 l = (*mb_ptr2len)(ptr);
6711 else
6712 #endif
6713 l = 1;
6715 /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
6716 * contains "onemore". */
6717 if (ptr[l] == NUL
6718 #ifdef FEAT_VIRTUALEDIT
6719 && (ve_flags & VE_ONEMORE) == 0
6720 #endif
6722 return FAIL;
6723 curwin->w_cursor.col += l;
6725 curwin->w_set_curswant = TRUE;
6726 return OK;
6730 oneleft()
6732 #ifdef FEAT_VIRTUALEDIT
6733 if (virtual_active())
6735 int width;
6736 int v = getviscol();
6738 if (v == 0)
6739 return FAIL;
6741 # ifdef FEAT_LINEBREAK
6742 /* We might get stuck on 'showbreak', skip over it. */
6743 width = 1;
6744 for (;;)
6746 coladvance(v - width);
6747 /* getviscol() is slow, skip it when 'showbreak' is empty and
6748 * there are no multi-byte characters */
6749 if ((*p_sbr == NUL
6750 # ifdef FEAT_MBYTE
6751 && !has_mbyte
6752 # endif
6753 ) || getviscol() < v)
6754 break;
6755 ++width;
6757 # else
6758 coladvance(v - 1);
6759 # endif
6761 if (curwin->w_cursor.coladd == 1)
6763 char_u *ptr;
6765 /* Adjust for multi-wide char (not a TAB) */
6766 ptr = ml_get_cursor();
6767 if (*ptr != TAB && vim_isprintc(
6768 # ifdef FEAT_MBYTE
6769 (*mb_ptr2char)(ptr)
6770 # else
6771 *ptr
6772 # endif
6773 ) && ptr2cells(ptr) > 1)
6774 curwin->w_cursor.coladd = 0;
6777 curwin->w_set_curswant = TRUE;
6778 return OK;
6780 #endif
6782 if (curwin->w_cursor.col == 0)
6783 return FAIL;
6785 curwin->w_set_curswant = TRUE;
6786 --curwin->w_cursor.col;
6788 #ifdef FEAT_MBYTE
6789 /* if the character on the left of the current cursor is a multi-byte
6790 * character, move to its first byte */
6791 if (has_mbyte)
6792 mb_adjust_cursor();
6793 #endif
6794 return OK;
6798 cursor_up(n, upd_topline)
6799 long n;
6800 int upd_topline; /* When TRUE: update topline */
6802 linenr_T lnum;
6804 if (n > 0)
6806 lnum = curwin->w_cursor.lnum;
6807 /* This fails if the cursor is already in the first line or the count
6808 * is larger than the line number and '-' is in 'cpoptions' */
6809 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6810 return FAIL;
6811 if (n >= lnum)
6812 lnum = 1;
6813 else
6814 #ifdef FEAT_FOLDING
6815 if (hasAnyFolding(curwin))
6818 * Count each sequence of folded lines as one logical line.
6820 /* go to the the start of the current fold */
6821 (void)hasFolding(lnum, &lnum, NULL);
6823 while (n--)
6825 /* move up one line */
6826 --lnum;
6827 if (lnum <= 1)
6828 break;
6829 /* If we entered a fold, move to the beginning, unless in
6830 * Insert mode or when 'foldopen' contains "all": it will open
6831 * in a moment. */
6832 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
6833 (void)hasFolding(lnum, &lnum, NULL);
6835 if (lnum < 1)
6836 lnum = 1;
6838 else
6839 #endif
6840 lnum -= n;
6841 curwin->w_cursor.lnum = lnum;
6844 /* try to advance to the column we want to be at */
6845 coladvance(curwin->w_curswant);
6847 if (upd_topline)
6848 update_topline(); /* make sure curwin->w_topline is valid */
6850 return OK;
6854 * Cursor down a number of logical lines.
6857 cursor_down(n, upd_topline)
6858 long n;
6859 int upd_topline; /* When TRUE: update topline */
6861 linenr_T lnum;
6863 if (n > 0)
6865 lnum = curwin->w_cursor.lnum;
6866 #ifdef FEAT_FOLDING
6867 /* Move to last line of fold, will fail if it's the end-of-file. */
6868 (void)hasFolding(lnum, NULL, &lnum);
6869 #endif
6870 /* This fails if the cursor is already in the last line or would move
6871 * beyound the last line and '-' is in 'cpoptions' */
6872 if (lnum >= curbuf->b_ml.ml_line_count
6873 || (lnum + n > curbuf->b_ml.ml_line_count
6874 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6875 return FAIL;
6876 if (lnum + n >= curbuf->b_ml.ml_line_count)
6877 lnum = curbuf->b_ml.ml_line_count;
6878 else
6879 #ifdef FEAT_FOLDING
6880 if (hasAnyFolding(curwin))
6882 linenr_T last;
6884 /* count each sequence of folded lines as one logical line */
6885 while (n--)
6887 if (hasFolding(lnum, NULL, &last))
6888 lnum = last + 1;
6889 else
6890 ++lnum;
6891 if (lnum >= curbuf->b_ml.ml_line_count)
6892 break;
6894 if (lnum > curbuf->b_ml.ml_line_count)
6895 lnum = curbuf->b_ml.ml_line_count;
6897 else
6898 #endif
6899 lnum += n;
6900 curwin->w_cursor.lnum = lnum;
6903 /* try to advance to the column we want to be at */
6904 coladvance(curwin->w_curswant);
6906 if (upd_topline)
6907 update_topline(); /* make sure curwin->w_topline is valid */
6909 return OK;
6913 * Stuff the last inserted text in the read buffer.
6914 * Last_insert actually is a copy of the redo buffer, so we
6915 * first have to remove the command.
6918 stuff_inserted(c, count, no_esc)
6919 int c; /* Command character to be inserted */
6920 long count; /* Repeat this many times */
6921 int no_esc; /* Don't add an ESC at the end */
6923 char_u *esc_ptr;
6924 char_u *ptr;
6925 char_u *last_ptr;
6926 char_u last = NUL;
6928 ptr = get_last_insert();
6929 if (ptr == NULL)
6931 EMSG(_(e_noinstext));
6932 return FAIL;
6935 /* may want to stuff the command character, to start Insert mode */
6936 if (c != NUL)
6937 stuffcharReadbuff(c);
6938 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
6939 *esc_ptr = NUL; /* remove the ESC */
6941 /* when the last char is either "0" or "^" it will be quoted if no ESC
6942 * comes after it OR if it will inserted more than once and "ptr"
6943 * starts with ^D. -- Acevedo
6945 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
6946 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
6947 && (no_esc || (*ptr == Ctrl_D && count > 1)))
6949 last = *last_ptr;
6950 *last_ptr = NUL;
6955 stuffReadbuff(ptr);
6956 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
6957 if (last)
6958 stuffReadbuff((char_u *)(last == '0'
6959 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
6960 : IF_EB("\026^", CTRL_V_STR "^")));
6962 while (--count > 0);
6964 if (last)
6965 *last_ptr = last;
6967 if (esc_ptr != NULL)
6968 *esc_ptr = ESC; /* put the ESC back */
6970 /* may want to stuff a trailing ESC, to get out of Insert mode */
6971 if (!no_esc)
6972 stuffcharReadbuff(ESC);
6974 return OK;
6977 char_u *
6978 get_last_insert()
6980 if (last_insert == NULL)
6981 return NULL;
6982 return last_insert + last_insert_skip;
6986 * Get last inserted string, and remove trailing <Esc>.
6987 * Returns pointer to allocated memory (must be freed) or NULL.
6989 char_u *
6990 get_last_insert_save()
6992 char_u *s;
6993 int len;
6995 if (last_insert == NULL)
6996 return NULL;
6997 s = vim_strsave(last_insert + last_insert_skip);
6998 if (s != NULL)
7000 len = (int)STRLEN(s);
7001 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
7002 s[len - 1] = NUL;
7004 return s;
7008 * Check the word in front of the cursor for an abbreviation.
7009 * Called when the non-id character "c" has been entered.
7010 * When an abbreviation is recognized it is removed from the text and
7011 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
7013 static int
7014 echeck_abbr(c)
7015 int c;
7017 /* Don't check for abbreviation in paste mode, when disabled and just
7018 * after moving around with cursor keys. */
7019 if (p_paste || no_abbr || arrow_used)
7020 return FALSE;
7022 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
7023 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
7027 * replace-stack functions
7029 * When replacing characters, the replaced characters are remembered for each
7030 * new character. This is used to re-insert the old text when backspacing.
7032 * There is a NUL headed list of characters for each character that is
7033 * currently in the file after the insertion point. When BS is used, one NUL
7034 * headed list is put back for the deleted character.
7036 * For a newline, there are two NUL headed lists. One contains the characters
7037 * that the NL replaced. The extra one stores the characters after the cursor
7038 * that were deleted (always white space).
7040 * Replace_offset is normally 0, in which case replace_push will add a new
7041 * character at the end of the stack. If replace_offset is not 0, that many
7042 * characters will be left on the stack above the newly inserted character.
7045 static char_u *replace_stack = NULL;
7046 static long replace_stack_nr = 0; /* next entry in replace stack */
7047 static long replace_stack_len = 0; /* max. number of entries */
7049 void
7050 replace_push(c)
7051 int c; /* character that is replaced (NUL is none) */
7053 char_u *p;
7055 if (replace_stack_nr < replace_offset) /* nothing to do */
7056 return;
7057 if (replace_stack_len <= replace_stack_nr)
7059 replace_stack_len += 50;
7060 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
7061 if (p == NULL) /* out of memory */
7063 replace_stack_len -= 50;
7064 return;
7066 if (replace_stack != NULL)
7068 mch_memmove(p, replace_stack,
7069 (size_t)(replace_stack_nr * sizeof(char_u)));
7070 vim_free(replace_stack);
7072 replace_stack = p;
7074 p = replace_stack + replace_stack_nr - replace_offset;
7075 if (replace_offset)
7076 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
7077 *p = c;
7078 ++replace_stack_nr;
7081 #if defined(FEAT_MBYTE) || defined(PROTO)
7083 * Push a character onto the replace stack. Handles a multi-byte character in
7084 * reverse byte order, so that the first byte is popped off first.
7085 * Return the number of bytes done (includes composing characters).
7088 replace_push_mb(p)
7089 char_u *p;
7091 int l = (*mb_ptr2len)(p);
7092 int j;
7094 for (j = l - 1; j >= 0; --j)
7095 replace_push(p[j]);
7096 return l;
7098 #endif
7100 #if 0
7102 * call replace_push(c) with replace_offset set to the first NUL.
7104 static void
7105 replace_push_off(c)
7106 int c;
7108 char_u *p;
7110 p = replace_stack + replace_stack_nr;
7111 for (replace_offset = 1; replace_offset < replace_stack_nr;
7112 ++replace_offset)
7113 if (*--p == NUL)
7114 break;
7115 replace_push(c);
7116 replace_offset = 0;
7118 #endif
7121 * Pop one item from the replace stack.
7122 * return -1 if stack empty
7123 * return replaced character or NUL otherwise
7125 static int
7126 replace_pop()
7128 if (replace_stack_nr == 0)
7129 return -1;
7130 return (int)replace_stack[--replace_stack_nr];
7134 * Join the top two items on the replace stack. This removes to "off"'th NUL
7135 * encountered.
7137 static void
7138 replace_join(off)
7139 int off; /* offset for which NUL to remove */
7141 int i;
7143 for (i = replace_stack_nr; --i >= 0; )
7144 if (replace_stack[i] == NUL && off-- <= 0)
7146 --replace_stack_nr;
7147 mch_memmove(replace_stack + i, replace_stack + i + 1,
7148 (size_t)(replace_stack_nr - i));
7149 return;
7154 * Pop bytes from the replace stack until a NUL is found, and insert them
7155 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
7157 static void
7158 replace_pop_ins()
7160 int cc;
7161 int oldState = State;
7163 State = NORMAL; /* don't want REPLACE here */
7164 while ((cc = replace_pop()) > 0)
7166 #ifdef FEAT_MBYTE
7167 mb_replace_pop_ins(cc);
7168 #else
7169 ins_char(cc);
7170 #endif
7171 dec_cursor();
7173 State = oldState;
7176 #ifdef FEAT_MBYTE
7178 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
7179 * indicates a multi-byte char, pop the other bytes too.
7181 static void
7182 mb_replace_pop_ins(cc)
7183 int cc;
7185 int n;
7186 char_u buf[MB_MAXBYTES];
7187 int i;
7188 int c;
7190 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
7192 buf[0] = cc;
7193 for (i = 1; i < n; ++i)
7194 buf[i] = replace_pop();
7195 ins_bytes_len(buf, n);
7197 else
7198 ins_char(cc);
7200 if (enc_utf8)
7201 /* Handle composing chars. */
7202 for (;;)
7204 c = replace_pop();
7205 if (c == -1) /* stack empty */
7206 break;
7207 if ((n = MB_BYTE2LEN(c)) == 1)
7209 /* Not a multi-byte char, put it back. */
7210 replace_push(c);
7211 break;
7213 else
7215 buf[0] = c;
7216 for (i = 1; i < n; ++i)
7217 buf[i] = replace_pop();
7218 if (utf_iscomposing(utf_ptr2char(buf)))
7219 ins_bytes_len(buf, n);
7220 else
7222 /* Not a composing char, put it back. */
7223 for (i = n - 1; i >= 0; --i)
7224 replace_push(buf[i]);
7225 break;
7230 #endif
7233 * make the replace stack empty
7234 * (called when exiting replace mode)
7236 static void
7237 replace_flush()
7239 vim_free(replace_stack);
7240 replace_stack = NULL;
7241 replace_stack_len = 0;
7242 replace_stack_nr = 0;
7246 * Handle doing a BS for one character.
7247 * cc < 0: replace stack empty, just move cursor
7248 * cc == 0: character was inserted, delete it
7249 * cc > 0: character was replaced, put cc (first byte of original char) back
7250 * and check for more characters to be put back
7251 * When "limit_col" is >= 0, don't delete before this column. Matters when
7252 * using composing characters, use del_char_after_col() instead of del_char().
7254 static void
7255 replace_do_bs(limit_col)
7256 int limit_col;
7258 int cc;
7259 #ifdef FEAT_VREPLACE
7260 int orig_len = 0;
7261 int ins_len;
7262 int orig_vcols = 0;
7263 colnr_T start_vcol;
7264 char_u *p;
7265 int i;
7266 int vcol;
7267 #endif
7269 cc = replace_pop();
7270 if (cc > 0)
7272 #ifdef FEAT_VREPLACE
7273 if (State & VREPLACE_FLAG)
7275 /* Get the number of screen cells used by the character we are
7276 * going to delete. */
7277 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
7278 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
7280 #endif
7281 #ifdef FEAT_MBYTE
7282 if (has_mbyte)
7284 (void)del_char_after_col(limit_col);
7285 # ifdef FEAT_VREPLACE
7286 if (State & VREPLACE_FLAG)
7287 orig_len = (int)STRLEN(ml_get_cursor());
7288 # endif
7289 replace_push(cc);
7291 else
7292 #endif
7294 pchar_cursor(cc);
7295 #ifdef FEAT_VREPLACE
7296 if (State & VREPLACE_FLAG)
7297 orig_len = (int)STRLEN(ml_get_cursor()) - 1;
7298 #endif
7300 replace_pop_ins();
7302 #ifdef FEAT_VREPLACE
7303 if (State & VREPLACE_FLAG)
7305 /* Get the number of screen cells used by the inserted characters */
7306 p = ml_get_cursor();
7307 ins_len = (int)STRLEN(p) - orig_len;
7308 vcol = start_vcol;
7309 for (i = 0; i < ins_len; ++i)
7311 vcol += chartabsize(p + i, vcol);
7312 #ifdef FEAT_MBYTE
7313 i += (*mb_ptr2len)(p) - 1;
7314 #endif
7316 vcol -= start_vcol;
7318 /* Delete spaces that were inserted after the cursor to keep the
7319 * text aligned. */
7320 curwin->w_cursor.col += ins_len;
7321 while (vcol > orig_vcols && gchar_cursor() == ' ')
7323 del_char(FALSE);
7324 ++orig_vcols;
7326 curwin->w_cursor.col -= ins_len;
7328 #endif
7330 /* mark the buffer as changed and prepare for displaying */
7331 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
7333 else if (cc == 0)
7334 (void)del_char_after_col(limit_col);
7337 #ifdef FEAT_CINDENT
7339 * Return TRUE if C-indenting is on.
7341 static int
7342 cindent_on()
7344 return (!p_paste && (curbuf->b_p_cin
7345 # ifdef FEAT_EVAL
7346 || *curbuf->b_p_inde != NUL
7347 # endif
7350 #endif
7352 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
7354 * Re-indent the current line, based on the current contents of it and the
7355 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
7356 * confused what all the part that handles Control-T is doing that I'm not.
7357 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
7360 void
7361 fixthisline(get_the_indent)
7362 int (*get_the_indent) __ARGS((void));
7364 change_indent(INDENT_SET, get_the_indent(), FALSE, 0, TRUE);
7365 if (linewhite(curwin->w_cursor.lnum))
7366 did_ai = TRUE; /* delete the indent if the line stays empty */
7369 void
7370 fix_indent()
7372 if (p_paste)
7373 return;
7374 # ifdef FEAT_LISP
7375 if (curbuf->b_p_lisp && curbuf->b_p_ai)
7376 fixthisline(get_lisp_indent);
7377 # endif
7378 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
7379 else
7380 # endif
7381 # ifdef FEAT_CINDENT
7382 if (cindent_on())
7383 do_c_expr_indent();
7384 # endif
7387 #endif
7389 #ifdef FEAT_CINDENT
7391 * return TRUE if 'cinkeys' contains the key "keytyped",
7392 * when == '*': Only if key is preceded with '*' (indent before insert)
7393 * when == '!': Only if key is prededed with '!' (don't insert)
7394 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
7396 * "keytyped" can have a few special values:
7397 * KEY_OPEN_FORW
7398 * KEY_OPEN_BACK
7399 * KEY_COMPLETE just finished completion.
7401 * If line_is_empty is TRUE accept keys with '0' before them.
7404 in_cinkeys(keytyped, when, line_is_empty)
7405 int keytyped;
7406 int when;
7407 int line_is_empty;
7409 char_u *look;
7410 int try_match;
7411 int try_match_word;
7412 char_u *p;
7413 char_u *line;
7414 int icase;
7415 int i;
7417 if (keytyped == NUL)
7418 /* Can happen with CTRL-Y and CTRL-E on a short line. */
7419 return FALSE;
7421 #ifdef FEAT_EVAL
7422 if (*curbuf->b_p_inde != NUL)
7423 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
7424 else
7425 #endif
7426 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
7427 while (*look)
7430 * Find out if we want to try a match with this key, depending on
7431 * 'when' and a '*' or '!' before the key.
7433 switch (when)
7435 case '*': try_match = (*look == '*'); break;
7436 case '!': try_match = (*look == '!'); break;
7437 default: try_match = (*look != '*'); break;
7439 if (*look == '*' || *look == '!')
7440 ++look;
7443 * If there is a '0', only accept a match if the line is empty.
7444 * But may still match when typing last char of a word.
7446 if (*look == '0')
7448 try_match_word = try_match;
7449 if (!line_is_empty)
7450 try_match = FALSE;
7451 ++look;
7453 else
7454 try_match_word = FALSE;
7457 * does it look like a control character?
7459 if (*look == '^'
7460 #ifdef EBCDIC
7461 && (Ctrl_chr(look[1]) != 0)
7462 #else
7463 && look[1] >= '?' && look[1] <= '_'
7464 #endif
7467 if (try_match && keytyped == Ctrl_chr(look[1]))
7468 return TRUE;
7469 look += 2;
7472 * 'o' means "o" command, open forward.
7473 * 'O' means "O" command, open backward.
7475 else if (*look == 'o')
7477 if (try_match && keytyped == KEY_OPEN_FORW)
7478 return TRUE;
7479 ++look;
7481 else if (*look == 'O')
7483 if (try_match && keytyped == KEY_OPEN_BACK)
7484 return TRUE;
7485 ++look;
7489 * 'e' means to check for "else" at start of line and just before the
7490 * cursor.
7492 else if (*look == 'e')
7494 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
7496 p = ml_get_curline();
7497 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
7498 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
7499 return TRUE;
7501 ++look;
7505 * ':' only causes an indent if it is at the end of a label or case
7506 * statement, or when it was before typing the ':' (to fix
7507 * class::method for C++).
7509 else if (*look == ':')
7511 if (try_match && keytyped == ':')
7513 p = ml_get_curline();
7514 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
7515 return TRUE;
7516 /* Need to get the line again after cin_islabel(). */
7517 p = ml_get_curline();
7518 if (curwin->w_cursor.col > 2
7519 && p[curwin->w_cursor.col - 1] == ':'
7520 && p[curwin->w_cursor.col - 2] == ':')
7522 p[curwin->w_cursor.col - 1] = ' ';
7523 i = (cin_iscase(p) || cin_isscopedecl(p)
7524 || cin_islabel(30));
7525 p = ml_get_curline();
7526 p[curwin->w_cursor.col - 1] = ':';
7527 if (i)
7528 return TRUE;
7531 ++look;
7536 * Is it a key in <>, maybe?
7538 else if (*look == '<')
7540 if (try_match)
7543 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7544 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7545 * >, *, : and ! keys if they really really want to.
7547 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7548 && keytyped == look[1])
7549 return TRUE;
7551 if (keytyped == get_special_key_code(look + 1))
7552 return TRUE;
7554 while (*look && *look != '>')
7555 look++;
7556 while (*look == '>')
7557 look++;
7561 * Is it a word: "=word"?
7563 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7565 ++look;
7566 if (*look == '~')
7568 icase = TRUE;
7569 ++look;
7571 else
7572 icase = FALSE;
7573 p = vim_strchr(look, ',');
7574 if (p == NULL)
7575 p = look + STRLEN(look);
7576 if ((try_match || try_match_word)
7577 && curwin->w_cursor.col >= (colnr_T)(p - look))
7579 int match = FALSE;
7581 #ifdef FEAT_INS_EXPAND
7582 if (keytyped == KEY_COMPLETE)
7584 char_u *s;
7586 /* Just completed a word, check if it starts with "look".
7587 * search back for the start of a word. */
7588 line = ml_get_curline();
7589 # ifdef FEAT_MBYTE
7590 if (has_mbyte)
7592 char_u *n;
7594 for (s = line + curwin->w_cursor.col; s > line; s = n)
7596 n = mb_prevptr(line, s);
7597 if (!vim_iswordp(n))
7598 break;
7601 else
7602 # endif
7603 for (s = line + curwin->w_cursor.col; s > line; --s)
7604 if (!vim_iswordc(s[-1]))
7605 break;
7606 if (s + (p - look) <= line + curwin->w_cursor.col
7607 && (icase
7608 ? MB_STRNICMP(s, look, p - look)
7609 : STRNCMP(s, look, p - look)) == 0)
7610 match = TRUE;
7612 else
7613 #endif
7614 /* TODO: multi-byte */
7615 if (keytyped == (int)p[-1] || (icase && keytyped < 256
7616 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7618 line = ml_get_cursor();
7619 if ((curwin->w_cursor.col == (colnr_T)(p - look)
7620 || !vim_iswordc(line[-(p - look) - 1]))
7621 && (icase
7622 ? MB_STRNICMP(line - (p - look), look, p - look)
7623 : STRNCMP(line - (p - look), look, p - look))
7624 == 0)
7625 match = TRUE;
7627 if (match && try_match_word && !try_match)
7629 /* "0=word": Check if there are only blanks before the
7630 * word. */
7631 line = ml_get_curline();
7632 if ((int)(skipwhite(line) - line) !=
7633 (int)(curwin->w_cursor.col - (p - look)))
7634 match = FALSE;
7636 if (match)
7637 return TRUE;
7639 look = p;
7643 * ok, it's a boring generic character.
7645 else
7647 if (try_match && *look == keytyped)
7648 return TRUE;
7649 ++look;
7653 * Skip over ", ".
7655 look = skip_to_option_part(look);
7657 return FALSE;
7659 #endif /* FEAT_CINDENT */
7661 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7663 * Map Hebrew keyboard when in hkmap mode.
7666 hkmap(c)
7667 int c;
7669 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
7671 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7672 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7673 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7674 static char_u map[26] =
7675 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
7676 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
7677 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
7678 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
7679 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
7680 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
7681 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
7682 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
7683 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
7685 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7686 return (int)(map[CharOrd(c)] - 1 + p_aleph);
7687 /* '-1'='sofit' */
7688 else if (c == 'x')
7689 return 'X';
7690 else if (c == 'q')
7691 return '\''; /* {geresh}={'} */
7692 else if (c == 246)
7693 return ' '; /* \"o --> ' ' for a german keyboard */
7694 else if (c == 228)
7695 return ' '; /* \"a --> ' ' -- / -- */
7696 else if (c == 252)
7697 return ' '; /* \"u --> ' ' -- / -- */
7698 #ifdef EBCDIC
7699 else if (islower(c))
7700 #else
7701 /* NOTE: islower() does not do the right thing for us on Linux so we
7702 * do this the same was as 5.7 and previous, so it works correctly on
7703 * all systems. Specifically, the e.g. Delete and Arrow keys are
7704 * munged and won't work if e.g. searching for Hebrew text.
7706 else if (c >= 'a' && c <= 'z')
7707 #endif
7708 return (int)(map[CharOrdLow(c)] + p_aleph);
7709 else
7710 return c;
7712 else
7714 switch (c)
7716 case '`': return ';';
7717 case '/': return '.';
7718 case '\'': return ',';
7719 case 'q': return '/';
7720 case 'w': return '\'';
7722 /* Hebrew letters - set offset from 'a' */
7723 case ',': c = '{'; break;
7724 case '.': c = 'v'; break;
7725 case ';': c = 't'; break;
7726 default: {
7727 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
7729 #ifdef EBCDIC
7730 /* see note about islower() above */
7731 if (!islower(c))
7732 #else
7733 if (c < 'a' || c > 'z')
7734 #endif
7735 return c;
7736 c = str[CharOrdLow(c)];
7737 break;
7741 return (int)(CharOrdLow(c) + p_aleph);
7744 #endif
7746 static void
7747 ins_reg()
7749 int need_redraw = FALSE;
7750 int regname;
7751 int literally = 0;
7752 #ifdef FEAT_VISUAL
7753 int vis_active = VIsual_active;
7754 #endif
7757 * If we are going to wait for a character, show a '"'.
7759 pc_status = PC_STATUS_UNSET;
7760 if (redrawing() && !char_avail())
7762 /* may need to redraw when no more chars available now */
7763 ins_redraw(FALSE);
7765 edit_putchar('"', TRUE);
7766 #ifdef FEAT_CMDL_INFO
7767 add_to_showcmd_c(Ctrl_R);
7768 #endif
7771 #ifdef USE_ON_FLY_SCROLL
7772 dont_scroll = TRUE; /* disallow scrolling here */
7773 #endif
7776 * Don't map the register name. This also prevents the mode message to be
7777 * deleted when ESC is hit.
7779 ++no_mapping;
7780 regname = plain_vgetc();
7781 LANGMAP_ADJUST(regname, TRUE);
7782 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
7784 /* Get a third key for literal register insertion */
7785 literally = regname;
7786 #ifdef FEAT_CMDL_INFO
7787 add_to_showcmd_c(literally);
7788 #endif
7789 regname = plain_vgetc();
7790 LANGMAP_ADJUST(regname, TRUE);
7792 --no_mapping;
7794 #ifdef FEAT_EVAL
7796 * Don't call u_sync() while getting the expression,
7797 * evaluating it or giving an error message for it!
7799 ++no_u_sync;
7800 if (regname == '=')
7802 # ifdef USE_IM_CONTROL
7803 int im_on = im_get_status();
7804 # endif
7805 regname = get_expr_register();
7806 # ifdef USE_IM_CONTROL
7807 /* Restore the Input Method. */
7808 if (im_on)
7809 im_set_active(TRUE);
7810 # endif
7812 if (regname == NUL || !valid_yank_reg(regname, FALSE))
7814 vim_beep();
7815 need_redraw = TRUE; /* remove the '"' */
7817 else
7819 #endif
7820 if (literally == Ctrl_O || literally == Ctrl_P)
7822 /* Append the command to the redo buffer. */
7823 AppendCharToRedobuff(Ctrl_R);
7824 AppendCharToRedobuff(literally);
7825 AppendCharToRedobuff(regname);
7827 do_put(regname, BACKWARD, 1L,
7828 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
7830 else if (insert_reg(regname, literally) == FAIL)
7832 vim_beep();
7833 need_redraw = TRUE; /* remove the '"' */
7835 else if (stop_insert_mode)
7836 /* When the '=' register was used and a function was invoked that
7837 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
7838 * insert anything, need to remove the '"' */
7839 need_redraw = TRUE;
7841 #ifdef FEAT_EVAL
7843 --no_u_sync;
7844 #endif
7845 #ifdef FEAT_CMDL_INFO
7846 clear_showcmd();
7847 #endif
7849 /* If the inserted register is empty, we need to remove the '"' */
7850 if (need_redraw || stuff_empty())
7851 edit_unputchar();
7853 #ifdef FEAT_VISUAL
7854 /* Disallow starting Visual mode here, would get a weird mode. */
7855 if (!vis_active && VIsual_active)
7856 end_visual_mode();
7857 #endif
7861 * CTRL-G commands in Insert mode.
7863 static void
7864 ins_ctrl_g()
7866 int c;
7868 #ifdef FEAT_INS_EXPAND
7869 /* Right after CTRL-X the cursor will be after the ruler. */
7870 setcursor();
7871 #endif
7874 * Don't map the second key. This also prevents the mode message to be
7875 * deleted when ESC is hit.
7877 ++no_mapping;
7878 c = plain_vgetc();
7879 --no_mapping;
7880 switch (c)
7882 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
7883 case K_UP:
7884 case Ctrl_K:
7885 case 'k': ins_up(TRUE);
7886 break;
7888 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
7889 case K_DOWN:
7890 case Ctrl_J:
7891 case 'j': ins_down(TRUE);
7892 break;
7894 /* CTRL-G u: start new undoable edit */
7895 case 'u': u_sync(TRUE);
7896 ins_need_undo = TRUE;
7898 /* Need to reset Insstart, esp. because a BS that joins
7899 * a line to the previous one must save for undo. */
7900 Insstart = curwin->w_cursor;
7901 break;
7903 /* Unknown CTRL-G command, reserved for future expansion. */
7904 default: vim_beep();
7909 * CTRL-^ in Insert mode.
7911 static void
7912 ins_ctrl_hat()
7914 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
7916 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
7917 if (State & LANGMAP)
7919 curbuf->b_p_iminsert = B_IMODE_NONE;
7920 State &= ~LANGMAP;
7922 else
7924 curbuf->b_p_iminsert = B_IMODE_LMAP;
7925 State |= LANGMAP;
7926 #ifdef USE_IM_CONTROL
7927 im_set_active(FALSE);
7928 #endif
7931 #ifdef USE_IM_CONTROL
7932 else
7934 /* There are no ":lmap" mappings, toggle IM */
7935 if (im_get_status())
7937 curbuf->b_p_iminsert = B_IMODE_NONE;
7938 im_set_active(FALSE);
7940 else
7942 curbuf->b_p_iminsert = B_IMODE_IM;
7943 State &= ~LANGMAP;
7944 im_set_active(TRUE);
7947 #endif
7948 set_iminsert_global();
7949 showmode();
7950 #ifdef FEAT_GUI
7951 /* may show different cursor shape or color */
7952 if (gui.in_use)
7953 gui_update_cursor(TRUE, FALSE);
7954 #endif
7955 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
7956 /* Show/unshow value of 'keymap' in status lines. */
7957 status_redraw_curbuf();
7958 #endif
7962 * Handle ESC in insert mode.
7963 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
7964 * insert.
7966 static int
7967 ins_esc(count, cmdchar, nomove)
7968 long *count;
7969 int cmdchar;
7970 int nomove; /* don't move cursor */
7972 int temp;
7973 static int disabled_redraw = FALSE;
7975 #ifdef FEAT_SPELL
7976 check_spell_redraw();
7977 #endif
7978 #if defined(FEAT_HANGULIN)
7979 # if defined(ESC_CHG_TO_ENG_MODE)
7980 hangul_input_state_set(0);
7981 # endif
7982 if (composing_hangul)
7984 push_raw_key(composing_hangul_buffer, 2);
7985 composing_hangul = 0;
7987 #endif
7989 temp = curwin->w_cursor.col;
7990 if (disabled_redraw)
7992 --RedrawingDisabled;
7993 disabled_redraw = FALSE;
7995 if (!arrow_used)
7998 * Don't append the ESC for "r<CR>" and "grx".
7999 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
8000 * when "count" is non-zero.
8002 if (cmdchar != 'r' && cmdchar != 'v')
8003 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
8006 * Repeating insert may take a long time. Check for
8007 * interrupt now and then.
8009 if (*count > 0)
8011 line_breakcheck();
8012 if (got_int)
8013 *count = 0;
8016 if (--*count > 0) /* repeat what was typed */
8018 /* Vi repeats the insert without replacing characters. */
8019 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
8020 State &= ~REPLACE_FLAG;
8022 (void)start_redo_ins();
8023 if (cmdchar == 'r' || cmdchar == 'v')
8024 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
8025 ++RedrawingDisabled;
8026 disabled_redraw = TRUE;
8027 return FALSE; /* repeat the insert */
8029 stop_insert(&curwin->w_cursor, TRUE);
8030 undisplay_dollar();
8033 /* When an autoindent was removed, curswant stays after the
8034 * indent */
8035 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
8036 curwin->w_set_curswant = TRUE;
8038 /* Remember the last Insert position in the '^ mark. */
8039 if (!cmdmod.keepjumps)
8040 curbuf->b_last_insert = curwin->w_cursor;
8043 * The cursor should end up on the last inserted character.
8044 * Don't do it for CTRL-O, unless past the end of the line.
8046 if (!nomove
8047 && (curwin->w_cursor.col != 0
8048 #ifdef FEAT_VIRTUALEDIT
8049 || curwin->w_cursor.coladd > 0
8050 #endif
8052 && (restart_edit == NUL
8053 || (gchar_cursor() == NUL
8054 #ifdef FEAT_VISUAL
8055 && !VIsual_active
8056 #endif
8058 #ifdef FEAT_RIGHTLEFT
8059 && !revins_on
8060 #endif
8063 #ifdef FEAT_VIRTUALEDIT
8064 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
8066 oneleft();
8067 if (restart_edit != NUL)
8068 ++curwin->w_cursor.coladd;
8070 else
8071 #endif
8073 --curwin->w_cursor.col;
8074 #ifdef FEAT_MBYTE
8075 /* Correct cursor for multi-byte character. */
8076 if (has_mbyte)
8077 mb_adjust_cursor();
8078 #endif
8082 #ifdef USE_IM_CONTROL
8083 /* Disable IM to allow typing English directly for Normal mode commands.
8084 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
8085 * well). */
8086 if (!(State & LANGMAP))
8087 im_save_status(&curbuf->b_p_iminsert);
8088 im_set_active(FALSE);
8089 #endif
8091 State = NORMAL;
8092 /* need to position cursor again (e.g. when on a TAB ) */
8093 changed_cline_bef_curs();
8095 #ifdef FEAT_MOUSE
8096 setmouse();
8097 #endif
8098 #ifdef CURSOR_SHAPE
8099 ui_cursor_shape(); /* may show different cursor shape */
8100 #endif
8103 * When recording or for CTRL-O, need to display the new mode.
8104 * Otherwise remove the mode message.
8106 if (Recording || restart_edit != NUL)
8107 showmode();
8108 else if (p_smd)
8109 MSG("");
8111 return TRUE; /* exit Insert mode */
8114 #ifdef FEAT_RIGHTLEFT
8116 * Toggle language: hkmap and revins_on.
8117 * Move to end of reverse inserted text.
8119 static void
8120 ins_ctrl_()
8122 if (revins_on && revins_chars && revins_scol >= 0)
8124 while (gchar_cursor() != NUL && revins_chars--)
8125 ++curwin->w_cursor.col;
8127 p_ri = !p_ri;
8128 revins_on = (State == INSERT && p_ri);
8129 if (revins_on)
8131 revins_scol = curwin->w_cursor.col;
8132 revins_legal++;
8133 revins_chars = 0;
8134 undisplay_dollar();
8136 else
8137 revins_scol = -1;
8138 #ifdef FEAT_FKMAP
8139 if (p_altkeymap)
8142 * to be consistent also for redo command, using '.'
8143 * set arrow_used to true and stop it - causing to redo
8144 * characters entered in one mode (normal/reverse insert).
8146 arrow_used = TRUE;
8147 (void)stop_arrow();
8148 p_fkmap = curwin->w_p_rl ^ p_ri;
8149 if (p_fkmap && p_ri)
8150 State = INSERT;
8152 else
8153 #endif
8154 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
8155 showmode();
8157 #endif
8159 #ifdef FEAT_VISUAL
8161 * If 'keymodel' contains "startsel", may start selection.
8162 * Returns TRUE when a CTRL-O and other keys stuffed.
8164 static int
8165 ins_start_select(c)
8166 int c;
8168 if (km_startsel)
8169 switch (c)
8171 case K_KHOME:
8172 case K_KEND:
8173 case K_PAGEUP:
8174 case K_KPAGEUP:
8175 case K_PAGEDOWN:
8176 case K_KPAGEDOWN:
8177 # ifdef MACOS
8178 case K_LEFT:
8179 case K_RIGHT:
8180 case K_UP:
8181 case K_DOWN:
8182 case K_END:
8183 case K_HOME:
8184 # endif
8185 if (!(mod_mask & MOD_MASK_SHIFT))
8186 break;
8187 /* FALLTHROUGH */
8188 case K_S_LEFT:
8189 case K_S_RIGHT:
8190 case K_S_UP:
8191 case K_S_DOWN:
8192 case K_S_END:
8193 case K_S_HOME:
8194 /* Start selection right away, the cursor can move with
8195 * CTRL-O when beyond the end of the line. */
8196 start_selection();
8198 /* Execute the key in (insert) Select mode. */
8199 stuffcharReadbuff(Ctrl_O);
8200 if (mod_mask)
8202 char_u buf[4];
8204 buf[0] = K_SPECIAL;
8205 buf[1] = KS_MODIFIER;
8206 buf[2] = mod_mask;
8207 buf[3] = NUL;
8208 stuffReadbuff(buf);
8210 stuffcharReadbuff(c);
8211 return TRUE;
8213 return FALSE;
8215 #endif
8218 * <Insert> key in Insert mode: toggle insert/remplace mode.
8220 static void
8221 ins_insert(replaceState)
8222 int replaceState;
8224 #ifdef FEAT_FKMAP
8225 if (p_fkmap && p_ri)
8227 beep_flush();
8228 EMSG(farsi_text_3); /* encoded in Farsi */
8229 return;
8231 #endif
8233 #ifdef FEAT_AUTOCMD
8234 # ifdef FEAT_EVAL
8235 set_vim_var_string(VV_INSERTMODE,
8236 (char_u *)((State & REPLACE_FLAG) ? "i" :
8237 # ifdef FEAT_VREPLACE
8238 replaceState == VREPLACE ? "v" :
8239 # endif
8240 "r"), 1);
8241 # endif
8242 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
8243 #endif
8244 if (State & REPLACE_FLAG)
8245 State = INSERT | (State & LANGMAP);
8246 else
8247 State = replaceState | (State & LANGMAP);
8248 AppendCharToRedobuff(K_INS);
8249 showmode();
8250 #ifdef CURSOR_SHAPE
8251 ui_cursor_shape(); /* may show different cursor shape */
8252 #endif
8256 * Pressed CTRL-O in Insert mode.
8258 static void
8259 ins_ctrl_o()
8261 #ifdef FEAT_VREPLACE
8262 if (State & VREPLACE_FLAG)
8263 restart_edit = 'V';
8264 else
8265 #endif
8266 if (State & REPLACE_FLAG)
8267 restart_edit = 'R';
8268 else
8269 restart_edit = 'I';
8270 #ifdef FEAT_VIRTUALEDIT
8271 if (virtual_active())
8272 ins_at_eol = FALSE; /* cursor always keeps its column */
8273 else
8274 #endif
8275 ins_at_eol = (gchar_cursor() == NUL);
8279 * If the cursor is on an indent, ^T/^D insert/delete one
8280 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
8281 * Always round the indent to 'shiftwidth', this is compatible
8282 * with vi. But vi only supports ^T and ^D after an
8283 * autoindent, we support it everywhere.
8285 static void
8286 ins_shift(c, lastc)
8287 int c;
8288 int lastc;
8290 if (stop_arrow() == FAIL)
8291 return;
8292 AppendCharToRedobuff(c);
8295 * 0^D and ^^D: remove all indent.
8297 if (c == Ctrl_D && (lastc == '0' || lastc == '^')
8298 && curwin->w_cursor.col > 0)
8300 --curwin->w_cursor.col;
8301 (void)del_char(FALSE); /* delete the '^' or '0' */
8302 /* In Replace mode, restore the characters that '^' or '0' replaced. */
8303 if (State & REPLACE_FLAG)
8304 replace_pop_ins();
8305 if (lastc == '^')
8306 old_indent = get_indent(); /* remember curr. indent */
8307 change_indent(INDENT_SET, 0, TRUE, 0, TRUE);
8309 else
8310 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE);
8312 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
8313 did_ai = FALSE;
8314 #ifdef FEAT_SMARTINDENT
8315 did_si = FALSE;
8316 can_si = FALSE;
8317 can_si_back = FALSE;
8318 #endif
8319 #ifdef FEAT_CINDENT
8320 can_cindent = FALSE; /* no cindenting after ^D or ^T */
8321 #endif
8324 static void
8325 ins_del()
8327 int temp;
8329 if (stop_arrow() == FAIL)
8330 return;
8331 if (gchar_cursor() == NUL) /* delete newline */
8333 temp = curwin->w_cursor.col;
8334 if (!can_bs(BS_EOL) /* only if "eol" included */
8335 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
8336 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
8337 || do_join(FALSE) == FAIL)
8338 vim_beep();
8339 else
8340 curwin->w_cursor.col = temp;
8342 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
8343 vim_beep();
8344 did_ai = FALSE;
8345 #ifdef FEAT_SMARTINDENT
8346 did_si = FALSE;
8347 can_si = FALSE;
8348 can_si_back = FALSE;
8349 #endif
8350 AppendCharToRedobuff(K_DEL);
8353 static void ins_bs_one __ARGS((colnr_T *vcolp));
8356 * Delete one character for ins_bs().
8358 static void
8359 ins_bs_one(vcolp)
8360 colnr_T *vcolp;
8362 dec_cursor();
8363 getvcol(curwin, &curwin->w_cursor, vcolp, NULL, NULL);
8364 if (State & REPLACE_FLAG)
8366 /* Don't delete characters before the insert point when in
8367 * Replace mode */
8368 if (curwin->w_cursor.lnum != Insstart.lnum
8369 || curwin->w_cursor.col >= Insstart.col)
8370 replace_do_bs(-1);
8372 else
8373 (void)del_char(FALSE);
8377 * Handle Backspace, delete-word and delete-line in Insert mode.
8378 * Return TRUE when backspace was actually used.
8380 static int
8381 ins_bs(c, mode, inserted_space_p)
8382 int c;
8383 int mode;
8384 int *inserted_space_p;
8386 linenr_T lnum;
8387 int cc;
8388 int temp = 0; /* init for GCC */
8389 colnr_T save_col;
8390 colnr_T mincol;
8391 int did_backspace = FALSE;
8392 int in_indent;
8393 int oldState;
8394 #ifdef FEAT_MBYTE
8395 int cpc[MAX_MCO]; /* composing characters */
8396 #endif
8399 * can't delete anything in an empty file
8400 * can't backup past first character in buffer
8401 * can't backup past starting point unless 'backspace' > 1
8402 * can backup to a previous line if 'backspace' == 0
8404 if ( bufempty()
8405 || (
8406 #ifdef FEAT_RIGHTLEFT
8407 !revins_on &&
8408 #endif
8409 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
8410 || (!can_bs(BS_START)
8411 && (arrow_used
8412 || (curwin->w_cursor.lnum == Insstart.lnum
8413 && curwin->w_cursor.col <= Insstart.col)))
8414 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
8415 && curwin->w_cursor.col <= ai_col)
8416 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
8418 vim_beep();
8419 return FALSE;
8422 if (stop_arrow() == FAIL)
8423 return FALSE;
8424 in_indent = inindent(0);
8425 #ifdef FEAT_CINDENT
8426 if (in_indent)
8427 can_cindent = FALSE;
8428 #endif
8429 #ifdef FEAT_COMMENTS
8430 end_comment_pending = NUL; /* After BS, don't auto-end comment */
8431 #endif
8432 #ifdef FEAT_RIGHTLEFT
8433 if (revins_on) /* put cursor after last inserted char */
8434 inc_cursor();
8435 #endif
8437 #ifdef FEAT_VIRTUALEDIT
8438 /* Virtualedit:
8439 * BACKSPACE_CHAR eats a virtual space
8440 * BACKSPACE_WORD eats all coladd
8441 * BACKSPACE_LINE eats all coladd and keeps going
8443 if (curwin->w_cursor.coladd > 0)
8445 if (mode == BACKSPACE_CHAR)
8447 --curwin->w_cursor.coladd;
8448 return TRUE;
8450 if (mode == BACKSPACE_WORD)
8452 curwin->w_cursor.coladd = 0;
8453 return TRUE;
8455 curwin->w_cursor.coladd = 0;
8457 #endif
8460 * delete newline!
8462 if (curwin->w_cursor.col == 0)
8464 lnum = Insstart.lnum;
8465 if (curwin->w_cursor.lnum == Insstart.lnum
8466 #ifdef FEAT_RIGHTLEFT
8467 || revins_on
8468 #endif
8471 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
8472 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
8473 return FALSE;
8474 --Insstart.lnum;
8475 Insstart.col = MAXCOL;
8478 * In replace mode:
8479 * cc < 0: NL was inserted, delete it
8480 * cc >= 0: NL was replaced, put original characters back
8482 cc = -1;
8483 if (State & REPLACE_FLAG)
8484 cc = replace_pop(); /* returns -1 if NL was inserted */
8486 * In replace mode, in the line we started replacing, we only move the
8487 * cursor.
8489 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
8491 dec_cursor();
8493 else
8495 #ifdef FEAT_VREPLACE
8496 if (!(State & VREPLACE_FLAG)
8497 || curwin->w_cursor.lnum > orig_line_count)
8498 #endif
8500 temp = gchar_cursor(); /* remember current char */
8501 --curwin->w_cursor.lnum;
8503 /* When "aw" is in 'formatoptions' we must delete the space at
8504 * the end of the line, otherwise the line will be broken
8505 * again when auto-formatting. */
8506 if (has_format_option(FO_AUTO)
8507 && has_format_option(FO_WHITE_PAR))
8509 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
8510 TRUE);
8511 int len;
8513 len = (int)STRLEN(ptr);
8514 if (len > 0 && ptr[len - 1] == ' ')
8515 ptr[len - 1] = NUL;
8518 (void)do_join(FALSE);
8519 if (temp == NUL && gchar_cursor() != NUL)
8520 inc_cursor();
8522 #ifdef FEAT_VREPLACE
8523 else
8524 dec_cursor();
8525 #endif
8528 * In REPLACE mode we have to put back the text that was replaced
8529 * by the NL. On the replace stack is first a NUL-terminated
8530 * sequence of characters that were deleted and then the
8531 * characters that NL replaced.
8533 if (State & REPLACE_FLAG)
8536 * Do the next ins_char() in NORMAL state, to
8537 * prevent ins_char() from replacing characters and
8538 * avoiding showmatch().
8540 oldState = State;
8541 State = NORMAL;
8543 * restore characters (blanks) deleted after cursor
8545 while (cc > 0)
8547 save_col = curwin->w_cursor.col;
8548 #ifdef FEAT_MBYTE
8549 mb_replace_pop_ins(cc);
8550 #else
8551 ins_char(cc);
8552 #endif
8553 curwin->w_cursor.col = save_col;
8554 cc = replace_pop();
8556 /* restore the characters that NL replaced */
8557 replace_pop_ins();
8558 State = oldState;
8561 did_ai = FALSE;
8563 else
8566 * Delete character(s) before the cursor.
8568 #ifdef FEAT_RIGHTLEFT
8569 if (revins_on) /* put cursor on last inserted char */
8570 dec_cursor();
8571 #endif
8572 mincol = 0;
8573 /* keep indent */
8574 if (mode == BACKSPACE_LINE
8575 && (curbuf->b_p_ai
8576 #ifdef FEAT_CINDENT
8577 || cindent_on()
8578 #endif
8580 #ifdef FEAT_RIGHTLEFT
8581 && !revins_on
8582 #endif
8585 save_col = curwin->w_cursor.col;
8586 beginline(BL_WHITE);
8587 if (curwin->w_cursor.col < save_col)
8588 mincol = curwin->w_cursor.col;
8589 curwin->w_cursor.col = save_col;
8593 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8595 if ( mode == BACKSPACE_CHAR
8596 && ((p_sta && in_indent)
8597 || (
8598 #ifdef FEAT_VARTABS
8599 (tabstop_count(curbuf->b_p_vsts_ary) != 0
8600 || curbuf->b_p_sts != 0)
8601 #else
8602 curbuf->b_p_sts != 0
8603 #endif
8604 && curwin->w_cursor.col > 0
8605 && (*(ml_get_cursor() - 1) == TAB
8606 || (*(ml_get_cursor() - 1) == ' '
8607 && (!*inserted_space_p
8608 || arrow_used))))))
8610 #ifndef FEAT_VARTABS
8611 int ts;
8612 #endif
8613 colnr_T vcol;
8614 colnr_T want_vcol;
8615 colnr_T start_vcol;
8617 *inserted_space_p = FALSE;
8618 #ifndef FEAT_VARTABS
8619 if (p_sta && in_indent)
8620 ts = curbuf->b_p_sw;
8621 else
8622 ts = curbuf->b_p_sts;
8623 #endif
8624 /* Compute the virtual column where we want to be. Since
8625 * 'showbreak' may get in the way, need to get the last column of
8626 * the previous character. */
8627 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8628 start_vcol = vcol;
8629 dec_cursor();
8630 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8631 inc_cursor();
8632 #ifdef FEAT_VARTABS
8633 if (p_sta && in_indent)
8634 want_vcol = (want_vcol / curbuf->b_p_sw) * curbuf->b_p_sw;
8635 else
8636 want_vcol = tabstop_start(want_vcol, curbuf->b_p_sts,
8637 curbuf->b_p_vsts_ary);
8638 #else
8639 want_vcol = (want_vcol / ts) * ts;
8640 #endif
8642 /* delete characters until we are at or before want_vcol */
8643 while (vcol > want_vcol
8644 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8645 ins_bs_one(&vcol);
8647 /* insert extra spaces until we are at want_vcol */
8648 while (vcol < want_vcol)
8650 /* Remember the first char we inserted */
8651 if (curwin->w_cursor.lnum == Insstart.lnum
8652 && curwin->w_cursor.col < Insstart.col)
8653 Insstart.col = curwin->w_cursor.col;
8655 #ifdef FEAT_VREPLACE
8656 if (State & VREPLACE_FLAG)
8657 ins_char(' ');
8658 else
8659 #endif
8661 ins_str((char_u *)" ");
8662 if ((State & REPLACE_FLAG))
8663 replace_push(NUL);
8665 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8668 /* If we are now back where we started delete one character. Can
8669 * happen when using 'sts' and 'linebreak'. */
8670 if (vcol >= start_vcol)
8671 ins_bs_one(&vcol);
8675 * Delete upto starting point, start of line or previous word.
8677 else do
8679 #ifdef FEAT_RIGHTLEFT
8680 if (!revins_on) /* put cursor on char to be deleted */
8681 #endif
8682 dec_cursor();
8684 /* start of word? */
8685 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8687 mode = BACKSPACE_WORD_NOT_SPACE;
8688 temp = vim_iswordc(gchar_cursor());
8690 /* end of word? */
8691 else if (mode == BACKSPACE_WORD_NOT_SPACE
8692 && (vim_isspace(cc = gchar_cursor())
8693 || vim_iswordc(cc) != temp))
8695 #ifdef FEAT_RIGHTLEFT
8696 if (!revins_on)
8697 #endif
8698 inc_cursor();
8699 #ifdef FEAT_RIGHTLEFT
8700 else if (State & REPLACE_FLAG)
8701 dec_cursor();
8702 #endif
8703 break;
8705 if (State & REPLACE_FLAG)
8706 replace_do_bs(-1);
8707 else
8709 #ifdef FEAT_MBYTE
8710 if (enc_utf8 && p_deco)
8711 (void)utfc_ptr2char(ml_get_cursor(), cpc);
8712 #endif
8713 (void)del_char(FALSE);
8714 #ifdef FEAT_MBYTE
8716 * If there are combining characters and 'delcombine' is set
8717 * move the cursor back. Don't back up before the base
8718 * character.
8720 if (enc_utf8 && p_deco && cpc[0] != NUL)
8721 inc_cursor();
8722 #endif
8723 #ifdef FEAT_RIGHTLEFT
8724 if (revins_chars)
8726 revins_chars--;
8727 revins_legal++;
8729 if (revins_on && gchar_cursor() == NUL)
8730 break;
8731 #endif
8733 /* Just a single backspace?: */
8734 if (mode == BACKSPACE_CHAR)
8735 break;
8736 } while (
8737 #ifdef FEAT_RIGHTLEFT
8738 revins_on ||
8739 #endif
8740 (curwin->w_cursor.col > mincol
8741 && (curwin->w_cursor.lnum != Insstart.lnum
8742 || curwin->w_cursor.col != Insstart.col)));
8743 did_backspace = TRUE;
8745 #ifdef FEAT_SMARTINDENT
8746 did_si = FALSE;
8747 can_si = FALSE;
8748 can_si_back = FALSE;
8749 #endif
8750 if (curwin->w_cursor.col <= 1)
8751 did_ai = FALSE;
8753 * It's a little strange to put backspaces into the redo
8754 * buffer, but it makes auto-indent a lot easier to deal
8755 * with.
8757 AppendCharToRedobuff(c);
8759 /* If deleted before the insertion point, adjust it */
8760 if (curwin->w_cursor.lnum == Insstart.lnum
8761 && curwin->w_cursor.col < Insstart.col)
8762 Insstart.col = curwin->w_cursor.col;
8764 /* vi behaviour: the cursor moves backward but the character that
8765 * was there remains visible
8766 * Vim behaviour: the cursor moves backward and the character that
8767 * was there is erased from the screen.
8768 * We can emulate the vi behaviour by pretending there is a dollar
8769 * displayed even when there isn't.
8770 * --pkv Sun Jan 19 01:56:40 EST 2003 */
8771 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
8772 dollar_vcol = curwin->w_virtcol;
8774 #ifdef FEAT_FOLDING
8775 /* When deleting a char the cursor line must never be in a closed fold.
8776 * E.g., when 'foldmethod' is indent and deleting the first non-white
8777 * char before a Tab. */
8778 if (did_backspace)
8779 foldOpenCursor();
8780 #endif
8782 return did_backspace;
8785 #ifdef FEAT_MOUSE
8786 static void
8787 ins_mouse(c)
8788 int c;
8790 pos_T tpos;
8791 win_T *old_curwin = curwin;
8793 # ifdef FEAT_GUI
8794 /* When GUI is active, also move/paste when 'mouse' is empty */
8795 if (!gui.in_use)
8796 # endif
8797 if (!mouse_has(MOUSE_INSERT))
8798 return;
8800 undisplay_dollar();
8801 tpos = curwin->w_cursor;
8802 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
8804 #ifdef FEAT_WINDOWS
8805 win_T *new_curwin = curwin;
8807 if (curwin != old_curwin && win_valid(old_curwin))
8809 /* Mouse took us to another window. We need to go back to the
8810 * previous one to stop insert there properly. */
8811 curwin = old_curwin;
8812 curbuf = curwin->w_buffer;
8814 #endif
8815 start_arrow(curwin == old_curwin ? &tpos : NULL);
8816 #ifdef FEAT_WINDOWS
8817 if (curwin != new_curwin && win_valid(new_curwin))
8819 curwin = new_curwin;
8820 curbuf = curwin->w_buffer;
8822 #endif
8823 # ifdef FEAT_CINDENT
8824 can_cindent = TRUE;
8825 # endif
8828 #ifdef FEAT_WINDOWS
8829 /* redraw status lines (in case another window became active) */
8830 redraw_statuslines();
8831 #endif
8834 static void
8835 ins_mousescroll(up)
8836 int up;
8838 pos_T tpos;
8839 # if defined(FEAT_WINDOWS)
8840 win_T *old_curwin = curwin;
8841 # endif
8842 # ifdef FEAT_INS_EXPAND
8843 int did_scroll = FALSE;
8844 # endif
8846 tpos = curwin->w_cursor;
8848 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8849 /* Currently the mouse coordinates are only known in the GUI. */
8850 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
8852 int row, col;
8854 row = mouse_row;
8855 col = mouse_col;
8857 /* find the window at the pointer coordinates */
8858 curwin = mouse_find_win(&row, &col);
8859 curbuf = curwin->w_buffer;
8861 if (curwin == old_curwin)
8862 # endif
8863 undisplay_dollar();
8865 # ifdef FEAT_INS_EXPAND
8866 /* Don't scroll the window in which completion is being done. */
8867 if (!pum_visible()
8868 # if defined(FEAT_WINDOWS)
8869 || curwin != old_curwin
8870 # endif
8872 # endif
8874 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
8875 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
8876 else
8877 scroll_redraw(up, 3L);
8878 # ifdef FEAT_INS_EXPAND
8879 did_scroll = TRUE;
8880 # endif
8883 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8884 curwin->w_redr_status = TRUE;
8886 curwin = old_curwin;
8887 curbuf = curwin->w_buffer;
8888 # endif
8890 # ifdef FEAT_INS_EXPAND
8891 /* The popup menu may overlay the window, need to redraw it.
8892 * TODO: Would be more efficient to only redraw the windows that are
8893 * overlapped by the popup menu. */
8894 if (pum_visible() && did_scroll)
8896 redraw_all_later(NOT_VALID);
8897 ins_compl_show_pum();
8899 # endif
8901 if (!equalpos(curwin->w_cursor, tpos))
8903 start_arrow(&tpos);
8904 # ifdef FEAT_CINDENT
8905 can_cindent = TRUE;
8906 # endif
8909 #endif
8911 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
8912 static void
8913 ins_tabline(c)
8914 int c;
8916 /* We will be leaving the current window, unless closing another tab. */
8917 if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
8918 || (current_tab != 0 && current_tab != tabpage_index(curtab)))
8920 undisplay_dollar();
8921 start_arrow(&curwin->w_cursor);
8922 # ifdef FEAT_CINDENT
8923 can_cindent = TRUE;
8924 # endif
8927 if (c == K_TABLINE)
8928 goto_tabpage(current_tab);
8929 else
8931 handle_tabmenu();
8932 redraw_statuslines(); /* will redraw the tabline when needed */
8935 #endif
8937 #if defined(FEAT_GUI) || defined(PROTO)
8938 void
8939 ins_scroll()
8941 pos_T tpos;
8943 undisplay_dollar();
8944 tpos = curwin->w_cursor;
8945 if (gui_do_scroll())
8947 start_arrow(&tpos);
8948 # ifdef FEAT_CINDENT
8949 can_cindent = TRUE;
8950 # endif
8954 void
8955 ins_horscroll()
8957 pos_T tpos;
8959 undisplay_dollar();
8960 tpos = curwin->w_cursor;
8961 if (gui_do_horiz_scroll())
8963 start_arrow(&tpos);
8964 # ifdef FEAT_CINDENT
8965 can_cindent = TRUE;
8966 # endif
8969 #endif
8971 static void
8972 ins_left()
8974 pos_T tpos;
8976 #ifdef FEAT_FOLDING
8977 if ((fdo_flags & FDO_HOR) && KeyTyped)
8978 foldOpenCursor();
8979 #endif
8980 undisplay_dollar();
8981 tpos = curwin->w_cursor;
8982 if (oneleft() == OK)
8984 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
8985 /* Only call start_arrow() when not busy with preediting, it will
8986 * break undo. K_LEFT is inserted in im_correct_cursor(). */
8987 if (!im_is_preediting())
8988 #endif
8989 start_arrow(&tpos);
8990 #ifdef FEAT_RIGHTLEFT
8991 /* If exit reversed string, position is fixed */
8992 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
8993 revins_legal++;
8994 revins_chars++;
8995 #endif
8999 * if 'whichwrap' set for cursor in insert mode may go to
9000 * previous line
9002 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
9004 start_arrow(&tpos);
9005 --(curwin->w_cursor.lnum);
9006 coladvance((colnr_T)MAXCOL);
9007 curwin->w_set_curswant = TRUE; /* so we stay at the end */
9009 else
9010 vim_beep();
9013 static void
9014 ins_home(c)
9015 int c;
9017 pos_T tpos;
9019 #ifdef FEAT_FOLDING
9020 if ((fdo_flags & FDO_HOR) && KeyTyped)
9021 foldOpenCursor();
9022 #endif
9023 undisplay_dollar();
9024 tpos = curwin->w_cursor;
9025 if (c == K_C_HOME)
9026 curwin->w_cursor.lnum = 1;
9027 curwin->w_cursor.col = 0;
9028 #ifdef FEAT_VIRTUALEDIT
9029 curwin->w_cursor.coladd = 0;
9030 #endif
9031 curwin->w_curswant = 0;
9032 start_arrow(&tpos);
9035 static void
9036 ins_end(c)
9037 int c;
9039 pos_T tpos;
9041 #ifdef FEAT_FOLDING
9042 if ((fdo_flags & FDO_HOR) && KeyTyped)
9043 foldOpenCursor();
9044 #endif
9045 undisplay_dollar();
9046 tpos = curwin->w_cursor;
9047 if (c == K_C_END)
9048 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9049 coladvance((colnr_T)MAXCOL);
9050 curwin->w_curswant = MAXCOL;
9052 start_arrow(&tpos);
9055 static void
9056 ins_s_left()
9058 #ifdef FEAT_FOLDING
9059 if ((fdo_flags & FDO_HOR) && KeyTyped)
9060 foldOpenCursor();
9061 #endif
9062 undisplay_dollar();
9063 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
9065 start_arrow(&curwin->w_cursor);
9066 (void)bck_word(1L, FALSE, FALSE);
9067 curwin->w_set_curswant = TRUE;
9069 else
9070 vim_beep();
9073 static void
9074 ins_right()
9076 #ifdef FEAT_FOLDING
9077 if ((fdo_flags & FDO_HOR) && KeyTyped)
9078 foldOpenCursor();
9079 #endif
9080 undisplay_dollar();
9081 if (gchar_cursor() != NUL
9082 #ifdef FEAT_VIRTUALEDIT
9083 || virtual_active()
9084 #endif
9087 start_arrow(&curwin->w_cursor);
9088 curwin->w_set_curswant = TRUE;
9089 #ifdef FEAT_VIRTUALEDIT
9090 if (virtual_active())
9091 oneright();
9092 else
9093 #endif
9095 #ifdef FEAT_MBYTE
9096 if (has_mbyte)
9097 curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
9098 else
9099 #endif
9100 ++curwin->w_cursor.col;
9103 #ifdef FEAT_RIGHTLEFT
9104 revins_legal++;
9105 if (revins_chars)
9106 revins_chars--;
9107 #endif
9109 /* if 'whichwrap' set for cursor in insert mode, may move the
9110 * cursor to the next line */
9111 else if (vim_strchr(p_ww, ']') != NULL
9112 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
9114 start_arrow(&curwin->w_cursor);
9115 curwin->w_set_curswant = TRUE;
9116 ++curwin->w_cursor.lnum;
9117 curwin->w_cursor.col = 0;
9119 else
9120 vim_beep();
9123 static void
9124 ins_s_right()
9126 #ifdef FEAT_FOLDING
9127 if ((fdo_flags & FDO_HOR) && KeyTyped)
9128 foldOpenCursor();
9129 #endif
9130 undisplay_dollar();
9131 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
9132 || gchar_cursor() != NUL)
9134 start_arrow(&curwin->w_cursor);
9135 (void)fwd_word(1L, FALSE, 0);
9136 curwin->w_set_curswant = TRUE;
9138 else
9139 vim_beep();
9142 static void
9143 ins_up(startcol)
9144 int startcol; /* when TRUE move to Insstart.col */
9146 pos_T tpos;
9147 linenr_T old_topline = curwin->w_topline;
9148 #ifdef FEAT_DIFF
9149 int old_topfill = curwin->w_topfill;
9150 #endif
9152 undisplay_dollar();
9153 tpos = curwin->w_cursor;
9154 if (cursor_up(1L, TRUE) == OK)
9156 if (startcol)
9157 coladvance(getvcol_nolist(&Insstart));
9158 if (old_topline != curwin->w_topline
9159 #ifdef FEAT_DIFF
9160 || old_topfill != curwin->w_topfill
9161 #endif
9163 redraw_later(VALID);
9164 start_arrow(&tpos);
9165 #ifdef FEAT_CINDENT
9166 can_cindent = TRUE;
9167 #endif
9169 else
9170 vim_beep();
9173 static void
9174 ins_pageup()
9176 pos_T tpos;
9178 undisplay_dollar();
9180 #ifdef FEAT_WINDOWS
9181 if (mod_mask & MOD_MASK_CTRL)
9183 /* <C-PageUp>: tab page back */
9184 if (first_tabpage->tp_next != NULL)
9186 start_arrow(&curwin->w_cursor);
9187 goto_tabpage(-1);
9189 return;
9191 #endif
9193 tpos = curwin->w_cursor;
9194 if (onepage(BACKWARD, 1L) == OK)
9196 start_arrow(&tpos);
9197 #ifdef FEAT_CINDENT
9198 can_cindent = TRUE;
9199 #endif
9201 else
9202 vim_beep();
9205 static void
9206 ins_down(startcol)
9207 int startcol; /* when TRUE move to Insstart.col */
9209 pos_T tpos;
9210 linenr_T old_topline = curwin->w_topline;
9211 #ifdef FEAT_DIFF
9212 int old_topfill = curwin->w_topfill;
9213 #endif
9215 undisplay_dollar();
9216 tpos = curwin->w_cursor;
9217 if (cursor_down(1L, TRUE) == OK)
9219 if (startcol)
9220 coladvance(getvcol_nolist(&Insstart));
9221 if (old_topline != curwin->w_topline
9222 #ifdef FEAT_DIFF
9223 || old_topfill != curwin->w_topfill
9224 #endif
9226 redraw_later(VALID);
9227 start_arrow(&tpos);
9228 #ifdef FEAT_CINDENT
9229 can_cindent = TRUE;
9230 #endif
9232 else
9233 vim_beep();
9236 static void
9237 ins_pagedown()
9239 pos_T tpos;
9241 undisplay_dollar();
9243 #ifdef FEAT_WINDOWS
9244 if (mod_mask & MOD_MASK_CTRL)
9246 /* <C-PageDown>: tab page forward */
9247 if (first_tabpage->tp_next != NULL)
9249 start_arrow(&curwin->w_cursor);
9250 goto_tabpage(0);
9252 return;
9254 #endif
9256 tpos = curwin->w_cursor;
9257 if (onepage(FORWARD, 1L) == OK)
9259 start_arrow(&tpos);
9260 #ifdef FEAT_CINDENT
9261 can_cindent = TRUE;
9262 #endif
9264 else
9265 vim_beep();
9268 #ifdef FEAT_DND
9269 static void
9270 ins_drop()
9272 do_put('~', BACKWARD, 1L, PUT_CURSEND);
9274 #endif
9277 * Handle TAB in Insert or Replace mode.
9278 * Return TRUE when the TAB needs to be inserted like a normal character.
9280 static int
9281 ins_tab()
9283 int ind;
9284 int i;
9285 int temp;
9287 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
9288 Insstart_blank_vcol = get_nolist_virtcol();
9289 if (echeck_abbr(TAB + ABBR_OFF))
9290 return FALSE;
9292 ind = inindent(0);
9293 #ifdef FEAT_CINDENT
9294 if (ind)
9295 can_cindent = FALSE;
9296 #endif
9299 * When nothing special, insert TAB like a normal character
9301 if (!curbuf->b_p_et
9302 #ifdef FEAT_VARTABS
9303 && !(p_sta && ind
9304 /* These five lines mean 'tabstop' != 'shiftwidth' */
9305 && ((tabstop_count(curbuf->b_p_vts_ary) > 1)
9306 || (tabstop_count(curbuf->b_p_vts_ary) == 1
9307 && tabstop_first(curbuf->b_p_vts_ary) != curbuf->b_p_sw)
9308 || (tabstop_count(curbuf->b_p_vts_ary) == 0
9309 && curbuf->b_p_ts != curbuf->b_p_sw)))
9310 && tabstop_count(curbuf->b_p_vsts_ary) == 0
9311 && curbuf->b_p_sts == 0
9312 #else
9313 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
9314 && curbuf->b_p_sts == 0
9315 #endif
9317 return TRUE;
9319 if (stop_arrow() == FAIL)
9320 return TRUE;
9322 did_ai = FALSE;
9323 #ifdef FEAT_SMARTINDENT
9324 did_si = FALSE;
9325 can_si = FALSE;
9326 can_si_back = FALSE;
9327 #endif
9328 AppendToRedobuff((char_u *)"\t");
9330 #ifdef FEAT_VARTABS
9331 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9333 temp = (int)curbuf->b_p_sw;
9334 temp -= get_nolist_virtcol() % temp;
9336 else if (tabstop_count(curbuf->b_p_vsts_ary) > 0 || curbuf->b_p_sts > 0)
9337 /* use 'softtabstop' when set */
9338 temp = tabstop_padding(get_nolist_virtcol(), curbuf->b_p_sts,
9339 curbuf->b_p_vsts_ary);
9340 else /* otherwise use 'tabstop' */
9341 temp = tabstop_padding(get_nolist_virtcol(), curbuf->b_p_ts,
9342 curbuf->b_p_vts_ary);
9343 #else
9344 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9345 temp = (int)curbuf->b_p_sw;
9346 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
9347 temp = (int)curbuf->b_p_sts;
9348 else /* otherwise use 'tabstop' */
9349 temp = (int)curbuf->b_p_ts;
9350 temp -= get_nolist_virtcol() % temp;
9351 #endif
9354 * Insert the first space with ins_char(). It will delete one char in
9355 * replace mode. Insert the rest with ins_str(); it will not delete any
9356 * chars. For VREPLACE mode, we use ins_char() for all characters.
9358 ins_char(' ');
9359 while (--temp > 0)
9361 #ifdef FEAT_VREPLACE
9362 if (State & VREPLACE_FLAG)
9363 ins_char(' ');
9364 else
9365 #endif
9367 ins_str((char_u *)" ");
9368 if (State & REPLACE_FLAG) /* no char replaced */
9369 replace_push(NUL);
9374 * When 'expandtab' not set: Replace spaces by TABs where possible.
9376 #ifdef FEAT_VARTABS
9377 if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_ary) > 0
9378 || curbuf->b_p_sts > 0
9379 || (p_sta && ind)))
9380 #else
9381 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
9382 #endif
9384 char_u *ptr;
9385 #ifdef FEAT_VREPLACE
9386 char_u *saved_line = NULL; /* init for GCC */
9387 pos_T pos;
9388 #endif
9389 pos_T fpos;
9390 pos_T *cursor;
9391 colnr_T want_vcol, vcol;
9392 int change_col = -1;
9393 int save_list = curwin->w_p_list;
9396 * Get the current line. For VREPLACE mode, don't make real changes
9397 * yet, just work on a copy of the line.
9399 #ifdef FEAT_VREPLACE
9400 if (State & VREPLACE_FLAG)
9402 pos = curwin->w_cursor;
9403 cursor = &pos;
9404 saved_line = vim_strsave(ml_get_curline());
9405 if (saved_line == NULL)
9406 return FALSE;
9407 ptr = saved_line + pos.col;
9409 else
9410 #endif
9412 ptr = ml_get_cursor();
9413 cursor = &curwin->w_cursor;
9416 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
9417 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9418 curwin->w_p_list = FALSE;
9420 /* Find first white before the cursor */
9421 fpos = curwin->w_cursor;
9422 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
9424 --fpos.col;
9425 --ptr;
9428 /* In Replace mode, don't change characters before the insert point. */
9429 if ((State & REPLACE_FLAG)
9430 && fpos.lnum == Insstart.lnum
9431 && fpos.col < Insstart.col)
9433 ptr += Insstart.col - fpos.col;
9434 fpos.col = Insstart.col;
9437 /* compute virtual column numbers of first white and cursor */
9438 getvcol(curwin, &fpos, &vcol, NULL, NULL);
9439 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
9441 /* Use as many TABs as possible. Beware of 'showbreak' and
9442 * 'linebreak' adding extra virtual columns. */
9443 while (vim_iswhite(*ptr))
9445 i = lbr_chartabsize((char_u *)"\t", vcol);
9446 if (vcol + i > want_vcol)
9447 break;
9448 if (*ptr != TAB)
9450 *ptr = TAB;
9451 if (change_col < 0)
9453 change_col = fpos.col; /* Column of first change */
9454 /* May have to adjust Insstart */
9455 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
9456 Insstart.col = fpos.col;
9459 ++fpos.col;
9460 ++ptr;
9461 vcol += i;
9464 if (change_col >= 0)
9466 int repl_off = 0;
9468 /* Skip over the spaces we need. */
9469 while (vcol < want_vcol && *ptr == ' ')
9471 vcol += lbr_chartabsize(ptr, vcol);
9472 ++ptr;
9473 ++repl_off;
9475 if (vcol > want_vcol)
9477 /* Must have a char with 'showbreak' just before it. */
9478 --ptr;
9479 --repl_off;
9481 fpos.col += repl_off;
9483 /* Delete following spaces. */
9484 i = cursor->col - fpos.col;
9485 if (i > 0)
9487 STRMOVE(ptr, ptr + i);
9488 /* correct replace stack. */
9489 if ((State & REPLACE_FLAG)
9490 #ifdef FEAT_VREPLACE
9491 && !(State & VREPLACE_FLAG)
9492 #endif
9494 for (temp = i; --temp >= 0; )
9495 replace_join(repl_off);
9497 #ifdef FEAT_NETBEANS_INTG
9498 if (usingNetbeans)
9500 netbeans_removed(curbuf, fpos.lnum, cursor->col,
9501 (long)(i + 1));
9502 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
9503 (char_u *)"\t", 1);
9505 #endif
9506 cursor->col -= i;
9508 #ifdef FEAT_VREPLACE
9510 * In VREPLACE mode, we haven't changed anything yet. Do it now by
9511 * backspacing over the changed spacing and then inserting the new
9512 * spacing.
9514 if (State & VREPLACE_FLAG)
9516 /* Backspace from real cursor to change_col */
9517 backspace_until_column(change_col);
9519 /* Insert each char in saved_line from changed_col to
9520 * ptr-cursor */
9521 ins_bytes_len(saved_line + change_col,
9522 cursor->col - change_col);
9524 #endif
9527 #ifdef FEAT_VREPLACE
9528 if (State & VREPLACE_FLAG)
9529 vim_free(saved_line);
9530 #endif
9531 curwin->w_p_list = save_list;
9534 return FALSE;
9538 * Handle CR or NL in insert mode.
9539 * Return TRUE when out of memory or can't undo.
9541 static int
9542 ins_eol(c)
9543 int c;
9545 int i;
9547 if (echeck_abbr(c + ABBR_OFF))
9548 return FALSE;
9549 if (stop_arrow() == FAIL)
9550 return TRUE;
9551 undisplay_dollar();
9554 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
9555 * character under the cursor. Only push a NUL on the replace stack,
9556 * nothing to put back when the NL is deleted.
9558 if ((State & REPLACE_FLAG)
9559 #ifdef FEAT_VREPLACE
9560 && !(State & VREPLACE_FLAG)
9561 #endif
9563 replace_push(NUL);
9566 * In VREPLACE mode, a NL replaces the rest of the line, and starts
9567 * replacing the next line, so we push all of the characters left on the
9568 * line onto the replace stack. This is not done here though, it is done
9569 * in open_line().
9572 #ifdef FEAT_VIRTUALEDIT
9573 /* Put cursor on NUL if on the last char and coladd is 1 (happens after
9574 * CTRL-O). */
9575 if (virtual_active() && curwin->w_cursor.coladd > 0)
9576 coladvance(getviscol());
9577 #endif
9579 #ifdef FEAT_RIGHTLEFT
9580 # ifdef FEAT_FKMAP
9581 if (p_altkeymap && p_fkmap)
9582 fkmap(NL);
9583 # endif
9584 /* NL in reverse insert will always start in the end of
9585 * current line. */
9586 if (revins_on)
9587 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9588 #endif
9590 AppendToRedobuff(NL_STR);
9591 i = open_line(FORWARD,
9592 #ifdef FEAT_COMMENTS
9593 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
9594 #endif
9595 0, old_indent);
9596 old_indent = 0;
9597 #ifdef FEAT_CINDENT
9598 can_cindent = TRUE;
9599 #endif
9600 #ifdef FEAT_FOLDING
9601 /* When inserting a line the cursor line must never be in a closed fold. */
9602 foldOpenCursor();
9603 #endif
9605 return (!i);
9608 #ifdef FEAT_DIGRAPHS
9610 * Handle digraph in insert mode.
9611 * Returns character still to be inserted, or NUL when nothing remaining to be
9612 * done.
9614 static int
9615 ins_digraph()
9617 int c;
9618 int cc;
9620 pc_status = PC_STATUS_UNSET;
9621 if (redrawing() && !char_avail())
9623 /* may need to redraw when no more chars available now */
9624 ins_redraw(FALSE);
9626 edit_putchar('?', TRUE);
9627 #ifdef FEAT_CMDL_INFO
9628 add_to_showcmd_c(Ctrl_K);
9629 #endif
9632 #ifdef USE_ON_FLY_SCROLL
9633 dont_scroll = TRUE; /* disallow scrolling here */
9634 #endif
9636 /* don't map the digraph chars. This also prevents the
9637 * mode message to be deleted when ESC is hit */
9638 ++no_mapping;
9639 ++allow_keys;
9640 c = plain_vgetc();
9641 --no_mapping;
9642 --allow_keys;
9643 if (IS_SPECIAL(c) || mod_mask) /* special key */
9645 #ifdef FEAT_CMDL_INFO
9646 clear_showcmd();
9647 #endif
9648 insert_special(c, TRUE, FALSE);
9649 return NUL;
9651 if (c != ESC)
9653 if (redrawing() && !char_avail())
9655 /* may need to redraw when no more chars available now */
9656 ins_redraw(FALSE);
9658 if (char2cells(c) == 1)
9660 /* first remove the '?', otherwise it's restored when typing
9661 * an ESC next */
9662 edit_unputchar();
9663 ins_redraw(FALSE);
9664 edit_putchar(c, TRUE);
9666 #ifdef FEAT_CMDL_INFO
9667 add_to_showcmd_c(c);
9668 #endif
9670 ++no_mapping;
9671 ++allow_keys;
9672 cc = plain_vgetc();
9673 --no_mapping;
9674 --allow_keys;
9675 if (cc != ESC)
9677 AppendToRedobuff((char_u *)CTRL_V_STR);
9678 c = getdigraph(c, cc, TRUE);
9679 #ifdef FEAT_CMDL_INFO
9680 clear_showcmd();
9681 #endif
9682 return c;
9685 edit_unputchar();
9686 #ifdef FEAT_CMDL_INFO
9687 clear_showcmd();
9688 #endif
9689 return NUL;
9691 #endif
9694 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9695 * Returns the char to be inserted, or NUL if none found.
9697 static int
9698 ins_copychar(lnum)
9699 linenr_T lnum;
9701 int c;
9702 int temp;
9703 char_u *ptr, *prev_ptr;
9705 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9707 vim_beep();
9708 return NUL;
9711 /* try to advance to the cursor column */
9712 temp = 0;
9713 ptr = ml_get(lnum);
9714 prev_ptr = ptr;
9715 validate_virtcol();
9716 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9718 prev_ptr = ptr;
9719 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
9721 if ((colnr_T)temp > curwin->w_virtcol)
9722 ptr = prev_ptr;
9724 #ifdef FEAT_MBYTE
9725 c = (*mb_ptr2char)(ptr);
9726 #else
9727 c = *ptr;
9728 #endif
9729 if (c == NUL)
9730 vim_beep();
9731 return c;
9735 * CTRL-Y or CTRL-E typed in Insert mode.
9737 static int
9738 ins_ctrl_ey(tc)
9739 int tc;
9741 int c = tc;
9743 #ifdef FEAT_INS_EXPAND
9744 if (ctrl_x_mode == CTRL_X_SCROLL)
9746 if (c == Ctrl_Y)
9747 scrolldown_clamp();
9748 else
9749 scrollup_clamp();
9750 redraw_later(VALID);
9752 else
9753 #endif
9755 c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
9756 if (c != NUL)
9758 long tw_save;
9760 /* The character must be taken literally, insert like it
9761 * was typed after a CTRL-V, and pretend 'textwidth'
9762 * wasn't set. Digits, 'o' and 'x' are special after a
9763 * CTRL-V, don't use it for these. */
9764 if (c < 256 && !isalnum(c))
9765 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
9766 tw_save = curbuf->b_p_tw;
9767 curbuf->b_p_tw = -1;
9768 insert_special(c, TRUE, FALSE);
9769 curbuf->b_p_tw = tw_save;
9770 #ifdef FEAT_RIGHTLEFT
9771 revins_chars++;
9772 revins_legal++;
9773 #endif
9774 c = Ctrl_V; /* pretend CTRL-V is last character */
9775 auto_format(FALSE, TRUE);
9778 return c;
9781 #ifdef FEAT_SMARTINDENT
9783 * Try to do some very smart auto-indenting.
9784 * Used when inserting a "normal" character.
9786 static void
9787 ins_try_si(c)
9788 int c;
9790 pos_T *pos, old_pos;
9791 char_u *ptr;
9792 int i;
9793 int temp;
9796 * do some very smart indenting when entering '{' or '}'
9798 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
9801 * for '}' set indent equal to indent of line containing matching '{'
9803 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
9805 old_pos = curwin->w_cursor;
9807 * If the matching '{' has a ')' immediately before it (ignoring
9808 * white-space), then line up with the start of the line
9809 * containing the matching '(' if there is one. This handles the
9810 * case where an "if (..\n..) {" statement continues over multiple
9811 * lines -- webb
9813 ptr = ml_get(pos->lnum);
9814 i = pos->col;
9815 if (i > 0) /* skip blanks before '{' */
9816 while (--i > 0 && vim_iswhite(ptr[i]))
9818 curwin->w_cursor.lnum = pos->lnum;
9819 curwin->w_cursor.col = i;
9820 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
9821 curwin->w_cursor = *pos;
9822 i = get_indent();
9823 curwin->w_cursor = old_pos;
9824 #ifdef FEAT_VREPLACE
9825 if (State & VREPLACE_FLAG)
9826 change_indent(INDENT_SET, i, FALSE, NUL, TRUE);
9827 else
9828 #endif
9829 (void)set_indent(i, SIN_CHANGED);
9831 else if (curwin->w_cursor.col > 0)
9834 * when inserting '{' after "O" reduce indent, but not
9835 * more than indent of previous line
9837 temp = TRUE;
9838 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
9840 old_pos = curwin->w_cursor;
9841 i = get_indent();
9842 while (curwin->w_cursor.lnum > 1)
9844 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
9846 /* ignore empty lines and lines starting with '#'. */
9847 if (*ptr != '#' && *ptr != NUL)
9848 break;
9850 if (get_indent() >= i)
9851 temp = FALSE;
9852 curwin->w_cursor = old_pos;
9854 if (temp)
9855 shift_line(TRUE, FALSE, 1, TRUE);
9860 * set indent of '#' always to 0
9862 if (curwin->w_cursor.col > 0 && can_si && c == '#')
9864 /* remember current indent for next line */
9865 old_indent = get_indent();
9866 (void)set_indent(0, SIN_CHANGED);
9869 /* Adjust ai_col, the char at this position can be deleted. */
9870 if (ai_col > curwin->w_cursor.col)
9871 ai_col = curwin->w_cursor.col;
9873 #endif
9876 * Get the value that w_virtcol would have when 'list' is off.
9877 * Unless 'cpo' contains the 'L' flag.
9879 static colnr_T
9880 get_nolist_virtcol()
9882 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9883 return getvcol_nolist(&curwin->w_cursor);
9884 validate_virtcol();
9885 return curwin->w_virtcol;