Sync with newest CVS repository.
[MacVim/jjgod.git] / src / edit.c
blob25fffad5870e92a73897224142ca692f97e91397
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * edit.c: functions for Insert mode
14 #include "vim.h"
16 #ifdef FEAT_INS_EXPAND
18 * definitions used for CTRL-X submode
20 #define CTRL_X_WANT_IDENT 0x100
22 #define CTRL_X_NOT_DEFINED_YET 1
23 #define CTRL_X_SCROLL 2
24 #define CTRL_X_WHOLE_LINE 3
25 #define CTRL_X_FILES 4
26 #define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
27 #define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
28 #define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
29 #define CTRL_X_FINISHED 8
30 #define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
31 #define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
32 #define CTRL_X_CMDLINE 11
33 #define CTRL_X_FUNCTION 12
34 #define CTRL_X_OMNI 13
35 #define CTRL_X_SPELL 14
36 #define CTRL_X_LOCAL_MSG 15 /* only used in "ctrl_x_msgs" */
38 #define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
40 static char *ctrl_x_msgs[] =
42 N_(" Keyword completion (^N^P)"), /* ctrl_x_mode == 0, ^P/^N compl. */
43 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
44 NULL,
45 N_(" Whole line completion (^L^N^P)"),
46 N_(" File name completion (^F^N^P)"),
47 N_(" Tag completion (^]^N^P)"),
48 N_(" Path pattern completion (^N^P)"),
49 N_(" Definition completion (^D^N^P)"),
50 NULL,
51 N_(" Dictionary completion (^K^N^P)"),
52 N_(" Thesaurus completion (^T^N^P)"),
53 N_(" Command-line completion (^V^N^P)"),
54 N_(" User defined completion (^U^N^P)"),
55 N_(" Omni completion (^O^N^P)"),
56 N_(" Spelling suggestion (s^N^P)"),
57 N_(" Keyword Local completion (^N^P)"),
60 static char_u e_hitend[] = N_("Hit end of paragraph");
63 * Structure used to store one match for insert completion.
65 typedef struct compl_S compl_T;
66 struct compl_S
68 compl_T *cp_next;
69 compl_T *cp_prev;
70 char_u *cp_str; /* matched text */
71 char cp_icase; /* TRUE or FALSE: ignore case */
72 char_u *(cp_text[CPT_COUNT]); /* text for the menu */
73 char_u *cp_fname; /* file containing the match, allocated when
74 * cp_flags has FREE_FNAME */
75 int cp_flags; /* ORIGINAL_TEXT, CONT_S_IPOS or FREE_FNAME */
76 int cp_number; /* sequence number */
79 #define ORIGINAL_TEXT (1) /* the original text when the expansion begun */
80 #define FREE_FNAME (2)
83 * All the current matches are stored in a list.
84 * "compl_first_match" points to the start of the list.
85 * "compl_curr_match" points to the currently selected entry.
86 * "compl_shown_match" is different from compl_curr_match during
87 * ins_compl_get_exp().
89 static compl_T *compl_first_match = NULL;
90 static compl_T *compl_curr_match = NULL;
91 static compl_T *compl_shown_match = NULL;
93 /* After using a cursor key <Enter> selects a match in the popup menu,
94 * otherwise it inserts a line break. */
95 static int compl_enter_selects = FALSE;
97 /* When "compl_leader" is not NULL only matches that start with this string
98 * are used. */
99 static char_u *compl_leader = NULL;
101 static int compl_get_longest = FALSE; /* put longest common string
102 in compl_leader */
104 static int compl_used_match; /* Selected one of the matches. When
105 FALSE the match was edited or using
106 the longest common string. */
108 /* When the first completion is done "compl_started" is set. When it's
109 * FALSE the word to be completed must be located. */
110 static int compl_started = FALSE;
112 static int compl_matches = 0;
113 static char_u *compl_pattern = NULL;
114 static int compl_direction = FORWARD;
115 static int compl_shows_dir = FORWARD;
116 static int compl_pending = 0; /* > 1 for postponed CTRL-N */
117 static pos_T compl_startpos;
118 static colnr_T compl_col = 0; /* column where the text starts
119 * that is being completed */
120 static char_u *compl_orig_text = NULL; /* text as it was before
121 * completion started */
122 static int compl_cont_mode = 0;
123 static expand_T compl_xp;
125 static void ins_ctrl_x __ARGS((void));
126 static int has_compl_option __ARGS((int dict_opt));
127 static int ins_compl_add __ARGS((char_u *str, int len, int icase, char_u *fname, char_u **cptext, int cdir, int flags, int dup));
128 static int ins_compl_equal __ARGS((compl_T *match, char_u *str, int len));
129 static void ins_compl_longest_match __ARGS((compl_T *match));
130 static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int icase));
131 static int ins_compl_make_cyclic __ARGS((void));
132 static void ins_compl_upd_pum __ARGS((void));
133 static void ins_compl_del_pum __ARGS((void));
134 static int pum_wanted __ARGS((void));
135 static int pum_enough_matches __ARGS((void));
136 static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int flags, int thesaurus));
137 static void ins_compl_files __ARGS((int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir));
138 static char_u *find_line_end __ARGS((char_u *ptr));
139 static void ins_compl_free __ARGS((void));
140 static void ins_compl_clear __ARGS((void));
141 static int ins_compl_bs __ARGS((void));
142 static void ins_compl_addleader __ARGS((int c));
143 static void ins_compl_set_original_text __ARGS((char_u *str));
144 static void ins_compl_addfrommatch __ARGS((void));
145 static int ins_compl_prep __ARGS((int c));
146 static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag));
147 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
148 static void ins_compl_add_list __ARGS((list_T *list));
149 #endif
150 static int ins_compl_get_exp __ARGS((pos_T *ini));
151 static void ins_compl_delete __ARGS((void));
152 static void ins_compl_insert __ARGS((void));
153 static int ins_compl_next __ARGS((int allow_get_expansion, int count, int insert_match));
154 static int ins_compl_key2dir __ARGS((int c));
155 static int ins_compl_pum_key __ARGS((int c));
156 static int ins_compl_key2count __ARGS((int c));
157 static int ins_compl_use_match __ARGS((int c));
158 static int ins_complete __ARGS((int c));
159 static int quote_meta __ARGS((char_u *dest, char_u *str, int len));
160 #endif /* FEAT_INS_EXPAND */
162 #define BACKSPACE_CHAR 1
163 #define BACKSPACE_WORD 2
164 #define BACKSPACE_WORD_NOT_SPACE 3
165 #define BACKSPACE_LINE 4
167 static void ins_redraw __ARGS((int ready));
168 static void ins_ctrl_v __ARGS((void));
169 static void undisplay_dollar __ARGS((void));
170 static void insert_special __ARGS((int, int, int));
171 static void internal_format __ARGS((int textwidth, int second_indent, int flags, int format_only));
172 static void check_auto_format __ARGS((int));
173 static void redo_literal __ARGS((int c));
174 static void start_arrow __ARGS((pos_T *end_insert_pos));
175 #ifdef FEAT_SPELL
176 static void check_spell_redraw __ARGS((void));
177 static void spell_back_to_badword __ARGS((void));
178 static int spell_bad_len = 0; /* length of located bad word */
179 #endif
180 static void stop_insert __ARGS((pos_T *end_insert_pos, int esc));
181 static int echeck_abbr __ARGS((int));
182 #if 0
183 static void replace_push_off __ARGS((int c));
184 #endif
185 static int replace_pop __ARGS((void));
186 static void replace_join __ARGS((int off));
187 static void replace_pop_ins __ARGS((void));
188 #ifdef FEAT_MBYTE
189 static void mb_replace_pop_ins __ARGS((int cc));
190 #endif
191 static void replace_flush __ARGS((void));
192 static void replace_do_bs __ARGS((void));
193 #ifdef FEAT_CINDENT
194 static int cindent_on __ARGS((void));
195 #endif
196 static void ins_reg __ARGS((void));
197 static void ins_ctrl_g __ARGS((void));
198 static void ins_ctrl_hat __ARGS((void));
199 static int ins_esc __ARGS((long *count, int cmdchar, int nomove));
200 #ifdef FEAT_RIGHTLEFT
201 static void ins_ctrl_ __ARGS((void));
202 #endif
203 #ifdef FEAT_VISUAL
204 static int ins_start_select __ARGS((int c));
205 #endif
206 static void ins_insert __ARGS((int replaceState));
207 static void ins_ctrl_o __ARGS((void));
208 static void ins_shift __ARGS((int c, int lastc));
209 static void ins_del __ARGS((void));
210 static int ins_bs __ARGS((int c, int mode, int *inserted_space_p));
211 #ifdef FEAT_MOUSE
212 static void ins_mouse __ARGS((int c));
213 static void ins_mousescroll __ARGS((int up));
214 #endif
215 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
216 static void ins_tabline __ARGS((int c));
217 #endif
218 static void ins_left __ARGS((void));
219 static void ins_home __ARGS((int c));
220 static void ins_end __ARGS((int c));
221 static void ins_s_left __ARGS((void));
222 static void ins_right __ARGS((void));
223 static void ins_s_right __ARGS((void));
224 static void ins_up __ARGS((int startcol));
225 static void ins_pageup __ARGS((void));
226 static void ins_down __ARGS((int startcol));
227 static void ins_pagedown __ARGS((void));
228 #ifdef FEAT_DND
229 static void ins_drop __ARGS((void));
230 #endif
231 static int ins_tab __ARGS((void));
232 static int ins_eol __ARGS((int c));
233 #ifdef FEAT_DIGRAPHS
234 static int ins_digraph __ARGS((void));
235 #endif
236 static int ins_copychar __ARGS((linenr_T lnum));
237 static int ins_ctrl_ey __ARGS((int tc));
238 #ifdef FEAT_SMARTINDENT
239 static void ins_try_si __ARGS((int c));
240 #endif
241 static colnr_T get_nolist_virtcol __ARGS((void));
243 static colnr_T Insstart_textlen; /* length of line when insert started */
244 static colnr_T Insstart_blank_vcol; /* vcol for first inserted blank */
246 static char_u *last_insert = NULL; /* the text of the previous insert,
247 K_SPECIAL and CSI are escaped */
248 static int last_insert_skip; /* nr of chars in front of previous insert */
249 static int new_insert_skip; /* nr of chars in front of current insert */
250 static int did_restart_edit; /* "restart_edit" when calling edit() */
252 #ifdef FEAT_CINDENT
253 static int can_cindent; /* may do cindenting on this line */
254 #endif
256 static int old_indent = 0; /* for ^^D command in insert mode */
258 #ifdef FEAT_RIGHTLEFT
259 static int revins_on; /* reverse insert mode on */
260 static int revins_chars; /* how much to skip after edit */
261 static int revins_legal; /* was the last char 'legal'? */
262 static int revins_scol; /* start column of revins session */
263 #endif
265 static int ins_need_undo; /* call u_save() before inserting a
266 char. Set when edit() is called.
267 after that arrow_used is used. */
269 static int did_add_space = FALSE; /* auto_format() added an extra space
270 under the cursor */
273 * edit(): Start inserting text.
275 * "cmdchar" can be:
276 * 'i' normal insert command
277 * 'a' normal append command
278 * 'R' replace command
279 * 'r' "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo,
280 * but still only one <CR> is inserted. The <Esc> is not used for redo.
281 * 'g' "gI" command.
282 * 'V' "gR" command for Virtual Replace mode.
283 * 'v' "gr" command for single character Virtual Replace mode.
285 * This function is not called recursively. For CTRL-O commands, it returns
286 * and lets the caller handle the Normal-mode command.
288 * Return TRUE if a CTRL-O command caused the return (insert mode pending).
291 edit(cmdchar, startln, count)
292 int cmdchar;
293 int startln; /* if set, insert at start of line */
294 long count;
296 int c = 0;
297 char_u *ptr;
298 int lastc;
299 colnr_T mincol;
300 static linenr_T o_lnum = 0;
301 int i;
302 int did_backspace = TRUE; /* previous char was backspace */
303 #ifdef FEAT_CINDENT
304 int line_is_white = FALSE; /* line is empty before insert */
305 #endif
306 linenr_T old_topline = 0; /* topline before insertion */
307 #ifdef FEAT_DIFF
308 int old_topfill = -1;
309 #endif
310 int inserted_space = FALSE; /* just inserted a space */
311 int replaceState = REPLACE;
312 int nomove = FALSE; /* don't move cursor on return */
314 /* Remember whether editing was restarted after CTRL-O. */
315 did_restart_edit = restart_edit;
317 /* sleep before redrawing, needed for "CTRL-O :" that results in an
318 * error message */
319 check_for_delay(TRUE);
321 #ifdef HAVE_SANDBOX
322 /* Don't allow inserting in the sandbox. */
323 if (sandbox != 0)
325 EMSG(_(e_sandbox));
326 return FALSE;
328 #endif
329 /* Don't allow changes in the buffer while editing the cmdline. The
330 * caller of getcmdline() may get confused. */
331 if (textlock != 0)
333 EMSG(_(e_secure));
334 return FALSE;
337 #ifdef FEAT_INS_EXPAND
338 ins_compl_clear(); /* clear stuff for CTRL-X mode */
339 #endif
341 #ifdef FEAT_AUTOCMD
343 * Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx".
345 if (cmdchar != 'r' && cmdchar != 'v')
347 # ifdef FEAT_EVAL
348 if (cmdchar == 'R')
349 ptr = (char_u *)"r";
350 else if (cmdchar == 'V')
351 ptr = (char_u *)"v";
352 else
353 ptr = (char_u *)"i";
354 set_vim_var_string(VV_INSERTMODE, ptr, 1);
355 # endif
356 apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf);
358 #endif
360 #ifdef FEAT_MOUSE
362 * When doing a paste with the middle mouse button, Insstart is set to
363 * where the paste started.
365 if (where_paste_started.lnum != 0)
366 Insstart = where_paste_started;
367 else
368 #endif
370 Insstart = curwin->w_cursor;
371 if (startln)
372 Insstart.col = 0;
374 Insstart_textlen = linetabsize(ml_get_curline());
375 Insstart_blank_vcol = MAXCOL;
376 if (!did_ai)
377 ai_col = 0;
379 if (cmdchar != NUL && restart_edit == 0)
381 ResetRedobuff();
382 AppendNumberToRedobuff(count);
383 #ifdef FEAT_VREPLACE
384 if (cmdchar == 'V' || cmdchar == 'v')
386 /* "gR" or "gr" command */
387 AppendCharToRedobuff('g');
388 AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R');
390 else
391 #endif
393 AppendCharToRedobuff(cmdchar);
394 if (cmdchar == 'g') /* "gI" command */
395 AppendCharToRedobuff('I');
396 else if (cmdchar == 'r') /* "r<CR>" command */
397 count = 1; /* insert only one <CR> */
401 if (cmdchar == 'R')
403 #ifdef FEAT_FKMAP
404 if (p_fkmap && p_ri)
406 beep_flush();
407 EMSG(farsi_text_3); /* encoded in Farsi */
408 State = INSERT;
410 else
411 #endif
412 State = REPLACE;
414 #ifdef FEAT_VREPLACE
415 else if (cmdchar == 'V' || cmdchar == 'v')
417 State = VREPLACE;
418 replaceState = VREPLACE;
419 orig_line_count = curbuf->b_ml.ml_line_count;
420 vr_lines_changed = 1;
422 #endif
423 else
424 State = INSERT;
426 stop_insert_mode = FALSE;
429 * Need to recompute the cursor position, it might move when the cursor is
430 * on a TAB or special character.
432 curs_columns(TRUE);
435 * Enable langmap or IME, indicated by 'iminsert'.
436 * Note that IME may enabled/disabled without us noticing here, thus the
437 * 'iminsert' value may not reflect what is actually used. It is updated
438 * when hitting <Esc>.
440 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
441 State |= LANGMAP;
442 #ifdef USE_IM_CONTROL
443 im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
444 #endif
446 #ifdef FEAT_MOUSE
447 setmouse();
448 #endif
449 #ifdef FEAT_CMDL_INFO
450 clear_showcmd();
451 #endif
452 #ifdef FEAT_RIGHTLEFT
453 /* there is no reverse replace mode */
454 revins_on = (State == INSERT && p_ri);
455 if (revins_on)
456 undisplay_dollar();
457 revins_chars = 0;
458 revins_legal = 0;
459 revins_scol = -1;
460 #endif
463 * Handle restarting Insert mode.
464 * Don't do this for "CTRL-O ." (repeat an insert): we get here with
465 * restart_edit non-zero, and something in the stuff buffer.
467 if (restart_edit != 0 && stuff_empty())
469 #ifdef FEAT_MOUSE
471 * After a paste we consider text typed to be part of the insert for
472 * the pasted text. You can backspace over the pasted text too.
474 if (where_paste_started.lnum)
475 arrow_used = FALSE;
476 else
477 #endif
478 arrow_used = TRUE;
479 restart_edit = 0;
482 * If the cursor was after the end-of-line before the CTRL-O and it is
483 * now at the end-of-line, put it after the end-of-line (this is not
484 * correct in very rare cases).
485 * Also do this if curswant is greater than the current virtual
486 * column. Eg after "^O$" or "^O80|".
488 validate_virtcol();
489 update_curswant();
490 if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
491 || curwin->w_curswant > curwin->w_virtcol)
492 && *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL)
494 if (ptr[1] == NUL)
495 ++curwin->w_cursor.col;
496 #ifdef FEAT_MBYTE
497 else if (has_mbyte)
499 i = (*mb_ptr2len)(ptr);
500 if (ptr[i] == NUL)
501 curwin->w_cursor.col += i;
503 #endif
505 ins_at_eol = FALSE;
507 else
508 arrow_used = FALSE;
510 /* we are in insert mode now, don't need to start it anymore */
511 need_start_insertmode = FALSE;
513 /* Need to save the line for undo before inserting the first char. */
514 ins_need_undo = TRUE;
516 #ifdef FEAT_MOUSE
517 where_paste_started.lnum = 0;
518 #endif
519 #ifdef FEAT_CINDENT
520 can_cindent = TRUE;
521 #endif
522 #ifdef FEAT_FOLDING
523 /* The cursor line is not in a closed fold, unless 'insertmode' is set or
524 * restarting. */
525 if (!p_im && did_restart_edit == 0)
526 foldOpenCursor();
527 #endif
530 * If 'showmode' is set, show the current (insert/replace/..) mode.
531 * A warning message for changing a readonly file is given here, before
532 * actually changing anything. It's put after the mode, if any.
534 i = 0;
535 if (p_smd && msg_silent == 0)
536 i = showmode();
538 if (!p_im && did_restart_edit == 0)
539 change_warning(i + 1);
541 #ifdef CURSOR_SHAPE
542 ui_cursor_shape(); /* may show different cursor shape */
543 #endif
544 #ifdef FEAT_DIGRAPHS
545 do_digraph(-1); /* clear digraphs */
546 #endif
549 * Get the current length of the redo buffer, those characters have to be
550 * skipped if we want to get to the inserted characters.
552 ptr = get_inserted();
553 if (ptr == NULL)
554 new_insert_skip = 0;
555 else
557 new_insert_skip = (int)STRLEN(ptr);
558 vim_free(ptr);
561 old_indent = 0;
564 * Main loop in Insert mode: repeat until Insert mode is left.
566 for (;;)
568 #ifdef FEAT_RIGHTLEFT
569 if (!revins_legal)
570 revins_scol = -1; /* reset on illegal motions */
571 else
572 revins_legal = 0;
573 #endif
574 if (arrow_used) /* don't repeat insert when arrow key used */
575 count = 0;
577 if (stop_insert_mode)
579 /* ":stopinsert" used or 'insertmode' reset */
580 count = 0;
581 goto doESCkey;
584 /* set curwin->w_curswant for next K_DOWN or K_UP */
585 if (!arrow_used)
586 curwin->w_set_curswant = TRUE;
588 /* If there is no typeahead may check for timestamps (e.g., for when a
589 * menu invoked a shell command). */
590 if (stuff_empty())
592 did_check_timestamps = FALSE;
593 if (need_check_timestamps)
594 check_timestamps(FALSE);
598 * When emsg() was called msg_scroll will have been set.
600 msg_scroll = FALSE;
602 #ifdef FEAT_GUI
603 /* When 'mousefocus' is set a mouse movement may have taken us to
604 * another window. "need_mouse_correct" may then be set because of an
605 * autocommand. */
606 if (need_mouse_correct)
607 gui_mouse_correct();
608 #endif
610 #ifdef FEAT_FOLDING
611 /* Open fold at the cursor line, according to 'foldopen'. */
612 if (fdo_flags & FDO_INSERT)
613 foldOpenCursor();
614 /* Close folds where the cursor isn't, according to 'foldclose' */
615 if (!char_avail())
616 foldCheckClose();
617 #endif
620 * If we inserted a character at the last position of the last line in
621 * the window, scroll the window one line up. This avoids an extra
622 * redraw.
623 * This is detected when the cursor column is smaller after inserting
624 * something.
625 * Don't do this when the topline changed already, it has
626 * already been adjusted (by insertchar() calling open_line())).
628 if (curbuf->b_mod_set
629 && curwin->w_p_wrap
630 && !did_backspace
631 && curwin->w_topline == old_topline
632 #ifdef FEAT_DIFF
633 && curwin->w_topfill == old_topfill
634 #endif
637 mincol = curwin->w_wcol;
638 validate_cursor_col();
640 if ((int)curwin->w_wcol < (int)mincol - curbuf->b_p_ts
641 && curwin->w_wrow == W_WINROW(curwin)
642 + curwin->w_height - 1 - p_so
643 && (curwin->w_cursor.lnum != curwin->w_topline
644 #ifdef FEAT_DIFF
645 || curwin->w_topfill > 0
646 #endif
649 #ifdef FEAT_DIFF
650 if (curwin->w_topfill > 0)
651 --curwin->w_topfill;
652 else
653 #endif
654 #ifdef FEAT_FOLDING
655 if (hasFolding(curwin->w_topline, NULL, &old_topline))
656 set_topline(curwin, old_topline + 1);
657 else
658 #endif
659 set_topline(curwin, curwin->w_topline + 1);
663 /* May need to adjust w_topline to show the cursor. */
664 update_topline();
666 did_backspace = FALSE;
668 validate_cursor(); /* may set must_redraw */
671 * Redraw the display when no characters are waiting.
672 * Also shows mode, ruler and positions cursor.
674 ins_redraw(TRUE);
676 #ifdef FEAT_SCROLLBIND
677 if (curwin->w_p_scb)
678 do_check_scrollbind(TRUE);
679 #endif
681 update_curswant();
682 old_topline = curwin->w_topline;
683 #ifdef FEAT_DIFF
684 old_topfill = curwin->w_topfill;
685 #endif
687 #ifdef USE_ON_FLY_SCROLL
688 dont_scroll = FALSE; /* allow scrolling here */
689 #endif
692 * Get a character for Insert mode.
694 lastc = c; /* remember previous char for CTRL-D */
695 c = safe_vgetc();
697 #ifdef FEAT_RIGHTLEFT
698 if (p_hkmap && KeyTyped)
699 c = hkmap(c); /* Hebrew mode mapping */
700 #endif
701 #ifdef FEAT_FKMAP
702 if (p_fkmap && KeyTyped)
703 c = fkmap(c); /* Farsi mode mapping */
704 #endif
706 #ifdef FEAT_INS_EXPAND
708 * Special handling of keys while the popup menu is visible or wanted
709 * and the cursor is still in the completed word.
711 if (compl_started && pum_wanted() && curwin->w_cursor.col >= compl_col)
713 /* BS: Delete one character from "compl_leader". */
714 if ((c == K_BS || c == Ctrl_H)
715 && curwin->w_cursor.col > compl_col
716 && (c = ins_compl_bs()) == NUL)
717 continue;
719 /* When no match was selected or it was edited. */
720 if (!compl_used_match)
722 /* CTRL-L: Add one character from the current match to
723 * "compl_leader". Except when at the original match and
724 * there is nothing to add, CTRL-L works like CTRL-P then. */
725 if (c == Ctrl_L
726 && (ctrl_x_mode != CTRL_X_WHOLE_LINE
727 || STRLEN(compl_shown_match->cp_str)
728 > curwin->w_cursor.col - compl_col))
730 ins_compl_addfrommatch();
731 continue;
734 /* A printable, non-white character: Add to "compl_leader". */
735 if (vim_isprintc(c) && !vim_iswhite(c))
737 ins_compl_addleader(c);
738 continue;
741 /* Pressing CTRL-Y selects the current match. Shen
742 * compl_enter_selects is set the Enter key does the same. */
743 if (c == Ctrl_Y || (compl_enter_selects
744 && (c == CAR || c == K_KENTER || c == NL)))
746 ins_compl_delete();
747 ins_compl_insert();
752 /* Prepare for or stop CTRL-X mode. This doesn't do completion, but
753 * it does fix up the text when finishing completion. */
754 compl_get_longest = FALSE;
755 if (c != K_IGNORE && ins_compl_prep(c))
756 continue;
757 #endif
759 /* CTRL-\ CTRL-N goes to Normal mode,
760 * CTRL-\ CTRL-G goes to mode selected with 'insertmode',
761 * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor. */
762 if (c == Ctrl_BSL)
764 /* may need to redraw when no more chars available now */
765 ins_redraw(FALSE);
766 ++no_mapping;
767 ++allow_keys;
768 c = safe_vgetc();
769 --no_mapping;
770 --allow_keys;
771 if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O)
773 /* it's something else */
774 vungetc(c);
775 c = Ctrl_BSL;
777 else if (c == Ctrl_G && p_im)
778 continue;
779 else
781 if (c == Ctrl_O)
783 ins_ctrl_o();
784 ins_at_eol = FALSE; /* cursor keeps its column */
785 nomove = TRUE;
787 count = 0;
788 goto doESCkey;
792 #ifdef FEAT_DIGRAPHS
793 c = do_digraph(c);
794 #endif
796 #ifdef FEAT_INS_EXPAND
797 if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
798 goto docomplete;
799 #endif
800 if (c == Ctrl_V || c == Ctrl_Q)
802 ins_ctrl_v();
803 c = Ctrl_V; /* pretend CTRL-V is last typed character */
804 continue;
807 #ifdef FEAT_CINDENT
808 if (cindent_on()
809 # ifdef FEAT_INS_EXPAND
810 && ctrl_x_mode == 0
811 # endif
814 /* A key name preceded by a bang means this key is not to be
815 * inserted. Skip ahead to the re-indenting below.
816 * A key name preceded by a star means that indenting has to be
817 * done before inserting the key. */
818 line_is_white = inindent(0);
819 if (in_cinkeys(c, '!', line_is_white))
820 goto force_cindent;
821 if (can_cindent && in_cinkeys(c, '*', line_is_white)
822 && stop_arrow() == OK)
823 do_c_expr_indent();
825 #endif
827 #ifdef FEAT_RIGHTLEFT
828 if (curwin->w_p_rl)
829 switch (c)
831 case K_LEFT: c = K_RIGHT; break;
832 case K_S_LEFT: c = K_S_RIGHT; break;
833 case K_C_LEFT: c = K_C_RIGHT; break;
834 case K_RIGHT: c = K_LEFT; break;
835 case K_S_RIGHT: c = K_S_LEFT; break;
836 case K_C_RIGHT: c = K_C_LEFT; break;
838 #endif
840 #ifdef FEAT_VISUAL
842 * If 'keymodel' contains "startsel", may start selection. If it
843 * does, a CTRL-O and c will be stuffed, we need to get these
844 * characters.
846 if (ins_start_select(c))
847 continue;
848 #endif
851 * The big switch to handle a character in insert mode.
853 switch (c)
855 case ESC: /* End input mode */
856 if (echeck_abbr(ESC + ABBR_OFF))
857 break;
858 /*FALLTHROUGH*/
860 case Ctrl_C: /* End input mode */
861 #ifdef FEAT_CMDWIN
862 if (c == Ctrl_C && cmdwin_type != 0)
864 /* Close the cmdline window. */
865 cmdwin_result = K_IGNORE;
866 got_int = FALSE; /* don't stop executing autocommands et al. */
867 goto doESCkey;
869 #endif
871 #ifdef UNIX
872 do_intr:
873 #endif
874 /* when 'insertmode' set, and not halfway a mapping, don't leave
875 * Insert mode */
876 if (goto_im())
878 if (got_int)
880 (void)vgetc(); /* flush all buffers */
881 got_int = FALSE;
883 else
884 vim_beep();
885 break;
887 doESCkey:
889 * This is the ONLY return from edit()!
891 /* Always update o_lnum, so that a "CTRL-O ." that adds a line
892 * still puts the cursor back after the inserted text. */
893 if (ins_at_eol && gchar_cursor() == NUL)
894 o_lnum = curwin->w_cursor.lnum;
896 if (ins_esc(&count, cmdchar, nomove))
898 #ifdef FEAT_AUTOCMD
899 if (cmdchar != 'r' && cmdchar != 'v')
900 apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
901 FALSE, curbuf);
902 #endif
903 return (c == Ctrl_O);
905 continue;
907 case Ctrl_Z: /* suspend when 'insertmode' set */
908 if (!p_im)
909 goto normalchar; /* insert CTRL-Z as normal char */
910 stuffReadbuff((char_u *)":st\r");
911 c = Ctrl_O;
912 /*FALLTHROUGH*/
914 case Ctrl_O: /* execute one command */
915 #ifdef FEAT_COMPL_FUNC
916 if (ctrl_x_mode == CTRL_X_OMNI)
917 goto docomplete;
918 #endif
919 if (echeck_abbr(Ctrl_O + ABBR_OFF))
920 break;
921 ins_ctrl_o();
922 count = 0;
923 goto doESCkey;
925 case K_INS: /* toggle insert/replace mode */
926 case K_KINS:
927 ins_insert(replaceState);
928 break;
930 case K_SELECT: /* end of Select mode mapping - ignore */
931 break;
933 #ifdef FEAT_SNIFF
934 case K_SNIFF: /* Sniff command received */
935 stuffcharReadbuff(K_SNIFF);
936 goto doESCkey;
937 #endif
939 case K_HELP: /* Help key works like <ESC> <Help> */
940 case K_F1:
941 case K_XF1:
942 stuffcharReadbuff(K_HELP);
943 if (p_im)
944 need_start_insertmode = TRUE;
945 goto doESCkey;
947 #ifdef FEAT_NETBEANS_INTG
948 case K_F21: /* NetBeans command */
949 ++no_mapping; /* don't map the next key hits */
950 i = safe_vgetc();
951 --no_mapping;
952 netbeans_keycommand(i);
953 break;
954 #endif
956 case K_ZERO: /* Insert the previously inserted text. */
957 case NUL:
958 case Ctrl_A:
959 /* For ^@ the trailing ESC will end the insert, unless there is an
960 * error. */
961 if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
962 && c != Ctrl_A && !p_im)
963 goto doESCkey; /* quit insert mode */
964 inserted_space = FALSE;
965 break;
967 case Ctrl_R: /* insert the contents of a register */
968 ins_reg();
969 auto_format(FALSE, TRUE);
970 inserted_space = FALSE;
971 break;
973 case Ctrl_G: /* commands starting with CTRL-G */
974 ins_ctrl_g();
975 break;
977 case Ctrl_HAT: /* switch input mode and/or langmap */
978 ins_ctrl_hat();
979 break;
981 #ifdef FEAT_RIGHTLEFT
982 case Ctrl__: /* switch between languages */
983 if (!p_ari)
984 goto normalchar;
985 ins_ctrl_();
986 break;
987 #endif
989 case Ctrl_D: /* Make indent one shiftwidth smaller. */
990 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
991 if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
992 goto docomplete;
993 #endif
994 /* FALLTHROUGH */
996 case Ctrl_T: /* Make indent one shiftwidth greater. */
997 # ifdef FEAT_INS_EXPAND
998 if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
1000 if (has_compl_option(FALSE))
1001 goto docomplete;
1002 break;
1004 # endif
1005 ins_shift(c, lastc);
1006 auto_format(FALSE, TRUE);
1007 inserted_space = FALSE;
1008 break;
1010 case K_DEL: /* delete character under the cursor */
1011 case K_KDEL:
1012 ins_del();
1013 auto_format(FALSE, TRUE);
1014 break;
1016 case K_BS: /* delete character before the cursor */
1017 case Ctrl_H:
1018 did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1019 auto_format(FALSE, TRUE);
1020 break;
1022 case Ctrl_W: /* delete word before the cursor */
1023 did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1024 auto_format(FALSE, TRUE);
1025 break;
1027 case Ctrl_U: /* delete all inserted text in current line */
1028 # ifdef FEAT_COMPL_FUNC
1029 /* CTRL-X CTRL-U completes with 'completefunc'. */
1030 if (ctrl_x_mode == CTRL_X_FUNCTION)
1031 goto docomplete;
1032 # endif
1033 did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1034 auto_format(FALSE, TRUE);
1035 inserted_space = FALSE;
1036 break;
1038 #ifdef FEAT_MOUSE
1039 case K_LEFTMOUSE: /* mouse keys */
1040 case K_LEFTMOUSE_NM:
1041 case K_LEFTDRAG:
1042 case K_LEFTRELEASE:
1043 case K_LEFTRELEASE_NM:
1044 case K_MIDDLEMOUSE:
1045 case K_MIDDLEDRAG:
1046 case K_MIDDLERELEASE:
1047 case K_RIGHTMOUSE:
1048 case K_RIGHTDRAG:
1049 case K_RIGHTRELEASE:
1050 case K_X1MOUSE:
1051 case K_X1DRAG:
1052 case K_X1RELEASE:
1053 case K_X2MOUSE:
1054 case K_X2DRAG:
1055 case K_X2RELEASE:
1056 ins_mouse(c);
1057 break;
1059 case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */
1060 ins_mousescroll(FALSE);
1061 break;
1063 case K_MOUSEUP: /* Default action for scroll wheel down: scroll down */
1064 ins_mousescroll(TRUE);
1065 break;
1066 #endif
1067 #ifdef FEAT_GUI_TABLINE
1068 case K_TABLINE:
1069 case K_TABMENU:
1070 ins_tabline(c);
1071 break;
1072 #endif
1074 case K_IGNORE: /* Something mapped to nothing */
1075 break;
1077 #ifdef FEAT_AUTOCMD
1078 case K_CURSORHOLD: /* Didn't type something for a while. */
1079 apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf);
1080 did_cursorhold = TRUE;
1081 break;
1082 #endif
1084 #ifdef FEAT_GUI_W32
1085 /* On Win32 ignore <M-F4>, we get it when closing the window was
1086 * cancelled. */
1087 case K_F4:
1088 if (mod_mask != MOD_MASK_ALT)
1089 goto normalchar;
1090 break;
1091 #endif
1093 #ifdef FEAT_GUI
1094 case K_VER_SCROLLBAR:
1095 ins_scroll();
1096 break;
1098 case K_HOR_SCROLLBAR:
1099 ins_horscroll();
1100 break;
1101 #endif
1103 case K_HOME: /* <Home> */
1104 case K_KHOME:
1105 case K_S_HOME:
1106 case K_C_HOME:
1107 ins_home(c);
1108 break;
1110 case K_END: /* <End> */
1111 case K_KEND:
1112 case K_S_END:
1113 case K_C_END:
1114 ins_end(c);
1115 break;
1117 case K_LEFT: /* <Left> */
1118 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1119 ins_s_left();
1120 else
1121 ins_left();
1122 break;
1124 case K_S_LEFT: /* <S-Left> */
1125 case K_C_LEFT:
1126 ins_s_left();
1127 break;
1129 case K_RIGHT: /* <Right> */
1130 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1131 ins_s_right();
1132 else
1133 ins_right();
1134 break;
1136 case K_S_RIGHT: /* <S-Right> */
1137 case K_C_RIGHT:
1138 ins_s_right();
1139 break;
1141 case K_UP: /* <Up> */
1142 #ifdef FEAT_INS_EXPAND
1143 if (pum_visible())
1144 goto docomplete;
1145 #endif
1146 if (mod_mask & MOD_MASK_SHIFT)
1147 ins_pageup();
1148 else
1149 ins_up(FALSE);
1150 break;
1152 case K_S_UP: /* <S-Up> */
1153 case K_PAGEUP:
1154 case K_KPAGEUP:
1155 #ifdef FEAT_INS_EXPAND
1156 if (pum_visible())
1157 goto docomplete;
1158 #endif
1159 ins_pageup();
1160 break;
1162 case K_DOWN: /* <Down> */
1163 #ifdef FEAT_INS_EXPAND
1164 if (pum_visible())
1165 goto docomplete;
1166 #endif
1167 if (mod_mask & MOD_MASK_SHIFT)
1168 ins_pagedown();
1169 else
1170 ins_down(FALSE);
1171 break;
1173 case K_S_DOWN: /* <S-Down> */
1174 case K_PAGEDOWN:
1175 case K_KPAGEDOWN:
1176 #ifdef FEAT_INS_EXPAND
1177 if (pum_visible())
1178 goto docomplete;
1179 #endif
1180 ins_pagedown();
1181 break;
1183 #ifdef FEAT_DND
1184 case K_DROP: /* drag-n-drop event */
1185 ins_drop();
1186 break;
1187 #endif
1189 case K_S_TAB: /* When not mapped, use like a normal TAB */
1190 c = TAB;
1191 /* FALLTHROUGH */
1193 case TAB: /* TAB or Complete patterns along path */
1194 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1195 if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1196 goto docomplete;
1197 #endif
1198 inserted_space = FALSE;
1199 if (ins_tab())
1200 goto normalchar; /* insert TAB as a normal char */
1201 auto_format(FALSE, TRUE);
1202 break;
1204 case K_KENTER: /* <Enter> */
1205 c = CAR;
1206 /* FALLTHROUGH */
1207 case CAR:
1208 case NL:
1209 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1210 /* In a quickfix window a <CR> jumps to the error under the
1211 * cursor. */
1212 if (bt_quickfix(curbuf) && c == CAR)
1214 if (curwin->w_llist_ref == NULL) /* quickfix window */
1215 do_cmdline_cmd((char_u *)".cc");
1216 else /* location list window */
1217 do_cmdline_cmd((char_u *)".ll");
1218 break;
1220 #endif
1221 #ifdef FEAT_CMDWIN
1222 if (cmdwin_type != 0)
1224 /* Execute the command in the cmdline window. */
1225 cmdwin_result = CAR;
1226 goto doESCkey;
1228 #endif
1229 if (ins_eol(c) && !p_im)
1230 goto doESCkey; /* out of memory */
1231 auto_format(FALSE, FALSE);
1232 inserted_space = FALSE;
1233 break;
1235 #if defined(FEAT_DIGRAPHS) || defined (FEAT_INS_EXPAND)
1236 case Ctrl_K: /* digraph or keyword completion */
1237 # ifdef FEAT_INS_EXPAND
1238 if (ctrl_x_mode == CTRL_X_DICTIONARY)
1240 if (has_compl_option(TRUE))
1241 goto docomplete;
1242 break;
1244 # endif
1245 # ifdef FEAT_DIGRAPHS
1246 c = ins_digraph();
1247 if (c == NUL)
1248 break;
1249 # endif
1250 goto normalchar;
1251 #endif
1253 #ifdef FEAT_INS_EXPAND
1254 case Ctrl_X: /* Enter CTRL-X mode */
1255 ins_ctrl_x();
1256 break;
1258 case Ctrl_RSB: /* Tag name completion after ^X */
1259 if (ctrl_x_mode != CTRL_X_TAGS)
1260 goto normalchar;
1261 goto docomplete;
1263 case Ctrl_F: /* File name completion after ^X */
1264 if (ctrl_x_mode != CTRL_X_FILES)
1265 goto normalchar;
1266 goto docomplete;
1268 case 's': /* Spelling completion after ^X */
1269 case Ctrl_S:
1270 if (ctrl_x_mode != CTRL_X_SPELL)
1271 goto normalchar;
1272 goto docomplete;
1273 #endif
1275 case Ctrl_L: /* Whole line completion after ^X */
1276 #ifdef FEAT_INS_EXPAND
1277 if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1278 #endif
1280 /* CTRL-L with 'insertmode' set: Leave Insert mode */
1281 if (p_im)
1283 if (echeck_abbr(Ctrl_L + ABBR_OFF))
1284 break;
1285 goto doESCkey;
1287 goto normalchar;
1289 #ifdef FEAT_INS_EXPAND
1290 /* FALLTHROUGH */
1292 case Ctrl_P: /* Do previous/next pattern completion */
1293 case Ctrl_N:
1294 /* if 'complete' is empty then plain ^P is no longer special,
1295 * but it is under other ^X modes */
1296 if (*curbuf->b_p_cpt == NUL
1297 && ctrl_x_mode != 0
1298 && !(compl_cont_status & CONT_LOCAL))
1299 goto normalchar;
1301 docomplete:
1302 if (ins_complete(c) == FAIL)
1303 compl_cont_status = 0;
1304 break;
1305 #endif /* FEAT_INS_EXPAND */
1307 case Ctrl_Y: /* copy from previous line or scroll down */
1308 case Ctrl_E: /* copy from next line or scroll up */
1309 c = ins_ctrl_ey(c);
1310 break;
1312 default:
1313 #ifdef UNIX
1314 if (c == intr_char) /* special interrupt char */
1315 goto do_intr;
1316 #endif
1319 * Insert a nomal character.
1321 normalchar:
1322 #ifdef FEAT_SMARTINDENT
1323 /* Try to perform smart-indenting. */
1324 ins_try_si(c);
1325 #endif
1327 if (c == ' ')
1329 inserted_space = TRUE;
1330 #ifdef FEAT_CINDENT
1331 if (inindent(0))
1332 can_cindent = FALSE;
1333 #endif
1334 if (Insstart_blank_vcol == MAXCOL
1335 && curwin->w_cursor.lnum == Insstart.lnum)
1336 Insstart_blank_vcol = get_nolist_virtcol();
1339 if (vim_iswordc(c) || !echeck_abbr(
1340 #ifdef FEAT_MBYTE
1341 /* Add ABBR_OFF for characters above 0x100, this is
1342 * what check_abbr() expects. */
1343 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1344 #endif
1347 insert_special(c, FALSE, FALSE);
1348 #ifdef FEAT_RIGHTLEFT
1349 revins_legal++;
1350 revins_chars++;
1351 #endif
1354 auto_format(FALSE, TRUE);
1356 #ifdef FEAT_FOLDING
1357 /* When inserting a character the cursor line must never be in a
1358 * closed fold. */
1359 foldOpenCursor();
1360 #endif
1361 break;
1362 } /* end of switch (c) */
1364 /* If the cursor was moved we didn't just insert a space */
1365 if (arrow_used)
1366 inserted_space = FALSE;
1368 #ifdef FEAT_CINDENT
1369 if (can_cindent && cindent_on()
1370 # ifdef FEAT_INS_EXPAND
1371 && ctrl_x_mode == 0
1372 # endif
1375 force_cindent:
1377 * Indent now if a key was typed that is in 'cinkeys'.
1379 if (in_cinkeys(c, ' ', line_is_white))
1381 if (stop_arrow() == OK)
1382 /* re-indent the current line */
1383 do_c_expr_indent();
1386 #endif /* FEAT_CINDENT */
1388 } /* for (;;) */
1389 /* NOTREACHED */
1393 * Redraw for Insert mode.
1394 * This is postponed until getting the next character to make '$' in the 'cpo'
1395 * option work correctly.
1396 * Only redraw when there are no characters available. This speeds up
1397 * inserting sequences of characters (e.g., for CTRL-R).
1399 /*ARGSUSED*/
1400 static void
1401 ins_redraw(ready)
1402 int ready; /* not busy with something */
1404 if (!char_avail())
1406 #ifdef FEAT_AUTOCMD
1407 /* Trigger CursorMoved if the cursor moved. Not when the popup menu is
1408 * visible, the command might delete it. */
1409 if (ready && has_cursormovedI()
1410 && !equalpos(last_cursormoved, curwin->w_cursor)
1411 # ifdef FEAT_INS_EXPAND
1412 && !pum_visible()
1413 # endif
1416 apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf);
1417 last_cursormoved = curwin->w_cursor;
1419 #endif
1420 if (must_redraw)
1421 update_screen(0);
1422 else if (clear_cmdline || redraw_cmdline)
1423 showmode(); /* clear cmdline and show mode */
1424 showruler(FALSE);
1425 setcursor();
1426 emsg_on_display = FALSE; /* may remove error message now */
1431 * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1433 static void
1434 ins_ctrl_v()
1436 int c;
1438 /* may need to redraw when no more chars available now */
1439 ins_redraw(FALSE);
1441 if (redrawing() && !char_avail())
1442 edit_putchar('^', TRUE);
1443 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1445 #ifdef FEAT_CMDL_INFO
1446 add_to_showcmd_c(Ctrl_V);
1447 #endif
1449 c = get_literal();
1450 #ifdef FEAT_CMDL_INFO
1451 clear_showcmd();
1452 #endif
1453 insert_special(c, FALSE, TRUE);
1454 #ifdef FEAT_RIGHTLEFT
1455 revins_chars++;
1456 revins_legal++;
1457 #endif
1461 * Put a character directly onto the screen. It's not stored in a buffer.
1462 * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1464 static int pc_status;
1465 #define PC_STATUS_UNSET 0 /* pc_bytes was not set */
1466 #define PC_STATUS_RIGHT 1 /* right halve of double-wide char */
1467 #define PC_STATUS_LEFT 2 /* left halve of double-wide char */
1468 #define PC_STATUS_SET 3 /* pc_bytes was filled */
1469 #ifdef FEAT_MBYTE
1470 static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1471 #else
1472 static char_u pc_bytes[2]; /* saved bytes */
1473 #endif
1474 static int pc_attr;
1475 static int pc_row;
1476 static int pc_col;
1478 void
1479 edit_putchar(c, highlight)
1480 int c;
1481 int highlight;
1483 int attr;
1485 if (ScreenLines != NULL)
1487 update_topline(); /* just in case w_topline isn't valid */
1488 validate_cursor();
1489 if (highlight)
1490 attr = hl_attr(HLF_8);
1491 else
1492 attr = 0;
1493 pc_row = W_WINROW(curwin) + curwin->w_wrow;
1494 pc_col = W_WINCOL(curwin);
1495 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1496 pc_status = PC_STATUS_UNSET;
1497 #endif
1498 #ifdef FEAT_RIGHTLEFT
1499 if (curwin->w_p_rl)
1501 pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1502 # ifdef FEAT_MBYTE
1503 if (has_mbyte)
1505 int fix_col = mb_fix_col(pc_col, pc_row);
1507 if (fix_col != pc_col)
1509 screen_putchar(' ', pc_row, fix_col, attr);
1510 --curwin->w_wcol;
1511 pc_status = PC_STATUS_RIGHT;
1514 # endif
1516 else
1517 #endif
1519 pc_col += curwin->w_wcol;
1520 #ifdef FEAT_MBYTE
1521 if (mb_lefthalve(pc_row, pc_col))
1522 pc_status = PC_STATUS_LEFT;
1523 #endif
1526 /* save the character to be able to put it back */
1527 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1528 if (pc_status == PC_STATUS_UNSET)
1529 #endif
1531 screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1532 pc_status = PC_STATUS_SET;
1534 screen_putchar(c, pc_row, pc_col, attr);
1539 * Undo the previous edit_putchar().
1541 void
1542 edit_unputchar()
1544 if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1546 #if defined(FEAT_MBYTE)
1547 if (pc_status == PC_STATUS_RIGHT)
1548 ++curwin->w_wcol;
1549 if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1550 redrawWinline(curwin->w_cursor.lnum, FALSE);
1551 else
1552 #endif
1553 screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1558 * Called when p_dollar is set: display a '$' at the end of the changed text
1559 * Only works when cursor is in the line that changes.
1561 void
1562 display_dollar(col)
1563 colnr_T col;
1565 colnr_T save_col;
1567 if (!redrawing())
1568 return;
1570 cursor_off();
1571 save_col = curwin->w_cursor.col;
1572 curwin->w_cursor.col = col;
1573 #ifdef FEAT_MBYTE
1574 if (has_mbyte)
1576 char_u *p;
1578 /* If on the last byte of a multi-byte move to the first byte. */
1579 p = ml_get_curline();
1580 curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1582 #endif
1583 curs_columns(FALSE); /* recompute w_wrow and w_wcol */
1584 if (curwin->w_wcol < W_WIDTH(curwin))
1586 edit_putchar('$', FALSE);
1587 dollar_vcol = curwin->w_virtcol;
1589 curwin->w_cursor.col = save_col;
1593 * Call this function before moving the cursor from the normal insert position
1594 * in insert mode.
1596 static void
1597 undisplay_dollar()
1599 if (dollar_vcol)
1601 dollar_vcol = 0;
1602 redrawWinline(curwin->w_cursor.lnum, FALSE);
1607 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1608 * Keep the cursor on the same character.
1609 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1610 * type == INDENT_DEC decrease indent (for CTRL-D)
1611 * type == INDENT_SET set indent to "amount"
1612 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1614 void
1615 change_indent(type, amount, round, replaced)
1616 int type;
1617 int amount;
1618 int round;
1619 int replaced; /* replaced character, put on replace stack */
1621 int vcol;
1622 int last_vcol;
1623 int insstart_less; /* reduction for Insstart.col */
1624 int new_cursor_col;
1625 int i;
1626 char_u *ptr;
1627 int save_p_list;
1628 int start_col;
1629 colnr_T vc;
1630 #ifdef FEAT_VREPLACE
1631 colnr_T orig_col = 0; /* init for GCC */
1632 char_u *new_line, *orig_line = NULL; /* init for GCC */
1634 /* VREPLACE mode needs to know what the line was like before changing */
1635 if (State & VREPLACE_FLAG)
1637 orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */
1638 orig_col = curwin->w_cursor.col;
1640 #endif
1642 /* for the following tricks we don't want list mode */
1643 save_p_list = curwin->w_p_list;
1644 curwin->w_p_list = FALSE;
1645 vc = getvcol_nolist(&curwin->w_cursor);
1646 vcol = vc;
1649 * For Replace mode we need to fix the replace stack later, which is only
1650 * possible when the cursor is in the indent. Remember the number of
1651 * characters before the cursor if it's possible.
1653 start_col = curwin->w_cursor.col;
1655 /* determine offset from first non-blank */
1656 new_cursor_col = curwin->w_cursor.col;
1657 beginline(BL_WHITE);
1658 new_cursor_col -= curwin->w_cursor.col;
1660 insstart_less = curwin->w_cursor.col;
1663 * If the cursor is in the indent, compute how many screen columns the
1664 * cursor is to the left of the first non-blank.
1666 if (new_cursor_col < 0)
1667 vcol = get_indent() - vcol;
1669 if (new_cursor_col > 0) /* can't fix replace stack */
1670 start_col = -1;
1673 * Set the new indent. The cursor will be put on the first non-blank.
1675 if (type == INDENT_SET)
1676 (void)set_indent(amount, SIN_CHANGED);
1677 else
1679 #ifdef FEAT_VREPLACE
1680 int save_State = State;
1682 /* Avoid being called recursively. */
1683 if (State & VREPLACE_FLAG)
1684 State = INSERT;
1685 #endif
1686 shift_line(type == INDENT_DEC, round, 1);
1687 #ifdef FEAT_VREPLACE
1688 State = save_State;
1689 #endif
1691 insstart_less -= curwin->w_cursor.col;
1694 * Try to put cursor on same character.
1695 * If the cursor is at or after the first non-blank in the line,
1696 * compute the cursor column relative to the column of the first
1697 * non-blank character.
1698 * If we are not in insert mode, leave the cursor on the first non-blank.
1699 * If the cursor is before the first non-blank, position it relative
1700 * to the first non-blank, counted in screen columns.
1702 if (new_cursor_col >= 0)
1705 * When changing the indent while the cursor is touching it, reset
1706 * Insstart_col to 0.
1708 if (new_cursor_col == 0)
1709 insstart_less = MAXCOL;
1710 new_cursor_col += curwin->w_cursor.col;
1712 else if (!(State & INSERT))
1713 new_cursor_col = curwin->w_cursor.col;
1714 else
1717 * Compute the screen column where the cursor should be.
1719 vcol = get_indent() - vcol;
1720 curwin->w_virtcol = (vcol < 0) ? 0 : vcol;
1723 * Advance the cursor until we reach the right screen column.
1725 vcol = last_vcol = 0;
1726 new_cursor_col = -1;
1727 ptr = ml_get_curline();
1728 while (vcol <= (int)curwin->w_virtcol)
1730 last_vcol = vcol;
1731 #ifdef FEAT_MBYTE
1732 if (has_mbyte && new_cursor_col >= 0)
1733 new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1734 else
1735 #endif
1736 ++new_cursor_col;
1737 vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol);
1739 vcol = last_vcol;
1742 * May need to insert spaces to be able to position the cursor on
1743 * the right screen column.
1745 if (vcol != (int)curwin->w_virtcol)
1747 curwin->w_cursor.col = new_cursor_col;
1748 i = (int)curwin->w_virtcol - vcol;
1749 ptr = alloc(i + 1);
1750 if (ptr != NULL)
1752 new_cursor_col += i;
1753 ptr[i] = NUL;
1754 while (--i >= 0)
1755 ptr[i] = ' ';
1756 ins_str(ptr);
1757 vim_free(ptr);
1762 * When changing the indent while the cursor is in it, reset
1763 * Insstart_col to 0.
1765 insstart_less = MAXCOL;
1768 curwin->w_p_list = save_p_list;
1770 if (new_cursor_col <= 0)
1771 curwin->w_cursor.col = 0;
1772 else
1773 curwin->w_cursor.col = new_cursor_col;
1774 curwin->w_set_curswant = TRUE;
1775 changed_cline_bef_curs();
1778 * May have to adjust the start of the insert.
1780 if (State & INSERT)
1782 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1784 if ((int)Insstart.col <= insstart_less)
1785 Insstart.col = 0;
1786 else
1787 Insstart.col -= insstart_less;
1789 if ((int)ai_col <= insstart_less)
1790 ai_col = 0;
1791 else
1792 ai_col -= insstart_less;
1796 * For REPLACE mode, may have to fix the replace stack, if it's possible.
1797 * If the number of characters before the cursor decreased, need to pop a
1798 * few characters from the replace stack.
1799 * If the number of characters before the cursor increased, need to push a
1800 * few NULs onto the replace stack.
1802 if (REPLACE_NORMAL(State) && start_col >= 0)
1804 while (start_col > (int)curwin->w_cursor.col)
1806 replace_join(0); /* remove a NUL from the replace stack */
1807 --start_col;
1809 while (start_col < (int)curwin->w_cursor.col || replaced)
1811 replace_push(NUL);
1812 if (replaced)
1814 replace_push(replaced);
1815 replaced = NUL;
1817 ++start_col;
1821 #ifdef FEAT_VREPLACE
1823 * For VREPLACE mode, we also have to fix the replace stack. In this case
1824 * it is always possible because we backspace over the whole line and then
1825 * put it back again the way we wanted it.
1827 if (State & VREPLACE_FLAG)
1829 /* If orig_line didn't allocate, just return. At least we did the job,
1830 * even if you can't backspace. */
1831 if (orig_line == NULL)
1832 return;
1834 /* Save new line */
1835 new_line = vim_strsave(ml_get_curline());
1836 if (new_line == NULL)
1837 return;
1839 /* We only put back the new line up to the cursor */
1840 new_line[curwin->w_cursor.col] = NUL;
1842 /* Put back original line */
1843 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1844 curwin->w_cursor.col = orig_col;
1846 /* Backspace from cursor to start of line */
1847 backspace_until_column(0);
1849 /* Insert new stuff into line again */
1850 ins_bytes(new_line);
1852 vim_free(new_line);
1854 #endif
1858 * Truncate the space at the end of a line. This is to be used only in an
1859 * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE
1860 * modes.
1862 void
1863 truncate_spaces(line)
1864 char_u *line;
1866 int i;
1868 /* find start of trailing white space */
1869 for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
1871 if (State & REPLACE_FLAG)
1872 replace_join(0); /* remove a NUL from the replace stack */
1874 line[i + 1] = NUL;
1877 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1878 || defined(FEAT_COMMENTS) || defined(PROTO)
1880 * Backspace the cursor until the given column. Handles REPLACE and VREPLACE
1881 * modes correctly. May also be used when not in insert mode at all.
1883 void
1884 backspace_until_column(col)
1885 int col;
1887 while ((int)curwin->w_cursor.col > col)
1889 curwin->w_cursor.col--;
1890 if (State & REPLACE_FLAG)
1891 replace_do_bs();
1892 else
1893 (void)del_char(FALSE);
1896 #endif
1898 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
1900 * CTRL-X pressed in Insert mode.
1902 static void
1903 ins_ctrl_x()
1905 /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
1906 * CTRL-V works like CTRL-N */
1907 if (ctrl_x_mode != CTRL_X_CMDLINE)
1909 /* if the next ^X<> won't ADD nothing, then reset
1910 * compl_cont_status */
1911 if (compl_cont_status & CONT_N_ADDS)
1912 compl_cont_status |= CONT_INTRPT;
1913 else
1914 compl_cont_status = 0;
1915 /* We're not sure which CTRL-X mode it will be yet */
1916 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
1917 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
1918 edit_submode_pre = NULL;
1919 showmode();
1924 * Return TRUE if the 'dict' or 'tsr' option can be used.
1926 static int
1927 has_compl_option(dict_opt)
1928 int dict_opt;
1930 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
1931 # ifdef FEAT_SPELL
1932 && !curwin->w_p_spell
1933 # endif
1935 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
1937 ctrl_x_mode = 0;
1938 edit_submode = NULL;
1939 msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty")
1940 : (char_u *)_("'thesaurus' option is empty"),
1941 hl_attr(HLF_E));
1942 if (emsg_silent == 0)
1944 vim_beep();
1945 setcursor();
1946 out_flush();
1947 ui_delay(2000L, FALSE);
1949 return FALSE;
1951 return TRUE;
1955 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
1956 * This depends on the current mode.
1959 vim_is_ctrl_x_key(c)
1960 int c;
1962 /* Always allow ^R - let it's results then be checked */
1963 if (c == Ctrl_R)
1964 return TRUE;
1966 /* Accept <PageUp> and <PageDown> if the popup menu is visible. */
1967 if (ins_compl_pum_key(c))
1968 return TRUE;
1970 switch (ctrl_x_mode)
1972 case 0: /* Not in any CTRL-X mode */
1973 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
1974 case CTRL_X_NOT_DEFINED_YET:
1975 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
1976 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
1977 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
1978 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
1979 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
1980 || c == Ctrl_S || c == 's');
1981 case CTRL_X_SCROLL:
1982 return (c == Ctrl_Y || c == Ctrl_E);
1983 case CTRL_X_WHOLE_LINE:
1984 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
1985 case CTRL_X_FILES:
1986 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
1987 case CTRL_X_DICTIONARY:
1988 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
1989 case CTRL_X_THESAURUS:
1990 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
1991 case CTRL_X_TAGS:
1992 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
1993 #ifdef FEAT_FIND_ID
1994 case CTRL_X_PATH_PATTERNS:
1995 return (c == Ctrl_P || c == Ctrl_N);
1996 case CTRL_X_PATH_DEFINES:
1997 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
1998 #endif
1999 case CTRL_X_CMDLINE:
2000 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
2001 || c == Ctrl_X);
2002 #ifdef FEAT_COMPL_FUNC
2003 case CTRL_X_FUNCTION:
2004 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
2005 case CTRL_X_OMNI:
2006 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
2007 #endif
2008 case CTRL_X_SPELL:
2009 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
2011 EMSG(_(e_internal));
2012 return FALSE;
2016 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
2017 * case of the originally typed text is used, and the case of the completed
2018 * text is infered, ie this tries to work out what case you probably wanted
2019 * the rest of the word to be in -- webb
2020 * TODO: make this work for multi-byte characters.
2023 ins_compl_add_infercase(str, len, icase, fname, dir, flags)
2024 char_u *str;
2025 int len;
2026 int icase;
2027 char_u *fname;
2028 int dir;
2029 int flags;
2031 int has_lower = FALSE;
2032 int was_letter = FALSE;
2033 int idx;
2035 if (p_ic && curbuf->b_p_inf && len < IOSIZE)
2037 /* Infer case of completed part -- webb */
2038 /* Use IObuff, str would change text in buffer! */
2039 vim_strncpy(IObuff, str, len);
2041 /* Rule 1: Were any chars converted to lower? */
2042 for (idx = 0; idx < compl_length; ++idx)
2044 if (islower(compl_orig_text[idx]))
2046 has_lower = TRUE;
2047 if (isupper(IObuff[idx]))
2049 /* Rule 1 is satisfied */
2050 for (idx = compl_length; idx < len; ++idx)
2051 IObuff[idx] = TOLOWER_LOC(IObuff[idx]);
2052 break;
2058 * Rule 2: No lower case, 2nd consecutive letter converted to
2059 * upper case.
2061 if (!has_lower)
2063 for (idx = 0; idx < compl_length; ++idx)
2065 if (was_letter && isupper(compl_orig_text[idx])
2066 && islower(IObuff[idx]))
2068 /* Rule 2 is satisfied */
2069 for (idx = compl_length; idx < len; ++idx)
2070 IObuff[idx] = TOUPPER_LOC(IObuff[idx]);
2071 break;
2073 was_letter = isalpha(compl_orig_text[idx]);
2077 /* Copy the original case of the part we typed */
2078 STRNCPY(IObuff, compl_orig_text, compl_length);
2080 return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2081 flags, FALSE);
2083 return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2087 * Add a match to the list of matches.
2088 * If the given string is already in the list of completions, then return
2089 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2090 * maybe because alloc() returns NULL, then FAIL is returned.
2092 static int
2093 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, dup)
2094 char_u *str;
2095 int len;
2096 int icase;
2097 char_u *fname;
2098 char_u **cptext; /* extra text for popup menu or NULL */
2099 int cdir;
2100 int flags;
2101 int dup; /* accept duplicate match */
2103 compl_T *match;
2104 int dir = (cdir == 0 ? compl_direction : cdir);
2106 ui_breakcheck();
2107 if (got_int)
2108 return FAIL;
2109 if (len < 0)
2110 len = (int)STRLEN(str);
2113 * If the same match is already present, don't add it.
2115 if (compl_first_match != NULL && !dup)
2117 match = compl_first_match;
2120 if ( !(match->cp_flags & ORIGINAL_TEXT)
2121 && ins_compl_equal(match, str, len)
2122 && match->cp_str[len] == NUL)
2123 return NOTDONE;
2124 match = match->cp_next;
2125 } while (match != NULL && match != compl_first_match);
2128 /* Remove any popup menu before changing the list of matches. */
2129 ins_compl_del_pum();
2132 * Allocate a new match structure.
2133 * Copy the values to the new match structure.
2135 match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2136 if (match == NULL)
2137 return FAIL;
2138 match->cp_number = -1;
2139 if (flags & ORIGINAL_TEXT)
2140 match->cp_number = 0;
2141 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2143 vim_free(match);
2144 return FAIL;
2146 match->cp_icase = icase;
2148 /* match-fname is:
2149 * - compl_curr_match->cp_fname if it is a string equal to fname.
2150 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2151 * - NULL otherwise. --Acevedo */
2152 if (fname != NULL
2153 && compl_curr_match != NULL
2154 && compl_curr_match->cp_fname != NULL
2155 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2156 match->cp_fname = compl_curr_match->cp_fname;
2157 else if (fname != NULL)
2159 match->cp_fname = vim_strsave(fname);
2160 flags |= FREE_FNAME;
2162 else
2163 match->cp_fname = NULL;
2164 match->cp_flags = flags;
2166 if (cptext != NULL)
2168 int i;
2170 for (i = 0; i < CPT_COUNT; ++i)
2171 if (cptext[i] != NULL && *cptext[i] != NUL)
2172 match->cp_text[i] = vim_strsave(cptext[i]);
2176 * Link the new match structure in the list of matches.
2178 if (compl_first_match == NULL)
2179 match->cp_next = match->cp_prev = NULL;
2180 else if (dir == FORWARD)
2182 match->cp_next = compl_curr_match->cp_next;
2183 match->cp_prev = compl_curr_match;
2185 else /* BACKWARD */
2187 match->cp_next = compl_curr_match;
2188 match->cp_prev = compl_curr_match->cp_prev;
2190 if (match->cp_next)
2191 match->cp_next->cp_prev = match;
2192 if (match->cp_prev)
2193 match->cp_prev->cp_next = match;
2194 else /* if there's nothing before, it is the first match */
2195 compl_first_match = match;
2196 compl_curr_match = match;
2199 * Find the longest common string if still doing that.
2201 if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2202 ins_compl_longest_match(match);
2204 return OK;
2208 * Return TRUE if "str[len]" matches with match->cp_str, considering
2209 * match->cp_icase.
2211 static int
2212 ins_compl_equal(match, str, len)
2213 compl_T *match;
2214 char_u *str;
2215 int len;
2217 if (match->cp_icase)
2218 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2219 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2223 * Reduce the longest common string for match "match".
2225 static void
2226 ins_compl_longest_match(match)
2227 compl_T *match;
2229 char_u *p, *s;
2230 int c1, c2;
2231 int had_match;
2233 if (compl_leader == NULL)
2235 /* First match, use it as a whole. */
2236 compl_leader = vim_strsave(match->cp_str);
2237 if (compl_leader != NULL)
2239 had_match = (curwin->w_cursor.col > compl_col);
2240 ins_compl_delete();
2241 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
2242 ins_redraw(FALSE);
2244 /* When the match isn't there (to avoid matching itself) remove it
2245 * again after redrawing. */
2246 if (!had_match)
2247 ins_compl_delete();
2248 compl_used_match = FALSE;
2251 else
2253 /* Reduce the text if this match differs from compl_leader. */
2254 p = compl_leader;
2255 s = match->cp_str;
2256 while (*p != NUL)
2258 #ifdef FEAT_MBYTE
2259 if (has_mbyte)
2261 c1 = mb_ptr2char(p);
2262 c2 = mb_ptr2char(s);
2264 else
2265 #endif
2267 c1 = *p;
2268 c2 = *s;
2270 if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2271 : (c1 != c2))
2272 break;
2273 #ifdef FEAT_MBYTE
2274 if (has_mbyte)
2276 mb_ptr_adv(p);
2277 mb_ptr_adv(s);
2279 else
2280 #endif
2282 ++p;
2283 ++s;
2287 if (*p != NUL)
2289 /* Leader was shortened, need to change the inserted text. */
2290 *p = NUL;
2291 had_match = (curwin->w_cursor.col > compl_col);
2292 ins_compl_delete();
2293 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
2294 ins_redraw(FALSE);
2296 /* When the match isn't there (to avoid matching itself) remove it
2297 * again after redrawing. */
2298 if (!had_match)
2299 ins_compl_delete();
2302 compl_used_match = FALSE;
2307 * Add an array of matches to the list of matches.
2308 * Frees matches[].
2310 static void
2311 ins_compl_add_matches(num_matches, matches, icase)
2312 int num_matches;
2313 char_u **matches;
2314 int icase;
2316 int i;
2317 int add_r = OK;
2318 int dir = compl_direction;
2320 for (i = 0; i < num_matches && add_r != FAIL; i++)
2321 if ((add_r = ins_compl_add(matches[i], -1, icase,
2322 NULL, NULL, dir, 0, FALSE)) == OK)
2323 /* if dir was BACKWARD then honor it just once */
2324 dir = FORWARD;
2325 FreeWild(num_matches, matches);
2328 /* Make the completion list cyclic.
2329 * Return the number of matches (excluding the original).
2331 static int
2332 ins_compl_make_cyclic()
2334 compl_T *match;
2335 int count = 0;
2337 if (compl_first_match != NULL)
2340 * Find the end of the list.
2342 match = compl_first_match;
2343 /* there's always an entry for the compl_orig_text, it doesn't count. */
2344 while (match->cp_next != NULL && match->cp_next != compl_first_match)
2346 match = match->cp_next;
2347 ++count;
2349 match->cp_next = compl_first_match;
2350 compl_first_match->cp_prev = match;
2352 return count;
2356 * Start completion for the complete() function.
2357 * "startcol" is where the matched text starts (1 is first column).
2358 * "list" is the list of matches.
2360 void
2361 set_completion(startcol, list)
2362 int startcol;
2363 list_T *list;
2365 /* If already doing completions stop it. */
2366 if (ctrl_x_mode != 0)
2367 ins_compl_prep(' ');
2368 ins_compl_clear();
2370 if (stop_arrow() == FAIL)
2371 return;
2373 if (startcol > (int)curwin->w_cursor.col)
2374 startcol = curwin->w_cursor.col;
2375 compl_col = startcol;
2376 compl_length = curwin->w_cursor.col - startcol;
2377 /* compl_pattern doesn't need to be set */
2378 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2379 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2380 -1, FALSE, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2381 return;
2383 /* Handle like dictionary completion. */
2384 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2386 ins_compl_add_list(list);
2387 compl_matches = ins_compl_make_cyclic();
2388 compl_started = TRUE;
2389 compl_used_match = TRUE;
2391 compl_curr_match = compl_first_match;
2392 ins_complete(Ctrl_N);
2393 out_flush();
2397 /* "compl_match_array" points the currently displayed list of entries in the
2398 * popup menu. It is NULL when there is no popup menu. */
2399 static pumitem_T *compl_match_array = NULL;
2400 static int compl_match_arraysize;
2403 * Update the screen and when there is any scrolling remove the popup menu.
2405 static void
2406 ins_compl_upd_pum()
2408 int h;
2410 if (compl_match_array != NULL)
2412 h = curwin->w_cline_height;
2413 update_screen(0);
2414 if (h != curwin->w_cline_height)
2415 ins_compl_del_pum();
2420 * Remove any popup menu.
2422 static void
2423 ins_compl_del_pum()
2425 if (compl_match_array != NULL)
2427 pum_undisplay();
2428 vim_free(compl_match_array);
2429 compl_match_array = NULL;
2434 * Return TRUE if the popup menu should be displayed.
2436 static int
2437 pum_wanted()
2439 /* 'completeopt' must contain "menu" or "menuone" */
2440 if (vim_strchr(p_cot, 'm') == NULL)
2441 return FALSE;
2443 /* The display looks bad on a B&W display. */
2444 if (t_colors < 8
2445 #ifdef FEAT_GUI
2446 && !gui.in_use
2447 #endif
2449 return FALSE;
2450 return TRUE;
2454 * Return TRUE if there are two or more matches to be shown in the popup menu.
2455 * One if 'completopt' contains "menuone".
2457 static int
2458 pum_enough_matches()
2460 compl_T *compl;
2461 int i;
2463 /* Don't display the popup menu if there are no matches or there is only
2464 * one (ignoring the original text). */
2465 compl = compl_first_match;
2466 i = 0;
2469 if (compl == NULL
2470 || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2471 break;
2472 compl = compl->cp_next;
2473 } while (compl != compl_first_match);
2475 if (strstr((char *)p_cot, "menuone") != NULL)
2476 return (i >= 1);
2477 return (i >= 2);
2481 * Show the popup menu for the list of matches.
2482 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2484 void
2485 ins_compl_show_pum()
2487 compl_T *compl;
2488 compl_T *shown_compl = NULL;
2489 int did_find_shown_match = FALSE;
2490 int shown_match_ok = FALSE;
2491 int i;
2492 int cur = -1;
2493 colnr_T col;
2494 int lead_len = 0;
2496 if (!pum_wanted() || !pum_enough_matches())
2497 return;
2499 #if defined(FEAT_EVAL)
2500 /* Dirty hard-coded hack: remove any matchparen highlighting. */
2501 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2502 #endif
2504 /* Update the screen before drawing the popup menu over it. */
2505 update_screen(0);
2507 if (compl_match_array == NULL)
2509 /* Need to build the popup menu list. */
2510 compl_match_arraysize = 0;
2511 compl = compl_first_match;
2512 if (compl_leader != NULL)
2513 lead_len = (int)STRLEN(compl_leader);
2516 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2517 && (compl_leader == NULL
2518 || ins_compl_equal(compl, compl_leader, lead_len)))
2519 ++compl_match_arraysize;
2520 compl = compl->cp_next;
2521 } while (compl != NULL && compl != compl_first_match);
2522 if (compl_match_arraysize == 0)
2523 return;
2524 compl_match_array = (pumitem_T *)alloc_clear(
2525 (unsigned)(sizeof(pumitem_T)
2526 * compl_match_arraysize));
2527 if (compl_match_array != NULL)
2529 /* If the current match is the original text don't find the first
2530 * match after it, don't highlight anything. */
2531 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2532 shown_match_ok = TRUE;
2534 i = 0;
2535 compl = compl_first_match;
2538 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2539 && (compl_leader == NULL
2540 || ins_compl_equal(compl, compl_leader, lead_len)))
2542 if (!shown_match_ok)
2544 if (compl == compl_shown_match || did_find_shown_match)
2546 /* This item is the shown match or this is the
2547 * first displayed item after the shown match. */
2548 compl_shown_match = compl;
2549 did_find_shown_match = TRUE;
2550 shown_match_ok = TRUE;
2552 else
2553 /* Remember this displayed match for when the
2554 * shown match is just below it. */
2555 shown_compl = compl;
2556 cur = i;
2559 if (compl->cp_text[CPT_ABBR] != NULL)
2560 compl_match_array[i].pum_text =
2561 compl->cp_text[CPT_ABBR];
2562 else
2563 compl_match_array[i].pum_text = compl->cp_str;
2564 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2565 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2566 if (compl->cp_text[CPT_MENU] != NULL)
2567 compl_match_array[i++].pum_extra =
2568 compl->cp_text[CPT_MENU];
2569 else
2570 compl_match_array[i++].pum_extra = compl->cp_fname;
2573 if (compl == compl_shown_match)
2575 did_find_shown_match = TRUE;
2577 /* When the original text is the shown match don't set
2578 * compl_shown_match. */
2579 if (compl->cp_flags & ORIGINAL_TEXT)
2580 shown_match_ok = TRUE;
2582 if (!shown_match_ok && shown_compl != NULL)
2584 /* The shown match isn't displayed, set it to the
2585 * previously displayed match. */
2586 compl_shown_match = shown_compl;
2587 shown_match_ok = TRUE;
2590 compl = compl->cp_next;
2591 } while (compl != NULL && compl != compl_first_match);
2593 if (!shown_match_ok) /* no displayed match at all */
2594 cur = -1;
2597 else
2599 /* popup menu already exists, only need to find the current item.*/
2600 for (i = 0; i < compl_match_arraysize; ++i)
2601 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2602 || compl_match_array[i].pum_text
2603 == compl_shown_match->cp_text[CPT_ABBR])
2605 cur = i;
2606 break;
2610 if (compl_match_array != NULL)
2612 /* Compute the screen column of the start of the completed text.
2613 * Use the cursor to get all wrapping and other settings right. */
2614 col = curwin->w_cursor.col;
2615 curwin->w_cursor.col = compl_col;
2616 pum_display(compl_match_array, compl_match_arraysize, cur);
2617 curwin->w_cursor.col = col;
2621 #define DICT_FIRST (1) /* use just first element in "dict" */
2622 #define DICT_EXACT (2) /* "dict" is the exact name of a file */
2625 * Add any identifiers that match the given pattern in the list of dictionary
2626 * files "dict_start" to the list of completions.
2628 static void
2629 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2630 char_u *dict_start;
2631 char_u *pat;
2632 int flags; /* DICT_FIRST and/or DICT_EXACT */
2633 int thesaurus; /* Thesaurus completion */
2635 char_u *dict = dict_start;
2636 char_u *ptr;
2637 char_u *buf;
2638 regmatch_T regmatch;
2639 char_u **files;
2640 int count;
2641 int i;
2642 int save_p_scs;
2643 int dir = compl_direction;
2645 if (*dict == NUL)
2647 #ifdef FEAT_SPELL
2648 /* When 'dictionary' is empty and spell checking is enabled use
2649 * "spell". */
2650 if (!thesaurus && curwin->w_p_spell)
2651 dict = (char_u *)"spell";
2652 else
2653 #endif
2654 return;
2657 buf = alloc(LSIZE);
2658 if (buf == NULL)
2659 return;
2661 /* If 'infercase' is set, don't use 'smartcase' here */
2662 save_p_scs = p_scs;
2663 if (curbuf->b_p_inf)
2664 p_scs = FALSE;
2666 /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
2667 * to only match at the start of a line. Otherwise just match the
2668 * pattern. Also need to double backslashes. */
2669 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2671 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
2673 if (pat_esc == NULL)
2674 return ;
2675 i = (int)STRLEN(pat_esc) + 10;
2676 ptr = alloc(i);
2677 if (ptr == NULL)
2679 vim_free(pat_esc);
2680 return;
2682 vim_snprintf((char *)ptr, i, "^\\s*\\zs\\V%s", pat_esc);
2683 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
2684 vim_free(pat_esc);
2685 vim_free(ptr);
2687 else
2689 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2690 if (regmatch.regprog == NULL)
2691 goto theend;
2694 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2695 regmatch.rm_ic = ignorecase(pat);
2696 while (*dict != NUL && !got_int && !compl_interrupted)
2698 /* copy one dictionary file name into buf */
2699 if (flags == DICT_EXACT)
2701 count = 1;
2702 files = &dict;
2704 else
2706 /* Expand wildcards in the dictionary name, but do not allow
2707 * backticks (for security, the 'dict' option may have been set in
2708 * a modeline). */
2709 copy_option_part(&dict, buf, LSIZE, ",");
2710 # ifdef FEAT_SPELL
2711 if (!thesaurus && STRCMP(buf, "spell") == 0)
2712 count = -1;
2713 else
2714 # endif
2715 if (vim_strchr(buf, '`') != NULL
2716 || expand_wildcards(1, &buf, &count, &files,
2717 EW_FILE|EW_SILENT) != OK)
2718 count = 0;
2721 # ifdef FEAT_SPELL
2722 if (count == -1)
2724 /* Complete from active spelling. Skip "\<" in the pattern, we
2725 * don't use it as a RE. */
2726 if (pat[0] == '\\' && pat[1] == '<')
2727 ptr = pat + 2;
2728 else
2729 ptr = pat;
2730 spell_dump_compl(curbuf, ptr, regmatch.rm_ic, &dir, 0);
2732 else
2733 # endif
2735 ins_compl_files(count, files, thesaurus, flags,
2736 &regmatch, buf, &dir);
2737 if (flags != DICT_EXACT)
2738 FreeWild(count, files);
2740 if (flags != 0)
2741 break;
2744 theend:
2745 p_scs = save_p_scs;
2746 vim_free(regmatch.regprog);
2747 vim_free(buf);
2750 static void
2751 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
2752 int count;
2753 char_u **files;
2754 int thesaurus;
2755 int flags;
2756 regmatch_T *regmatch;
2757 char_u *buf;
2758 int *dir;
2760 char_u *ptr;
2761 int i;
2762 FILE *fp;
2763 int add_r;
2765 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
2767 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
2768 if (flags != DICT_EXACT)
2770 vim_snprintf((char *)IObuff, IOSIZE,
2771 _("Scanning dictionary: %s"), (char *)files[i]);
2772 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
2775 if (fp != NULL)
2778 * Read dictionary file line by line.
2779 * Check each line for a match.
2781 while (!got_int && !compl_interrupted
2782 && !vim_fgets(buf, LSIZE, fp))
2784 ptr = buf;
2785 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
2787 ptr = regmatch->startp[0];
2788 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2789 ptr = find_line_end(ptr);
2790 else
2791 ptr = find_word_end(ptr);
2792 add_r = ins_compl_add_infercase(regmatch->startp[0],
2793 (int)(ptr - regmatch->startp[0]),
2794 p_ic, files[i], *dir, 0);
2795 if (thesaurus)
2797 char_u *wstart;
2800 * Add the other matches on the line
2802 while (!got_int)
2804 /* Find start of the next word. Skip white
2805 * space and punctuation. */
2806 ptr = find_word_start(ptr);
2807 if (*ptr == NUL || *ptr == NL)
2808 break;
2809 wstart = ptr;
2811 /* Find end of the word and add it. */
2812 #ifdef FEAT_MBYTE
2813 if (has_mbyte)
2814 /* Japanese words may have characters in
2815 * different classes, only separate words
2816 * with single-byte non-word characters. */
2817 while (*ptr != NUL)
2819 int l = (*mb_ptr2len)(ptr);
2821 if (l < 2 && !vim_iswordc(*ptr))
2822 break;
2823 ptr += l;
2825 else
2826 #endif
2827 ptr = find_word_end(ptr);
2828 add_r = ins_compl_add_infercase(wstart,
2829 (int)(ptr - wstart),
2830 p_ic, files[i], *dir, 0);
2833 if (add_r == OK)
2834 /* if dir was BACKWARD then honor it just once */
2835 *dir = FORWARD;
2836 else if (add_r == FAIL)
2837 break;
2838 /* avoid expensive call to vim_regexec() when at end
2839 * of line */
2840 if (*ptr == '\n' || got_int)
2841 break;
2843 line_breakcheck();
2844 ins_compl_check_keys(50);
2846 fclose(fp);
2852 * Find the start of the next word.
2853 * Returns a pointer to the first char of the word. Also stops at a NUL.
2855 char_u *
2856 find_word_start(ptr)
2857 char_u *ptr;
2859 #ifdef FEAT_MBYTE
2860 if (has_mbyte)
2861 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2862 ptr += (*mb_ptr2len)(ptr);
2863 else
2864 #endif
2865 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2866 ++ptr;
2867 return ptr;
2871 * Find the end of the word. Assumes it starts inside a word.
2872 * Returns a pointer to just after the word.
2874 char_u *
2875 find_word_end(ptr)
2876 char_u *ptr;
2878 #ifdef FEAT_MBYTE
2879 int start_class;
2881 if (has_mbyte)
2883 start_class = mb_get_class(ptr);
2884 if (start_class > 1)
2885 while (*ptr != NUL)
2887 ptr += (*mb_ptr2len)(ptr);
2888 if (mb_get_class(ptr) != start_class)
2889 break;
2892 else
2893 #endif
2894 while (vim_iswordc(*ptr))
2895 ++ptr;
2896 return ptr;
2900 * Find the end of the line, omitting CR and NL at the end.
2901 * Returns a pointer to just after the line.
2903 static char_u *
2904 find_line_end(ptr)
2905 char_u *ptr;
2907 char_u *s;
2909 s = ptr + STRLEN(ptr);
2910 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2911 --s;
2912 return s;
2916 * Free the list of completions
2918 static void
2919 ins_compl_free()
2921 compl_T *match;
2922 int i;
2924 vim_free(compl_pattern);
2925 compl_pattern = NULL;
2926 vim_free(compl_leader);
2927 compl_leader = NULL;
2929 if (compl_first_match == NULL)
2930 return;
2932 ins_compl_del_pum();
2933 pum_clear();
2935 compl_curr_match = compl_first_match;
2938 match = compl_curr_match;
2939 compl_curr_match = compl_curr_match->cp_next;
2940 vim_free(match->cp_str);
2941 /* several entries may use the same fname, free it just once. */
2942 if (match->cp_flags & FREE_FNAME)
2943 vim_free(match->cp_fname);
2944 for (i = 0; i < CPT_COUNT; ++i)
2945 vim_free(match->cp_text[i]);
2946 vim_free(match);
2947 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
2948 compl_first_match = compl_curr_match = NULL;
2951 static void
2952 ins_compl_clear()
2954 compl_cont_status = 0;
2955 compl_started = FALSE;
2956 compl_matches = 0;
2957 vim_free(compl_pattern);
2958 compl_pattern = NULL;
2959 vim_free(compl_leader);
2960 compl_leader = NULL;
2961 edit_submode_extra = NULL;
2962 vim_free(compl_orig_text);
2963 compl_orig_text = NULL;
2964 compl_enter_selects = FALSE;
2968 * Return TRUE when Insert completion is active.
2971 ins_compl_active()
2973 return compl_started;
2977 * Delete one character before the cursor and show the subset of the matches
2978 * that match the word that is now before the cursor.
2979 * Returns the character to be used, NUL if the work is done and another char
2980 * to be got from the user.
2982 static int
2983 ins_compl_bs()
2985 char_u *line;
2986 char_u *p;
2988 line = ml_get_curline();
2989 p = line + curwin->w_cursor.col;
2990 mb_ptr_back(line, p);
2992 /* Stop completion when the whole word was deleted. */
2993 if ((int)(p - line) - (int)compl_col <= 0)
2994 return K_BS;
2996 if (curwin->w_cursor.col <= compl_col + compl_length)
2998 /* Deleted more than what was used to find matches, need to look for
2999 * matches all over again. */
3000 ins_compl_free();
3001 compl_started = FALSE;
3002 compl_matches = 0;
3003 compl_cont_status = 0;
3004 compl_cont_mode = 0;
3007 vim_free(compl_leader);
3008 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3009 if (compl_leader != NULL)
3011 ins_compl_del_pum();
3012 ins_compl_delete();
3013 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
3015 if (compl_started)
3016 ins_compl_set_original_text(compl_leader);
3017 else
3019 #ifdef FEAT_SPELL
3020 spell_bad_len = 0; /* need to redetect bad word */
3021 #endif
3022 /* Matches were cleared, need to search for them now. */
3023 if (ins_complete(Ctrl_N) == FAIL)
3024 compl_cont_status = 0;
3025 else
3027 /* Remove the completed word again. */
3028 ins_compl_delete();
3029 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
3033 /* Go to the original text, since none of the matches is inserted. */
3034 if (compl_first_match->cp_prev != NULL
3035 && (compl_first_match->cp_prev->cp_flags & ORIGINAL_TEXT))
3036 compl_shown_match = compl_first_match->cp_prev;
3037 else
3038 compl_shown_match = compl_first_match;
3039 compl_curr_match = compl_shown_match;
3040 compl_shows_dir = compl_direction;
3042 /* Show the popup menu with a different set of matches. */
3043 ins_compl_show_pum();
3044 compl_used_match = FALSE;
3045 compl_enter_selects = FALSE;
3047 return NUL;
3049 return K_BS;
3053 * Append one character to the match leader. May reduce the number of
3054 * matches.
3056 static void
3057 ins_compl_addleader(c)
3058 int c;
3060 #ifdef FEAT_MBYTE
3061 int cc;
3063 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3065 char_u buf[MB_MAXBYTES + 1];
3067 (*mb_char2bytes)(c, buf);
3068 buf[cc] = NUL;
3069 ins_char_bytes(buf, cc);
3071 else
3072 #endif
3073 ins_char(c);
3075 vim_free(compl_leader);
3076 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3077 curwin->w_cursor.col - compl_col);
3078 if (compl_leader != NULL)
3080 /* Show the popup menu with a different set of matches. */
3081 ins_compl_del_pum();
3082 ins_compl_show_pum();
3083 compl_used_match = FALSE;
3084 compl_enter_selects = FALSE;
3085 ins_compl_set_original_text(compl_leader);
3090 * Set the first match, the original text.
3092 static void
3093 ins_compl_set_original_text(str)
3094 char_u *str;
3096 char_u *p;
3098 /* Replace the original text entry. */
3099 if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */
3101 p = vim_strsave(str);
3102 if (p != NULL)
3104 vim_free(compl_first_match->cp_str);
3105 compl_first_match->cp_str = p;
3111 * Append one character to the match leader. May reduce the number of
3112 * matches.
3114 static void
3115 ins_compl_addfrommatch()
3117 char_u *p;
3118 int len = curwin->w_cursor.col - compl_col;
3119 int c;
3121 p = compl_shown_match->cp_str;
3122 if ((int)STRLEN(p) <= len) /* the match is too short */
3123 return;
3124 p += len;
3125 #ifdef FEAT_MBYTE
3126 c = mb_ptr2char(p);
3127 #else
3128 c = *p;
3129 #endif
3130 ins_compl_addleader(c);
3134 * Prepare for Insert mode completion, or stop it.
3135 * Called just after typing a character in Insert mode.
3136 * Returns TRUE when the character is not to be inserted;
3138 static int
3139 ins_compl_prep(c)
3140 int c;
3142 char_u *ptr;
3143 int temp;
3144 int want_cindent;
3145 int retval = FALSE;
3147 /* Forget any previous 'special' messages if this is actually
3148 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3150 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3151 edit_submode_extra = NULL;
3153 /* Ignore end of Select mode mapping */
3154 if (c == K_SELECT)
3155 return retval;
3157 /* Set "compl_get_longest" when finding the first matches. */
3158 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3159 || (ctrl_x_mode == 0 && !compl_started))
3161 compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3162 compl_used_match = TRUE;
3165 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3168 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3169 * it will be yet. Now we decide.
3171 switch (c)
3173 case Ctrl_E:
3174 case Ctrl_Y:
3175 ctrl_x_mode = CTRL_X_SCROLL;
3176 if (!(State & REPLACE_FLAG))
3177 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3178 else
3179 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3180 edit_submode_pre = NULL;
3181 showmode();
3182 break;
3183 case Ctrl_L:
3184 ctrl_x_mode = CTRL_X_WHOLE_LINE;
3185 break;
3186 case Ctrl_F:
3187 ctrl_x_mode = CTRL_X_FILES;
3188 break;
3189 case Ctrl_K:
3190 ctrl_x_mode = CTRL_X_DICTIONARY;
3191 break;
3192 case Ctrl_R:
3193 /* Simply allow ^R to happen without affecting ^X mode */
3194 break;
3195 case Ctrl_T:
3196 ctrl_x_mode = CTRL_X_THESAURUS;
3197 break;
3198 #ifdef FEAT_COMPL_FUNC
3199 case Ctrl_U:
3200 ctrl_x_mode = CTRL_X_FUNCTION;
3201 break;
3202 case Ctrl_O:
3203 ctrl_x_mode = CTRL_X_OMNI;
3204 break;
3205 #endif
3206 case 's':
3207 case Ctrl_S:
3208 ctrl_x_mode = CTRL_X_SPELL;
3209 #ifdef FEAT_SPELL
3210 ++emsg_off; /* Avoid getting the E756 error twice. */
3211 spell_back_to_badword();
3212 --emsg_off;
3213 #endif
3214 break;
3215 case Ctrl_RSB:
3216 ctrl_x_mode = CTRL_X_TAGS;
3217 break;
3218 #ifdef FEAT_FIND_ID
3219 case Ctrl_I:
3220 case K_S_TAB:
3221 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3222 break;
3223 case Ctrl_D:
3224 ctrl_x_mode = CTRL_X_PATH_DEFINES;
3225 break;
3226 #endif
3227 case Ctrl_V:
3228 case Ctrl_Q:
3229 ctrl_x_mode = CTRL_X_CMDLINE;
3230 break;
3231 case Ctrl_P:
3232 case Ctrl_N:
3233 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
3234 * just started ^X mode, or there were enough ^X's to cancel
3235 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3236 * do normal expansion when interrupting a different mode (say
3237 * ^X^F^X^P or ^P^X^X^P, see below)
3238 * nothing changes if interrupting mode 0, (eg, the flag
3239 * doesn't change when going to ADDING mode -- Acevedo */
3240 if (!(compl_cont_status & CONT_INTRPT))
3241 compl_cont_status |= CONT_LOCAL;
3242 else if (compl_cont_mode != 0)
3243 compl_cont_status &= ~CONT_LOCAL;
3244 /* FALLTHROUGH */
3245 default:
3246 /* If we have typed at least 2 ^X's... for modes != 0, we set
3247 * compl_cont_status = 0 (eg, as if we had just started ^X
3248 * mode).
3249 * For mode 0, we set "compl_cont_mode" to an impossible
3250 * value, in both cases ^X^X can be used to restart the same
3251 * mode (avoiding ADDING mode).
3252 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3253 * 'complete' and local ^P expansions respectively.
3254 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3255 * mode -- Acevedo */
3256 if (c == Ctrl_X)
3258 if (compl_cont_mode != 0)
3259 compl_cont_status = 0;
3260 else
3261 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3263 ctrl_x_mode = 0;
3264 edit_submode = NULL;
3265 showmode();
3266 break;
3269 else if (ctrl_x_mode != 0)
3271 /* We're already in CTRL-X mode, do we stay in it? */
3272 if (!vim_is_ctrl_x_key(c))
3274 if (ctrl_x_mode == CTRL_X_SCROLL)
3275 ctrl_x_mode = 0;
3276 else
3277 ctrl_x_mode = CTRL_X_FINISHED;
3278 edit_submode = NULL;
3280 showmode();
3283 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3285 /* Show error message from attempted keyword completion (probably
3286 * 'Pattern not found') until another key is hit, then go back to
3287 * showing what mode we are in. */
3288 showmode();
3289 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3290 && !ins_compl_pum_key(c))
3291 || ctrl_x_mode == CTRL_X_FINISHED)
3293 /* Get here when we have finished typing a sequence of ^N and
3294 * ^P or other completion characters in CTRL-X mode. Free up
3295 * memory that was used, and make sure we can redo the insert. */
3296 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3298 char_u *p;
3301 * If any of the original typed text has been changed, eg when
3302 * ignorecase is set, we must add back-spaces to the redo
3303 * buffer. We add as few as necessary to delete just the part
3304 * of the original text that has changed.
3305 * When using the longest match, edited the match or used
3306 * CTRL-E then don't use the current match.
3308 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3309 ptr = compl_curr_match->cp_str;
3310 else if (compl_leader != NULL)
3311 ptr = compl_leader;
3312 else
3313 ptr = compl_orig_text;
3314 p = compl_orig_text;
3315 for (temp = 0; p[temp] != NUL && p[temp] == ptr[temp]; ++temp)
3317 #ifdef FEAT_MBYTE
3318 if (temp > 0)
3319 temp -= (*mb_head_off)(compl_orig_text, p + temp);
3320 #endif
3321 for (p += temp; *p != NUL; mb_ptr_adv(p))
3322 AppendCharToRedobuff(K_BS);
3323 AppendToRedobuffLit(ptr + temp, -1);
3326 #ifdef FEAT_CINDENT
3327 want_cindent = (can_cindent && cindent_on());
3328 #endif
3330 * When completing whole lines: fix indent for 'cindent'.
3331 * Otherwise, break line if it's too long.
3333 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3335 #ifdef FEAT_CINDENT
3336 /* re-indent the current line */
3337 if (want_cindent)
3339 do_c_expr_indent();
3340 want_cindent = FALSE; /* don't do it again */
3342 #endif
3344 else
3346 /* put the cursor on the last char, for 'tw' formatting */
3347 curwin->w_cursor.col--;
3348 if (stop_arrow() == OK)
3349 insertchar(NUL, 0, -1);
3350 curwin->w_cursor.col++;
3353 auto_format(FALSE, TRUE);
3355 /* If the popup menu is displayed pressing CTRL-Y means accepting
3356 * the selection without inserting anything. When
3357 * compl_enter_selects is set the Enter key does the same. */
3358 if ((c == Ctrl_Y || (compl_enter_selects
3359 && (c == CAR || c == K_KENTER || c == NL)))
3360 && pum_visible())
3361 retval = TRUE;
3363 /* CTRL-E means completion is Ended, go back to the typed text. */
3364 if (c == Ctrl_E)
3366 ins_compl_delete();
3367 if (compl_leader != NULL)
3368 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
3369 else if (compl_first_match != NULL)
3370 ins_bytes(compl_orig_text
3371 + curwin->w_cursor.col - compl_col);
3372 retval = TRUE;
3375 ins_compl_free();
3376 compl_started = FALSE;
3377 compl_matches = 0;
3378 msg_clr_cmdline(); /* necessary for "noshowmode" */
3379 ctrl_x_mode = 0;
3380 compl_enter_selects = FALSE;
3381 if (edit_submode != NULL)
3383 edit_submode = NULL;
3384 showmode();
3387 #ifdef FEAT_CINDENT
3389 * Indent now if a key was typed that is in 'cinkeys'.
3391 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3392 do_c_expr_indent();
3393 #endif
3397 /* reset continue_* if we left expansion-mode, if we stay they'll be
3398 * (re)set properly in ins_complete() */
3399 if (!vim_is_ctrl_x_key(c))
3401 compl_cont_status = 0;
3402 compl_cont_mode = 0;
3405 return retval;
3409 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3410 * (depending on flag) starting from buf and looking for a non-scanned
3411 * buffer (other than curbuf). curbuf is special, if it is called with
3412 * buf=curbuf then it has to be the first call for a given flag/expansion.
3414 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3416 static buf_T *
3417 ins_compl_next_buf(buf, flag)
3418 buf_T *buf;
3419 int flag;
3421 #ifdef FEAT_WINDOWS
3422 static win_T *wp;
3423 #endif
3425 if (flag == 'w') /* just windows */
3427 #ifdef FEAT_WINDOWS
3428 if (buf == curbuf) /* first call for this flag/expansion */
3429 wp = curwin;
3430 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3431 && wp->w_buffer->b_scanned)
3433 buf = wp->w_buffer;
3434 #else
3435 buf = curbuf;
3436 #endif
3438 else
3439 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3440 * (unlisted buffers)
3441 * When completing whole lines skip unloaded buffers. */
3442 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3443 && ((flag == 'U'
3444 ? buf->b_p_bl
3445 : (!buf->b_p_bl
3446 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3447 || buf->b_scanned))
3449 return buf;
3452 #ifdef FEAT_COMPL_FUNC
3453 static void expand_by_function __ARGS((int type, char_u *base));
3456 * Execute user defined complete function 'completefunc' or 'omnifunc', and
3457 * get matches in "matches".
3459 static void
3460 expand_by_function(type, base)
3461 int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3462 char_u *base;
3464 list_T *matchlist;
3465 char_u *args[2];
3466 char_u *funcname;
3467 pos_T pos;
3469 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3470 if (*funcname == NUL)
3471 return;
3473 /* Call 'completefunc' to obtain the list of matches. */
3474 args[0] = (char_u *)"0";
3475 args[1] = base;
3477 pos = curwin->w_cursor;
3478 matchlist = call_func_retlist(funcname, 2, args, FALSE);
3479 curwin->w_cursor = pos; /* restore the cursor position */
3480 if (matchlist == NULL)
3481 return;
3483 ins_compl_add_list(matchlist);
3484 list_unref(matchlist);
3486 #endif /* FEAT_COMPL_FUNC */
3488 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
3490 * Add completions from a list.
3492 static void
3493 ins_compl_add_list(list)
3494 list_T *list;
3496 listitem_T *li;
3497 int dir = compl_direction;
3499 /* Go through the List with matches and add each of them. */
3500 for (li = list->lv_first; li != NULL; li = li->li_next)
3502 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
3503 /* if dir was BACKWARD then honor it just once */
3504 dir = FORWARD;
3505 else if (did_emsg)
3506 break;
3511 * Add a match to the list of matches from a typeval_T.
3512 * If the given string is already in the list of completions, then return
3513 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3514 * maybe because alloc() returns NULL, then FAIL is returned.
3517 ins_compl_add_tv(tv, dir)
3518 typval_T *tv;
3519 int dir;
3521 char_u *word;
3522 int icase = p_ic;
3523 int dup = FALSE;
3524 char_u *(cptext[CPT_COUNT]);
3526 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3528 word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
3529 cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
3530 (char_u *)"abbr", FALSE);
3531 cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
3532 (char_u *)"menu", FALSE);
3533 cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
3534 (char_u *)"kind", FALSE);
3535 cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
3536 (char_u *)"info", FALSE);
3537 if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
3538 icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
3539 if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
3540 dup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
3542 else
3544 word = get_tv_string_chk(tv);
3545 vim_memset(cptext, 0, sizeof(cptext));
3547 if (word == NULL || *word == NUL)
3548 return FAIL;
3549 return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, dup);
3551 #endif
3554 * Get the next expansion(s), using "compl_pattern".
3555 * The search starts at position "ini" in curbuf and in the direction
3556 * compl_direction.
3557 * When "compl_started" is FALSE start at that position, otherwise continue
3558 * where we stopped searching before.
3559 * This may return before finding all the matches.
3560 * Return the total number of matches or -1 if still unknown -- Acevedo
3562 static int
3563 ins_compl_get_exp(ini)
3564 pos_T *ini;
3566 static pos_T first_match_pos;
3567 static pos_T last_match_pos;
3568 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
3569 static int found_all = FALSE; /* Found all matches of a
3570 certain type. */
3571 static buf_T *ins_buf = NULL; /* buffer being scanned */
3573 pos_T *pos;
3574 char_u **matches;
3575 int save_p_scs;
3576 int save_p_ws;
3577 int save_p_ic;
3578 int i;
3579 int num_matches;
3580 int len;
3581 int found_new_match;
3582 int type = ctrl_x_mode;
3583 char_u *ptr;
3584 char_u *dict = NULL;
3585 int dict_f = 0;
3586 compl_T *old_match;
3588 if (!compl_started)
3590 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
3591 ins_buf->b_scanned = 0;
3592 found_all = FALSE;
3593 ins_buf = curbuf;
3594 e_cpt = (compl_cont_status & CONT_LOCAL)
3595 ? (char_u *)"." : curbuf->b_p_cpt;
3596 last_match_pos = first_match_pos = *ini;
3599 old_match = compl_curr_match; /* remember the last current match */
3600 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3601 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
3602 for (;;)
3604 found_new_match = FAIL;
3606 /* For ^N/^P pick a new entry from e_cpt if compl_started is off,
3607 * or if found_all says this entry is done. For ^X^L only use the
3608 * entries from 'complete' that look in loaded buffers. */
3609 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3610 && (!compl_started || found_all))
3612 found_all = FALSE;
3613 while (*e_cpt == ',' || *e_cpt == ' ')
3614 e_cpt++;
3615 if (*e_cpt == '.' && !curbuf->b_scanned)
3617 ins_buf = curbuf;
3618 first_match_pos = *ini;
3619 /* So that ^N can match word immediately after cursor */
3620 if (ctrl_x_mode == 0)
3621 dec(&first_match_pos);
3622 last_match_pos = first_match_pos;
3623 type = 0;
3625 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3626 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
3628 /* Scan a buffer, but not the current one. */
3629 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
3631 compl_started = TRUE;
3632 first_match_pos.col = last_match_pos.col = 0;
3633 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
3634 last_match_pos.lnum = 0;
3635 type = 0;
3637 else /* unloaded buffer, scan like dictionary */
3639 found_all = TRUE;
3640 if (ins_buf->b_fname == NULL)
3641 continue;
3642 type = CTRL_X_DICTIONARY;
3643 dict = ins_buf->b_fname;
3644 dict_f = DICT_EXACT;
3646 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3647 ins_buf->b_fname == NULL
3648 ? buf_spname(ins_buf)
3649 : ins_buf->b_sfname == NULL
3650 ? (char *)ins_buf->b_fname
3651 : (char *)ins_buf->b_sfname);
3652 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3654 else if (*e_cpt == NUL)
3655 break;
3656 else
3658 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3659 type = -1;
3660 else if (*e_cpt == 'k' || *e_cpt == 's')
3662 if (*e_cpt == 'k')
3663 type = CTRL_X_DICTIONARY;
3664 else
3665 type = CTRL_X_THESAURUS;
3666 if (*++e_cpt != ',' && *e_cpt != NUL)
3668 dict = e_cpt;
3669 dict_f = DICT_FIRST;
3672 #ifdef FEAT_FIND_ID
3673 else if (*e_cpt == 'i')
3674 type = CTRL_X_PATH_PATTERNS;
3675 else if (*e_cpt == 'd')
3676 type = CTRL_X_PATH_DEFINES;
3677 #endif
3678 else if (*e_cpt == ']' || *e_cpt == 't')
3680 type = CTRL_X_TAGS;
3681 sprintf((char*)IObuff, _("Scanning tags."));
3682 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3684 else
3685 type = -1;
3687 /* in any case e_cpt is advanced to the next entry */
3688 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
3690 found_all = TRUE;
3691 if (type == -1)
3692 continue;
3696 switch (type)
3698 case -1:
3699 break;
3700 #ifdef FEAT_FIND_ID
3701 case CTRL_X_PATH_PATTERNS:
3702 case CTRL_X_PATH_DEFINES:
3703 find_pattern_in_path(compl_pattern, compl_direction,
3704 (int)STRLEN(compl_pattern), FALSE, FALSE,
3705 (type == CTRL_X_PATH_DEFINES
3706 && !(compl_cont_status & CONT_SOL))
3707 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
3708 (linenr_T)1, (linenr_T)MAXLNUM);
3709 break;
3710 #endif
3712 case CTRL_X_DICTIONARY:
3713 case CTRL_X_THESAURUS:
3714 ins_compl_dictionaries(
3715 dict != NULL ? dict
3716 : (type == CTRL_X_THESAURUS
3717 ? (*curbuf->b_p_tsr == NUL
3718 ? p_tsr
3719 : curbuf->b_p_tsr)
3720 : (*curbuf->b_p_dict == NUL
3721 ? p_dict
3722 : curbuf->b_p_dict)),
3723 compl_pattern,
3724 dict != NULL ? dict_f
3725 : 0, type == CTRL_X_THESAURUS);
3726 dict = NULL;
3727 break;
3729 case CTRL_X_TAGS:
3730 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
3731 save_p_ic = p_ic;
3732 p_ic = ignorecase(compl_pattern);
3734 /* Find up to TAG_MANY matches. Avoids that an enourmous number
3735 * of matches is found when compl_pattern is empty */
3736 if (find_tags(compl_pattern, &num_matches, &matches,
3737 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
3738 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
3739 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3741 ins_compl_add_matches(num_matches, matches, p_ic);
3743 p_ic = save_p_ic;
3744 break;
3746 case CTRL_X_FILES:
3747 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3748 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
3751 /* May change home directory back to "~". */
3752 tilde_replace(compl_pattern, num_matches, matches);
3753 ins_compl_add_matches(num_matches, matches,
3754 #ifdef CASE_INSENSITIVE_FILENAME
3755 TRUE
3756 #else
3757 FALSE
3758 #endif
3761 break;
3763 case CTRL_X_CMDLINE:
3764 if (expand_cmdline(&compl_xp, compl_pattern,
3765 (int)STRLEN(compl_pattern),
3766 &num_matches, &matches) == EXPAND_OK)
3767 ins_compl_add_matches(num_matches, matches, FALSE);
3768 break;
3770 #ifdef FEAT_COMPL_FUNC
3771 case CTRL_X_FUNCTION:
3772 case CTRL_X_OMNI:
3773 expand_by_function(type, compl_pattern);
3774 break;
3775 #endif
3777 case CTRL_X_SPELL:
3778 #ifdef FEAT_SPELL
3779 num_matches = expand_spelling(first_match_pos.lnum,
3780 first_match_pos.col, compl_pattern, &matches);
3781 if (num_matches > 0)
3782 ins_compl_add_matches(num_matches, matches, FALSE);
3783 #endif
3784 break;
3786 default: /* normal ^P/^N and ^X^L */
3788 * If 'infercase' is set, don't use 'smartcase' here
3790 save_p_scs = p_scs;
3791 if (ins_buf->b_p_inf)
3792 p_scs = FALSE;
3794 /* buffers other than curbuf are scanned from the beginning or the
3795 * end but never from the middle, thus setting nowrapscan in this
3796 * buffers is a good idea, on the other hand, we always set
3797 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
3798 save_p_ws = p_ws;
3799 if (ins_buf != curbuf)
3800 p_ws = FALSE;
3801 else if (*e_cpt == '.')
3802 p_ws = TRUE;
3803 for (;;)
3805 int flags = 0;
3807 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
3808 * has added a word that was at the beginning of the line */
3809 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
3810 || (compl_cont_status & CONT_SOL))
3811 found_new_match = search_for_exact_line(ins_buf, pos,
3812 compl_direction, compl_pattern);
3813 else
3814 found_new_match = searchit(NULL, ins_buf, pos,
3815 compl_direction,
3816 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
3817 RE_LAST, (linenr_T)0);
3818 if (!compl_started)
3820 /* set "compl_started" even on fail */
3821 compl_started = TRUE;
3822 first_match_pos = *pos;
3823 last_match_pos = *pos;
3825 else if (first_match_pos.lnum == last_match_pos.lnum
3826 && first_match_pos.col == last_match_pos.col)
3827 found_new_match = FAIL;
3828 if (found_new_match == FAIL)
3830 if (ins_buf == curbuf)
3831 found_all = TRUE;
3832 break;
3835 /* when ADDING, the text before the cursor matches, skip it */
3836 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
3837 && ini->lnum == pos->lnum
3838 && ini->col == pos->col)
3839 continue;
3840 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
3841 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3843 if (compl_cont_status & CONT_ADDING)
3845 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
3846 continue;
3847 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3848 if (!p_paste)
3849 ptr = skipwhite(ptr);
3851 len = (int)STRLEN(ptr);
3853 else
3855 char_u *tmp_ptr = ptr;
3857 if (compl_cont_status & CONT_ADDING)
3859 tmp_ptr += compl_length;
3860 /* Skip if already inside a word. */
3861 if (vim_iswordp(tmp_ptr))
3862 continue;
3863 /* Find start of next word. */
3864 tmp_ptr = find_word_start(tmp_ptr);
3866 /* Find end of this word. */
3867 tmp_ptr = find_word_end(tmp_ptr);
3868 len = (int)(tmp_ptr - ptr);
3870 if ((compl_cont_status & CONT_ADDING)
3871 && len == compl_length)
3873 if (pos->lnum < ins_buf->b_ml.ml_line_count)
3875 /* Try next line, if any. the new word will be
3876 * "join" as if the normal command "J" was used.
3877 * IOSIZE is always greater than
3878 * compl_length, so the next STRNCPY always
3879 * works -- Acevedo */
3880 STRNCPY(IObuff, ptr, len);
3881 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3882 tmp_ptr = ptr = skipwhite(ptr);
3883 /* Find start of next word. */
3884 tmp_ptr = find_word_start(tmp_ptr);
3885 /* Find end of next word. */
3886 tmp_ptr = find_word_end(tmp_ptr);
3887 if (tmp_ptr > ptr)
3889 if (*ptr != ')' && IObuff[len - 1] != TAB)
3891 if (IObuff[len - 1] != ' ')
3892 IObuff[len++] = ' ';
3893 /* IObuf =~ "\k.* ", thus len >= 2 */
3894 if (p_js
3895 && (IObuff[len - 2] == '.'
3896 || (vim_strchr(p_cpo, CPO_JOINSP)
3897 == NULL
3898 && (IObuff[len - 2] == '?'
3899 || IObuff[len - 2] == '!'))))
3900 IObuff[len++] = ' ';
3902 /* copy as much as posible of the new word */
3903 if (tmp_ptr - ptr >= IOSIZE - len)
3904 tmp_ptr = ptr + IOSIZE - len - 1;
3905 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3906 len += (int)(tmp_ptr - ptr);
3907 flags |= CONT_S_IPOS;
3909 IObuff[len] = NUL;
3910 ptr = IObuff;
3912 if (len == compl_length)
3913 continue;
3916 if (ins_compl_add_infercase(ptr, len, p_ic,
3917 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
3918 0, flags) != NOTDONE)
3920 found_new_match = OK;
3921 break;
3924 p_scs = save_p_scs;
3925 p_ws = save_p_ws;
3928 /* check if compl_curr_match has changed, (e.g. other type of
3929 * expansion added somenthing) */
3930 if (type != 0 && compl_curr_match != old_match)
3931 found_new_match = OK;
3933 /* break the loop for specialized modes (use 'complete' just for the
3934 * generic ctrl_x_mode == 0) or when we've found a new match */
3935 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
3936 || found_new_match != FAIL)
3938 if (got_int)
3939 break;
3940 /* Fill the popup menu as soon as possible. */
3941 if (pum_wanted() && type != -1)
3942 ins_compl_check_keys(0);
3944 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
3945 || compl_interrupted)
3946 break;
3947 compl_started = TRUE;
3949 else
3951 /* Mark a buffer scanned when it has been scanned completely */
3952 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3953 ins_buf->b_scanned = TRUE;
3955 compl_started = FALSE;
3958 compl_started = TRUE;
3960 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3961 && *e_cpt == NUL) /* Got to end of 'complete' */
3962 found_new_match = FAIL;
3964 i = -1; /* total of matches, unknown */
3965 if (found_new_match == FAIL
3966 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
3967 i = ins_compl_make_cyclic();
3969 /* If several matches were added (FORWARD) or the search failed and has
3970 * just been made cyclic then we have to move compl_curr_match to the next
3971 * or previous entry (if any) -- Acevedo */
3972 compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
3973 : old_match->cp_prev;
3974 if (compl_curr_match == NULL)
3975 compl_curr_match = old_match;
3976 return i;
3979 /* Delete the old text being completed. */
3980 static void
3981 ins_compl_delete()
3983 int i;
3986 * In insert mode: Delete the typed part.
3987 * In replace mode: Put the old characters back, if any.
3989 i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
3990 backspace_until_column(i);
3991 changed_cline_bef_curs();
3994 /* Insert the new text being completed. */
3995 static void
3996 ins_compl_insert()
3998 ins_bytes(compl_shown_match->cp_str + curwin->w_cursor.col - compl_col);
3999 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4000 compl_used_match = FALSE;
4001 else
4002 compl_used_match = TRUE;
4006 * Fill in the next completion in the current direction.
4007 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4008 * get more completions. If it is FALSE, then we just do nothing when there
4009 * are no more completions in a given direction. The latter case is used when
4010 * we are still in the middle of finding completions, to allow browsing
4011 * through the ones found so far.
4012 * Return the total number of matches, or -1 if still unknown -- webb.
4014 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4015 * compl_shown_match here.
4017 * Note that this function may be called recursively once only. First with
4018 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4019 * calls this function with "allow_get_expansion" FALSE.
4021 static int
4022 ins_compl_next(allow_get_expansion, count, insert_match)
4023 int allow_get_expansion;
4024 int count; /* repeat completion this many times; should
4025 be at least 1 */
4026 int insert_match; /* Insert the newly selected match */
4028 int num_matches = -1;
4029 int i;
4030 int todo = count;
4031 compl_T *found_compl = NULL;
4032 int found_end = FALSE;
4033 int advance;
4035 if (compl_leader != NULL
4036 && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4038 /* Set "compl_shown_match" to the actually shown match, it may differ
4039 * when "compl_leader" is used to omit some of the matches. */
4040 while (!ins_compl_equal(compl_shown_match,
4041 compl_leader, (int)STRLEN(compl_leader))
4042 && compl_shown_match->cp_next != NULL
4043 && compl_shown_match->cp_next != compl_first_match)
4044 compl_shown_match = compl_shown_match->cp_next;
4047 if (allow_get_expansion && insert_match
4048 && (!compl_get_longest || compl_used_match))
4049 /* Delete old text to be replaced */
4050 ins_compl_delete();
4052 /* When finding the longest common text we stick at the original text,
4053 * don't let CTRL-N or CTRL-P move to the first match. */
4054 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4056 /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4057 * around. */
4058 while (--todo >= 0)
4060 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4062 if (compl_pending != 0)
4063 --compl_pending;
4064 compl_shown_match = compl_shown_match->cp_next;
4065 found_end = (compl_first_match != NULL
4066 && (compl_shown_match->cp_next == compl_first_match
4067 || compl_shown_match == compl_first_match));
4069 else if (compl_shows_dir == BACKWARD
4070 && compl_shown_match->cp_prev != NULL)
4072 if (compl_pending != 0)
4073 ++compl_pending;
4074 found_end = (compl_shown_match == compl_first_match);
4075 compl_shown_match = compl_shown_match->cp_prev;
4076 found_end |= (compl_shown_match == compl_first_match);
4078 else
4080 if (advance)
4082 if (compl_shows_dir == BACKWARD)
4083 --compl_pending;
4084 else
4085 ++compl_pending;
4087 if (!allow_get_expansion)
4088 return -1;
4090 num_matches = ins_compl_get_exp(&compl_startpos);
4091 if (compl_pending != 0 && compl_direction == compl_shows_dir
4092 && advance)
4093 compl_shown_match = compl_curr_match;
4094 found_end = FALSE;
4096 if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4097 && compl_leader != NULL
4098 && !ins_compl_equal(compl_shown_match,
4099 compl_leader, (int)STRLEN(compl_leader)))
4100 ++todo;
4101 else
4102 /* Remember a matching item. */
4103 found_compl = compl_shown_match;
4105 /* Stop at the end of the list when we found a usable match. */
4106 if (found_end)
4108 if (found_compl != NULL)
4110 compl_shown_match = found_compl;
4111 break;
4113 todo = 1; /* use first usable match after wrapping around */
4117 /* Insert the text of the new completion, or the compl_leader. */
4118 if (insert_match)
4120 if (!compl_get_longest || compl_used_match)
4121 ins_compl_insert();
4122 else
4123 ins_bytes(compl_leader + curwin->w_cursor.col - compl_col);
4125 else
4126 compl_used_match = FALSE;
4128 if (!allow_get_expansion)
4130 /* may undisplay the popup menu first */
4131 ins_compl_upd_pum();
4133 /* redraw to show the user what was inserted */
4134 update_screen(0);
4136 /* display the updated popup menu */
4137 ins_compl_show_pum();
4139 /* Delete old text to be replaced, since we're still searching and
4140 * don't want to match ourselves! */
4141 ins_compl_delete();
4144 /* Enter will select a match when the match wasn't inserted and the popup
4145 * menu is visislbe. */
4146 compl_enter_selects = !insert_match && compl_match_array != NULL;
4149 * Show the file name for the match (if any)
4150 * Truncate the file name to avoid a wait for return.
4152 if (compl_shown_match->cp_fname != NULL)
4154 STRCPY(IObuff, "match in file ");
4155 i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4156 if (i <= 0)
4157 i = 0;
4158 else
4159 STRCAT(IObuff, "<");
4160 STRCAT(IObuff, compl_shown_match->cp_fname + i);
4161 msg(IObuff);
4162 redraw_cmdline = FALSE; /* don't overwrite! */
4165 return num_matches;
4169 * Call this while finding completions, to check whether the user has hit a key
4170 * that should change the currently displayed completion, or exit completion
4171 * mode. Also, when compl_pending is not zero, show a completion as soon as
4172 * possible. -- webb
4173 * "frequency" specifies out of how many calls we actually check.
4175 void
4176 ins_compl_check_keys(frequency)
4177 int frequency;
4179 static int count = 0;
4181 int c;
4183 /* Don't check when reading keys from a script. That would break the test
4184 * scripts */
4185 if (using_script())
4186 return;
4188 /* Only do this at regular intervals */
4189 if (++count < frequency)
4190 return;
4191 count = 0;
4193 ++no_mapping;
4194 c = vpeekc_any();
4195 --no_mapping;
4196 if (c != NUL)
4198 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4200 c = safe_vgetc(); /* Eat the character */
4201 compl_shows_dir = ins_compl_key2dir(c);
4202 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4203 c != K_UP && c != K_DOWN);
4205 else if (c != Ctrl_R)
4206 compl_interrupted = TRUE;
4208 if (compl_pending != 0 && !got_int)
4209 (void)ins_compl_next(FALSE, compl_pending > 0
4210 ? compl_pending : -compl_pending, TRUE);
4214 * Decide the direction of Insert mode complete from the key typed.
4215 * Returns BACKWARD or FORWARD.
4217 static int
4218 ins_compl_key2dir(c)
4219 int c;
4221 if (c == Ctrl_P || c == Ctrl_L
4222 || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4223 || c == K_S_UP || c == K_UP)))
4224 return BACKWARD;
4225 return FORWARD;
4229 * Return TRUE for keys that are used for completion only when the popup menu
4230 * is visible.
4232 static int
4233 ins_compl_pum_key(c)
4234 int c;
4236 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4237 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4238 || c == K_UP || c == K_DOWN);
4242 * Decide the number of completions to move forward.
4243 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4245 static int
4246 ins_compl_key2count(c)
4247 int c;
4249 int h;
4251 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4253 h = pum_get_height();
4254 if (h > 3)
4255 h -= 2; /* keep some context */
4256 return h;
4258 return 1;
4262 * Return TRUE if completion with "c" should insert the match, FALSE if only
4263 * to change the currently selected completion.
4265 static int
4266 ins_compl_use_match(c)
4267 int c;
4269 switch (c)
4271 case K_UP:
4272 case K_DOWN:
4273 case K_PAGEDOWN:
4274 case K_KPAGEDOWN:
4275 case K_S_DOWN:
4276 case K_PAGEUP:
4277 case K_KPAGEUP:
4278 case K_S_UP:
4279 return FALSE;
4281 return TRUE;
4285 * Do Insert mode completion.
4286 * Called when character "c" was typed, which has a meaning for completion.
4287 * Returns OK if completion was done, FAIL if something failed (out of mem).
4289 static int
4290 ins_complete(c)
4291 int c;
4293 char_u *line;
4294 int startcol = 0; /* column where searched text starts */
4295 colnr_T curs_col; /* cursor column */
4296 int n;
4298 compl_direction = ins_compl_key2dir(c);
4299 if (!compl_started)
4301 /* First time we hit ^N or ^P (in a row, I mean) */
4303 did_ai = FALSE;
4304 #ifdef FEAT_SMARTINDENT
4305 did_si = FALSE;
4306 can_si = FALSE;
4307 can_si_back = FALSE;
4308 #endif
4309 if (stop_arrow() == FAIL)
4310 return FAIL;
4312 line = ml_get(curwin->w_cursor.lnum);
4313 curs_col = curwin->w_cursor.col;
4314 compl_pending = 0;
4316 /* if this same ctrl_x_mode has been interrupted use the text from
4317 * "compl_startpos" to the cursor as a pattern to add a new word
4318 * instead of expand the one before the cursor, in word-wise if
4319 * "compl_startpos"
4320 * is not in the same line as the cursor then fix it (the line has
4321 * been split because it was longer than 'tw'). if SOL is set then
4322 * skip the previous pattern, a word at the beginning of the line has
4323 * been inserted, we'll look for that -- Acevedo. */
4324 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4325 && compl_cont_mode == ctrl_x_mode)
4328 * it is a continued search
4330 compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */
4331 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4332 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4334 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4336 /* line (probably) wrapped, set compl_startpos to the
4337 * first non_blank in the line, if it is not a wordchar
4338 * include it to get a better pattern, but then we don't
4339 * want the "\\<" prefix, check it bellow */
4340 compl_col = (colnr_T)(skipwhite(line) - line);
4341 compl_startpos.col = compl_col;
4342 compl_startpos.lnum = curwin->w_cursor.lnum;
4343 compl_cont_status &= ~CONT_SOL; /* clear SOL if present */
4345 else
4347 /* S_IPOS was set when we inserted a word that was at the
4348 * beginning of the line, which means that we'll go to SOL
4349 * mode but first we need to redefine compl_startpos */
4350 if (compl_cont_status & CONT_S_IPOS)
4352 compl_cont_status |= CONT_SOL;
4353 compl_startpos.col = (colnr_T)(skipwhite(
4354 line + compl_length
4355 + compl_startpos.col) - line);
4357 compl_col = compl_startpos.col;
4359 compl_length = curwin->w_cursor.col - (int)compl_col;
4360 /* IObuff is used to add a "word from the next line" would we
4361 * have enough space? just being paranoic */
4362 #define MIN_SPACE 75
4363 if (compl_length > (IOSIZE - MIN_SPACE))
4365 compl_cont_status &= ~CONT_SOL;
4366 compl_length = (IOSIZE - MIN_SPACE);
4367 compl_col = curwin->w_cursor.col - compl_length;
4369 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4370 if (compl_length < 1)
4371 compl_cont_status &= CONT_LOCAL;
4373 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4374 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4375 else
4376 compl_cont_status = 0;
4378 else
4379 compl_cont_status &= CONT_LOCAL;
4381 if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */
4383 compl_cont_mode = ctrl_x_mode;
4384 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
4385 compl_cont_status = 0;
4386 compl_cont_status |= CONT_N_ADDS;
4387 compl_startpos = curwin->w_cursor;
4388 startcol = (int)curs_col;
4389 compl_col = 0;
4392 /* Work out completion pattern and original text -- webb */
4393 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
4395 if ((compl_cont_status & CONT_SOL)
4396 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4398 if (!(compl_cont_status & CONT_ADDING))
4400 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4402 compl_col += ++startcol;
4403 compl_length = curs_col - startcol;
4405 if (p_ic)
4406 compl_pattern = str_foldcase(line + compl_col,
4407 compl_length, NULL, 0);
4408 else
4409 compl_pattern = vim_strnsave(line + compl_col,
4410 compl_length);
4411 if (compl_pattern == NULL)
4412 return FAIL;
4414 else if (compl_cont_status & CONT_ADDING)
4416 char_u *prefix = (char_u *)"\\<";
4418 /* we need 3 extra chars, 1 for the NUL and
4419 * 2 >= strlen(prefix) -- Acevedo */
4420 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4421 compl_length) + 3);
4422 if (compl_pattern == NULL)
4423 return FAIL;
4424 if (!vim_iswordp(line + compl_col)
4425 || (compl_col > 0
4426 && (
4427 #ifdef FEAT_MBYTE
4428 vim_iswordp(mb_prevptr(line, line + compl_col))
4429 #else
4430 vim_iswordc(line[compl_col - 1])
4431 #endif
4433 prefix = (char_u *)"";
4434 STRCPY((char *)compl_pattern, prefix);
4435 (void)quote_meta(compl_pattern + STRLEN(prefix),
4436 line + compl_col, compl_length);
4438 else if (--startcol < 0 ||
4439 #ifdef FEAT_MBYTE
4440 !vim_iswordp(mb_prevptr(line, line + startcol + 1))
4441 #else
4442 !vim_iswordc(line[startcol])
4443 #endif
4446 /* Match any word of at least two chars */
4447 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4448 if (compl_pattern == NULL)
4449 return FAIL;
4450 compl_col += curs_col;
4451 compl_length = 0;
4453 else
4455 #ifdef FEAT_MBYTE
4456 /* Search the point of change class of multibyte character
4457 * or not a word single byte character backward. */
4458 if (has_mbyte)
4460 int base_class;
4461 int head_off;
4463 startcol -= (*mb_head_off)(line, line + startcol);
4464 base_class = mb_get_class(line + startcol);
4465 while (--startcol >= 0)
4467 head_off = (*mb_head_off)(line, line + startcol);
4468 if (base_class != mb_get_class(line + startcol
4469 - head_off))
4470 break;
4471 startcol -= head_off;
4474 else
4475 #endif
4476 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4478 compl_col += ++startcol;
4479 compl_length = (int)curs_col - startcol;
4480 if (compl_length == 1)
4482 /* Only match word with at least two chars -- webb
4483 * there's no need to call quote_meta,
4484 * alloc(7) is enough -- Acevedo
4486 compl_pattern = alloc(7);
4487 if (compl_pattern == NULL)
4488 return FAIL;
4489 STRCPY((char *)compl_pattern, "\\<");
4490 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4491 STRCAT((char *)compl_pattern, "\\k");
4493 else
4495 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4496 compl_length) + 3);
4497 if (compl_pattern == NULL)
4498 return FAIL;
4499 STRCPY((char *)compl_pattern, "\\<");
4500 (void)quote_meta(compl_pattern + 2, line + compl_col,
4501 compl_length);
4505 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4507 compl_col = (colnr_T)(skipwhite(line) - line);
4508 compl_length = (int)curs_col - (int)compl_col;
4509 if (compl_length < 0) /* cursor in indent: empty pattern */
4510 compl_length = 0;
4511 if (p_ic)
4512 compl_pattern = str_foldcase(line + compl_col, compl_length,
4513 NULL, 0);
4514 else
4515 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4516 if (compl_pattern == NULL)
4517 return FAIL;
4519 else if (ctrl_x_mode == CTRL_X_FILES)
4521 while (--startcol >= 0 && vim_isfilec(line[startcol]))
4523 compl_col += ++startcol;
4524 compl_length = (int)curs_col - startcol;
4525 compl_pattern = addstar(line + compl_col, compl_length,
4526 EXPAND_FILES);
4527 if (compl_pattern == NULL)
4528 return FAIL;
4530 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4532 compl_pattern = vim_strnsave(line, curs_col);
4533 if (compl_pattern == NULL)
4534 return FAIL;
4535 set_cmd_context(&compl_xp, compl_pattern,
4536 (int)STRLEN(compl_pattern), curs_col);
4537 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4538 || compl_xp.xp_context == EXPAND_NOTHING)
4539 return FAIL;
4540 startcol = (int)(compl_xp.xp_pattern - compl_pattern);
4541 compl_col = startcol;
4542 compl_length = curs_col - startcol;
4544 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
4546 #ifdef FEAT_COMPL_FUNC
4548 * Call user defined function 'completefunc' with "a:findstart"
4549 * set to 1 to obtain the length of text to use for completion.
4551 char_u *args[2];
4552 int col;
4553 char_u *funcname;
4554 pos_T pos;
4556 /* Call 'completefunc' or 'omnifunc' and get pattern length as a
4557 * string */
4558 funcname = ctrl_x_mode == CTRL_X_FUNCTION
4559 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
4560 if (*funcname == NUL)
4562 EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4563 ? "completefunc" : "omnifunc");
4564 return FAIL;
4567 args[0] = (char_u *)"1";
4568 args[1] = NULL;
4569 pos = curwin->w_cursor;
4570 col = call_func_retnr(funcname, 2, args, FALSE);
4571 curwin->w_cursor = pos; /* restore the cursor position */
4573 if (col < 0)
4574 col = curs_col;
4575 compl_col = col;
4576 if ((colnr_T)compl_col > curs_col)
4577 compl_col = curs_col;
4579 /* Setup variables for completion. Need to obtain "line" again,
4580 * it may have become invalid. */
4581 line = ml_get(curwin->w_cursor.lnum);
4582 compl_length = curs_col - compl_col;
4583 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4584 if (compl_pattern == NULL)
4585 #endif
4586 return FAIL;
4588 else if (ctrl_x_mode == CTRL_X_SPELL)
4590 #ifdef FEAT_SPELL
4591 if (spell_bad_len > 0)
4592 compl_col = curs_col - spell_bad_len;
4593 else
4594 compl_col = spell_word_start(startcol);
4595 if (compl_col >= (colnr_T)startcol)
4596 return FAIL;
4597 spell_expand_check_cap(compl_col);
4598 /* Need to obtain "line" again, it may have become invalid. */
4599 line = ml_get(curwin->w_cursor.lnum);
4600 compl_length = (int)curs_col - compl_col;
4601 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4602 if (compl_pattern == NULL)
4603 #endif
4604 return FAIL;
4606 else
4608 EMSG2(_(e_intern2), "ins_complete()");
4609 return FAIL;
4612 if (compl_cont_status & CONT_ADDING)
4614 edit_submode_pre = (char_u *)_(" Adding");
4615 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4617 /* Insert a new line, keep indentation but ignore 'comments' */
4618 #ifdef FEAT_COMMENTS
4619 char_u *old = curbuf->b_p_com;
4621 curbuf->b_p_com = (char_u *)"";
4622 #endif
4623 compl_startpos.lnum = curwin->w_cursor.lnum;
4624 compl_startpos.col = compl_col;
4625 ins_eol('\r');
4626 #ifdef FEAT_COMMENTS
4627 curbuf->b_p_com = old;
4628 #endif
4629 compl_length = 0;
4630 compl_col = curwin->w_cursor.col;
4633 else
4635 edit_submode_pre = NULL;
4636 compl_startpos.col = compl_col;
4639 if (compl_cont_status & CONT_LOCAL)
4640 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
4641 else
4642 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
4644 /* Always add completion for the original text. */
4645 vim_free(compl_orig_text);
4646 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
4647 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
4648 -1, FALSE, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
4650 vim_free(compl_pattern);
4651 compl_pattern = NULL;
4652 vim_free(compl_orig_text);
4653 compl_orig_text = NULL;
4654 return FAIL;
4657 /* showmode might reset the internal line pointers, so it must
4658 * be called before line = ml_get(), or when this address is no
4659 * longer needed. -- Acevedo.
4661 edit_submode_extra = (char_u *)_("-- Searching...");
4662 edit_submode_highl = HLF_COUNT;
4663 showmode();
4664 edit_submode_extra = NULL;
4665 out_flush();
4668 compl_shown_match = compl_curr_match;
4669 compl_shows_dir = compl_direction;
4672 * Find next match (and following matches).
4674 n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
4676 /* may undisplay the popup menu */
4677 ins_compl_upd_pum();
4679 if (n > 1) /* all matches have been found */
4680 compl_matches = n;
4681 compl_curr_match = compl_shown_match;
4682 compl_direction = compl_shows_dir;
4683 compl_interrupted = FALSE;
4685 /* eat the ESC to avoid leaving insert mode */
4686 if (got_int && !global_busy)
4688 (void)vgetc();
4689 got_int = FALSE;
4692 /* we found no match if the list has only the "compl_orig_text"-entry */
4693 if (compl_first_match == compl_first_match->cp_next)
4695 edit_submode_extra = (compl_cont_status & CONT_ADDING)
4696 && compl_length > 1
4697 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
4698 edit_submode_highl = HLF_E;
4699 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
4700 * because we couldn't expand anything at first place, but if we used
4701 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
4702 * (such as M in M'exico) if not tried already. -- Acevedo */
4703 if ( compl_length > 1
4704 || (compl_cont_status & CONT_ADDING)
4705 || (ctrl_x_mode != 0
4706 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
4707 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
4708 compl_cont_status &= ~CONT_N_ADDS;
4711 if (compl_curr_match->cp_flags & CONT_S_IPOS)
4712 compl_cont_status |= CONT_S_IPOS;
4713 else
4714 compl_cont_status &= ~CONT_S_IPOS;
4716 if (edit_submode_extra == NULL)
4718 if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
4720 edit_submode_extra = (char_u *)_("Back at original");
4721 edit_submode_highl = HLF_W;
4723 else if (compl_cont_status & CONT_S_IPOS)
4725 edit_submode_extra = (char_u *)_("Word from other line");
4726 edit_submode_highl = HLF_COUNT;
4728 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
4730 edit_submode_extra = (char_u *)_("The only match");
4731 edit_submode_highl = HLF_COUNT;
4733 else
4735 /* Update completion sequence number when needed. */
4736 if (compl_curr_match->cp_number == -1)
4738 int number = 0;
4739 compl_T *match;
4741 if (compl_direction == FORWARD)
4743 /* search backwards for the first valid (!= -1) number.
4744 * This should normally succeed already at the first loop
4745 * cycle, so it's fast! */
4746 for (match = compl_curr_match->cp_prev; match != NULL
4747 && match != compl_first_match;
4748 match = match->cp_prev)
4749 if (match->cp_number != -1)
4751 number = match->cp_number;
4752 break;
4754 if (match != NULL)
4755 /* go up and assign all numbers which are not assigned
4756 * yet */
4757 for (match = match->cp_next;
4758 match != NULL && match->cp_number == -1;
4759 match = match->cp_next)
4760 match->cp_number = ++number;
4762 else /* BACKWARD */
4764 /* search forwards (upwards) for the first valid (!= -1)
4765 * number. This should normally succeed already at the
4766 * first loop cycle, so it's fast! */
4767 for (match = compl_curr_match->cp_next; match != NULL
4768 && match != compl_first_match;
4769 match = match->cp_next)
4770 if (match->cp_number != -1)
4772 number = match->cp_number;
4773 break;
4775 if (match != NULL)
4776 /* go down and assign all numbers which are not
4777 * assigned yet */
4778 for (match = match->cp_prev; match
4779 && match->cp_number == -1;
4780 match = match->cp_prev)
4781 match->cp_number = ++number;
4785 /* The match should always have a sequence number now, this is
4786 * just a safety check. */
4787 if (compl_curr_match->cp_number != -1)
4789 /* Space for 10 text chars. + 2x10-digit no.s */
4790 static char_u match_ref[31];
4792 if (compl_matches > 0)
4793 sprintf((char *)IObuff, _("match %d of %d"),
4794 compl_curr_match->cp_number, compl_matches);
4795 else
4796 sprintf((char *)IObuff, _("match %d"),
4797 compl_curr_match->cp_number);
4798 vim_strncpy(match_ref, IObuff, 30);
4799 edit_submode_extra = match_ref;
4800 edit_submode_highl = HLF_R;
4801 if (dollar_vcol)
4802 curs_columns(FALSE);
4807 /* Show a message about what (completion) mode we're in. */
4808 showmode();
4809 if (edit_submode_extra != NULL)
4811 if (!p_smd)
4812 msg_attr(edit_submode_extra,
4813 edit_submode_highl < HLF_COUNT
4814 ? hl_attr(edit_submode_highl) : 0);
4816 else
4817 msg_clr_cmdline(); /* necessary for "noshowmode" */
4819 /* RedrawingDisabled may be set when invoked through complete(). */
4820 n = RedrawingDisabled;
4821 RedrawingDisabled = 0;
4822 ins_compl_show_pum();
4823 setcursor();
4824 RedrawingDisabled = n;
4826 return OK;
4830 * Looks in the first "len" chars. of "src" for search-metachars.
4831 * If dest is not NULL the chars. are copied there quoting (with
4832 * a backslash) the metachars, and dest would be NUL terminated.
4833 * Returns the length (needed) of dest
4835 static int
4836 quote_meta(dest, src, len)
4837 char_u *dest;
4838 char_u *src;
4839 int len;
4841 int m;
4843 for (m = len; --len >= 0; src++)
4845 switch (*src)
4847 case '.':
4848 case '*':
4849 case '[':
4850 if (ctrl_x_mode == CTRL_X_DICTIONARY
4851 || ctrl_x_mode == CTRL_X_THESAURUS)
4852 break;
4853 case '~':
4854 if (!p_magic) /* quote these only if magic is set */
4855 break;
4856 case '\\':
4857 if (ctrl_x_mode == CTRL_X_DICTIONARY
4858 || ctrl_x_mode == CTRL_X_THESAURUS)
4859 break;
4860 case '^': /* currently it's not needed. */
4861 case '$':
4862 m++;
4863 if (dest != NULL)
4864 *dest++ = '\\';
4865 break;
4867 if (dest != NULL)
4868 *dest++ = *src;
4869 # ifdef FEAT_MBYTE
4870 /* Copy remaining bytes of a multibyte character. */
4871 if (has_mbyte)
4873 int i, mb_len;
4875 mb_len = (*mb_ptr2len)(src) - 1;
4876 if (mb_len > 0 && len >= mb_len)
4877 for (i = 0; i < mb_len; ++i)
4879 --len;
4880 ++src;
4881 if (dest != NULL)
4882 *dest++ = *src;
4885 # endif
4887 if (dest != NULL)
4888 *dest = NUL;
4890 return m;
4892 #endif /* FEAT_INS_EXPAND */
4895 * Next character is interpreted literally.
4896 * A one, two or three digit decimal number is interpreted as its byte value.
4897 * If one or two digits are entered, the next character is given to vungetc().
4898 * For Unicode a character > 255 may be returned.
4901 get_literal()
4903 int cc;
4904 int nc;
4905 int i;
4906 int hex = FALSE;
4907 int octal = FALSE;
4908 #ifdef FEAT_MBYTE
4909 int unicode = 0;
4910 #endif
4912 if (got_int)
4913 return Ctrl_C;
4915 #ifdef FEAT_GUI
4917 * In GUI there is no point inserting the internal code for a special key.
4918 * It is more useful to insert the string "<KEY>" instead. This would
4919 * probably be useful in a text window too, but it would not be
4920 * vi-compatible (maybe there should be an option for it?) -- webb
4922 if (gui.in_use)
4923 ++allow_keys;
4924 #endif
4925 #ifdef USE_ON_FLY_SCROLL
4926 dont_scroll = TRUE; /* disallow scrolling here */
4927 #endif
4928 ++no_mapping; /* don't map the next key hits */
4929 cc = 0;
4930 i = 0;
4931 for (;;)
4934 nc = safe_vgetc();
4935 while (nc == K_IGNORE || nc == K_VER_SCROLLBAR
4936 || nc == K_HOR_SCROLLBAR);
4937 #ifdef FEAT_CMDL_INFO
4938 if (!(State & CMDLINE)
4939 # ifdef FEAT_MBYTE
4940 && MB_BYTE2LEN_CHECK(nc) == 1
4941 # endif
4943 add_to_showcmd(nc);
4944 #endif
4945 if (nc == 'x' || nc == 'X')
4946 hex = TRUE;
4947 else if (nc == 'o' || nc == 'O')
4948 octal = TRUE;
4949 #ifdef FEAT_MBYTE
4950 else if (nc == 'u' || nc == 'U')
4951 unicode = nc;
4952 #endif
4953 else
4955 if (hex
4956 #ifdef FEAT_MBYTE
4957 || unicode != 0
4958 #endif
4961 if (!vim_isxdigit(nc))
4962 break;
4963 cc = cc * 16 + hex2nr(nc);
4965 else if (octal)
4967 if (nc < '0' || nc > '7')
4968 break;
4969 cc = cc * 8 + nc - '0';
4971 else
4973 if (!VIM_ISDIGIT(nc))
4974 break;
4975 cc = cc * 10 + nc - '0';
4978 ++i;
4981 if (cc > 255
4982 #ifdef FEAT_MBYTE
4983 && unicode == 0
4984 #endif
4986 cc = 255; /* limit range to 0-255 */
4987 nc = 0;
4989 if (hex) /* hex: up to two chars */
4991 if (i >= 2)
4992 break;
4994 #ifdef FEAT_MBYTE
4995 else if (unicode) /* Unicode: up to four or eight chars */
4997 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
4998 break;
5000 #endif
5001 else if (i >= 3) /* decimal or octal: up to three chars */
5002 break;
5004 if (i == 0) /* no number entered */
5006 if (nc == K_ZERO) /* NUL is stored as NL */
5008 cc = '\n';
5009 nc = 0;
5011 else
5013 cc = nc;
5014 nc = 0;
5018 if (cc == 0) /* NUL is stored as NL */
5019 cc = '\n';
5020 #ifdef FEAT_MBYTE
5021 if (enc_dbcs && (cc & 0xff) == 0)
5022 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
5023 second byte will cause trouble! */
5024 #endif
5026 --no_mapping;
5027 #ifdef FEAT_GUI
5028 if (gui.in_use)
5029 --allow_keys;
5030 #endif
5031 if (nc)
5032 vungetc(nc);
5033 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
5034 return cc;
5038 * Insert character, taking care of special keys and mod_mask
5040 static void
5041 insert_special(c, allow_modmask, ctrlv)
5042 int c;
5043 int allow_modmask;
5044 int ctrlv; /* c was typed after CTRL-V */
5046 char_u *p;
5047 int len;
5050 * Special function key, translate into "<Key>". Up to the last '>' is
5051 * inserted with ins_str(), so as not to replace characters in replace
5052 * mode.
5053 * Only use mod_mask for special keys, to avoid things like <S-Space>,
5054 * unless 'allow_modmask' is TRUE.
5056 #ifdef MACOS
5057 /* Command-key never produces a normal key */
5058 if (mod_mask & MOD_MASK_CMD)
5059 allow_modmask = TRUE;
5060 #endif
5061 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5063 p = get_special_key_name(c, mod_mask);
5064 len = (int)STRLEN(p);
5065 c = p[len - 1];
5066 if (len > 2)
5068 if (stop_arrow() == FAIL)
5069 return;
5070 p[len - 1] = NUL;
5071 ins_str(p);
5072 AppendToRedobuffLit(p, -1);
5073 ctrlv = FALSE;
5076 if (stop_arrow() == OK)
5077 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5081 * Special characters in this context are those that need processing other
5082 * than the simple insertion that can be performed here. This includes ESC
5083 * which terminates the insert, and CR/NL which need special processing to
5084 * open up a new line. This routine tries to optimize insertions performed by
5085 * the "redo", "undo" or "put" commands, so it needs to know when it should
5086 * stop and defer processing to the "normal" mechanism.
5087 * '0' and '^' are special, because they can be followed by CTRL-D.
5089 #ifdef EBCDIC
5090 # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
5091 #else
5092 # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5093 #endif
5095 #ifdef FEAT_MBYTE
5096 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5097 #else
5098 # define WHITECHAR(cc) vim_iswhite(cc)
5099 #endif
5101 void
5102 insertchar(c, flags, second_indent)
5103 int c; /* character to insert or NUL */
5104 int flags; /* INSCHAR_FORMAT, etc. */
5105 int second_indent; /* indent for second line if >= 0 */
5107 int textwidth;
5108 #ifdef FEAT_COMMENTS
5109 char_u *p;
5110 #endif
5111 int fo_ins_blank;
5113 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5114 fo_ins_blank = has_format_option(FO_INS_BLANK);
5117 * Try to break the line in two or more pieces when:
5118 * - Always do this if we have been called to do formatting only.
5119 * - Always do this when 'formatoptions' has the 'a' flag and the line
5120 * ends in white space.
5121 * - Otherwise:
5122 * - Don't do this if inserting a blank
5123 * - Don't do this if an existing character is being replaced, unless
5124 * we're in VREPLACE mode.
5125 * - Do this if the cursor is not on the line where insert started
5126 * or - 'formatoptions' doesn't have 'l' or the line was not too long
5127 * before the insert.
5128 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5129 * before 'textwidth'
5131 if (textwidth > 0
5132 && ((flags & INSCHAR_FORMAT)
5133 || (!vim_iswhite(c)
5134 && !((State & REPLACE_FLAG)
5135 #ifdef FEAT_VREPLACE
5136 && !(State & VREPLACE_FLAG)
5137 #endif
5138 && *ml_get_cursor() != NUL)
5139 && (curwin->w_cursor.lnum != Insstart.lnum
5140 || ((!has_format_option(FO_INS_LONG)
5141 || Insstart_textlen <= (colnr_T)textwidth)
5142 && (!fo_ins_blank
5143 || Insstart_blank_vcol <= (colnr_T)textwidth
5144 ))))))
5146 /* Format with 'formatexpr' when it's set. Use internal formatting
5147 * when 'formatexpr' isn't set or it returns non-zero. */
5148 #if defined(FEAT_EVAL)
5149 if (*curbuf->b_p_fex == NUL
5150 || fex_format(curwin->w_cursor.lnum, 1L) != 0)
5151 #endif
5152 internal_format(textwidth, second_indent, flags, c == NUL);
5155 if (c == NUL) /* only formatting was wanted */
5156 return;
5158 #ifdef FEAT_COMMENTS
5159 /* Check whether this character should end a comment. */
5160 if (did_ai && (int)c == end_comment_pending)
5162 char_u *line;
5163 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5164 int middle_len, end_len;
5165 int i;
5168 * Need to remove existing (middle) comment leader and insert end
5169 * comment leader. First, check what comment leader we can find.
5171 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
5172 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
5174 /* Skip middle-comment string */
5175 while (*p && p[-1] != ':') /* find end of middle flags */
5176 ++p;
5177 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5178 /* Don't count trailing white space for middle_len */
5179 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5180 --middle_len;
5182 /* Find the end-comment string */
5183 while (*p && p[-1] != ':') /* find end of end flags */
5184 ++p;
5185 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5187 /* Skip white space before the cursor */
5188 i = curwin->w_cursor.col;
5189 while (--i >= 0 && vim_iswhite(line[i]))
5191 i++;
5193 /* Skip to before the middle leader */
5194 i -= middle_len;
5196 /* Check some expected things before we go on */
5197 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5199 /* Backspace over all the stuff we want to replace */
5200 backspace_until_column(i);
5203 * Insert the end-comment string, except for the last
5204 * character, which will get inserted as normal later.
5206 ins_bytes_len(lead_end, end_len - 1);
5210 end_comment_pending = NUL;
5211 #endif
5213 did_ai = FALSE;
5214 #ifdef FEAT_SMARTINDENT
5215 did_si = FALSE;
5216 can_si = FALSE;
5217 can_si_back = FALSE;
5218 #endif
5221 * If there's any pending input, grab up to INPUT_BUFLEN at once.
5222 * This speeds up normal text input considerably.
5223 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5224 * need to re-indent at a ':', or any other character (but not what
5225 * 'paste' is set)..
5227 #ifdef USE_ON_FLY_SCROLL
5228 dont_scroll = FALSE; /* allow scrolling here */
5229 #endif
5231 if ( !ISSPECIAL(c)
5232 #ifdef FEAT_MBYTE
5233 && (!has_mbyte || (*mb_char2len)(c) == 1)
5234 #endif
5235 && vpeekc() != NUL
5236 && !(State & REPLACE_FLAG)
5237 #ifdef FEAT_CINDENT
5238 && !cindent_on()
5239 #endif
5240 #ifdef FEAT_RIGHTLEFT
5241 && !p_ri
5242 #endif
5245 #define INPUT_BUFLEN 100
5246 char_u buf[INPUT_BUFLEN + 1];
5247 int i;
5248 colnr_T virtcol = 0;
5250 buf[0] = c;
5251 i = 1;
5252 if (textwidth > 0)
5253 virtcol = get_nolist_virtcol();
5255 * Stop the string when:
5256 * - no more chars available
5257 * - finding a special character (command key)
5258 * - buffer is full
5259 * - running into the 'textwidth' boundary
5260 * - need to check for abbreviation: A non-word char after a word-char
5262 while ( (c = vpeekc()) != NUL
5263 && !ISSPECIAL(c)
5264 #ifdef FEAT_MBYTE
5265 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5266 #endif
5267 && i < INPUT_BUFLEN
5268 && (textwidth == 0
5269 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5270 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5272 #ifdef FEAT_RIGHTLEFT
5273 c = vgetc();
5274 if (p_hkmap && KeyTyped)
5275 c = hkmap(c); /* Hebrew mode mapping */
5276 # ifdef FEAT_FKMAP
5277 if (p_fkmap && KeyTyped)
5278 c = fkmap(c); /* Farsi mode mapping */
5279 # endif
5280 buf[i++] = c;
5281 #else
5282 buf[i++] = vgetc();
5283 #endif
5286 #ifdef FEAT_DIGRAPHS
5287 do_digraph(-1); /* clear digraphs */
5288 do_digraph(buf[i-1]); /* may be the start of a digraph */
5289 #endif
5290 buf[i] = NUL;
5291 ins_str(buf);
5292 if (flags & INSCHAR_CTRLV)
5294 redo_literal(*buf);
5295 i = 1;
5297 else
5298 i = 0;
5299 if (buf[i] != NUL)
5300 AppendToRedobuffLit(buf + i, -1);
5302 else
5304 #ifdef FEAT_MBYTE
5305 int cc;
5307 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
5309 char_u buf[MB_MAXBYTES + 1];
5311 (*mb_char2bytes)(c, buf);
5312 buf[cc] = NUL;
5313 ins_char_bytes(buf, cc);
5314 AppendCharToRedobuff(c);
5316 else
5317 #endif
5319 ins_char(c);
5320 if (flags & INSCHAR_CTRLV)
5321 redo_literal(c);
5322 else
5323 AppendCharToRedobuff(c);
5329 * Format text at the current insert position.
5331 static void
5332 internal_format(textwidth, second_indent, flags, format_only)
5333 int textwidth;
5334 int second_indent;
5335 int flags;
5336 int format_only;
5338 int cc;
5339 int save_char = NUL;
5340 int haveto_redraw = FALSE;
5341 int fo_ins_blank = has_format_option(FO_INS_BLANK);
5342 #ifdef FEAT_MBYTE
5343 int fo_multibyte = has_format_option(FO_MBYTE_BREAK);
5344 #endif
5345 int fo_white_par = has_format_option(FO_WHITE_PAR);
5346 int first_line = TRUE;
5347 #ifdef FEAT_COMMENTS
5348 colnr_T leader_len;
5349 int no_leader = FALSE;
5350 int do_comments = (flags & INSCHAR_DO_COM);
5351 #endif
5354 * When 'ai' is off we don't want a space under the cursor to be
5355 * deleted. Replace it with an 'x' temporarily.
5357 if (!curbuf->b_p_ai)
5359 cc = gchar_cursor();
5360 if (vim_iswhite(cc))
5362 save_char = cc;
5363 pchar_cursor('x');
5368 * Repeat breaking lines, until the current line is not too long.
5370 while (!got_int)
5372 int startcol; /* Cursor column at entry */
5373 int wantcol; /* column at textwidth border */
5374 int foundcol; /* column for start of spaces */
5375 int end_foundcol = 0; /* column for start of word */
5376 colnr_T len;
5377 colnr_T virtcol;
5378 #ifdef FEAT_VREPLACE
5379 int orig_col = 0;
5380 char_u *saved_text = NULL;
5381 #endif
5382 colnr_T col;
5384 virtcol = get_nolist_virtcol();
5385 if (virtcol < (colnr_T)textwidth)
5386 break;
5388 #ifdef FEAT_COMMENTS
5389 if (no_leader)
5390 do_comments = FALSE;
5391 else if (!(flags & INSCHAR_FORMAT)
5392 && has_format_option(FO_WRAP_COMS))
5393 do_comments = TRUE;
5395 /* Don't break until after the comment leader */
5396 if (do_comments)
5397 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
5398 else
5399 leader_len = 0;
5401 /* If the line doesn't start with a comment leader, then don't
5402 * start one in a following broken line. Avoids that a %word
5403 * moved to the start of the next line causes all following lines
5404 * to start with %. */
5405 if (leader_len == 0)
5406 no_leader = TRUE;
5407 #endif
5408 if (!(flags & INSCHAR_FORMAT)
5409 #ifdef FEAT_COMMENTS
5410 && leader_len == 0
5411 #endif
5412 && !has_format_option(FO_WRAP))
5415 textwidth = 0;
5416 break;
5418 if ((startcol = curwin->w_cursor.col) == 0)
5419 break;
5421 /* find column of textwidth border */
5422 coladvance((colnr_T)textwidth);
5423 wantcol = curwin->w_cursor.col;
5425 curwin->w_cursor.col = startcol - 1;
5426 #ifdef FEAT_MBYTE
5427 /* Correct cursor for multi-byte character. */
5428 if (has_mbyte)
5429 mb_adjust_cursor();
5430 #endif
5431 foundcol = 0;
5434 * Find position to break at.
5435 * Stop at first entered white when 'formatoptions' has 'v'
5437 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
5438 || curwin->w_cursor.lnum != Insstart.lnum
5439 || curwin->w_cursor.col >= Insstart.col)
5441 cc = gchar_cursor();
5442 if (WHITECHAR(cc))
5444 /* remember position of blank just before text */
5445 end_foundcol = curwin->w_cursor.col;
5447 /* find start of sequence of blanks */
5448 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
5450 dec_cursor();
5451 cc = gchar_cursor();
5453 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
5454 break; /* only spaces in front of text */
5455 #ifdef FEAT_COMMENTS
5456 /* Don't break until after the comment leader */
5457 if (curwin->w_cursor.col < leader_len)
5458 break;
5459 #endif
5460 if (has_format_option(FO_ONE_LETTER))
5462 /* do not break after one-letter words */
5463 if (curwin->w_cursor.col == 0)
5464 break; /* one-letter word at begin */
5466 col = curwin->w_cursor.col;
5467 dec_cursor();
5468 cc = gchar_cursor();
5470 if (WHITECHAR(cc))
5471 continue; /* one-letter, continue */
5472 curwin->w_cursor.col = col;
5474 #ifdef FEAT_MBYTE
5475 if (has_mbyte)
5476 foundcol = curwin->w_cursor.col
5477 + (*mb_ptr2len)(ml_get_cursor());
5478 else
5479 #endif
5480 foundcol = curwin->w_cursor.col + 1;
5481 if (curwin->w_cursor.col < (colnr_T)wantcol)
5482 break;
5484 #ifdef FEAT_MBYTE
5485 else if (cc >= 0x100 && fo_multibyte
5486 && curwin->w_cursor.col <= (colnr_T)wantcol)
5488 /* Break after or before a multi-byte character. */
5489 foundcol = curwin->w_cursor.col;
5490 if (curwin->w_cursor.col < (colnr_T)wantcol)
5491 foundcol += (*mb_char2len)(cc);
5492 end_foundcol = foundcol;
5493 break;
5495 #endif
5496 if (curwin->w_cursor.col == 0)
5497 break;
5498 dec_cursor();
5501 if (foundcol == 0) /* no spaces, cannot break line */
5503 curwin->w_cursor.col = startcol;
5504 break;
5507 /* Going to break the line, remove any "$" now. */
5508 undisplay_dollar();
5511 * Offset between cursor position and line break is used by replace
5512 * stack functions. VREPLACE does not use this, and backspaces
5513 * over the text instead.
5515 #ifdef FEAT_VREPLACE
5516 if (State & VREPLACE_FLAG)
5517 orig_col = startcol; /* Will start backspacing from here */
5518 else
5519 #endif
5520 replace_offset = startcol - end_foundcol - 1;
5523 * adjust startcol for spaces that will be deleted and
5524 * characters that will remain on top line
5526 curwin->w_cursor.col = foundcol;
5527 while (cc = gchar_cursor(), WHITECHAR(cc))
5528 inc_cursor();
5529 startcol -= curwin->w_cursor.col;
5530 if (startcol < 0)
5531 startcol = 0;
5533 #ifdef FEAT_VREPLACE
5534 if (State & VREPLACE_FLAG)
5537 * In VREPLACE mode, we will backspace over the text to be
5538 * wrapped, so save a copy now to put on the next line.
5540 saved_text = vim_strsave(ml_get_cursor());
5541 curwin->w_cursor.col = orig_col;
5542 if (saved_text == NULL)
5543 break; /* Can't do it, out of memory */
5544 saved_text[startcol] = NUL;
5546 /* Backspace over characters that will move to the next line */
5547 if (!fo_white_par)
5548 backspace_until_column(foundcol);
5550 else
5551 #endif
5553 /* put cursor after pos. to break line */
5554 if (!fo_white_par)
5555 curwin->w_cursor.col = foundcol;
5559 * Split the line just before the margin.
5560 * Only insert/delete lines, but don't really redraw the window.
5562 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
5563 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
5564 #ifdef FEAT_COMMENTS
5565 + (do_comments ? OPENLINE_DO_COM : 0)
5566 #endif
5567 , old_indent);
5568 old_indent = 0;
5570 replace_offset = 0;
5571 if (first_line)
5573 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
5574 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
5575 if (second_indent >= 0)
5577 #ifdef FEAT_VREPLACE
5578 if (State & VREPLACE_FLAG)
5579 change_indent(INDENT_SET, second_indent, FALSE, NUL);
5580 else
5581 #endif
5582 (void)set_indent(second_indent, SIN_CHANGED);
5584 first_line = FALSE;
5587 #ifdef FEAT_VREPLACE
5588 if (State & VREPLACE_FLAG)
5591 * In VREPLACE mode we have backspaced over the text to be
5592 * moved, now we re-insert it into the new line.
5594 ins_bytes(saved_text);
5595 vim_free(saved_text);
5597 else
5598 #endif
5601 * Check if cursor is not past the NUL off the line, cindent
5602 * may have added or removed indent.
5604 curwin->w_cursor.col += startcol;
5605 len = (colnr_T)STRLEN(ml_get_curline());
5606 if (curwin->w_cursor.col > len)
5607 curwin->w_cursor.col = len;
5610 haveto_redraw = TRUE;
5611 #ifdef FEAT_CINDENT
5612 can_cindent = TRUE;
5613 #endif
5614 /* moved the cursor, don't autoindent or cindent now */
5615 did_ai = FALSE;
5616 #ifdef FEAT_SMARTINDENT
5617 did_si = FALSE;
5618 can_si = FALSE;
5619 can_si_back = FALSE;
5620 #endif
5621 line_breakcheck();
5624 if (save_char != NUL) /* put back space after cursor */
5625 pchar_cursor(save_char);
5627 if (!format_only && haveto_redraw)
5629 update_topline();
5630 redraw_curbuf_later(VALID);
5635 * Called after inserting or deleting text: When 'formatoptions' includes the
5636 * 'a' flag format from the current line until the end of the paragraph.
5637 * Keep the cursor at the same position relative to the text.
5638 * The caller must have saved the cursor line for undo, following ones will be
5639 * saved here.
5641 void
5642 auto_format(trailblank, prev_line)
5643 int trailblank; /* when TRUE also format with trailing blank */
5644 int prev_line; /* may start in previous line */
5646 pos_T pos;
5647 colnr_T len;
5648 char_u *old;
5649 char_u *new, *pnew;
5650 int wasatend;
5651 int cc;
5653 if (!has_format_option(FO_AUTO))
5654 return;
5656 pos = curwin->w_cursor;
5657 old = ml_get_curline();
5659 /* may remove added space */
5660 check_auto_format(FALSE);
5662 /* Don't format in Insert mode when the cursor is on a trailing blank, the
5663 * user might insert normal text next. Also skip formatting when "1" is
5664 * in 'formatoptions' and there is a single character before the cursor.
5665 * Otherwise the line would be broken and when typing another non-white
5666 * next they are not joined back together. */
5667 wasatend = (pos.col == STRLEN(old));
5668 if (*old != NUL && !trailblank && wasatend)
5670 dec_cursor();
5671 cc = gchar_cursor();
5672 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
5673 && has_format_option(FO_ONE_LETTER))
5674 dec_cursor();
5675 cc = gchar_cursor();
5676 if (WHITECHAR(cc))
5678 curwin->w_cursor = pos;
5679 return;
5681 curwin->w_cursor = pos;
5684 #ifdef FEAT_COMMENTS
5685 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
5686 * comments. */
5687 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
5688 && get_leader_len(old, NULL, FALSE) == 0)
5689 return;
5690 #endif
5693 * May start formatting in a previous line, so that after "x" a word is
5694 * moved to the previous line if it fits there now. Only when this is not
5695 * the start of a paragraph.
5697 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
5699 --curwin->w_cursor.lnum;
5700 if (u_save_cursor() == FAIL)
5701 return;
5705 * Do the formatting and restore the cursor position. "saved_cursor" will
5706 * be adjusted for the text formatting.
5708 saved_cursor = pos;
5709 format_lines((linenr_T)-1);
5710 curwin->w_cursor = saved_cursor;
5711 saved_cursor.lnum = 0;
5713 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
5715 /* "cannot happen" */
5716 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5717 coladvance((colnr_T)MAXCOL);
5719 else
5720 check_cursor_col();
5722 /* Insert mode: If the cursor is now after the end of the line while it
5723 * previously wasn't, the line was broken. Because of the rule above we
5724 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
5725 * formatted. */
5726 if (!wasatend && has_format_option(FO_WHITE_PAR))
5728 new = ml_get_curline();
5729 len = (colnr_T)STRLEN(new);
5730 if (curwin->w_cursor.col == len)
5732 pnew = vim_strnsave(new, len + 2);
5733 pnew[len] = ' ';
5734 pnew[len + 1] = NUL;
5735 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
5736 /* remove the space later */
5737 did_add_space = TRUE;
5739 else
5740 /* may remove added space */
5741 check_auto_format(FALSE);
5744 check_cursor();
5748 * When an extra space was added to continue a paragraph for auto-formatting,
5749 * delete it now. The space must be under the cursor, just after the insert
5750 * position.
5752 static void
5753 check_auto_format(end_insert)
5754 int end_insert; /* TRUE when ending Insert mode */
5756 int c = ' ';
5757 int cc;
5759 if (did_add_space)
5761 cc = gchar_cursor();
5762 if (!WHITECHAR(cc))
5763 /* Somehow the space was removed already. */
5764 did_add_space = FALSE;
5765 else
5767 if (!end_insert)
5769 inc_cursor();
5770 c = gchar_cursor();
5771 dec_cursor();
5773 if (c != NUL)
5775 /* The space is no longer at the end of the line, delete it. */
5776 del_char(FALSE);
5777 did_add_space = FALSE;
5784 * Find out textwidth to be used for formatting:
5785 * if 'textwidth' option is set, use it
5786 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
5787 * if invalid value, use 0.
5788 * Set default to window width (maximum 79) for "gq" operator.
5791 comp_textwidth(ff)
5792 int ff; /* force formatting (for "Q" command) */
5794 int textwidth;
5796 textwidth = curbuf->b_p_tw;
5797 if (textwidth == 0 && curbuf->b_p_wm)
5799 /* The width is the window width minus 'wrapmargin' minus all the
5800 * things that add to the margin. */
5801 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
5802 #ifdef FEAT_CMDWIN
5803 if (cmdwin_type != 0)
5804 textwidth -= 1;
5805 #endif
5806 #ifdef FEAT_FOLDING
5807 textwidth -= curwin->w_p_fdc;
5808 #endif
5809 #ifdef FEAT_SIGNS
5810 if (curwin->w_buffer->b_signlist != NULL
5811 # ifdef FEAT_NETBEANS_INTG
5812 || usingNetbeans
5813 # endif
5815 textwidth -= 1;
5816 #endif
5817 if (curwin->w_p_nu)
5818 textwidth -= 8;
5820 if (textwidth < 0)
5821 textwidth = 0;
5822 if (ff && textwidth == 0)
5824 textwidth = W_WIDTH(curwin) - 1;
5825 if (textwidth > 79)
5826 textwidth = 79;
5828 return textwidth;
5832 * Put a character in the redo buffer, for when just after a CTRL-V.
5834 static void
5835 redo_literal(c)
5836 int c;
5838 char_u buf[10];
5840 /* Only digits need special treatment. Translate them into a string of
5841 * three digits. */
5842 if (VIM_ISDIGIT(c))
5844 sprintf((char *)buf, "%03d", c);
5845 AppendToRedobuff(buf);
5847 else
5848 AppendCharToRedobuff(c);
5852 * start_arrow() is called when an arrow key is used in insert mode.
5853 * For undo/redo it resembles hitting the <ESC> key.
5855 static void
5856 start_arrow(end_insert_pos)
5857 pos_T *end_insert_pos; /* can be NULL */
5859 if (!arrow_used) /* something has been inserted */
5861 AppendToRedobuff(ESC_STR);
5862 stop_insert(end_insert_pos, FALSE);
5863 arrow_used = TRUE; /* this means we stopped the current insert */
5865 #ifdef FEAT_SPELL
5866 check_spell_redraw();
5867 #endif
5870 #ifdef FEAT_SPELL
5872 * If we skipped highlighting word at cursor, do it now.
5873 * It may be skipped again, thus reset spell_redraw_lnum first.
5875 static void
5876 check_spell_redraw()
5878 if (spell_redraw_lnum != 0)
5880 linenr_T lnum = spell_redraw_lnum;
5882 spell_redraw_lnum = 0;
5883 redrawWinline(lnum, FALSE);
5888 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5889 * spelled word, if there is one.
5891 static void
5892 spell_back_to_badword()
5894 pos_T tpos = curwin->w_cursor;
5896 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
5897 if (curwin->w_cursor.col != tpos.col)
5898 start_arrow(&tpos);
5900 #endif
5903 * stop_arrow() is called before a change is made in insert mode.
5904 * If an arrow key has been used, start a new insertion.
5905 * Returns FAIL if undo is impossible, shouldn't insert then.
5908 stop_arrow()
5910 if (arrow_used)
5912 if (u_save_cursor() == OK)
5914 arrow_used = FALSE;
5915 ins_need_undo = FALSE;
5917 Insstart = curwin->w_cursor; /* new insertion starts here */
5918 Insstart_textlen = linetabsize(ml_get_curline());
5919 ai_col = 0;
5920 #ifdef FEAT_VREPLACE
5921 if (State & VREPLACE_FLAG)
5923 orig_line_count = curbuf->b_ml.ml_line_count;
5924 vr_lines_changed = 1;
5926 #endif
5927 ResetRedobuff();
5928 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
5929 new_insert_skip = 2;
5931 else if (ins_need_undo)
5933 if (u_save_cursor() == OK)
5934 ins_need_undo = FALSE;
5937 #ifdef FEAT_FOLDING
5938 /* Always open fold at the cursor line when inserting something. */
5939 foldOpenCursor();
5940 #endif
5942 return (arrow_used || ins_need_undo ? FAIL : OK);
5946 * Do a few things to stop inserting.
5947 * "end_insert_pos" is where insert ended. It is NULL when we already jumped
5948 * to another window/buffer.
5950 static void
5951 stop_insert(end_insert_pos, esc)
5952 pos_T *end_insert_pos;
5953 int esc; /* called by ins_esc() */
5955 int cc;
5956 char_u *ptr;
5958 stop_redo_ins();
5959 replace_flush(); /* abandon replace stack */
5962 * Save the inserted text for later redo with ^@ and CTRL-A.
5963 * Don't do it when "restart_edit" was set and nothing was inserted,
5964 * otherwise CTRL-O w and then <Left> will clear "last_insert".
5966 ptr = get_inserted();
5967 if (did_restart_edit == 0 || (ptr != NULL
5968 && (int)STRLEN(ptr) > new_insert_skip))
5970 vim_free(last_insert);
5971 last_insert = ptr;
5972 last_insert_skip = new_insert_skip;
5974 else
5975 vim_free(ptr);
5977 if (!arrow_used && end_insert_pos != NULL)
5979 /* Auto-format now. It may seem strange to do this when stopping an
5980 * insertion (or moving the cursor), but it's required when appending
5981 * a line and having it end in a space. But only do it when something
5982 * was actually inserted, otherwise undo won't work. */
5983 if (!ins_need_undo && has_format_option(FO_AUTO))
5985 pos_T tpos = curwin->w_cursor;
5987 /* When the cursor is at the end of the line after a space the
5988 * formatting will move it to the following word. Avoid that by
5989 * moving the cursor onto the space. */
5990 cc = 'x';
5991 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
5993 dec_cursor();
5994 cc = gchar_cursor();
5995 if (!vim_iswhite(cc))
5996 curwin->w_cursor = tpos;
5999 auto_format(TRUE, FALSE);
6001 if (vim_iswhite(cc))
6003 if (gchar_cursor() != NUL)
6004 inc_cursor();
6005 #ifdef FEAT_VIRTUALEDIT
6006 /* If the cursor is still at the same character, also keep
6007 * the "coladd". */
6008 if (gchar_cursor() == NUL
6009 && curwin->w_cursor.lnum == tpos.lnum
6010 && curwin->w_cursor.col == tpos.col)
6011 curwin->w_cursor.coladd = tpos.coladd;
6012 #endif
6016 /* If a space was inserted for auto-formatting, remove it now. */
6017 check_auto_format(TRUE);
6019 /* If we just did an auto-indent, remove the white space from the end
6020 * of the line, and put the cursor back.
6021 * Do this when ESC was used or moving the cursor up/down. */
6022 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6023 && curwin->w_cursor.lnum != end_insert_pos->lnum)))
6025 pos_T tpos = curwin->w_cursor;
6027 curwin->w_cursor = *end_insert_pos;
6028 for (;;)
6030 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6031 --curwin->w_cursor.col;
6032 cc = gchar_cursor();
6033 if (!vim_iswhite(cc))
6034 break;
6035 (void)del_char(TRUE);
6037 if (curwin->w_cursor.lnum != tpos.lnum)
6038 curwin->w_cursor = tpos;
6039 else if (cc != NUL)
6040 ++curwin->w_cursor.col; /* put cursor back on the NUL */
6042 #ifdef FEAT_VISUAL
6043 /* <C-S-Right> may have started Visual mode, adjust the position for
6044 * deleted characters. */
6045 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6047 cc = (int)STRLEN(ml_get_curline());
6048 if (VIsual.col > (colnr_T)cc)
6050 VIsual.col = cc;
6051 # ifdef FEAT_VIRTUALEDIT
6052 VIsual.coladd = 0;
6053 # endif
6056 #endif
6059 did_ai = FALSE;
6060 #ifdef FEAT_SMARTINDENT
6061 did_si = FALSE;
6062 can_si = FALSE;
6063 can_si_back = FALSE;
6064 #endif
6066 /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are
6067 * now in a different buffer. */
6068 if (end_insert_pos != NULL)
6070 curbuf->b_op_start = Insstart;
6071 curbuf->b_op_end = *end_insert_pos;
6076 * Set the last inserted text to a single character.
6077 * Used for the replace command.
6079 void
6080 set_last_insert(c)
6081 int c;
6083 char_u *s;
6085 vim_free(last_insert);
6086 #ifdef FEAT_MBYTE
6087 last_insert = alloc(MB_MAXBYTES * 3 + 5);
6088 #else
6089 last_insert = alloc(6);
6090 #endif
6091 if (last_insert != NULL)
6093 s = last_insert;
6094 /* Use the CTRL-V only when entering a special char */
6095 if (c < ' ' || c == DEL)
6096 *s++ = Ctrl_V;
6097 s = add_char2buf(c, s);
6098 *s++ = ESC;
6099 *s++ = NUL;
6100 last_insert_skip = 0;
6104 #if defined(EXITFREE) || defined(PROTO)
6105 void
6106 free_last_insert()
6108 vim_free(last_insert);
6109 last_insert = NULL;
6110 vim_free(compl_orig_text);
6111 compl_orig_text = NULL;
6113 #endif
6116 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
6117 * and CSI. Handle multi-byte characters.
6118 * Returns a pointer to after the added bytes.
6120 char_u *
6121 add_char2buf(c, s)
6122 int c;
6123 char_u *s;
6125 #ifdef FEAT_MBYTE
6126 char_u temp[MB_MAXBYTES];
6127 int i;
6128 int len;
6130 len = (*mb_char2bytes)(c, temp);
6131 for (i = 0; i < len; ++i)
6133 c = temp[i];
6134 #endif
6135 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6136 if (c == K_SPECIAL)
6138 *s++ = K_SPECIAL;
6139 *s++ = KS_SPECIAL;
6140 *s++ = KE_FILLER;
6142 #ifdef FEAT_GUI
6143 else if (c == CSI)
6145 *s++ = CSI;
6146 *s++ = KS_EXTRA;
6147 *s++ = (int)KE_CSI;
6149 #endif
6150 else
6151 *s++ = c;
6152 #ifdef FEAT_MBYTE
6154 #endif
6155 return s;
6159 * move cursor to start of line
6160 * if flags & BL_WHITE move to first non-white
6161 * if flags & BL_SOL move to first non-white if startofline is set,
6162 * otherwise keep "curswant" column
6163 * if flags & BL_FIX don't leave the cursor on a NUL.
6165 void
6166 beginline(flags)
6167 int flags;
6169 if ((flags & BL_SOL) && !p_sol)
6170 coladvance(curwin->w_curswant);
6171 else
6173 curwin->w_cursor.col = 0;
6174 #ifdef FEAT_VIRTUALEDIT
6175 curwin->w_cursor.coladd = 0;
6176 #endif
6178 if (flags & (BL_WHITE | BL_SOL))
6180 char_u *ptr;
6182 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6183 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6184 ++curwin->w_cursor.col;
6186 curwin->w_set_curswant = TRUE;
6191 * oneright oneleft cursor_down cursor_up
6193 * Move one char {right,left,down,up}.
6194 * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6195 * Return OK when successful, FAIL when we hit a line of file boundary.
6199 oneright()
6201 char_u *ptr;
6202 int l;
6204 #ifdef FEAT_VIRTUALEDIT
6205 if (virtual_active())
6207 pos_T prevpos = curwin->w_cursor;
6209 /* Adjust for multi-wide char (excluding TAB) */
6210 ptr = ml_get_cursor();
6211 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
6212 # ifdef FEAT_MBYTE
6213 (*mb_ptr2char)(ptr)
6214 # else
6215 *ptr
6216 # endif
6218 ? ptr2cells(ptr) : 1));
6219 curwin->w_set_curswant = TRUE;
6220 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
6221 return (prevpos.col != curwin->w_cursor.col
6222 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
6224 #endif
6226 ptr = ml_get_cursor();
6227 if (*ptr == NUL)
6228 return FAIL; /* already at the very end */
6230 #ifdef FEAT_MBYTE
6231 if (has_mbyte)
6232 l = (*mb_ptr2len)(ptr);
6233 else
6234 #endif
6235 l = 1;
6237 /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
6238 * contains "onemore". */
6239 if (ptr[l] == NUL
6240 #ifdef FEAT_VIRTUALEDIT
6241 && (ve_flags & VE_ONEMORE) == 0
6242 #endif
6244 return FAIL;
6245 curwin->w_cursor.col += l;
6247 curwin->w_set_curswant = TRUE;
6248 return OK;
6252 oneleft()
6254 #ifdef FEAT_VIRTUALEDIT
6255 if (virtual_active())
6257 int width;
6258 int v = getviscol();
6260 if (v == 0)
6261 return FAIL;
6263 # ifdef FEAT_LINEBREAK
6264 /* We might get stuck on 'showbreak', skip over it. */
6265 width = 1;
6266 for (;;)
6268 coladvance(v - width);
6269 /* getviscol() is slow, skip it when 'showbreak' is empty and
6270 * there are no multi-byte characters */
6271 if ((*p_sbr == NUL
6272 # ifdef FEAT_MBYTE
6273 && !has_mbyte
6274 # endif
6275 ) || getviscol() < v)
6276 break;
6277 ++width;
6279 # else
6280 coladvance(v - 1);
6281 # endif
6283 if (curwin->w_cursor.coladd == 1)
6285 char_u *ptr;
6287 /* Adjust for multi-wide char (not a TAB) */
6288 ptr = ml_get_cursor();
6289 if (*ptr != TAB && vim_isprintc(
6290 # ifdef FEAT_MBYTE
6291 (*mb_ptr2char)(ptr)
6292 # else
6293 *ptr
6294 # endif
6295 ) && ptr2cells(ptr) > 1)
6296 curwin->w_cursor.coladd = 0;
6299 curwin->w_set_curswant = TRUE;
6300 return OK;
6302 #endif
6304 if (curwin->w_cursor.col == 0)
6305 return FAIL;
6307 curwin->w_set_curswant = TRUE;
6308 --curwin->w_cursor.col;
6310 #ifdef FEAT_MBYTE
6311 /* if the character on the left of the current cursor is a multi-byte
6312 * character, move to its first byte */
6313 if (has_mbyte)
6314 mb_adjust_cursor();
6315 #endif
6316 return OK;
6320 cursor_up(n, upd_topline)
6321 long n;
6322 int upd_topline; /* When TRUE: update topline */
6324 linenr_T lnum;
6326 if (n > 0)
6328 lnum = curwin->w_cursor.lnum;
6329 /* This fails if the cursor is already in the first line or the count
6330 * is larger than the line number and '-' is in 'cpoptions' */
6331 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6332 return FAIL;
6333 if (n >= lnum)
6334 lnum = 1;
6335 else
6336 #ifdef FEAT_FOLDING
6337 if (hasAnyFolding(curwin))
6340 * Count each sequence of folded lines as one logical line.
6342 /* go to the the start of the current fold */
6343 (void)hasFolding(lnum, &lnum, NULL);
6345 while (n--)
6347 /* move up one line */
6348 --lnum;
6349 if (lnum <= 1)
6350 break;
6351 /* If we entered a fold, move to the beginning, unless in
6352 * Insert mode or when 'foldopen' contains "all": it will open
6353 * in a moment. */
6354 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
6355 (void)hasFolding(lnum, &lnum, NULL);
6357 if (lnum < 1)
6358 lnum = 1;
6360 else
6361 #endif
6362 lnum -= n;
6363 curwin->w_cursor.lnum = lnum;
6366 /* try to advance to the column we want to be at */
6367 coladvance(curwin->w_curswant);
6369 if (upd_topline)
6370 update_topline(); /* make sure curwin->w_topline is valid */
6372 return OK;
6376 * Cursor down a number of logical lines.
6379 cursor_down(n, upd_topline)
6380 long n;
6381 int upd_topline; /* When TRUE: update topline */
6383 linenr_T lnum;
6385 if (n > 0)
6387 lnum = curwin->w_cursor.lnum;
6388 #ifdef FEAT_FOLDING
6389 /* Move to last line of fold, will fail if it's the end-of-file. */
6390 (void)hasFolding(lnum, NULL, &lnum);
6391 #endif
6392 /* This fails if the cursor is already in the last line or would move
6393 * beyound the last line and '-' is in 'cpoptions' */
6394 if (lnum >= curbuf->b_ml.ml_line_count
6395 || (lnum + n > curbuf->b_ml.ml_line_count
6396 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6397 return FAIL;
6398 if (lnum + n >= curbuf->b_ml.ml_line_count)
6399 lnum = curbuf->b_ml.ml_line_count;
6400 else
6401 #ifdef FEAT_FOLDING
6402 if (hasAnyFolding(curwin))
6404 linenr_T last;
6406 /* count each sequence of folded lines as one logical line */
6407 while (n--)
6409 if (hasFolding(lnum, NULL, &last))
6410 lnum = last + 1;
6411 else
6412 ++lnum;
6413 if (lnum >= curbuf->b_ml.ml_line_count)
6414 break;
6416 if (lnum > curbuf->b_ml.ml_line_count)
6417 lnum = curbuf->b_ml.ml_line_count;
6419 else
6420 #endif
6421 lnum += n;
6422 curwin->w_cursor.lnum = lnum;
6425 /* try to advance to the column we want to be at */
6426 coladvance(curwin->w_curswant);
6428 if (upd_topline)
6429 update_topline(); /* make sure curwin->w_topline is valid */
6431 return OK;
6435 * Stuff the last inserted text in the read buffer.
6436 * Last_insert actually is a copy of the redo buffer, so we
6437 * first have to remove the command.
6440 stuff_inserted(c, count, no_esc)
6441 int c; /* Command character to be inserted */
6442 long count; /* Repeat this many times */
6443 int no_esc; /* Don't add an ESC at the end */
6445 char_u *esc_ptr;
6446 char_u *ptr;
6447 char_u *last_ptr;
6448 char_u last = NUL;
6450 ptr = get_last_insert();
6451 if (ptr == NULL)
6453 EMSG(_(e_noinstext));
6454 return FAIL;
6457 /* may want to stuff the command character, to start Insert mode */
6458 if (c != NUL)
6459 stuffcharReadbuff(c);
6460 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
6461 *esc_ptr = NUL; /* remove the ESC */
6463 /* when the last char is either "0" or "^" it will be quoted if no ESC
6464 * comes after it OR if it will inserted more than once and "ptr"
6465 * starts with ^D. -- Acevedo
6467 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
6468 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
6469 && (no_esc || (*ptr == Ctrl_D && count > 1)))
6471 last = *last_ptr;
6472 *last_ptr = NUL;
6477 stuffReadbuff(ptr);
6478 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
6479 if (last)
6480 stuffReadbuff((char_u *)(last == '0'
6481 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
6482 : IF_EB("\026^", CTRL_V_STR "^")));
6484 while (--count > 0);
6486 if (last)
6487 *last_ptr = last;
6489 if (esc_ptr != NULL)
6490 *esc_ptr = ESC; /* put the ESC back */
6492 /* may want to stuff a trailing ESC, to get out of Insert mode */
6493 if (!no_esc)
6494 stuffcharReadbuff(ESC);
6496 return OK;
6499 char_u *
6500 get_last_insert()
6502 if (last_insert == NULL)
6503 return NULL;
6504 return last_insert + last_insert_skip;
6508 * Get last inserted string, and remove trailing <Esc>.
6509 * Returns pointer to allocated memory (must be freed) or NULL.
6511 char_u *
6512 get_last_insert_save()
6514 char_u *s;
6515 int len;
6517 if (last_insert == NULL)
6518 return NULL;
6519 s = vim_strsave(last_insert + last_insert_skip);
6520 if (s != NULL)
6522 len = (int)STRLEN(s);
6523 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
6524 s[len - 1] = NUL;
6526 return s;
6530 * Check the word in front of the cursor for an abbreviation.
6531 * Called when the non-id character "c" has been entered.
6532 * When an abbreviation is recognized it is removed from the text and
6533 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
6535 static int
6536 echeck_abbr(c)
6537 int c;
6539 /* Don't check for abbreviation in paste mode, when disabled and just
6540 * after moving around with cursor keys. */
6541 if (p_paste || no_abbr || arrow_used)
6542 return FALSE;
6544 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
6545 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
6549 * replace-stack functions
6551 * When replacing characters, the replaced characters are remembered for each
6552 * new character. This is used to re-insert the old text when backspacing.
6554 * There is a NUL headed list of characters for each character that is
6555 * currently in the file after the insertion point. When BS is used, one NUL
6556 * headed list is put back for the deleted character.
6558 * For a newline, there are two NUL headed lists. One contains the characters
6559 * that the NL replaced. The extra one stores the characters after the cursor
6560 * that were deleted (always white space).
6562 * Replace_offset is normally 0, in which case replace_push will add a new
6563 * character at the end of the stack. If replace_offset is not 0, that many
6564 * characters will be left on the stack above the newly inserted character.
6567 static char_u *replace_stack = NULL;
6568 static long replace_stack_nr = 0; /* next entry in replace stack */
6569 static long replace_stack_len = 0; /* max. number of entries */
6571 void
6572 replace_push(c)
6573 int c; /* character that is replaced (NUL is none) */
6575 char_u *p;
6577 if (replace_stack_nr < replace_offset) /* nothing to do */
6578 return;
6579 if (replace_stack_len <= replace_stack_nr)
6581 replace_stack_len += 50;
6582 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
6583 if (p == NULL) /* out of memory */
6585 replace_stack_len -= 50;
6586 return;
6588 if (replace_stack != NULL)
6590 mch_memmove(p, replace_stack,
6591 (size_t)(replace_stack_nr * sizeof(char_u)));
6592 vim_free(replace_stack);
6594 replace_stack = p;
6596 p = replace_stack + replace_stack_nr - replace_offset;
6597 if (replace_offset)
6598 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
6599 *p = c;
6600 ++replace_stack_nr;
6603 #if 0
6605 * call replace_push(c) with replace_offset set to the first NUL.
6607 static void
6608 replace_push_off(c)
6609 int c;
6611 char_u *p;
6613 p = replace_stack + replace_stack_nr;
6614 for (replace_offset = 1; replace_offset < replace_stack_nr;
6615 ++replace_offset)
6616 if (*--p == NUL)
6617 break;
6618 replace_push(c);
6619 replace_offset = 0;
6621 #endif
6624 * Pop one item from the replace stack.
6625 * return -1 if stack empty
6626 * return replaced character or NUL otherwise
6628 static int
6629 replace_pop()
6631 if (replace_stack_nr == 0)
6632 return -1;
6633 return (int)replace_stack[--replace_stack_nr];
6637 * Join the top two items on the replace stack. This removes to "off"'th NUL
6638 * encountered.
6640 static void
6641 replace_join(off)
6642 int off; /* offset for which NUL to remove */
6644 int i;
6646 for (i = replace_stack_nr; --i >= 0; )
6647 if (replace_stack[i] == NUL && off-- <= 0)
6649 --replace_stack_nr;
6650 mch_memmove(replace_stack + i, replace_stack + i + 1,
6651 (size_t)(replace_stack_nr - i));
6652 return;
6657 * Pop bytes from the replace stack until a NUL is found, and insert them
6658 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
6660 static void
6661 replace_pop_ins()
6663 int cc;
6664 int oldState = State;
6666 State = NORMAL; /* don't want REPLACE here */
6667 while ((cc = replace_pop()) > 0)
6669 #ifdef FEAT_MBYTE
6670 mb_replace_pop_ins(cc);
6671 #else
6672 ins_char(cc);
6673 #endif
6674 dec_cursor();
6676 State = oldState;
6679 #ifdef FEAT_MBYTE
6681 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
6682 * indicates a multi-byte char, pop the other bytes too.
6684 static void
6685 mb_replace_pop_ins(cc)
6686 int cc;
6688 int n;
6689 char_u buf[MB_MAXBYTES];
6690 int i;
6691 int c;
6693 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
6695 buf[0] = cc;
6696 for (i = 1; i < n; ++i)
6697 buf[i] = replace_pop();
6698 ins_bytes_len(buf, n);
6700 else
6701 ins_char(cc);
6703 if (enc_utf8)
6704 /* Handle composing chars. */
6705 for (;;)
6707 c = replace_pop();
6708 if (c == -1) /* stack empty */
6709 break;
6710 if ((n = MB_BYTE2LEN(c)) == 1)
6712 /* Not a multi-byte char, put it back. */
6713 replace_push(c);
6714 break;
6716 else
6718 buf[0] = c;
6719 for (i = 1; i < n; ++i)
6720 buf[i] = replace_pop();
6721 if (utf_iscomposing(utf_ptr2char(buf)))
6722 ins_bytes_len(buf, n);
6723 else
6725 /* Not a composing char, put it back. */
6726 for (i = n - 1; i >= 0; --i)
6727 replace_push(buf[i]);
6728 break;
6733 #endif
6736 * make the replace stack empty
6737 * (called when exiting replace mode)
6739 static void
6740 replace_flush()
6742 vim_free(replace_stack);
6743 replace_stack = NULL;
6744 replace_stack_len = 0;
6745 replace_stack_nr = 0;
6749 * Handle doing a BS for one character.
6750 * cc < 0: replace stack empty, just move cursor
6751 * cc == 0: character was inserted, delete it
6752 * cc > 0: character was replaced, put cc (first byte of original char) back
6753 * and check for more characters to be put back
6755 static void
6756 replace_do_bs()
6758 int cc;
6759 #ifdef FEAT_VREPLACE
6760 int orig_len = 0;
6761 int ins_len;
6762 int orig_vcols = 0;
6763 colnr_T start_vcol;
6764 char_u *p;
6765 int i;
6766 int vcol;
6767 #endif
6769 cc = replace_pop();
6770 if (cc > 0)
6772 #ifdef FEAT_VREPLACE
6773 if (State & VREPLACE_FLAG)
6775 /* Get the number of screen cells used by the character we are
6776 * going to delete. */
6777 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
6778 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
6780 #endif
6781 #ifdef FEAT_MBYTE
6782 if (has_mbyte)
6784 del_char(FALSE);
6785 # ifdef FEAT_VREPLACE
6786 if (State & VREPLACE_FLAG)
6787 orig_len = (int)STRLEN(ml_get_cursor());
6788 # endif
6789 replace_push(cc);
6791 else
6792 #endif
6794 pchar_cursor(cc);
6795 #ifdef FEAT_VREPLACE
6796 if (State & VREPLACE_FLAG)
6797 orig_len = (int)STRLEN(ml_get_cursor()) - 1;
6798 #endif
6800 replace_pop_ins();
6802 #ifdef FEAT_VREPLACE
6803 if (State & VREPLACE_FLAG)
6805 /* Get the number of screen cells used by the inserted characters */
6806 p = ml_get_cursor();
6807 ins_len = (int)STRLEN(p) - orig_len;
6808 vcol = start_vcol;
6809 for (i = 0; i < ins_len; ++i)
6811 vcol += chartabsize(p + i, vcol);
6812 #ifdef FEAT_MBYTE
6813 i += (*mb_ptr2len)(p) - 1;
6814 #endif
6816 vcol -= start_vcol;
6818 /* Delete spaces that were inserted after the cursor to keep the
6819 * text aligned. */
6820 curwin->w_cursor.col += ins_len;
6821 while (vcol > orig_vcols && gchar_cursor() == ' ')
6823 del_char(FALSE);
6824 ++orig_vcols;
6826 curwin->w_cursor.col -= ins_len;
6828 #endif
6830 /* mark the buffer as changed and prepare for displaying */
6831 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
6833 else if (cc == 0)
6834 (void)del_char(FALSE);
6837 #ifdef FEAT_CINDENT
6839 * Return TRUE if C-indenting is on.
6841 static int
6842 cindent_on()
6844 return (!p_paste && (curbuf->b_p_cin
6845 # ifdef FEAT_EVAL
6846 || *curbuf->b_p_inde != NUL
6847 # endif
6850 #endif
6852 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
6854 * Re-indent the current line, based on the current contents of it and the
6855 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
6856 * confused what all the part that handles Control-T is doing that I'm not.
6857 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
6860 void
6861 fixthisline(get_the_indent)
6862 int (*get_the_indent) __ARGS((void));
6864 change_indent(INDENT_SET, get_the_indent(), FALSE, 0);
6865 if (linewhite(curwin->w_cursor.lnum))
6866 did_ai = TRUE; /* delete the indent if the line stays empty */
6869 void
6870 fix_indent()
6872 if (p_paste)
6873 return;
6874 # ifdef FEAT_LISP
6875 if (curbuf->b_p_lisp && curbuf->b_p_ai)
6876 fixthisline(get_lisp_indent);
6877 # endif
6878 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
6879 else
6880 # endif
6881 # ifdef FEAT_CINDENT
6882 if (cindent_on())
6883 do_c_expr_indent();
6884 # endif
6887 #endif
6889 #ifdef FEAT_CINDENT
6891 * return TRUE if 'cinkeys' contains the key "keytyped",
6892 * when == '*': Only if key is preceded with '*' (indent before insert)
6893 * when == '!': Only if key is prededed with '!' (don't insert)
6894 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
6896 * "keytyped" can have a few special values:
6897 * KEY_OPEN_FORW
6898 * KEY_OPEN_BACK
6899 * KEY_COMPLETE just finished completion.
6901 * If line_is_empty is TRUE accept keys with '0' before them.
6904 in_cinkeys(keytyped, when, line_is_empty)
6905 int keytyped;
6906 int when;
6907 int line_is_empty;
6909 char_u *look;
6910 int try_match;
6911 int try_match_word;
6912 char_u *p;
6913 char_u *line;
6914 int icase;
6915 int i;
6917 #ifdef FEAT_EVAL
6918 if (*curbuf->b_p_inde != NUL)
6919 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
6920 else
6921 #endif
6922 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
6923 while (*look)
6926 * Find out if we want to try a match with this key, depending on
6927 * 'when' and a '*' or '!' before the key.
6929 switch (when)
6931 case '*': try_match = (*look == '*'); break;
6932 case '!': try_match = (*look == '!'); break;
6933 default: try_match = (*look != '*'); break;
6935 if (*look == '*' || *look == '!')
6936 ++look;
6939 * If there is a '0', only accept a match if the line is empty.
6940 * But may still match when typing last char of a word.
6942 if (*look == '0')
6944 try_match_word = try_match;
6945 if (!line_is_empty)
6946 try_match = FALSE;
6947 ++look;
6949 else
6950 try_match_word = FALSE;
6953 * does it look like a control character?
6955 if (*look == '^'
6956 #ifdef EBCDIC
6957 && (Ctrl_chr(look[1]) != 0)
6958 #else
6959 && look[1] >= '?' && look[1] <= '_'
6960 #endif
6963 if (try_match && keytyped == Ctrl_chr(look[1]))
6964 return TRUE;
6965 look += 2;
6968 * 'o' means "o" command, open forward.
6969 * 'O' means "O" command, open backward.
6971 else if (*look == 'o')
6973 if (try_match && keytyped == KEY_OPEN_FORW)
6974 return TRUE;
6975 ++look;
6977 else if (*look == 'O')
6979 if (try_match && keytyped == KEY_OPEN_BACK)
6980 return TRUE;
6981 ++look;
6985 * 'e' means to check for "else" at start of line and just before the
6986 * cursor.
6988 else if (*look == 'e')
6990 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
6992 p = ml_get_curline();
6993 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
6994 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
6995 return TRUE;
6997 ++look;
7001 * ':' only causes an indent if it is at the end of a label or case
7002 * statement, or when it was before typing the ':' (to fix
7003 * class::method for C++).
7005 else if (*look == ':')
7007 if (try_match && keytyped == ':')
7009 p = ml_get_curline();
7010 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
7011 return TRUE;
7012 if (curwin->w_cursor.col > 2
7013 && p[curwin->w_cursor.col - 1] == ':'
7014 && p[curwin->w_cursor.col - 2] == ':')
7016 p[curwin->w_cursor.col - 1] = ' ';
7017 i = (cin_iscase(p) || cin_isscopedecl(p)
7018 || cin_islabel(30));
7019 p = ml_get_curline();
7020 p[curwin->w_cursor.col - 1] = ':';
7021 if (i)
7022 return TRUE;
7025 ++look;
7030 * Is it a key in <>, maybe?
7032 else if (*look == '<')
7034 if (try_match)
7037 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7038 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7039 * >, *, : and ! keys if they really really want to.
7041 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7042 && keytyped == look[1])
7043 return TRUE;
7045 if (keytyped == get_special_key_code(look + 1))
7046 return TRUE;
7048 while (*look && *look != '>')
7049 look++;
7050 while (*look == '>')
7051 look++;
7055 * Is it a word: "=word"?
7057 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7059 ++look;
7060 if (*look == '~')
7062 icase = TRUE;
7063 ++look;
7065 else
7066 icase = FALSE;
7067 p = vim_strchr(look, ',');
7068 if (p == NULL)
7069 p = look + STRLEN(look);
7070 if ((try_match || try_match_word)
7071 && curwin->w_cursor.col >= (colnr_T)(p - look))
7073 int match = FALSE;
7075 #ifdef FEAT_INS_EXPAND
7076 if (keytyped == KEY_COMPLETE)
7078 char_u *s;
7080 /* Just completed a word, check if it starts with "look".
7081 * search back for the start of a word. */
7082 line = ml_get_curline();
7083 # ifdef FEAT_MBYTE
7084 if (has_mbyte)
7086 char_u *n;
7088 for (s = line + curwin->w_cursor.col; s > line; s = n)
7090 n = mb_prevptr(line, s);
7091 if (!vim_iswordp(n))
7092 break;
7095 else
7096 # endif
7097 for (s = line + curwin->w_cursor.col; s > line; --s)
7098 if (!vim_iswordc(s[-1]))
7099 break;
7100 if (s + (p - look) <= line + curwin->w_cursor.col
7101 && (icase
7102 ? MB_STRNICMP(s, look, p - look)
7103 : STRNCMP(s, look, p - look)) == 0)
7104 match = TRUE;
7106 else
7107 #endif
7108 /* TODO: multi-byte */
7109 if (keytyped == (int)p[-1] || (icase && keytyped < 256
7110 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7112 line = ml_get_cursor();
7113 if ((curwin->w_cursor.col == (colnr_T)(p - look)
7114 || !vim_iswordc(line[-(p - look) - 1]))
7115 && (icase
7116 ? MB_STRNICMP(line - (p - look), look, p - look)
7117 : STRNCMP(line - (p - look), look, p - look))
7118 == 0)
7119 match = TRUE;
7121 if (match && try_match_word && !try_match)
7123 /* "0=word": Check if there are only blanks before the
7124 * word. */
7125 line = ml_get_curline();
7126 if ((int)(skipwhite(line) - line) !=
7127 (int)(curwin->w_cursor.col - (p - look)))
7128 match = FALSE;
7130 if (match)
7131 return TRUE;
7133 look = p;
7137 * ok, it's a boring generic character.
7139 else
7141 if (try_match && *look == keytyped)
7142 return TRUE;
7143 ++look;
7147 * Skip over ", ".
7149 look = skip_to_option_part(look);
7151 return FALSE;
7153 #endif /* FEAT_CINDENT */
7155 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7157 * Map Hebrew keyboard when in hkmap mode.
7160 hkmap(c)
7161 int c;
7163 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
7165 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7166 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7167 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7168 static char_u map[26] =
7169 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
7170 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
7171 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
7172 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
7173 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
7174 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
7175 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
7176 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
7177 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
7179 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7180 return (int)(map[CharOrd(c)] - 1 + p_aleph);
7181 /* '-1'='sofit' */
7182 else if (c == 'x')
7183 return 'X';
7184 else if (c == 'q')
7185 return '\''; /* {geresh}={'} */
7186 else if (c == 246)
7187 return ' '; /* \"o --> ' ' for a german keyboard */
7188 else if (c == 228)
7189 return ' '; /* \"a --> ' ' -- / -- */
7190 else if (c == 252)
7191 return ' '; /* \"u --> ' ' -- / -- */
7192 #ifdef EBCDIC
7193 else if (islower(c))
7194 #else
7195 /* NOTE: islower() does not do the right thing for us on Linux so we
7196 * do this the same was as 5.7 and previous, so it works correctly on
7197 * all systems. Specifically, the e.g. Delete and Arrow keys are
7198 * munged and won't work if e.g. searching for Hebrew text.
7200 else if (c >= 'a' && c <= 'z')
7201 #endif
7202 return (int)(map[CharOrdLow(c)] + p_aleph);
7203 else
7204 return c;
7206 else
7208 switch (c)
7210 case '`': return ';';
7211 case '/': return '.';
7212 case '\'': return ',';
7213 case 'q': return '/';
7214 case 'w': return '\'';
7216 /* Hebrew letters - set offset from 'a' */
7217 case ',': c = '{'; break;
7218 case '.': c = 'v'; break;
7219 case ';': c = 't'; break;
7220 default: {
7221 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
7223 #ifdef EBCDIC
7224 /* see note about islower() above */
7225 if (!islower(c))
7226 #else
7227 if (c < 'a' || c > 'z')
7228 #endif
7229 return c;
7230 c = str[CharOrdLow(c)];
7231 break;
7235 return (int)(CharOrdLow(c) + p_aleph);
7238 #endif
7240 static void
7241 ins_reg()
7243 int need_redraw = FALSE;
7244 int regname;
7245 int literally = 0;
7248 * If we are going to wait for a character, show a '"'.
7250 pc_status = PC_STATUS_UNSET;
7251 if (redrawing() && !char_avail())
7253 /* may need to redraw when no more chars available now */
7254 ins_redraw(FALSE);
7256 edit_putchar('"', TRUE);
7257 #ifdef FEAT_CMDL_INFO
7258 add_to_showcmd_c(Ctrl_R);
7259 #endif
7262 #ifdef USE_ON_FLY_SCROLL
7263 dont_scroll = TRUE; /* disallow scrolling here */
7264 #endif
7267 * Don't map the register name. This also prevents the mode message to be
7268 * deleted when ESC is hit.
7270 ++no_mapping;
7271 regname = safe_vgetc();
7272 #ifdef FEAT_LANGMAP
7273 LANGMAP_ADJUST(regname, TRUE);
7274 #endif
7275 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
7277 /* Get a third key for literal register insertion */
7278 literally = regname;
7279 #ifdef FEAT_CMDL_INFO
7280 add_to_showcmd_c(literally);
7281 #endif
7282 regname = safe_vgetc();
7283 #ifdef FEAT_LANGMAP
7284 LANGMAP_ADJUST(regname, TRUE);
7285 #endif
7287 --no_mapping;
7289 #ifdef FEAT_EVAL
7291 * Don't call u_sync() while getting the expression,
7292 * evaluating it or giving an error message for it!
7294 ++no_u_sync;
7295 if (regname == '=')
7297 # ifdef USE_IM_CONTROL
7298 int im_on = im_get_status();
7299 # endif
7300 regname = get_expr_register();
7301 # ifdef USE_IM_CONTROL
7302 /* Restore the Input Method. */
7303 if (im_on)
7304 im_set_active(TRUE);
7305 # endif
7307 if (regname == NUL || !valid_yank_reg(regname, FALSE))
7309 vim_beep();
7310 need_redraw = TRUE; /* remove the '"' */
7312 else
7314 #endif
7315 if (literally == Ctrl_O || literally == Ctrl_P)
7317 /* Append the command to the redo buffer. */
7318 AppendCharToRedobuff(Ctrl_R);
7319 AppendCharToRedobuff(literally);
7320 AppendCharToRedobuff(regname);
7322 do_put(regname, BACKWARD, 1L,
7323 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
7325 else if (insert_reg(regname, literally) == FAIL)
7327 vim_beep();
7328 need_redraw = TRUE; /* remove the '"' */
7330 else if (stop_insert_mode)
7331 /* When the '=' register was used and a function was invoked that
7332 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
7333 * insert anything, need to remove the '"' */
7334 need_redraw = TRUE;
7336 #ifdef FEAT_EVAL
7338 --no_u_sync;
7339 #endif
7340 #ifdef FEAT_CMDL_INFO
7341 clear_showcmd();
7342 #endif
7344 /* If the inserted register is empty, we need to remove the '"' */
7345 if (need_redraw || stuff_empty())
7346 edit_unputchar();
7350 * CTRL-G commands in Insert mode.
7352 static void
7353 ins_ctrl_g()
7355 int c;
7357 #ifdef FEAT_INS_EXPAND
7358 /* Right after CTRL-X the cursor will be after the ruler. */
7359 setcursor();
7360 #endif
7363 * Don't map the second key. This also prevents the mode message to be
7364 * deleted when ESC is hit.
7366 ++no_mapping;
7367 c = safe_vgetc();
7368 --no_mapping;
7369 switch (c)
7371 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
7372 case K_UP:
7373 case Ctrl_K:
7374 case 'k': ins_up(TRUE);
7375 break;
7377 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
7378 case K_DOWN:
7379 case Ctrl_J:
7380 case 'j': ins_down(TRUE);
7381 break;
7383 /* CTRL-G u: start new undoable edit */
7384 case 'u': u_sync(TRUE);
7385 ins_need_undo = TRUE;
7387 /* Need to reset Insstart, esp. because a BS that joins
7388 * aline to the previous one must save for undo. */
7389 Insstart = curwin->w_cursor;
7390 break;
7392 /* Unknown CTRL-G command, reserved for future expansion. */
7393 default: vim_beep();
7398 * CTRL-^ in Insert mode.
7400 static void
7401 ins_ctrl_hat()
7403 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
7405 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
7406 if (State & LANGMAP)
7408 curbuf->b_p_iminsert = B_IMODE_NONE;
7409 State &= ~LANGMAP;
7411 else
7413 curbuf->b_p_iminsert = B_IMODE_LMAP;
7414 State |= LANGMAP;
7415 #ifdef USE_IM_CONTROL
7416 im_set_active(FALSE);
7417 #endif
7420 #ifdef USE_IM_CONTROL
7421 else
7423 /* There are no ":lmap" mappings, toggle IM */
7424 if (im_get_status())
7426 curbuf->b_p_iminsert = B_IMODE_NONE;
7427 im_set_active(FALSE);
7429 else
7431 curbuf->b_p_iminsert = B_IMODE_IM;
7432 State &= ~LANGMAP;
7433 im_set_active(TRUE);
7436 #endif
7437 set_iminsert_global();
7438 showmode();
7439 #ifdef FEAT_GUI
7440 /* may show different cursor shape or color */
7441 if (gui.in_use)
7442 gui_update_cursor(TRUE, FALSE);
7443 #endif
7444 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
7445 /* Show/unshow value of 'keymap' in status lines. */
7446 status_redraw_curbuf();
7447 #endif
7451 * Handle ESC in insert mode.
7452 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
7453 * insert.
7455 static int
7456 ins_esc(count, cmdchar, nomove)
7457 long *count;
7458 int cmdchar;
7459 int nomove; /* don't move cursor */
7461 int temp;
7462 static int disabled_redraw = FALSE;
7464 #ifdef FEAT_SPELL
7465 check_spell_redraw();
7466 #endif
7467 #if defined(FEAT_HANGULIN)
7468 # if defined(ESC_CHG_TO_ENG_MODE)
7469 hangul_input_state_set(0);
7470 # endif
7471 if (composing_hangul)
7473 push_raw_key(composing_hangul_buffer, 2);
7474 composing_hangul = 0;
7476 #endif
7478 temp = curwin->w_cursor.col;
7479 if (disabled_redraw)
7481 --RedrawingDisabled;
7482 disabled_redraw = FALSE;
7484 if (!arrow_used)
7487 * Don't append the ESC for "r<CR>" and "grx".
7488 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
7489 * when "count" is non-zero.
7491 if (cmdchar != 'r' && cmdchar != 'v')
7492 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
7495 * Repeating insert may take a long time. Check for
7496 * interrupt now and then.
7498 if (*count > 0)
7500 line_breakcheck();
7501 if (got_int)
7502 *count = 0;
7505 if (--*count > 0) /* repeat what was typed */
7507 /* Vi repeats the insert without replacing characters. */
7508 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
7509 State &= ~REPLACE_FLAG;
7511 (void)start_redo_ins();
7512 if (cmdchar == 'r' || cmdchar == 'v')
7513 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
7514 ++RedrawingDisabled;
7515 disabled_redraw = TRUE;
7516 return FALSE; /* repeat the insert */
7518 stop_insert(&curwin->w_cursor, TRUE);
7519 undisplay_dollar();
7522 /* When an autoindent was removed, curswant stays after the
7523 * indent */
7524 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
7525 curwin->w_set_curswant = TRUE;
7527 /* Remember the last Insert position in the '^ mark. */
7528 if (!cmdmod.keepjumps)
7529 curbuf->b_last_insert = curwin->w_cursor;
7532 * The cursor should end up on the last inserted character.
7533 * Don't do it for CTRL-O, unless past the end of the line.
7535 if (!nomove
7536 && (curwin->w_cursor.col != 0
7537 #ifdef FEAT_VIRTUALEDIT
7538 || curwin->w_cursor.coladd > 0
7539 #endif
7541 && (restart_edit == NUL
7542 || (gchar_cursor() == NUL
7543 #ifdef FEAT_VISUAL
7544 && !VIsual_active
7545 #endif
7547 #ifdef FEAT_RIGHTLEFT
7548 && !revins_on
7549 #endif
7552 #ifdef FEAT_VIRTUALEDIT
7553 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
7555 oneleft();
7556 if (restart_edit != NUL)
7557 ++curwin->w_cursor.coladd;
7559 else
7560 #endif
7562 --curwin->w_cursor.col;
7563 #ifdef FEAT_MBYTE
7564 /* Correct cursor for multi-byte character. */
7565 if (has_mbyte)
7566 mb_adjust_cursor();
7567 #endif
7571 #ifdef USE_IM_CONTROL
7572 /* Disable IM to allow typing English directly for Normal mode commands.
7573 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
7574 * well). */
7575 if (!(State & LANGMAP))
7576 im_save_status(&curbuf->b_p_iminsert);
7577 im_set_active(FALSE);
7578 #endif
7580 State = NORMAL;
7581 /* need to position cursor again (e.g. when on a TAB ) */
7582 changed_cline_bef_curs();
7584 #ifdef FEAT_MOUSE
7585 setmouse();
7586 #endif
7587 #ifdef CURSOR_SHAPE
7588 ui_cursor_shape(); /* may show different cursor shape */
7589 #endif
7592 * When recording or for CTRL-O, need to display the new mode.
7593 * Otherwise remove the mode message.
7595 if (Recording || restart_edit != NUL)
7596 showmode();
7597 else if (p_smd)
7598 MSG("");
7600 return TRUE; /* exit Insert mode */
7603 #ifdef FEAT_RIGHTLEFT
7605 * Toggle language: hkmap and revins_on.
7606 * Move to end of reverse inserted text.
7608 static void
7609 ins_ctrl_()
7611 if (revins_on && revins_chars && revins_scol >= 0)
7613 while (gchar_cursor() != NUL && revins_chars--)
7614 ++curwin->w_cursor.col;
7616 p_ri = !p_ri;
7617 revins_on = (State == INSERT && p_ri);
7618 if (revins_on)
7620 revins_scol = curwin->w_cursor.col;
7621 revins_legal++;
7622 revins_chars = 0;
7623 undisplay_dollar();
7625 else
7626 revins_scol = -1;
7627 #ifdef FEAT_FKMAP
7628 if (p_altkeymap)
7631 * to be consistent also for redo command, using '.'
7632 * set arrow_used to true and stop it - causing to redo
7633 * characters entered in one mode (normal/reverse insert).
7635 arrow_used = TRUE;
7636 (void)stop_arrow();
7637 p_fkmap = curwin->w_p_rl ^ p_ri;
7638 if (p_fkmap && p_ri)
7639 State = INSERT;
7641 else
7642 #endif
7643 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
7644 showmode();
7646 #endif
7648 #ifdef FEAT_VISUAL
7650 * If 'keymodel' contains "startsel", may start selection.
7651 * Returns TRUE when a CTRL-O and other keys stuffed.
7653 static int
7654 ins_start_select(c)
7655 int c;
7657 if (km_startsel)
7658 switch (c)
7660 case K_KHOME:
7661 case K_KEND:
7662 case K_PAGEUP:
7663 case K_KPAGEUP:
7664 case K_PAGEDOWN:
7665 case K_KPAGEDOWN:
7666 # ifdef MACOS
7667 case K_LEFT:
7668 case K_RIGHT:
7669 case K_UP:
7670 case K_DOWN:
7671 case K_END:
7672 case K_HOME:
7673 # endif
7674 if (!(mod_mask & MOD_MASK_SHIFT))
7675 break;
7676 /* FALLTHROUGH */
7677 case K_S_LEFT:
7678 case K_S_RIGHT:
7679 case K_S_UP:
7680 case K_S_DOWN:
7681 case K_S_END:
7682 case K_S_HOME:
7683 /* Start selection right away, the cursor can move with
7684 * CTRL-O when beyond the end of the line. */
7685 start_selection();
7687 /* Execute the key in (insert) Select mode. */
7688 stuffcharReadbuff(Ctrl_O);
7689 if (mod_mask)
7691 char_u buf[4];
7693 buf[0] = K_SPECIAL;
7694 buf[1] = KS_MODIFIER;
7695 buf[2] = mod_mask;
7696 buf[3] = NUL;
7697 stuffReadbuff(buf);
7699 stuffcharReadbuff(c);
7700 return TRUE;
7702 return FALSE;
7704 #endif
7707 * <Insert> key in Insert mode: toggle insert/remplace mode.
7709 static void
7710 ins_insert(replaceState)
7711 int replaceState;
7713 #ifdef FEAT_FKMAP
7714 if (p_fkmap && p_ri)
7716 beep_flush();
7717 EMSG(farsi_text_3); /* encoded in Farsi */
7718 return;
7720 #endif
7722 #ifdef FEAT_AUTOCMD
7723 # ifdef FEAT_EVAL
7724 set_vim_var_string(VV_INSERTMODE,
7725 (char_u *)((State & REPLACE_FLAG) ? "i" :
7726 # ifdef FEAT_VREPLACE
7727 replaceState == VREPLACE ? "v" :
7728 # endif
7729 "r"), 1);
7730 # endif
7731 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
7732 #endif
7733 if (State & REPLACE_FLAG)
7734 State = INSERT | (State & LANGMAP);
7735 else
7736 State = replaceState | (State & LANGMAP);
7737 AppendCharToRedobuff(K_INS);
7738 showmode();
7739 #ifdef CURSOR_SHAPE
7740 ui_cursor_shape(); /* may show different cursor shape */
7741 #endif
7745 * Pressed CTRL-O in Insert mode.
7747 static void
7748 ins_ctrl_o()
7750 #ifdef FEAT_VREPLACE
7751 if (State & VREPLACE_FLAG)
7752 restart_edit = 'V';
7753 else
7754 #endif
7755 if (State & REPLACE_FLAG)
7756 restart_edit = 'R';
7757 else
7758 restart_edit = 'I';
7759 #ifdef FEAT_VIRTUALEDIT
7760 if (virtual_active())
7761 ins_at_eol = FALSE; /* cursor always keeps its column */
7762 else
7763 #endif
7764 ins_at_eol = (gchar_cursor() == NUL);
7768 * If the cursor is on an indent, ^T/^D insert/delete one
7769 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
7770 * Always round the indent to 'shiftwith', this is compatible
7771 * with vi. But vi only supports ^T and ^D after an
7772 * autoindent, we support it everywhere.
7774 static void
7775 ins_shift(c, lastc)
7776 int c;
7777 int lastc;
7779 if (stop_arrow() == FAIL)
7780 return;
7781 AppendCharToRedobuff(c);
7784 * 0^D and ^^D: remove all indent.
7786 if ((lastc == '0' || lastc == '^') && curwin->w_cursor.col)
7788 --curwin->w_cursor.col;
7789 (void)del_char(FALSE); /* delete the '^' or '0' */
7790 /* In Replace mode, restore the characters that '^' or '0' replaced. */
7791 if (State & REPLACE_FLAG)
7792 replace_pop_ins();
7793 if (lastc == '^')
7794 old_indent = get_indent(); /* remember curr. indent */
7795 change_indent(INDENT_SET, 0, TRUE, 0);
7797 else
7798 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0);
7800 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
7801 did_ai = FALSE;
7802 #ifdef FEAT_SMARTINDENT
7803 did_si = FALSE;
7804 can_si = FALSE;
7805 can_si_back = FALSE;
7806 #endif
7807 #ifdef FEAT_CINDENT
7808 can_cindent = FALSE; /* no cindenting after ^D or ^T */
7809 #endif
7812 static void
7813 ins_del()
7815 int temp;
7817 if (stop_arrow() == FAIL)
7818 return;
7819 if (gchar_cursor() == NUL) /* delete newline */
7821 temp = curwin->w_cursor.col;
7822 if (!can_bs(BS_EOL) /* only if "eol" included */
7823 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
7824 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
7825 || do_join(FALSE) == FAIL)
7826 vim_beep();
7827 else
7828 curwin->w_cursor.col = temp;
7830 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
7831 vim_beep();
7832 did_ai = FALSE;
7833 #ifdef FEAT_SMARTINDENT
7834 did_si = FALSE;
7835 can_si = FALSE;
7836 can_si_back = FALSE;
7837 #endif
7838 AppendCharToRedobuff(K_DEL);
7842 * Handle Backspace, delete-word and delete-line in Insert mode.
7843 * Return TRUE when backspace was actually used.
7845 static int
7846 ins_bs(c, mode, inserted_space_p)
7847 int c;
7848 int mode;
7849 int *inserted_space_p;
7851 linenr_T lnum;
7852 int cc;
7853 int temp = 0; /* init for GCC */
7854 colnr_T mincol;
7855 int did_backspace = FALSE;
7856 int in_indent;
7857 int oldState;
7858 #ifdef FEAT_MBYTE
7859 int cpc[MAX_MCO]; /* composing characters */
7860 #endif
7863 * can't delete anything in an empty file
7864 * can't backup past first character in buffer
7865 * can't backup past starting point unless 'backspace' > 1
7866 * can backup to a previous line if 'backspace' == 0
7868 if ( bufempty()
7869 || (
7870 #ifdef FEAT_RIGHTLEFT
7871 !revins_on &&
7872 #endif
7873 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
7874 || (!can_bs(BS_START)
7875 && (arrow_used
7876 || (curwin->w_cursor.lnum == Insstart.lnum
7877 && curwin->w_cursor.col <= Insstart.col)))
7878 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
7879 && curwin->w_cursor.col <= ai_col)
7880 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
7882 vim_beep();
7883 return FALSE;
7886 if (stop_arrow() == FAIL)
7887 return FALSE;
7888 in_indent = inindent(0);
7889 #ifdef FEAT_CINDENT
7890 if (in_indent)
7891 can_cindent = FALSE;
7892 #endif
7893 #ifdef FEAT_COMMENTS
7894 end_comment_pending = NUL; /* After BS, don't auto-end comment */
7895 #endif
7896 #ifdef FEAT_RIGHTLEFT
7897 if (revins_on) /* put cursor after last inserted char */
7898 inc_cursor();
7899 #endif
7901 #ifdef FEAT_VIRTUALEDIT
7902 /* Virtualedit:
7903 * BACKSPACE_CHAR eats a virtual space
7904 * BACKSPACE_WORD eats all coladd
7905 * BACKSPACE_LINE eats all coladd and keeps going
7907 if (curwin->w_cursor.coladd > 0)
7909 if (mode == BACKSPACE_CHAR)
7911 --curwin->w_cursor.coladd;
7912 return TRUE;
7914 if (mode == BACKSPACE_WORD)
7916 curwin->w_cursor.coladd = 0;
7917 return TRUE;
7919 curwin->w_cursor.coladd = 0;
7921 #endif
7924 * delete newline!
7926 if (curwin->w_cursor.col == 0)
7928 lnum = Insstart.lnum;
7929 if (curwin->w_cursor.lnum == Insstart.lnum
7930 #ifdef FEAT_RIGHTLEFT
7931 || revins_on
7932 #endif
7935 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
7936 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
7937 return FALSE;
7938 --Insstart.lnum;
7939 Insstart.col = MAXCOL;
7942 * In replace mode:
7943 * cc < 0: NL was inserted, delete it
7944 * cc >= 0: NL was replaced, put original characters back
7946 cc = -1;
7947 if (State & REPLACE_FLAG)
7948 cc = replace_pop(); /* returns -1 if NL was inserted */
7950 * In replace mode, in the line we started replacing, we only move the
7951 * cursor.
7953 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
7955 dec_cursor();
7957 else
7959 #ifdef FEAT_VREPLACE
7960 if (!(State & VREPLACE_FLAG)
7961 || curwin->w_cursor.lnum > orig_line_count)
7962 #endif
7964 temp = gchar_cursor(); /* remember current char */
7965 --curwin->w_cursor.lnum;
7967 /* When "aw" is in 'formatoptions' we must delete the space at
7968 * the end of the line, otherwise the line will be broken
7969 * again when auto-formatting. */
7970 if (has_format_option(FO_AUTO)
7971 && has_format_option(FO_WHITE_PAR))
7973 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
7974 TRUE);
7975 int len;
7977 len = (int)STRLEN(ptr);
7978 if (len > 0 && ptr[len - 1] == ' ')
7979 ptr[len - 1] = NUL;
7982 (void)do_join(FALSE);
7983 if (temp == NUL && gchar_cursor() != NUL)
7984 inc_cursor();
7986 #ifdef FEAT_VREPLACE
7987 else
7988 dec_cursor();
7989 #endif
7992 * In REPLACE mode we have to put back the text that was replaced
7993 * by the NL. On the replace stack is first a NUL-terminated
7994 * sequence of characters that were deleted and then the
7995 * characters that NL replaced.
7997 if (State & REPLACE_FLAG)
8000 * Do the next ins_char() in NORMAL state, to
8001 * prevent ins_char() from replacing characters and
8002 * avoiding showmatch().
8004 oldState = State;
8005 State = NORMAL;
8007 * restore characters (blanks) deleted after cursor
8009 while (cc > 0)
8011 temp = curwin->w_cursor.col;
8012 #ifdef FEAT_MBYTE
8013 mb_replace_pop_ins(cc);
8014 #else
8015 ins_char(cc);
8016 #endif
8017 curwin->w_cursor.col = temp;
8018 cc = replace_pop();
8020 /* restore the characters that NL replaced */
8021 replace_pop_ins();
8022 State = oldState;
8025 did_ai = FALSE;
8027 else
8030 * Delete character(s) before the cursor.
8032 #ifdef FEAT_RIGHTLEFT
8033 if (revins_on) /* put cursor on last inserted char */
8034 dec_cursor();
8035 #endif
8036 mincol = 0;
8037 /* keep indent */
8038 if (mode == BACKSPACE_LINE && curbuf->b_p_ai
8039 #ifdef FEAT_RIGHTLEFT
8040 && !revins_on
8041 #endif
8044 temp = curwin->w_cursor.col;
8045 beginline(BL_WHITE);
8046 if (curwin->w_cursor.col < (colnr_T)temp)
8047 mincol = curwin->w_cursor.col;
8048 curwin->w_cursor.col = temp;
8052 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8054 if ( mode == BACKSPACE_CHAR
8055 && ((p_sta && in_indent)
8056 || (curbuf->b_p_sts != 0
8057 && (*(ml_get_cursor() - 1) == TAB
8058 || (*(ml_get_cursor() - 1) == ' '
8059 && (!*inserted_space_p
8060 || arrow_used))))))
8062 int ts;
8063 colnr_T vcol;
8064 colnr_T want_vcol;
8065 #if 0
8066 int extra = 0;
8067 #endif
8069 *inserted_space_p = FALSE;
8070 if (p_sta && in_indent)
8071 ts = curbuf->b_p_sw;
8072 else
8073 ts = curbuf->b_p_sts;
8074 /* Compute the virtual column where we want to be. Since
8075 * 'showbreak' may get in the way, need to get the last column of
8076 * the previous character. */
8077 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8078 dec_cursor();
8079 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8080 inc_cursor();
8081 want_vcol = (want_vcol / ts) * ts;
8083 /* delete characters until we are at or before want_vcol */
8084 while (vcol > want_vcol
8085 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8087 dec_cursor();
8088 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8089 if (State & REPLACE_FLAG)
8091 /* Don't delete characters before the insert point when in
8092 * Replace mode */
8093 if (curwin->w_cursor.lnum != Insstart.lnum
8094 || curwin->w_cursor.col >= Insstart.col)
8096 #if 0 /* what was this for? It causes problems when sw != ts. */
8097 if (State == REPLACE && (int)vcol < want_vcol)
8099 (void)del_char(FALSE);
8100 extra = 2; /* don't pop too much */
8102 else
8103 #endif
8104 replace_do_bs();
8107 else
8108 (void)del_char(FALSE);
8111 /* insert extra spaces until we are at want_vcol */
8112 while (vcol < want_vcol)
8114 /* Remember the first char we inserted */
8115 if (curwin->w_cursor.lnum == Insstart.lnum
8116 && curwin->w_cursor.col < Insstart.col)
8117 Insstart.col = curwin->w_cursor.col;
8119 #ifdef FEAT_VREPLACE
8120 if (State & VREPLACE_FLAG)
8121 ins_char(' ');
8122 else
8123 #endif
8125 ins_str((char_u *)" ");
8126 if ((State & REPLACE_FLAG) /* && extra <= 1 */)
8128 #if 0
8129 if (extra)
8130 replace_push_off(NUL);
8131 else
8132 #endif
8133 replace_push(NUL);
8135 #if 0
8136 if (extra == 2)
8137 extra = 1;
8138 #endif
8140 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8145 * Delete upto starting point, start of line or previous word.
8147 else do
8149 #ifdef FEAT_RIGHTLEFT
8150 if (!revins_on) /* put cursor on char to be deleted */
8151 #endif
8152 dec_cursor();
8154 /* start of word? */
8155 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8157 mode = BACKSPACE_WORD_NOT_SPACE;
8158 temp = vim_iswordc(gchar_cursor());
8160 /* end of word? */
8161 else if (mode == BACKSPACE_WORD_NOT_SPACE
8162 && (vim_isspace(cc = gchar_cursor())
8163 || vim_iswordc(cc) != temp))
8165 #ifdef FEAT_RIGHTLEFT
8166 if (!revins_on)
8167 #endif
8168 inc_cursor();
8169 #ifdef FEAT_RIGHTLEFT
8170 else if (State & REPLACE_FLAG)
8171 dec_cursor();
8172 #endif
8173 break;
8175 if (State & REPLACE_FLAG)
8176 replace_do_bs();
8177 else
8179 #ifdef FEAT_MBYTE
8180 if (enc_utf8 && p_deco)
8181 (void)utfc_ptr2char(ml_get_cursor(), cpc);
8182 #endif
8183 (void)del_char(FALSE);
8184 #ifdef FEAT_MBYTE
8186 * If there are combining characters and 'delcombine' is set
8187 * move the cursor back. Don't back up before the base
8188 * character.
8190 if (enc_utf8 && p_deco && cpc[0] != NUL)
8191 inc_cursor();
8192 #endif
8193 #ifdef FEAT_RIGHTLEFT
8194 if (revins_chars)
8196 revins_chars--;
8197 revins_legal++;
8199 if (revins_on && gchar_cursor() == NUL)
8200 break;
8201 #endif
8203 /* Just a single backspace?: */
8204 if (mode == BACKSPACE_CHAR)
8205 break;
8206 } while (
8207 #ifdef FEAT_RIGHTLEFT
8208 revins_on ||
8209 #endif
8210 (curwin->w_cursor.col > mincol
8211 && (curwin->w_cursor.lnum != Insstart.lnum
8212 || curwin->w_cursor.col != Insstart.col)));
8213 did_backspace = TRUE;
8215 #ifdef FEAT_SMARTINDENT
8216 did_si = FALSE;
8217 can_si = FALSE;
8218 can_si_back = FALSE;
8219 #endif
8220 if (curwin->w_cursor.col <= 1)
8221 did_ai = FALSE;
8223 * It's a little strange to put backspaces into the redo
8224 * buffer, but it makes auto-indent a lot easier to deal
8225 * with.
8227 AppendCharToRedobuff(c);
8229 /* If deleted before the insertion point, adjust it */
8230 if (curwin->w_cursor.lnum == Insstart.lnum
8231 && curwin->w_cursor.col < Insstart.col)
8232 Insstart.col = curwin->w_cursor.col;
8234 /* vi behaviour: the cursor moves backward but the character that
8235 * was there remains visible
8236 * Vim behaviour: the cursor moves backward and the character that
8237 * was there is erased from the screen.
8238 * We can emulate the vi behaviour by pretending there is a dollar
8239 * displayed even when there isn't.
8240 * --pkv Sun Jan 19 01:56:40 EST 2003 */
8241 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
8242 dollar_vcol = curwin->w_virtcol;
8244 return did_backspace;
8247 #ifdef FEAT_MOUSE
8248 static void
8249 ins_mouse(c)
8250 int c;
8252 pos_T tpos;
8253 win_T *old_curwin = curwin;
8255 # ifdef FEAT_GUI
8256 /* When GUI is active, also move/paste when 'mouse' is empty */
8257 if (!gui.in_use)
8258 # endif
8259 if (!mouse_has(MOUSE_INSERT))
8260 return;
8262 undisplay_dollar();
8263 tpos = curwin->w_cursor;
8264 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
8266 #ifdef FEAT_WINDOWS
8267 win_T *new_curwin = curwin;
8269 if (curwin != old_curwin && win_valid(old_curwin))
8271 /* Mouse took us to another window. We need to go back to the
8272 * previous one to stop insert there properly. */
8273 curwin = old_curwin;
8274 curbuf = curwin->w_buffer;
8276 #endif
8277 start_arrow(curwin == old_curwin ? &tpos : NULL);
8278 #ifdef FEAT_WINDOWS
8279 if (curwin != new_curwin && win_valid(new_curwin))
8281 curwin = new_curwin;
8282 curbuf = curwin->w_buffer;
8284 #endif
8285 # ifdef FEAT_CINDENT
8286 can_cindent = TRUE;
8287 # endif
8290 #ifdef FEAT_WINDOWS
8291 /* redraw status lines (in case another window became active) */
8292 redraw_statuslines();
8293 #endif
8296 static void
8297 ins_mousescroll(up)
8298 int up;
8300 pos_T tpos;
8301 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8302 win_T *old_curwin;
8303 # endif
8305 tpos = curwin->w_cursor;
8307 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8308 old_curwin = curwin;
8310 /* Currently the mouse coordinates are only known in the GUI. */
8311 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
8313 int row, col;
8315 row = mouse_row;
8316 col = mouse_col;
8318 /* find the window at the pointer coordinates */
8319 curwin = mouse_find_win(&row, &col);
8320 curbuf = curwin->w_buffer;
8322 if (curwin == old_curwin)
8323 # endif
8324 undisplay_dollar();
8326 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
8327 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
8328 else
8329 scroll_redraw(up, 3L);
8331 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8332 curwin->w_redr_status = TRUE;
8334 curwin = old_curwin;
8335 curbuf = curwin->w_buffer;
8336 # endif
8338 if (!equalpos(curwin->w_cursor, tpos))
8340 start_arrow(&tpos);
8341 # ifdef FEAT_CINDENT
8342 can_cindent = TRUE;
8343 # endif
8346 #endif
8348 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
8349 static void
8350 ins_tabline(c)
8351 int c;
8353 /* We will be leaving the current window, unless closing another tab. */
8354 if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
8355 || (current_tab != 0 && current_tab != tabpage_index(curtab)))
8357 undisplay_dollar();
8358 start_arrow(&curwin->w_cursor);
8359 # ifdef FEAT_CINDENT
8360 can_cindent = TRUE;
8361 # endif
8364 if (c == K_TABLINE)
8365 goto_tabpage(current_tab);
8366 else
8367 handle_tabmenu();
8370 #endif
8372 #if defined(FEAT_GUI) || defined(PROTO)
8373 void
8374 ins_scroll()
8376 pos_T tpos;
8378 undisplay_dollar();
8379 tpos = curwin->w_cursor;
8380 if (gui_do_scroll())
8382 start_arrow(&tpos);
8383 # ifdef FEAT_CINDENT
8384 can_cindent = TRUE;
8385 # endif
8389 void
8390 ins_horscroll()
8392 pos_T tpos;
8394 undisplay_dollar();
8395 tpos = curwin->w_cursor;
8396 if (gui_do_horiz_scroll())
8398 start_arrow(&tpos);
8399 # ifdef FEAT_CINDENT
8400 can_cindent = TRUE;
8401 # endif
8404 #endif
8406 static void
8407 ins_left()
8409 pos_T tpos;
8411 #ifdef FEAT_FOLDING
8412 if ((fdo_flags & FDO_HOR) && KeyTyped)
8413 foldOpenCursor();
8414 #endif
8415 undisplay_dollar();
8416 tpos = curwin->w_cursor;
8417 if (oneleft() == OK)
8419 start_arrow(&tpos);
8420 #ifdef FEAT_RIGHTLEFT
8421 /* If exit reversed string, position is fixed */
8422 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
8423 revins_legal++;
8424 revins_chars++;
8425 #endif
8429 * if 'whichwrap' set for cursor in insert mode may go to
8430 * previous line
8432 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
8434 start_arrow(&tpos);
8435 --(curwin->w_cursor.lnum);
8436 coladvance((colnr_T)MAXCOL);
8437 curwin->w_set_curswant = TRUE; /* so we stay at the end */
8439 else
8440 vim_beep();
8443 static void
8444 ins_home(c)
8445 int c;
8447 pos_T tpos;
8449 #ifdef FEAT_FOLDING
8450 if ((fdo_flags & FDO_HOR) && KeyTyped)
8451 foldOpenCursor();
8452 #endif
8453 undisplay_dollar();
8454 tpos = curwin->w_cursor;
8455 if (c == K_C_HOME)
8456 curwin->w_cursor.lnum = 1;
8457 curwin->w_cursor.col = 0;
8458 #ifdef FEAT_VIRTUALEDIT
8459 curwin->w_cursor.coladd = 0;
8460 #endif
8461 curwin->w_curswant = 0;
8462 start_arrow(&tpos);
8465 static void
8466 ins_end(c)
8467 int c;
8469 pos_T tpos;
8471 #ifdef FEAT_FOLDING
8472 if ((fdo_flags & FDO_HOR) && KeyTyped)
8473 foldOpenCursor();
8474 #endif
8475 undisplay_dollar();
8476 tpos = curwin->w_cursor;
8477 if (c == K_C_END)
8478 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
8479 coladvance((colnr_T)MAXCOL);
8480 curwin->w_curswant = MAXCOL;
8482 start_arrow(&tpos);
8485 static void
8486 ins_s_left()
8488 #ifdef FEAT_FOLDING
8489 if ((fdo_flags & FDO_HOR) && KeyTyped)
8490 foldOpenCursor();
8491 #endif
8492 undisplay_dollar();
8493 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
8495 start_arrow(&curwin->w_cursor);
8496 (void)bck_word(1L, FALSE, FALSE);
8497 curwin->w_set_curswant = TRUE;
8499 else
8500 vim_beep();
8503 static void
8504 ins_right()
8506 #ifdef FEAT_FOLDING
8507 if ((fdo_flags & FDO_HOR) && KeyTyped)
8508 foldOpenCursor();
8509 #endif
8510 undisplay_dollar();
8511 if (gchar_cursor() != NUL || virtual_active()
8514 start_arrow(&curwin->w_cursor);
8515 curwin->w_set_curswant = TRUE;
8516 #ifdef FEAT_VIRTUALEDIT
8517 if (virtual_active())
8518 oneright();
8519 else
8520 #endif
8522 #ifdef FEAT_MBYTE
8523 if (has_mbyte)
8524 curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
8525 else
8526 #endif
8527 ++curwin->w_cursor.col;
8530 #ifdef FEAT_RIGHTLEFT
8531 revins_legal++;
8532 if (revins_chars)
8533 revins_chars--;
8534 #endif
8536 /* if 'whichwrap' set for cursor in insert mode, may move the
8537 * cursor to the next line */
8538 else if (vim_strchr(p_ww, ']') != NULL
8539 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
8541 start_arrow(&curwin->w_cursor);
8542 curwin->w_set_curswant = TRUE;
8543 ++curwin->w_cursor.lnum;
8544 curwin->w_cursor.col = 0;
8546 else
8547 vim_beep();
8550 static void
8551 ins_s_right()
8553 #ifdef FEAT_FOLDING
8554 if ((fdo_flags & FDO_HOR) && KeyTyped)
8555 foldOpenCursor();
8556 #endif
8557 undisplay_dollar();
8558 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
8559 || gchar_cursor() != NUL)
8561 start_arrow(&curwin->w_cursor);
8562 (void)fwd_word(1L, FALSE, 0);
8563 curwin->w_set_curswant = TRUE;
8565 else
8566 vim_beep();
8569 static void
8570 ins_up(startcol)
8571 int startcol; /* when TRUE move to Insstart.col */
8573 pos_T tpos;
8574 linenr_T old_topline = curwin->w_topline;
8575 #ifdef FEAT_DIFF
8576 int old_topfill = curwin->w_topfill;
8577 #endif
8579 undisplay_dollar();
8580 tpos = curwin->w_cursor;
8581 if (cursor_up(1L, TRUE) == OK)
8583 if (startcol)
8584 coladvance(getvcol_nolist(&Insstart));
8585 if (old_topline != curwin->w_topline
8586 #ifdef FEAT_DIFF
8587 || old_topfill != curwin->w_topfill
8588 #endif
8590 redraw_later(VALID);
8591 start_arrow(&tpos);
8592 #ifdef FEAT_CINDENT
8593 can_cindent = TRUE;
8594 #endif
8596 else
8597 vim_beep();
8600 static void
8601 ins_pageup()
8603 pos_T tpos;
8605 undisplay_dollar();
8607 #ifdef FEAT_WINDOWS
8608 if (mod_mask & MOD_MASK_CTRL)
8610 /* <C-PageUp>: tab page back */
8611 goto_tabpage(-1);
8612 return;
8614 #endif
8616 tpos = curwin->w_cursor;
8617 if (onepage(BACKWARD, 1L) == OK)
8619 start_arrow(&tpos);
8620 #ifdef FEAT_CINDENT
8621 can_cindent = TRUE;
8622 #endif
8624 else
8625 vim_beep();
8628 static void
8629 ins_down(startcol)
8630 int startcol; /* when TRUE move to Insstart.col */
8632 pos_T tpos;
8633 linenr_T old_topline = curwin->w_topline;
8634 #ifdef FEAT_DIFF
8635 int old_topfill = curwin->w_topfill;
8636 #endif
8638 undisplay_dollar();
8639 tpos = curwin->w_cursor;
8640 if (cursor_down(1L, TRUE) == OK)
8642 if (startcol)
8643 coladvance(getvcol_nolist(&Insstart));
8644 if (old_topline != curwin->w_topline
8645 #ifdef FEAT_DIFF
8646 || old_topfill != curwin->w_topfill
8647 #endif
8649 redraw_later(VALID);
8650 start_arrow(&tpos);
8651 #ifdef FEAT_CINDENT
8652 can_cindent = TRUE;
8653 #endif
8655 else
8656 vim_beep();
8659 static void
8660 ins_pagedown()
8662 pos_T tpos;
8664 undisplay_dollar();
8666 #ifdef FEAT_WINDOWS
8667 if (mod_mask & MOD_MASK_CTRL)
8669 /* <C-PageDown>: tab page forward */
8670 goto_tabpage(0);
8671 return;
8673 #endif
8675 tpos = curwin->w_cursor;
8676 if (onepage(FORWARD, 1L) == OK)
8678 start_arrow(&tpos);
8679 #ifdef FEAT_CINDENT
8680 can_cindent = TRUE;
8681 #endif
8683 else
8684 vim_beep();
8687 #ifdef FEAT_DND
8688 static void
8689 ins_drop()
8691 do_put('~', BACKWARD, 1L, PUT_CURSEND);
8693 #endif
8696 * Handle TAB in Insert or Replace mode.
8697 * Return TRUE when the TAB needs to be inserted like a normal character.
8699 static int
8700 ins_tab()
8702 int ind;
8703 int i;
8704 int temp;
8706 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
8707 Insstart_blank_vcol = get_nolist_virtcol();
8708 if (echeck_abbr(TAB + ABBR_OFF))
8709 return FALSE;
8711 ind = inindent(0);
8712 #ifdef FEAT_CINDENT
8713 if (ind)
8714 can_cindent = FALSE;
8715 #endif
8718 * When nothing special, insert TAB like a normal character
8720 if (!curbuf->b_p_et
8721 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
8722 && curbuf->b_p_sts == 0)
8723 return TRUE;
8725 if (stop_arrow() == FAIL)
8726 return TRUE;
8728 did_ai = FALSE;
8729 #ifdef FEAT_SMARTINDENT
8730 did_si = FALSE;
8731 can_si = FALSE;
8732 can_si_back = FALSE;
8733 #endif
8734 AppendToRedobuff((char_u *)"\t");
8736 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
8737 temp = (int)curbuf->b_p_sw;
8738 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
8739 temp = (int)curbuf->b_p_sts;
8740 else /* otherwise use 'tabstop' */
8741 temp = (int)curbuf->b_p_ts;
8742 temp -= get_nolist_virtcol() % temp;
8745 * Insert the first space with ins_char(). It will delete one char in
8746 * replace mode. Insert the rest with ins_str(); it will not delete any
8747 * chars. For VREPLACE mode, we use ins_char() for all characters.
8749 ins_char(' ');
8750 while (--temp > 0)
8752 #ifdef FEAT_VREPLACE
8753 if (State & VREPLACE_FLAG)
8754 ins_char(' ');
8755 else
8756 #endif
8758 ins_str((char_u *)" ");
8759 if (State & REPLACE_FLAG) /* no char replaced */
8760 replace_push(NUL);
8765 * When 'expandtab' not set: Replace spaces by TABs where possible.
8767 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
8769 char_u *ptr;
8770 #ifdef FEAT_VREPLACE
8771 char_u *saved_line = NULL; /* init for GCC */
8772 pos_T pos;
8773 #endif
8774 pos_T fpos;
8775 pos_T *cursor;
8776 colnr_T want_vcol, vcol;
8777 int change_col = -1;
8778 int save_list = curwin->w_p_list;
8781 * Get the current line. For VREPLACE mode, don't make real changes
8782 * yet, just work on a copy of the line.
8784 #ifdef FEAT_VREPLACE
8785 if (State & VREPLACE_FLAG)
8787 pos = curwin->w_cursor;
8788 cursor = &pos;
8789 saved_line = vim_strsave(ml_get_curline());
8790 if (saved_line == NULL)
8791 return FALSE;
8792 ptr = saved_line + pos.col;
8794 else
8795 #endif
8797 ptr = ml_get_cursor();
8798 cursor = &curwin->w_cursor;
8801 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
8802 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
8803 curwin->w_p_list = FALSE;
8805 /* Find first white before the cursor */
8806 fpos = curwin->w_cursor;
8807 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
8809 --fpos.col;
8810 --ptr;
8813 /* In Replace mode, don't change characters before the insert point. */
8814 if ((State & REPLACE_FLAG)
8815 && fpos.lnum == Insstart.lnum
8816 && fpos.col < Insstart.col)
8818 ptr += Insstart.col - fpos.col;
8819 fpos.col = Insstart.col;
8822 /* compute virtual column numbers of first white and cursor */
8823 getvcol(curwin, &fpos, &vcol, NULL, NULL);
8824 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
8826 /* Use as many TABs as possible. Beware of 'showbreak' and
8827 * 'linebreak' adding extra virtual columns. */
8828 while (vim_iswhite(*ptr))
8830 i = lbr_chartabsize((char_u *)"\t", vcol);
8831 if (vcol + i > want_vcol)
8832 break;
8833 if (*ptr != TAB)
8835 *ptr = TAB;
8836 if (change_col < 0)
8838 change_col = fpos.col; /* Column of first change */
8839 /* May have to adjust Insstart */
8840 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
8841 Insstart.col = fpos.col;
8844 ++fpos.col;
8845 ++ptr;
8846 vcol += i;
8849 if (change_col >= 0)
8851 int repl_off = 0;
8853 /* Skip over the spaces we need. */
8854 while (vcol < want_vcol && *ptr == ' ')
8856 vcol += lbr_chartabsize(ptr, vcol);
8857 ++ptr;
8858 ++repl_off;
8860 if (vcol > want_vcol)
8862 /* Must have a char with 'showbreak' just before it. */
8863 --ptr;
8864 --repl_off;
8866 fpos.col += repl_off;
8868 /* Delete following spaces. */
8869 i = cursor->col - fpos.col;
8870 if (i > 0)
8872 mch_memmove(ptr, ptr + i, STRLEN(ptr + i) + 1);
8873 /* correct replace stack. */
8874 if ((State & REPLACE_FLAG)
8875 #ifdef FEAT_VREPLACE
8876 && !(State & VREPLACE_FLAG)
8877 #endif
8879 for (temp = i; --temp >= 0; )
8880 replace_join(repl_off);
8882 #ifdef FEAT_NETBEANS_INTG
8883 if (usingNetbeans)
8885 netbeans_removed(curbuf, fpos.lnum, cursor->col,
8886 (long)(i + 1));
8887 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
8888 (char_u *)"\t", 1);
8890 #endif
8891 cursor->col -= i;
8893 #ifdef FEAT_VREPLACE
8895 * In VREPLACE mode, we haven't changed anything yet. Do it now by
8896 * backspacing over the changed spacing and then inserting the new
8897 * spacing.
8899 if (State & VREPLACE_FLAG)
8901 /* Backspace from real cursor to change_col */
8902 backspace_until_column(change_col);
8904 /* Insert each char in saved_line from changed_col to
8905 * ptr-cursor */
8906 ins_bytes_len(saved_line + change_col,
8907 cursor->col - change_col);
8909 #endif
8912 #ifdef FEAT_VREPLACE
8913 if (State & VREPLACE_FLAG)
8914 vim_free(saved_line);
8915 #endif
8916 curwin->w_p_list = save_list;
8919 return FALSE;
8923 * Handle CR or NL in insert mode.
8924 * Return TRUE when out of memory or can't undo.
8926 static int
8927 ins_eol(c)
8928 int c;
8930 int i;
8932 if (echeck_abbr(c + ABBR_OFF))
8933 return FALSE;
8934 if (stop_arrow() == FAIL)
8935 return TRUE;
8936 undisplay_dollar();
8939 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
8940 * character under the cursor. Only push a NUL on the replace stack,
8941 * nothing to put back when the NL is deleted.
8943 if ((State & REPLACE_FLAG)
8944 #ifdef FEAT_VREPLACE
8945 && !(State & VREPLACE_FLAG)
8946 #endif
8948 replace_push(NUL);
8951 * In VREPLACE mode, a NL replaces the rest of the line, and starts
8952 * replacing the next line, so we push all of the characters left on the
8953 * line onto the replace stack. This is not done here though, it is done
8954 * in open_line().
8957 #ifdef FEAT_RIGHTLEFT
8958 # ifdef FEAT_FKMAP
8959 if (p_altkeymap && p_fkmap)
8960 fkmap(NL);
8961 # endif
8962 /* NL in reverse insert will always start in the end of
8963 * current line. */
8964 if (revins_on)
8965 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
8966 #endif
8968 AppendToRedobuff(NL_STR);
8969 i = open_line(FORWARD,
8970 #ifdef FEAT_COMMENTS
8971 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
8972 #endif
8973 0, old_indent);
8974 old_indent = 0;
8975 #ifdef FEAT_CINDENT
8976 can_cindent = TRUE;
8977 #endif
8979 return (!i);
8982 #ifdef FEAT_DIGRAPHS
8984 * Handle digraph in insert mode.
8985 * Returns character still to be inserted, or NUL when nothing remaining to be
8986 * done.
8988 static int
8989 ins_digraph()
8991 int c;
8992 int cc;
8994 pc_status = PC_STATUS_UNSET;
8995 if (redrawing() && !char_avail())
8997 /* may need to redraw when no more chars available now */
8998 ins_redraw(FALSE);
9000 edit_putchar('?', TRUE);
9001 #ifdef FEAT_CMDL_INFO
9002 add_to_showcmd_c(Ctrl_K);
9003 #endif
9006 #ifdef USE_ON_FLY_SCROLL
9007 dont_scroll = TRUE; /* disallow scrolling here */
9008 #endif
9010 /* don't map the digraph chars. This also prevents the
9011 * mode message to be deleted when ESC is hit */
9012 ++no_mapping;
9013 ++allow_keys;
9014 c = safe_vgetc();
9015 --no_mapping;
9016 --allow_keys;
9017 if (IS_SPECIAL(c) || mod_mask) /* special key */
9019 #ifdef FEAT_CMDL_INFO
9020 clear_showcmd();
9021 #endif
9022 insert_special(c, TRUE, FALSE);
9023 return NUL;
9025 if (c != ESC)
9027 if (redrawing() && !char_avail())
9029 /* may need to redraw when no more chars available now */
9030 ins_redraw(FALSE);
9032 if (char2cells(c) == 1)
9034 /* first remove the '?', otherwise it's restored when typing
9035 * an ESC next */
9036 edit_unputchar();
9037 ins_redraw(FALSE);
9038 edit_putchar(c, TRUE);
9040 #ifdef FEAT_CMDL_INFO
9041 add_to_showcmd_c(c);
9042 #endif
9044 ++no_mapping;
9045 ++allow_keys;
9046 cc = safe_vgetc();
9047 --no_mapping;
9048 --allow_keys;
9049 if (cc != ESC)
9051 AppendToRedobuff((char_u *)CTRL_V_STR);
9052 c = getdigraph(c, cc, TRUE);
9053 #ifdef FEAT_CMDL_INFO
9054 clear_showcmd();
9055 #endif
9056 return c;
9059 edit_unputchar();
9060 #ifdef FEAT_CMDL_INFO
9061 clear_showcmd();
9062 #endif
9063 return NUL;
9065 #endif
9068 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9069 * Returns the char to be inserted, or NUL if none found.
9071 static int
9072 ins_copychar(lnum)
9073 linenr_T lnum;
9075 int c;
9076 int temp;
9077 char_u *ptr, *prev_ptr;
9079 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9081 vim_beep();
9082 return NUL;
9085 /* try to advance to the cursor column */
9086 temp = 0;
9087 ptr = ml_get(lnum);
9088 prev_ptr = ptr;
9089 validate_virtcol();
9090 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9092 prev_ptr = ptr;
9093 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
9095 if ((colnr_T)temp > curwin->w_virtcol)
9096 ptr = prev_ptr;
9098 #ifdef FEAT_MBYTE
9099 c = (*mb_ptr2char)(ptr);
9100 #else
9101 c = *ptr;
9102 #endif
9103 if (c == NUL)
9104 vim_beep();
9105 return c;
9109 * CTRL-Y or CTRL-E typed in Insert mode.
9111 static int
9112 ins_ctrl_ey(tc)
9113 int tc;
9115 int c = tc;
9117 #ifdef FEAT_INS_EXPAND
9118 if (ctrl_x_mode == CTRL_X_SCROLL)
9120 if (c == Ctrl_Y)
9121 scrolldown_clamp();
9122 else
9123 scrollup_clamp();
9124 redraw_later(VALID);
9126 else
9127 #endif
9129 c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
9130 if (c != NUL)
9132 long tw_save;
9134 /* The character must be taken literally, insert like it
9135 * was typed after a CTRL-V, and pretend 'textwidth'
9136 * wasn't set. Digits, 'o' and 'x' are special after a
9137 * CTRL-V, don't use it for these. */
9138 if (c < 256 && !isalnum(c))
9139 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
9140 tw_save = curbuf->b_p_tw;
9141 curbuf->b_p_tw = -1;
9142 insert_special(c, TRUE, FALSE);
9143 curbuf->b_p_tw = tw_save;
9144 #ifdef FEAT_RIGHTLEFT
9145 revins_chars++;
9146 revins_legal++;
9147 #endif
9148 c = Ctrl_V; /* pretend CTRL-V is last character */
9149 auto_format(FALSE, TRUE);
9152 return c;
9155 #ifdef FEAT_SMARTINDENT
9157 * Try to do some very smart auto-indenting.
9158 * Used when inserting a "normal" character.
9160 static void
9161 ins_try_si(c)
9162 int c;
9164 pos_T *pos, old_pos;
9165 char_u *ptr;
9166 int i;
9167 int temp;
9170 * do some very smart indenting when entering '{' or '}'
9172 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
9175 * for '}' set indent equal to indent of line containing matching '{'
9177 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
9179 old_pos = curwin->w_cursor;
9181 * If the matching '{' has a ')' immediately before it (ignoring
9182 * white-space), then line up with the start of the line
9183 * containing the matching '(' if there is one. This handles the
9184 * case where an "if (..\n..) {" statement continues over multiple
9185 * lines -- webb
9187 ptr = ml_get(pos->lnum);
9188 i = pos->col;
9189 if (i > 0) /* skip blanks before '{' */
9190 while (--i > 0 && vim_iswhite(ptr[i]))
9192 curwin->w_cursor.lnum = pos->lnum;
9193 curwin->w_cursor.col = i;
9194 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
9195 curwin->w_cursor = *pos;
9196 i = get_indent();
9197 curwin->w_cursor = old_pos;
9198 #ifdef FEAT_VREPLACE
9199 if (State & VREPLACE_FLAG)
9200 change_indent(INDENT_SET, i, FALSE, NUL);
9201 else
9202 #endif
9203 (void)set_indent(i, SIN_CHANGED);
9205 else if (curwin->w_cursor.col > 0)
9208 * when inserting '{' after "O" reduce indent, but not
9209 * more than indent of previous line
9211 temp = TRUE;
9212 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
9214 old_pos = curwin->w_cursor;
9215 i = get_indent();
9216 while (curwin->w_cursor.lnum > 1)
9218 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
9220 /* ignore empty lines and lines starting with '#'. */
9221 if (*ptr != '#' && *ptr != NUL)
9222 break;
9224 if (get_indent() >= i)
9225 temp = FALSE;
9226 curwin->w_cursor = old_pos;
9228 if (temp)
9229 shift_line(TRUE, FALSE, 1);
9234 * set indent of '#' always to 0
9236 if (curwin->w_cursor.col > 0 && can_si && c == '#')
9238 /* remember current indent for next line */
9239 old_indent = get_indent();
9240 (void)set_indent(0, SIN_CHANGED);
9243 /* Adjust ai_col, the char at this position can be deleted. */
9244 if (ai_col > curwin->w_cursor.col)
9245 ai_col = curwin->w_cursor.col;
9247 #endif
9250 * Get the value that w_virtcol would have when 'list' is off.
9251 * Unless 'cpo' contains the 'L' flag.
9253 static colnr_T
9254 get_nolist_virtcol()
9256 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9257 return getvcol_nolist(&curwin->w_cursor);
9258 validate_virtcol();
9259 return curwin->w_virtcol;