Merge branch 'feat/tagfunc'
[vim_extended.git] / src / edit.c
blobb4997afe232f25275e4c05e062e7bf448efc7ea7
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * edit.c: functions for Insert mode
14 #include "vim.h"
16 #ifdef FEAT_INS_EXPAND
18 * definitions used for CTRL-X submode
20 #define CTRL_X_WANT_IDENT 0x100
22 #define CTRL_X_NOT_DEFINED_YET 1
23 #define CTRL_X_SCROLL 2
24 #define CTRL_X_WHOLE_LINE 3
25 #define CTRL_X_FILES 4
26 #define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
27 #define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
28 #define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
29 #define CTRL_X_FINISHED 8
30 #define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
31 #define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
32 #define CTRL_X_CMDLINE 11
33 #define CTRL_X_FUNCTION 12
34 #define CTRL_X_OMNI 13
35 #define CTRL_X_SPELL 14
36 #define CTRL_X_LOCAL_MSG 15 /* only used in "ctrl_x_msgs" */
38 #define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
40 static char *ctrl_x_msgs[] =
42 N_(" Keyword completion (^N^P)"), /* ctrl_x_mode == 0, ^P/^N compl. */
43 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
44 NULL,
45 N_(" Whole line completion (^L^N^P)"),
46 N_(" File name completion (^F^N^P)"),
47 N_(" Tag completion (^]^N^P)"),
48 N_(" Path pattern completion (^N^P)"),
49 N_(" Definition completion (^D^N^P)"),
50 NULL,
51 N_(" Dictionary completion (^K^N^P)"),
52 N_(" Thesaurus completion (^T^N^P)"),
53 N_(" Command-line completion (^V^N^P)"),
54 N_(" User defined completion (^U^N^P)"),
55 N_(" Omni completion (^O^N^P)"),
56 N_(" Spelling suggestion (s^N^P)"),
57 N_(" Keyword Local completion (^N^P)"),
60 static char e_hitend[] = N_("Hit end of paragraph");
63 * Structure used to store one match for insert completion.
65 typedef struct compl_S compl_T;
66 struct compl_S
68 compl_T *cp_next;
69 compl_T *cp_prev;
70 char_u *cp_str; /* matched text */
71 char cp_icase; /* TRUE or FALSE: ignore case */
72 char_u *(cp_text[CPT_COUNT]); /* text for the menu */
73 char_u *cp_fname; /* file containing the match, allocated when
74 * cp_flags has FREE_FNAME */
75 int cp_flags; /* ORIGINAL_TEXT, CONT_S_IPOS or FREE_FNAME */
76 int cp_number; /* sequence number */
79 #define ORIGINAL_TEXT (1) /* the original text when the expansion begun */
80 #define FREE_FNAME (2)
83 * All the current matches are stored in a list.
84 * "compl_first_match" points to the start of the list.
85 * "compl_curr_match" points to the currently selected entry.
86 * "compl_shown_match" is different from compl_curr_match during
87 * ins_compl_get_exp().
89 static compl_T *compl_first_match = NULL;
90 static compl_T *compl_curr_match = NULL;
91 static compl_T *compl_shown_match = NULL;
93 /* After using a cursor key <Enter> selects a match in the popup menu,
94 * otherwise it inserts a line break. */
95 static int compl_enter_selects = FALSE;
97 /* When "compl_leader" is not NULL only matches that start with this string
98 * are used. */
99 static char_u *compl_leader = NULL;
101 static int compl_get_longest = FALSE; /* put longest common string
102 in compl_leader */
104 static int compl_used_match; /* Selected one of the matches. When
105 FALSE the match was edited or using
106 the longest common string. */
108 static int compl_was_interrupted = FALSE; /* didn't finish finding
109 completions. */
111 static int compl_restarting = FALSE; /* don't insert match */
113 /* When the first completion is done "compl_started" is set. When it's
114 * FALSE the word to be completed must be located. */
115 static int compl_started = FALSE;
117 /* Set when doing something for completion that may call edit() recursively,
118 * which is not allowed. */
119 static int compl_busy = FALSE;
121 static int compl_matches = 0;
122 static char_u *compl_pattern = NULL;
123 static int compl_direction = FORWARD;
124 static int compl_shows_dir = FORWARD;
125 static int compl_pending = 0; /* > 1 for postponed CTRL-N */
126 static pos_T compl_startpos;
127 static colnr_T compl_col = 0; /* column where the text starts
128 * that is being completed */
129 static char_u *compl_orig_text = NULL; /* text as it was before
130 * completion started */
131 static int compl_cont_mode = 0;
132 static expand_T compl_xp;
134 static void ins_ctrl_x __ARGS((void));
135 static int has_compl_option __ARGS((int dict_opt));
136 static int ins_compl_accept_char __ARGS((int c));
137 static int ins_compl_add __ARGS((char_u *str, int len, int icase, char_u *fname, char_u **cptext, int cdir, int flags, int adup));
138 static int ins_compl_equal __ARGS((compl_T *match, char_u *str, int len));
139 static void ins_compl_longest_match __ARGS((compl_T *match));
140 static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int icase));
141 static int ins_compl_make_cyclic __ARGS((void));
142 static void ins_compl_upd_pum __ARGS((void));
143 static void ins_compl_del_pum __ARGS((void));
144 static int pum_wanted __ARGS((void));
145 static int pum_enough_matches __ARGS((void));
146 static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int flags, int thesaurus));
147 static void ins_compl_files __ARGS((int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir));
148 static char_u *find_line_end __ARGS((char_u *ptr));
149 static void ins_compl_free __ARGS((void));
150 static void ins_compl_clear __ARGS((void));
151 static int ins_compl_bs __ARGS((void));
152 static void ins_compl_new_leader __ARGS((void));
153 static void ins_compl_addleader __ARGS((int c));
154 static int ins_compl_len __ARGS((void));
155 static void ins_compl_restart __ARGS((void));
156 static void ins_compl_set_original_text __ARGS((char_u *str));
157 static void ins_compl_addfrommatch __ARGS((void));
158 static int ins_compl_prep __ARGS((int c));
159 static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag));
160 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
161 static void ins_compl_add_list __ARGS((list_T *list));
162 #endif
163 static int ins_compl_get_exp __ARGS((pos_T *ini));
164 static void ins_compl_delete __ARGS((void));
165 static void ins_compl_insert __ARGS((void));
166 static int ins_compl_next __ARGS((int allow_get_expansion, int count, int insert_match));
167 static int ins_compl_key2dir __ARGS((int c));
168 static int ins_compl_pum_key __ARGS((int c));
169 static int ins_compl_key2count __ARGS((int c));
170 static int ins_compl_use_match __ARGS((int c));
171 static int ins_complete __ARGS((int c));
172 static unsigned quote_meta __ARGS((char_u *dest, char_u *str, int len));
173 #endif /* FEAT_INS_EXPAND */
175 #define BACKSPACE_CHAR 1
176 #define BACKSPACE_WORD 2
177 #define BACKSPACE_WORD_NOT_SPACE 3
178 #define BACKSPACE_LINE 4
180 static void ins_redraw __ARGS((int ready));
181 static void ins_ctrl_v __ARGS((void));
182 static void undisplay_dollar __ARGS((void));
183 static void insert_special __ARGS((int, int, int));
184 static void internal_format __ARGS((int textwidth, int second_indent, int flags, int format_only, int c));
185 static void check_auto_format __ARGS((int));
186 static void redo_literal __ARGS((int c));
187 static void start_arrow __ARGS((pos_T *end_insert_pos));
188 #ifdef FEAT_SPELL
189 static void check_spell_redraw __ARGS((void));
190 static void spell_back_to_badword __ARGS((void));
191 static int spell_bad_len = 0; /* length of located bad word */
192 #endif
193 static void stop_insert __ARGS((pos_T *end_insert_pos, int esc));
194 static int echeck_abbr __ARGS((int));
195 #if 0
196 static void replace_push_off __ARGS((int c));
197 #endif
198 static int replace_pop __ARGS((void));
199 static void replace_join __ARGS((int off));
200 static void replace_pop_ins __ARGS((void));
201 #ifdef FEAT_MBYTE
202 static void mb_replace_pop_ins __ARGS((int cc));
203 #endif
204 static void replace_flush __ARGS((void));
205 static void replace_do_bs __ARGS((int limit_col));
206 static int del_char_after_col __ARGS((int limit_col));
207 #ifdef FEAT_CINDENT
208 static int cindent_on __ARGS((void));
209 #endif
210 static void ins_reg __ARGS((void));
211 static void ins_ctrl_g __ARGS((void));
212 static void ins_ctrl_hat __ARGS((void));
213 static int ins_esc __ARGS((long *count, int cmdchar, int nomove));
214 #ifdef FEAT_RIGHTLEFT
215 static void ins_ctrl_ __ARGS((void));
216 #endif
217 #ifdef FEAT_VISUAL
218 static int ins_start_select __ARGS((int c));
219 #endif
220 static void ins_insert __ARGS((int replaceState));
221 static void ins_ctrl_o __ARGS((void));
222 static void ins_shift __ARGS((int c, int lastc));
223 static void ins_del __ARGS((void));
224 static int ins_bs __ARGS((int c, int mode, int *inserted_space_p));
225 #ifdef FEAT_MOUSE
226 static void ins_mouse __ARGS((int c));
227 static void ins_mousescroll __ARGS((int up));
228 #endif
229 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
230 static void ins_tabline __ARGS((int c));
231 #endif
232 static void ins_left __ARGS((void));
233 static void ins_home __ARGS((int c));
234 static void ins_end __ARGS((int c));
235 static void ins_s_left __ARGS((void));
236 static void ins_right __ARGS((void));
237 static void ins_s_right __ARGS((void));
238 static void ins_up __ARGS((int startcol));
239 static void ins_pageup __ARGS((void));
240 static void ins_down __ARGS((int startcol));
241 static void ins_pagedown __ARGS((void));
242 #ifdef FEAT_DND
243 static void ins_drop __ARGS((void));
244 #endif
245 static int ins_tab __ARGS((void));
246 static int ins_eol __ARGS((int c));
247 #ifdef FEAT_DIGRAPHS
248 static int ins_digraph __ARGS((void));
249 #endif
250 static int ins_copychar __ARGS((linenr_T lnum));
251 static int ins_ctrl_ey __ARGS((int tc));
252 #ifdef FEAT_SMARTINDENT
253 static void ins_try_si __ARGS((int c));
254 #endif
255 static colnr_T get_nolist_virtcol __ARGS((void));
257 static colnr_T Insstart_textlen; /* length of line when insert started */
258 static colnr_T Insstart_blank_vcol; /* vcol for first inserted blank */
260 static char_u *last_insert = NULL; /* the text of the previous insert,
261 K_SPECIAL and CSI are escaped */
262 static int last_insert_skip; /* nr of chars in front of previous insert */
263 static int new_insert_skip; /* nr of chars in front of current insert */
264 static int did_restart_edit; /* "restart_edit" when calling edit() */
266 #ifdef FEAT_CINDENT
267 static int can_cindent; /* may do cindenting on this line */
268 #endif
270 static int old_indent = 0; /* for ^^D command in insert mode */
272 #ifdef FEAT_RIGHTLEFT
273 static int revins_on; /* reverse insert mode on */
274 static int revins_chars; /* how much to skip after edit */
275 static int revins_legal; /* was the last char 'legal'? */
276 static int revins_scol; /* start column of revins session */
277 #endif
279 static int ins_need_undo; /* call u_save() before inserting a
280 char. Set when edit() is called.
281 after that arrow_used is used. */
283 static int did_add_space = FALSE; /* auto_format() added an extra space
284 under the cursor */
287 * edit(): Start inserting text.
289 * "cmdchar" can be:
290 * 'i' normal insert command
291 * 'a' normal append command
292 * 'R' replace command
293 * 'r' "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo,
294 * but still only one <CR> is inserted. The <Esc> is not used for redo.
295 * 'g' "gI" command.
296 * 'V' "gR" command for Virtual Replace mode.
297 * 'v' "gr" command for single character Virtual Replace mode.
299 * This function is not called recursively. For CTRL-O commands, it returns
300 * and lets the caller handle the Normal-mode command.
302 * Return TRUE if a CTRL-O command caused the return (insert mode pending).
305 edit(cmdchar, startln, count)
306 int cmdchar;
307 int startln; /* if set, insert at start of line */
308 long count;
310 int c = 0;
311 char_u *ptr;
312 int lastc;
313 int mincol;
314 static linenr_T o_lnum = 0;
315 int i;
316 int did_backspace = TRUE; /* previous char was backspace */
317 #ifdef FEAT_CINDENT
318 int line_is_white = FALSE; /* line is empty before insert */
319 #endif
320 linenr_T old_topline = 0; /* topline before insertion */
321 #ifdef FEAT_DIFF
322 int old_topfill = -1;
323 #endif
324 int inserted_space = FALSE; /* just inserted a space */
325 int replaceState = REPLACE;
326 int nomove = FALSE; /* don't move cursor on return */
328 /* Remember whether editing was restarted after CTRL-O. */
329 did_restart_edit = restart_edit;
331 /* sleep before redrawing, needed for "CTRL-O :" that results in an
332 * error message */
333 check_for_delay(TRUE);
335 #ifdef HAVE_SANDBOX
336 /* Don't allow inserting in the sandbox. */
337 if (sandbox != 0)
339 EMSG(_(e_sandbox));
340 return FALSE;
342 #endif
343 /* Don't allow changes in the buffer while editing the cmdline. The
344 * caller of getcmdline() may get confused. */
345 if (textlock != 0)
347 EMSG(_(e_secure));
348 return FALSE;
351 #ifdef FEAT_INS_EXPAND
352 /* Don't allow recursive insert mode when busy with completion. */
353 if (compl_started || compl_busy || pum_visible())
355 EMSG(_(e_secure));
356 return FALSE;
358 ins_compl_clear(); /* clear stuff for CTRL-X mode */
359 #endif
361 #ifdef FEAT_AUTOCMD
363 * Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx".
365 if (cmdchar != 'r' && cmdchar != 'v')
367 # ifdef FEAT_EVAL
368 if (cmdchar == 'R')
369 ptr = (char_u *)"r";
370 else if (cmdchar == 'V')
371 ptr = (char_u *)"v";
372 else
373 ptr = (char_u *)"i";
374 set_vim_var_string(VV_INSERTMODE, ptr, 1);
375 # endif
376 apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf);
378 #endif
380 #ifdef FEAT_MOUSE
382 * When doing a paste with the middle mouse button, Insstart is set to
383 * where the paste started.
385 if (where_paste_started.lnum != 0)
386 Insstart = where_paste_started;
387 else
388 #endif
390 Insstart = curwin->w_cursor;
391 if (startln)
392 Insstart.col = 0;
394 Insstart_textlen = (colnr_T)linetabsize(ml_get_curline(), Insstart.lnum);
395 Insstart_blank_vcol = MAXCOL;
396 if (!did_ai)
397 ai_col = 0;
399 if (cmdchar != NUL && restart_edit == 0)
401 ResetRedobuff();
402 AppendNumberToRedobuff(count);
403 #ifdef FEAT_VREPLACE
404 if (cmdchar == 'V' || cmdchar == 'v')
406 /* "gR" or "gr" command */
407 AppendCharToRedobuff('g');
408 AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R');
410 else
411 #endif
413 AppendCharToRedobuff(cmdchar);
414 if (cmdchar == 'g') /* "gI" command */
415 AppendCharToRedobuff('I');
416 else if (cmdchar == 'r') /* "r<CR>" command */
417 count = 1; /* insert only one <CR> */
421 if (cmdchar == 'R')
423 #ifdef FEAT_FKMAP
424 if (p_fkmap && p_ri)
426 beep_flush();
427 EMSG(farsi_text_3); /* encoded in Farsi */
428 State = INSERT;
430 else
431 #endif
432 State = REPLACE;
434 #ifdef FEAT_VREPLACE
435 else if (cmdchar == 'V' || cmdchar == 'v')
437 State = VREPLACE;
438 replaceState = VREPLACE;
439 orig_line_count = curbuf->b_ml.ml_line_count;
440 vr_lines_changed = 1;
442 #endif
443 else
444 State = INSERT;
446 stop_insert_mode = FALSE;
449 * Need to recompute the cursor position, it might move when the cursor is
450 * on a TAB or special character.
452 curs_columns(TRUE);
455 * Enable langmap or IME, indicated by 'iminsert'.
456 * Note that IME may enabled/disabled without us noticing here, thus the
457 * 'iminsert' value may not reflect what is actually used. It is updated
458 * when hitting <Esc>.
460 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
461 State |= LANGMAP;
462 #ifdef USE_IM_CONTROL
463 im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
464 #endif
466 #ifdef FEAT_MOUSE
467 setmouse();
468 #endif
469 #ifdef FEAT_CMDL_INFO
470 clear_showcmd();
471 #endif
472 #ifdef FEAT_RIGHTLEFT
473 /* there is no reverse replace mode */
474 revins_on = (State == INSERT && p_ri);
475 if (revins_on)
476 undisplay_dollar();
477 revins_chars = 0;
478 revins_legal = 0;
479 revins_scol = -1;
480 #endif
483 * Handle restarting Insert mode.
484 * Don't do this for "CTRL-O ." (repeat an insert): we get here with
485 * restart_edit non-zero, and something in the stuff buffer.
487 if (restart_edit != 0 && stuff_empty())
489 #ifdef FEAT_MOUSE
491 * After a paste we consider text typed to be part of the insert for
492 * the pasted text. You can backspace over the pasted text too.
494 if (where_paste_started.lnum)
495 arrow_used = FALSE;
496 else
497 #endif
498 arrow_used = TRUE;
499 restart_edit = 0;
502 * If the cursor was after the end-of-line before the CTRL-O and it is
503 * now at the end-of-line, put it after the end-of-line (this is not
504 * correct in very rare cases).
505 * Also do this if curswant is greater than the current virtual
506 * column. Eg after "^O$" or "^O80|".
508 validate_virtcol();
509 update_curswant();
510 if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
511 || curwin->w_curswant > curwin->w_virtcol)
512 && *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL)
514 if (ptr[1] == NUL)
515 ++curwin->w_cursor.col;
516 #ifdef FEAT_MBYTE
517 else if (has_mbyte)
519 i = (*mb_ptr2len)(ptr);
520 if (ptr[i] == NUL)
521 curwin->w_cursor.col += i;
523 #endif
525 ins_at_eol = FALSE;
527 else
528 arrow_used = FALSE;
530 /* we are in insert mode now, don't need to start it anymore */
531 need_start_insertmode = FALSE;
533 /* Need to save the line for undo before inserting the first char. */
534 ins_need_undo = TRUE;
536 #ifdef FEAT_MOUSE
537 where_paste_started.lnum = 0;
538 #endif
539 #ifdef FEAT_CINDENT
540 can_cindent = TRUE;
541 #endif
542 #ifdef FEAT_FOLDING
543 /* The cursor line is not in a closed fold, unless 'insertmode' is set or
544 * restarting. */
545 if (!p_im && did_restart_edit == 0)
546 foldOpenCursor();
547 #endif
550 * If 'showmode' is set, show the current (insert/replace/..) mode.
551 * A warning message for changing a readonly file is given here, before
552 * actually changing anything. It's put after the mode, if any.
554 i = 0;
555 if (p_smd && msg_silent == 0)
556 i = showmode();
558 if (!p_im && did_restart_edit == 0)
559 change_warning(i == 0 ? 0 : i + 1);
561 #ifdef CURSOR_SHAPE
562 ui_cursor_shape(); /* may show different cursor shape */
563 #endif
564 #ifdef FEAT_DIGRAPHS
565 do_digraph(-1); /* clear digraphs */
566 #endif
569 * Get the current length of the redo buffer, those characters have to be
570 * skipped if we want to get to the inserted characters.
572 ptr = get_inserted();
573 if (ptr == NULL)
574 new_insert_skip = 0;
575 else
577 new_insert_skip = (int)STRLEN(ptr);
578 vim_free(ptr);
581 old_indent = 0;
584 * Main loop in Insert mode: repeat until Insert mode is left.
586 for (;;)
588 #ifdef FEAT_RIGHTLEFT
589 if (!revins_legal)
590 revins_scol = -1; /* reset on illegal motions */
591 else
592 revins_legal = 0;
593 #endif
594 if (arrow_used) /* don't repeat insert when arrow key used */
595 count = 0;
597 if (stop_insert_mode)
599 /* ":stopinsert" used or 'insertmode' reset */
600 count = 0;
601 goto doESCkey;
604 /* set curwin->w_curswant for next K_DOWN or K_UP */
605 if (!arrow_used)
606 curwin->w_set_curswant = TRUE;
608 /* If there is no typeahead may check for timestamps (e.g., for when a
609 * menu invoked a shell command). */
610 if (stuff_empty())
612 did_check_timestamps = FALSE;
613 if (need_check_timestamps)
614 check_timestamps(FALSE);
618 * When emsg() was called msg_scroll will have been set.
620 msg_scroll = FALSE;
622 #ifdef FEAT_GUI
623 /* When 'mousefocus' is set a mouse movement may have taken us to
624 * another window. "need_mouse_correct" may then be set because of an
625 * autocommand. */
626 if (need_mouse_correct)
627 gui_mouse_correct();
628 #endif
630 #ifdef FEAT_FOLDING
631 /* Open fold at the cursor line, according to 'foldopen'. */
632 if (fdo_flags & FDO_INSERT)
633 foldOpenCursor();
634 /* Close folds where the cursor isn't, according to 'foldclose' */
635 if (!char_avail())
636 foldCheckClose();
637 #endif
640 * If we inserted a character at the last position of the last line in
641 * the window, scroll the window one line up. This avoids an extra
642 * redraw.
643 * This is detected when the cursor column is smaller after inserting
644 * something.
645 * Don't do this when the topline changed already, it has
646 * already been adjusted (by insertchar() calling open_line())).
648 if (curbuf->b_mod_set
649 && curwin->w_p_wrap
650 && !did_backspace
651 && curwin->w_topline == old_topline
652 #ifdef FEAT_DIFF
653 && curwin->w_topfill == old_topfill
654 #endif
657 mincol = curwin->w_wcol;
658 validate_cursor_col();
660 if (
661 #ifdef FEAT_VARTABS
662 (int)curwin->w_wcol < mincol
663 - tabstop_at(get_nolist_virtcol(), curbuf->b_p_ts, curbuf->b_p_vts_ary)
664 #else
665 (int)curwin->w_wcol < mincol - curbuf->b_p_ts
666 #endif
667 && curwin->w_wrow == W_WINROW(curwin)
668 + curwin->w_height - 1 - p_so
669 && (curwin->w_cursor.lnum != curwin->w_topline
670 #ifdef FEAT_DIFF
671 || curwin->w_topfill > 0
672 #endif
675 #ifdef FEAT_DIFF
676 if (curwin->w_topfill > 0)
677 --curwin->w_topfill;
678 else
679 #endif
680 #ifdef FEAT_FOLDING
681 if (hasFolding(curwin->w_topline, NULL, &old_topline))
682 set_topline(curwin, old_topline + 1);
683 else
684 #endif
685 set_topline(curwin, curwin->w_topline + 1);
689 /* May need to adjust w_topline to show the cursor. */
690 update_topline();
692 did_backspace = FALSE;
694 validate_cursor(); /* may set must_redraw */
697 * Redraw the display when no characters are waiting.
698 * Also shows mode, ruler and positions cursor.
700 ins_redraw(TRUE);
702 #ifdef FEAT_SCROLLBIND
703 if (curwin->w_p_scb)
704 do_check_scrollbind(TRUE);
705 #endif
707 update_curswant();
708 old_topline = curwin->w_topline;
709 #ifdef FEAT_DIFF
710 old_topfill = curwin->w_topfill;
711 #endif
713 #ifdef USE_ON_FLY_SCROLL
714 dont_scroll = FALSE; /* allow scrolling here */
715 #endif
718 * Get a character for Insert mode. Ignore K_IGNORE.
720 lastc = c; /* remember previous char for CTRL-D */
723 c = safe_vgetc();
724 } while (c == K_IGNORE);
726 #ifdef FEAT_AUTOCMD
727 /* Don't want K_CURSORHOLD for the second key, e.g., after CTRL-V. */
728 did_cursorhold = TRUE;
729 #endif
731 #ifdef FEAT_RIGHTLEFT
732 if (p_hkmap && KeyTyped)
733 c = hkmap(c); /* Hebrew mode mapping */
734 #endif
735 #ifdef FEAT_FKMAP
736 if (p_fkmap && KeyTyped)
737 c = fkmap(c); /* Farsi mode mapping */
738 #endif
740 #ifdef FEAT_INS_EXPAND
742 * Special handling of keys while the popup menu is visible or wanted
743 * and the cursor is still in the completed word. Only when there is
744 * a match, skip this when no matches were found.
746 if (compl_started
747 && pum_wanted()
748 && curwin->w_cursor.col >= compl_col
749 && (compl_shown_match == NULL
750 || compl_shown_match != compl_shown_match->cp_next))
752 /* BS: Delete one character from "compl_leader". */
753 if ((c == K_BS || c == Ctrl_H)
754 && curwin->w_cursor.col > compl_col
755 && (c = ins_compl_bs()) == NUL)
756 continue;
758 /* When no match was selected or it was edited. */
759 if (!compl_used_match)
761 /* CTRL-L: Add one character from the current match to
762 * "compl_leader". Except when at the original match and
763 * there is nothing to add, CTRL-L works like CTRL-P then. */
764 if (c == Ctrl_L
765 && (ctrl_x_mode != CTRL_X_WHOLE_LINE
766 || (int)STRLEN(compl_shown_match->cp_str)
767 > curwin->w_cursor.col - compl_col))
769 ins_compl_addfrommatch();
770 continue;
773 /* A non-white character that fits in with the current
774 * completion: Add to "compl_leader". */
775 if (ins_compl_accept_char(c))
777 ins_compl_addleader(c);
778 continue;
781 /* Pressing CTRL-Y selects the current match. When
782 * compl_enter_selects is set the Enter key does the same. */
783 if (c == Ctrl_Y || (compl_enter_selects
784 && (c == CAR || c == K_KENTER || c == NL)))
786 ins_compl_delete();
787 ins_compl_insert();
792 /* Prepare for or stop CTRL-X mode. This doesn't do completion, but
793 * it does fix up the text when finishing completion. */
794 compl_get_longest = FALSE;
795 if (ins_compl_prep(c))
796 continue;
797 #endif
799 /* CTRL-\ CTRL-N goes to Normal mode,
800 * CTRL-\ CTRL-G goes to mode selected with 'insertmode',
801 * CTRL-\ CTRL-O is like CTRL-O but without moving the cursor. */
802 if (c == Ctrl_BSL)
804 /* may need to redraw when no more chars available now */
805 ins_redraw(FALSE);
806 ++no_mapping;
807 ++allow_keys;
808 c = plain_vgetc();
809 --no_mapping;
810 --allow_keys;
811 if (c != Ctrl_N && c != Ctrl_G && c != Ctrl_O)
813 /* it's something else */
814 vungetc(c);
815 c = Ctrl_BSL;
817 else if (c == Ctrl_G && p_im)
818 continue;
819 else
821 if (c == Ctrl_O)
823 ins_ctrl_o();
824 ins_at_eol = FALSE; /* cursor keeps its column */
825 nomove = TRUE;
827 count = 0;
828 goto doESCkey;
832 #ifdef FEAT_DIGRAPHS
833 c = do_digraph(c);
834 #endif
836 #ifdef FEAT_INS_EXPAND
837 if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
838 goto docomplete;
839 #endif
840 if (c == Ctrl_V || c == Ctrl_Q)
842 ins_ctrl_v();
843 c = Ctrl_V; /* pretend CTRL-V is last typed character */
844 continue;
847 #ifdef FEAT_CINDENT
848 if (cindent_on()
849 # ifdef FEAT_INS_EXPAND
850 && ctrl_x_mode == 0
851 # endif
854 /* A key name preceded by a bang means this key is not to be
855 * inserted. Skip ahead to the re-indenting below.
856 * A key name preceded by a star means that indenting has to be
857 * done before inserting the key. */
858 line_is_white = inindent(0);
859 if (in_cinkeys(c, '!', line_is_white))
860 goto force_cindent;
861 if (can_cindent && in_cinkeys(c, '*', line_is_white)
862 && stop_arrow() == OK)
863 do_c_expr_indent();
865 #endif
867 #ifdef FEAT_RIGHTLEFT
868 if (curwin->w_p_rl)
869 switch (c)
871 case K_LEFT: c = K_RIGHT; break;
872 case K_S_LEFT: c = K_S_RIGHT; break;
873 case K_C_LEFT: c = K_C_RIGHT; break;
874 case K_RIGHT: c = K_LEFT; break;
875 case K_S_RIGHT: c = K_S_LEFT; break;
876 case K_C_RIGHT: c = K_C_LEFT; break;
878 #endif
880 #ifdef FEAT_VISUAL
882 * If 'keymodel' contains "startsel", may start selection. If it
883 * does, a CTRL-O and c will be stuffed, we need to get these
884 * characters.
886 if (ins_start_select(c))
887 continue;
888 #endif
891 * The big switch to handle a character in insert mode.
893 switch (c)
895 case ESC: /* End input mode */
896 if (echeck_abbr(ESC + ABBR_OFF))
897 break;
898 /*FALLTHROUGH*/
900 case Ctrl_C: /* End input mode */
901 #ifdef FEAT_CMDWIN
902 if (c == Ctrl_C && cmdwin_type != 0)
904 /* Close the cmdline window. */
905 cmdwin_result = K_IGNORE;
906 got_int = FALSE; /* don't stop executing autocommands et al. */
907 nomove = TRUE;
908 goto doESCkey;
910 #endif
912 #ifdef UNIX
913 do_intr:
914 #endif
915 /* when 'insertmode' set, and not halfway a mapping, don't leave
916 * Insert mode */
917 if (goto_im())
919 if (got_int)
921 (void)vgetc(); /* flush all buffers */
922 got_int = FALSE;
924 else
925 vim_beep();
926 break;
928 doESCkey:
930 * This is the ONLY return from edit()!
932 /* Always update o_lnum, so that a "CTRL-O ." that adds a line
933 * still puts the cursor back after the inserted text. */
934 if (ins_at_eol && gchar_cursor() == NUL)
935 o_lnum = curwin->w_cursor.lnum;
937 if (ins_esc(&count, cmdchar, nomove))
939 #ifdef FEAT_AUTOCMD
940 if (cmdchar != 'r' && cmdchar != 'v')
941 apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
942 FALSE, curbuf);
943 did_cursorhold = FALSE;
944 #endif
945 return (c == Ctrl_O);
947 continue;
949 case Ctrl_Z: /* suspend when 'insertmode' set */
950 if (!p_im)
951 goto normalchar; /* insert CTRL-Z as normal char */
952 stuffReadbuff((char_u *)":st\r");
953 c = Ctrl_O;
954 /*FALLTHROUGH*/
956 case Ctrl_O: /* execute one command */
957 #ifdef FEAT_COMPL_FUNC
958 if (ctrl_x_mode == CTRL_X_OMNI)
959 goto docomplete;
960 #endif
961 if (echeck_abbr(Ctrl_O + ABBR_OFF))
962 break;
963 ins_ctrl_o();
965 #ifdef FEAT_VIRTUALEDIT
966 /* don't move the cursor left when 'virtualedit' has "onemore". */
967 if (ve_flags & VE_ONEMORE)
969 ins_at_eol = FALSE;
970 nomove = TRUE;
972 #endif
973 count = 0;
974 goto doESCkey;
976 case K_INS: /* toggle insert/replace mode */
977 case K_KINS:
978 ins_insert(replaceState);
979 break;
981 case K_SELECT: /* end of Select mode mapping - ignore */
982 break;
984 #ifdef FEAT_SNIFF
985 case K_SNIFF: /* Sniff command received */
986 stuffcharReadbuff(K_SNIFF);
987 goto doESCkey;
988 #endif
990 case K_HELP: /* Help key works like <ESC> <Help> */
991 case K_F1:
992 case K_XF1:
993 stuffcharReadbuff(K_HELP);
994 if (p_im)
995 need_start_insertmode = TRUE;
996 goto doESCkey;
998 #ifdef FEAT_NETBEANS_INTG
999 case K_F21: /* NetBeans command */
1000 ++no_mapping; /* don't map the next key hits */
1001 i = plain_vgetc();
1002 --no_mapping;
1003 netbeans_keycommand(i);
1004 break;
1005 #endif
1007 case K_ZERO: /* Insert the previously inserted text. */
1008 case NUL:
1009 case Ctrl_A:
1010 /* For ^@ the trailing ESC will end the insert, unless there is an
1011 * error. */
1012 if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
1013 && c != Ctrl_A && !p_im)
1014 goto doESCkey; /* quit insert mode */
1015 inserted_space = FALSE;
1016 break;
1018 case Ctrl_R: /* insert the contents of a register */
1019 ins_reg();
1020 auto_format(FALSE, TRUE);
1021 inserted_space = FALSE;
1022 break;
1024 case Ctrl_G: /* commands starting with CTRL-G */
1025 ins_ctrl_g();
1026 break;
1028 case Ctrl_HAT: /* switch input mode and/or langmap */
1029 ins_ctrl_hat();
1030 break;
1032 #ifdef FEAT_RIGHTLEFT
1033 case Ctrl__: /* switch between languages */
1034 if (!p_ari)
1035 goto normalchar;
1036 ins_ctrl_();
1037 break;
1038 #endif
1040 case Ctrl_D: /* Make indent one shiftwidth smaller. */
1041 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1042 if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
1043 goto docomplete;
1044 #endif
1045 /* FALLTHROUGH */
1047 case Ctrl_T: /* Make indent one shiftwidth greater. */
1048 # ifdef FEAT_INS_EXPAND
1049 if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
1051 if (has_compl_option(FALSE))
1052 goto docomplete;
1053 break;
1055 # endif
1056 ins_shift(c, lastc);
1057 auto_format(FALSE, TRUE);
1058 inserted_space = FALSE;
1059 break;
1061 case K_DEL: /* delete character under the cursor */
1062 case K_KDEL:
1063 ins_del();
1064 auto_format(FALSE, TRUE);
1065 break;
1067 case K_BS: /* delete character before the cursor */
1068 case Ctrl_H:
1069 did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1070 auto_format(FALSE, TRUE);
1071 break;
1073 case Ctrl_W: /* delete word before the cursor */
1074 did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1075 auto_format(FALSE, TRUE);
1076 break;
1078 case Ctrl_U: /* delete all inserted text in current line */
1079 # ifdef FEAT_COMPL_FUNC
1080 /* CTRL-X CTRL-U completes with 'completefunc'. */
1081 if (ctrl_x_mode == CTRL_X_FUNCTION)
1082 goto docomplete;
1083 # endif
1084 did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1085 auto_format(FALSE, TRUE);
1086 inserted_space = FALSE;
1087 break;
1089 #ifdef FEAT_MOUSE
1090 case K_LEFTMOUSE: /* mouse keys */
1091 case K_LEFTMOUSE_NM:
1092 case K_LEFTDRAG:
1093 case K_LEFTRELEASE:
1094 case K_LEFTRELEASE_NM:
1095 case K_MIDDLEMOUSE:
1096 case K_MIDDLEDRAG:
1097 case K_MIDDLERELEASE:
1098 case K_RIGHTMOUSE:
1099 case K_RIGHTDRAG:
1100 case K_RIGHTRELEASE:
1101 case K_X1MOUSE:
1102 case K_X1DRAG:
1103 case K_X1RELEASE:
1104 case K_X2MOUSE:
1105 case K_X2DRAG:
1106 case K_X2RELEASE:
1107 ins_mouse(c);
1108 break;
1110 case K_MOUSEDOWN: /* Default action for scroll wheel up: scroll up */
1111 ins_mousescroll(FALSE);
1112 break;
1114 case K_MOUSEUP: /* Default action for scroll wheel down: scroll down */
1115 ins_mousescroll(TRUE);
1116 break;
1117 #endif
1118 #ifdef FEAT_GUI_TABLINE
1119 case K_TABLINE:
1120 case K_TABMENU:
1121 ins_tabline(c);
1122 break;
1123 #endif
1125 case K_IGNORE: /* Something mapped to nothing */
1126 break;
1128 #ifdef FEAT_AUTOCMD
1129 case K_CURSORHOLD: /* Didn't type something for a while. */
1130 apply_autocmds(EVENT_CURSORHOLDI, NULL, NULL, FALSE, curbuf);
1131 did_cursorhold = TRUE;
1132 break;
1133 #endif
1135 #ifdef FEAT_GUI_W32
1136 /* On Win32 ignore <M-F4>, we get it when closing the window was
1137 * cancelled. */
1138 case K_F4:
1139 if (mod_mask != MOD_MASK_ALT)
1140 goto normalchar;
1141 break;
1142 #endif
1144 #ifdef FEAT_GUI
1145 case K_VER_SCROLLBAR:
1146 ins_scroll();
1147 break;
1149 case K_HOR_SCROLLBAR:
1150 ins_horscroll();
1151 break;
1152 #endif
1154 case K_HOME: /* <Home> */
1155 case K_KHOME:
1156 case K_S_HOME:
1157 case K_C_HOME:
1158 ins_home(c);
1159 break;
1161 case K_END: /* <End> */
1162 case K_KEND:
1163 case K_S_END:
1164 case K_C_END:
1165 ins_end(c);
1166 break;
1168 case K_LEFT: /* <Left> */
1169 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1170 ins_s_left();
1171 else
1172 ins_left();
1173 break;
1175 case K_S_LEFT: /* <S-Left> */
1176 case K_C_LEFT:
1177 ins_s_left();
1178 break;
1180 case K_RIGHT: /* <Right> */
1181 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1182 ins_s_right();
1183 else
1184 ins_right();
1185 break;
1187 case K_S_RIGHT: /* <S-Right> */
1188 case K_C_RIGHT:
1189 ins_s_right();
1190 break;
1192 case K_UP: /* <Up> */
1193 #ifdef FEAT_INS_EXPAND
1194 if (pum_visible())
1195 goto docomplete;
1196 #endif
1197 if (mod_mask & MOD_MASK_SHIFT)
1198 ins_pageup();
1199 else
1200 ins_up(FALSE);
1201 break;
1203 case K_S_UP: /* <S-Up> */
1204 case K_PAGEUP:
1205 case K_KPAGEUP:
1206 #ifdef FEAT_INS_EXPAND
1207 if (pum_visible())
1208 goto docomplete;
1209 #endif
1210 ins_pageup();
1211 break;
1213 case K_DOWN: /* <Down> */
1214 #ifdef FEAT_INS_EXPAND
1215 if (pum_visible())
1216 goto docomplete;
1217 #endif
1218 if (mod_mask & MOD_MASK_SHIFT)
1219 ins_pagedown();
1220 else
1221 ins_down(FALSE);
1222 break;
1224 case K_S_DOWN: /* <S-Down> */
1225 case K_PAGEDOWN:
1226 case K_KPAGEDOWN:
1227 #ifdef FEAT_INS_EXPAND
1228 if (pum_visible())
1229 goto docomplete;
1230 #endif
1231 ins_pagedown();
1232 break;
1234 #ifdef FEAT_DND
1235 case K_DROP: /* drag-n-drop event */
1236 ins_drop();
1237 break;
1238 #endif
1240 case K_S_TAB: /* When not mapped, use like a normal TAB */
1241 c = TAB;
1242 /* FALLTHROUGH */
1244 case TAB: /* TAB or Complete patterns along path */
1245 #if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1246 if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1247 goto docomplete;
1248 #endif
1249 inserted_space = FALSE;
1250 if (ins_tab())
1251 goto normalchar; /* insert TAB as a normal char */
1252 auto_format(FALSE, TRUE);
1253 break;
1255 case K_KENTER: /* <Enter> */
1256 c = CAR;
1257 /* FALLTHROUGH */
1258 case CAR:
1259 case NL:
1260 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1261 /* In a quickfix window a <CR> jumps to the error under the
1262 * cursor. */
1263 if (bt_quickfix(curbuf) && c == CAR)
1265 if (curwin->w_llist_ref == NULL) /* quickfix window */
1266 do_cmdline_cmd((char_u *)".cc");
1267 else /* location list window */
1268 do_cmdline_cmd((char_u *)".ll");
1269 break;
1271 #endif
1272 #ifdef FEAT_CMDWIN
1273 if (cmdwin_type != 0)
1275 /* Execute the command in the cmdline window. */
1276 cmdwin_result = CAR;
1277 goto doESCkey;
1279 #endif
1280 if (ins_eol(c) && !p_im)
1281 goto doESCkey; /* out of memory */
1282 auto_format(FALSE, FALSE);
1283 inserted_space = FALSE;
1284 break;
1286 #if defined(FEAT_DIGRAPHS) || defined (FEAT_INS_EXPAND)
1287 case Ctrl_K: /* digraph or keyword completion */
1288 # ifdef FEAT_INS_EXPAND
1289 if (ctrl_x_mode == CTRL_X_DICTIONARY)
1291 if (has_compl_option(TRUE))
1292 goto docomplete;
1293 break;
1295 # endif
1296 # ifdef FEAT_DIGRAPHS
1297 c = ins_digraph();
1298 if (c == NUL)
1299 break;
1300 # endif
1301 goto normalchar;
1302 #endif
1304 #ifdef FEAT_INS_EXPAND
1305 case Ctrl_X: /* Enter CTRL-X mode */
1306 ins_ctrl_x();
1307 break;
1309 case Ctrl_RSB: /* Tag name completion after ^X */
1310 if (ctrl_x_mode != CTRL_X_TAGS)
1311 goto normalchar;
1312 goto docomplete;
1314 case Ctrl_F: /* File name completion after ^X */
1315 if (ctrl_x_mode != CTRL_X_FILES)
1316 goto normalchar;
1317 goto docomplete;
1319 case 's': /* Spelling completion after ^X */
1320 case Ctrl_S:
1321 if (ctrl_x_mode != CTRL_X_SPELL)
1322 goto normalchar;
1323 goto docomplete;
1324 #endif
1326 case Ctrl_L: /* Whole line completion after ^X */
1327 #ifdef FEAT_INS_EXPAND
1328 if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1329 #endif
1331 /* CTRL-L with 'insertmode' set: Leave Insert mode */
1332 if (p_im)
1334 if (echeck_abbr(Ctrl_L + ABBR_OFF))
1335 break;
1336 goto doESCkey;
1338 goto normalchar;
1340 #ifdef FEAT_INS_EXPAND
1341 /* FALLTHROUGH */
1343 case Ctrl_P: /* Do previous/next pattern completion */
1344 case Ctrl_N:
1345 /* if 'complete' is empty then plain ^P is no longer special,
1346 * but it is under other ^X modes */
1347 if (*curbuf->b_p_cpt == NUL
1348 && ctrl_x_mode != 0
1349 && !(compl_cont_status & CONT_LOCAL))
1350 goto normalchar;
1352 docomplete:
1353 compl_busy = TRUE;
1354 if (ins_complete(c) == FAIL)
1355 compl_cont_status = 0;
1356 compl_busy = FALSE;
1357 break;
1358 #endif /* FEAT_INS_EXPAND */
1360 case Ctrl_Y: /* copy from previous line or scroll down */
1361 case Ctrl_E: /* copy from next line or scroll up */
1362 c = ins_ctrl_ey(c);
1363 break;
1365 default:
1366 #ifdef UNIX
1367 if (c == intr_char) /* special interrupt char */
1368 goto do_intr;
1369 #endif
1372 * Insert a nomal character.
1374 normalchar:
1375 #ifdef FEAT_SMARTINDENT
1376 /* Try to perform smart-indenting. */
1377 ins_try_si(c);
1378 #endif
1380 if (c == ' ')
1382 inserted_space = TRUE;
1383 #ifdef FEAT_CINDENT
1384 if (inindent(0))
1385 can_cindent = FALSE;
1386 #endif
1387 if (Insstart_blank_vcol == MAXCOL
1388 && curwin->w_cursor.lnum == Insstart.lnum)
1389 Insstart_blank_vcol = get_nolist_virtcol();
1392 if (vim_iswordc(c) || !echeck_abbr(
1393 #ifdef FEAT_MBYTE
1394 /* Add ABBR_OFF for characters above 0x100, this is
1395 * what check_abbr() expects. */
1396 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1397 #endif
1400 insert_special(c, FALSE, FALSE);
1401 #ifdef FEAT_RIGHTLEFT
1402 revins_legal++;
1403 revins_chars++;
1404 #endif
1407 auto_format(FALSE, TRUE);
1409 #ifdef FEAT_FOLDING
1410 /* When inserting a character the cursor line must never be in a
1411 * closed fold. */
1412 foldOpenCursor();
1413 #endif
1414 break;
1415 } /* end of switch (c) */
1417 #ifdef FEAT_AUTOCMD
1418 /* If typed something may trigger CursorHoldI again. */
1419 if (c != K_CURSORHOLD)
1420 did_cursorhold = FALSE;
1421 #endif
1423 /* If the cursor was moved we didn't just insert a space */
1424 if (arrow_used)
1425 inserted_space = FALSE;
1427 #ifdef FEAT_CINDENT
1428 if (can_cindent && cindent_on()
1429 # ifdef FEAT_INS_EXPAND
1430 && ctrl_x_mode == 0
1431 # endif
1434 force_cindent:
1436 * Indent now if a key was typed that is in 'cinkeys'.
1438 if (in_cinkeys(c, ' ', line_is_white))
1440 if (stop_arrow() == OK)
1441 /* re-indent the current line */
1442 do_c_expr_indent();
1445 #endif /* FEAT_CINDENT */
1447 } /* for (;;) */
1448 /* NOTREACHED */
1452 * Redraw for Insert mode.
1453 * This is postponed until getting the next character to make '$' in the 'cpo'
1454 * option work correctly.
1455 * Only redraw when there are no characters available. This speeds up
1456 * inserting sequences of characters (e.g., for CTRL-R).
1458 static void
1459 ins_redraw(ready)
1460 int ready UNUSED; /* not busy with something */
1462 if (!char_avail())
1464 #ifdef FEAT_AUTOCMD
1465 /* Trigger CursorMoved if the cursor moved. Not when the popup menu is
1466 * visible, the command might delete it. */
1467 if (ready && has_cursormovedI()
1468 && !equalpos(last_cursormoved, curwin->w_cursor)
1469 # ifdef FEAT_INS_EXPAND
1470 && !pum_visible()
1471 # endif
1474 # ifdef FEAT_SYN_HL
1475 /* Need to update the screen first, to make sure syntax
1476 * highlighting is correct after making a change (e.g., inserting
1477 * a "(". The autocommand may also require a redraw, so it's done
1478 * again below, unfortunately. */
1479 if (syntax_present(curbuf) && must_redraw)
1480 update_screen(0);
1481 # endif
1482 apply_autocmds(EVENT_CURSORMOVEDI, NULL, NULL, FALSE, curbuf);
1483 last_cursormoved = curwin->w_cursor;
1485 #endif
1486 if (must_redraw)
1487 update_screen(0);
1488 else if (clear_cmdline || redraw_cmdline)
1489 showmode(); /* clear cmdline and show mode */
1490 showruler(FALSE);
1491 setcursor();
1492 emsg_on_display = FALSE; /* may remove error message now */
1497 * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1499 static void
1500 ins_ctrl_v()
1502 int c;
1504 /* may need to redraw when no more chars available now */
1505 ins_redraw(FALSE);
1507 if (redrawing() && !char_avail())
1508 edit_putchar('^', TRUE);
1509 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1511 #ifdef FEAT_CMDL_INFO
1512 add_to_showcmd_c(Ctrl_V);
1513 #endif
1515 c = get_literal();
1516 #ifdef FEAT_CMDL_INFO
1517 clear_showcmd();
1518 #endif
1519 insert_special(c, FALSE, TRUE);
1520 #ifdef FEAT_RIGHTLEFT
1521 revins_chars++;
1522 revins_legal++;
1523 #endif
1527 * Put a character directly onto the screen. It's not stored in a buffer.
1528 * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1530 static int pc_status;
1531 #define PC_STATUS_UNSET 0 /* pc_bytes was not set */
1532 #define PC_STATUS_RIGHT 1 /* right halve of double-wide char */
1533 #define PC_STATUS_LEFT 2 /* left halve of double-wide char */
1534 #define PC_STATUS_SET 3 /* pc_bytes was filled */
1535 #ifdef FEAT_MBYTE
1536 static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1537 #else
1538 static char_u pc_bytes[2]; /* saved bytes */
1539 #endif
1540 static int pc_attr;
1541 static int pc_row;
1542 static int pc_col;
1544 void
1545 edit_putchar(c, highlight)
1546 int c;
1547 int highlight;
1549 int attr;
1551 if (ScreenLines != NULL)
1553 update_topline(); /* just in case w_topline isn't valid */
1554 validate_cursor();
1555 if (highlight)
1556 attr = hl_attr(HLF_8);
1557 else
1558 attr = 0;
1559 pc_row = W_WINROW(curwin) + curwin->w_wrow;
1560 pc_col = W_WINCOL(curwin);
1561 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1562 pc_status = PC_STATUS_UNSET;
1563 #endif
1564 #ifdef FEAT_RIGHTLEFT
1565 if (curwin->w_p_rl)
1567 pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1568 # ifdef FEAT_MBYTE
1569 if (has_mbyte)
1571 int fix_col = mb_fix_col(pc_col, pc_row);
1573 if (fix_col != pc_col)
1575 screen_putchar(' ', pc_row, fix_col, attr);
1576 --curwin->w_wcol;
1577 pc_status = PC_STATUS_RIGHT;
1580 # endif
1582 else
1583 #endif
1585 pc_col += curwin->w_wcol;
1586 #ifdef FEAT_MBYTE
1587 if (mb_lefthalve(pc_row, pc_col))
1588 pc_status = PC_STATUS_LEFT;
1589 #endif
1592 /* save the character to be able to put it back */
1593 #if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1594 if (pc_status == PC_STATUS_UNSET)
1595 #endif
1597 screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1598 pc_status = PC_STATUS_SET;
1600 screen_putchar(c, pc_row, pc_col, attr);
1605 * Undo the previous edit_putchar().
1607 void
1608 edit_unputchar()
1610 if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1612 #if defined(FEAT_MBYTE)
1613 if (pc_status == PC_STATUS_RIGHT)
1614 ++curwin->w_wcol;
1615 if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1616 redrawWinline(curwin->w_cursor.lnum, FALSE);
1617 else
1618 #endif
1619 screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1624 * Called when p_dollar is set: display a '$' at the end of the changed text
1625 * Only works when cursor is in the line that changes.
1627 void
1628 display_dollar(col)
1629 colnr_T col;
1631 colnr_T save_col;
1633 if (!redrawing())
1634 return;
1636 cursor_off();
1637 save_col = curwin->w_cursor.col;
1638 curwin->w_cursor.col = col;
1639 #ifdef FEAT_MBYTE
1640 if (has_mbyte)
1642 char_u *p;
1644 /* If on the last byte of a multi-byte move to the first byte. */
1645 p = ml_get_curline();
1646 curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1648 #endif
1649 curs_columns(FALSE); /* recompute w_wrow and w_wcol */
1650 if (curwin->w_wcol < W_WIDTH(curwin))
1652 edit_putchar('$', FALSE);
1653 dollar_vcol = curwin->w_virtcol;
1655 curwin->w_cursor.col = save_col;
1659 * Call this function before moving the cursor from the normal insert position
1660 * in insert mode.
1662 static void
1663 undisplay_dollar()
1665 if (dollar_vcol)
1667 dollar_vcol = 0;
1668 redrawWinline(curwin->w_cursor.lnum, FALSE);
1673 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1674 * Keep the cursor on the same character.
1675 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1676 * type == INDENT_DEC decrease indent (for CTRL-D)
1677 * type == INDENT_SET set indent to "amount"
1678 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1680 void
1681 change_indent(type, amount, round, replaced, call_changed_bytes)
1682 int type;
1683 int amount;
1684 int round;
1685 int replaced; /* replaced character, put on replace stack */
1686 int call_changed_bytes; /* call changed_bytes() */
1688 int vcol;
1689 int last_vcol;
1690 int insstart_less; /* reduction for Insstart.col */
1691 int new_cursor_col;
1692 int i;
1693 char_u *ptr;
1694 int save_p_list;
1695 int start_col;
1696 colnr_T vc;
1697 #ifdef FEAT_VREPLACE
1698 colnr_T orig_col = 0; /* init for GCC */
1699 char_u *new_line, *orig_line = NULL; /* init for GCC */
1701 /* VREPLACE mode needs to know what the line was like before changing */
1702 if (State & VREPLACE_FLAG)
1704 orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */
1705 orig_col = curwin->w_cursor.col;
1707 #endif
1709 /* for the following tricks we don't want list mode */
1710 save_p_list = curwin->w_p_list;
1711 curwin->w_p_list = FALSE;
1712 vc = getvcol_nolist(&curwin->w_cursor);
1713 vcol = vc;
1716 * For Replace mode we need to fix the replace stack later, which is only
1717 * possible when the cursor is in the indent. Remember the number of
1718 * characters before the cursor if it's possible.
1720 start_col = curwin->w_cursor.col;
1722 /* determine offset from first non-blank */
1723 new_cursor_col = curwin->w_cursor.col;
1724 beginline(BL_WHITE);
1725 new_cursor_col -= curwin->w_cursor.col;
1727 insstart_less = curwin->w_cursor.col;
1730 * If the cursor is in the indent, compute how many screen columns the
1731 * cursor is to the left of the first non-blank.
1733 if (new_cursor_col < 0)
1734 vcol = get_indent() - vcol;
1736 if (new_cursor_col > 0) /* can't fix replace stack */
1737 start_col = -1;
1740 * Set the new indent. The cursor will be put on the first non-blank.
1742 if (type == INDENT_SET)
1743 (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
1744 else
1746 #ifdef FEAT_VREPLACE
1747 int save_State = State;
1749 /* Avoid being called recursively. */
1750 if (State & VREPLACE_FLAG)
1751 State = INSERT;
1752 #endif
1753 shift_line(type == INDENT_DEC, round, 1, call_changed_bytes);
1754 #ifdef FEAT_VREPLACE
1755 State = save_State;
1756 #endif
1758 insstart_less -= curwin->w_cursor.col;
1761 * Try to put cursor on same character.
1762 * If the cursor is at or after the first non-blank in the line,
1763 * compute the cursor column relative to the column of the first
1764 * non-blank character.
1765 * If we are not in insert mode, leave the cursor on the first non-blank.
1766 * If the cursor is before the first non-blank, position it relative
1767 * to the first non-blank, counted in screen columns.
1769 if (new_cursor_col >= 0)
1772 * When changing the indent while the cursor is touching it, reset
1773 * Insstart_col to 0.
1775 if (new_cursor_col == 0)
1776 insstart_less = MAXCOL;
1777 new_cursor_col += curwin->w_cursor.col;
1779 else if (!(State & INSERT))
1780 new_cursor_col = curwin->w_cursor.col;
1781 else
1784 * Compute the screen column where the cursor should be.
1786 vcol = get_indent() - vcol;
1787 curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);
1790 * Advance the cursor until we reach the right screen column.
1792 vcol = last_vcol = 0;
1793 new_cursor_col = -1;
1794 ptr = ml_get_curline();
1795 while (vcol <= (int)curwin->w_virtcol)
1797 last_vcol = vcol;
1798 #ifdef FEAT_MBYTE
1799 if (has_mbyte && new_cursor_col >= 0)
1800 new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1801 else
1802 #endif
1803 ++new_cursor_col;
1804 vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol, curwin->w_cursor.lnum);
1806 vcol = last_vcol;
1809 * May need to insert spaces to be able to position the cursor on
1810 * the right screen column.
1812 if (vcol != (int)curwin->w_virtcol)
1814 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1815 i = (int)curwin->w_virtcol - vcol;
1816 ptr = alloc((unsigned)(i + 1));
1817 if (ptr != NULL)
1819 new_cursor_col += i;
1820 ptr[i] = NUL;
1821 while (--i >= 0)
1822 ptr[i] = ' ';
1823 ins_str(ptr);
1824 vim_free(ptr);
1829 * When changing the indent while the cursor is in it, reset
1830 * Insstart_col to 0.
1832 insstart_less = MAXCOL;
1835 curwin->w_p_list = save_p_list;
1837 if (new_cursor_col <= 0)
1838 curwin->w_cursor.col = 0;
1839 else
1840 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1841 curwin->w_set_curswant = TRUE;
1842 changed_cline_bef_curs();
1845 * May have to adjust the start of the insert.
1847 if (State & INSERT)
1849 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1851 if ((int)Insstart.col <= insstart_less)
1852 Insstart.col = 0;
1853 else
1854 Insstart.col -= insstart_less;
1856 if ((int)ai_col <= insstart_less)
1857 ai_col = 0;
1858 else
1859 ai_col -= insstart_less;
1863 * For REPLACE mode, may have to fix the replace stack, if it's possible.
1864 * If the number of characters before the cursor decreased, need to pop a
1865 * few characters from the replace stack.
1866 * If the number of characters before the cursor increased, need to push a
1867 * few NULs onto the replace stack.
1869 if (REPLACE_NORMAL(State) && start_col >= 0)
1871 while (start_col > (int)curwin->w_cursor.col)
1873 replace_join(0); /* remove a NUL from the replace stack */
1874 --start_col;
1876 while (start_col < (int)curwin->w_cursor.col || replaced)
1878 replace_push(NUL);
1879 if (replaced)
1881 replace_push(replaced);
1882 replaced = NUL;
1884 ++start_col;
1888 #ifdef FEAT_VREPLACE
1890 * For VREPLACE mode, we also have to fix the replace stack. In this case
1891 * it is always possible because we backspace over the whole line and then
1892 * put it back again the way we wanted it.
1894 if (State & VREPLACE_FLAG)
1896 /* If orig_line didn't allocate, just return. At least we did the job,
1897 * even if you can't backspace. */
1898 if (orig_line == NULL)
1899 return;
1901 /* Save new line */
1902 new_line = vim_strsave(ml_get_curline());
1903 if (new_line == NULL)
1904 return;
1906 /* We only put back the new line up to the cursor */
1907 new_line[curwin->w_cursor.col] = NUL;
1909 /* Put back original line */
1910 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1911 curwin->w_cursor.col = orig_col;
1913 /* Backspace from cursor to start of line */
1914 backspace_until_column(0);
1916 /* Insert new stuff into line again */
1917 ins_bytes(new_line);
1919 vim_free(new_line);
1921 #endif
1925 * Truncate the space at the end of a line. This is to be used only in an
1926 * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE
1927 * modes.
1929 void
1930 truncate_spaces(line)
1931 char_u *line;
1933 int i;
1935 /* find start of trailing white space */
1936 for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
1938 if (State & REPLACE_FLAG)
1939 replace_join(0); /* remove a NUL from the replace stack */
1941 line[i + 1] = NUL;
1944 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1945 || defined(FEAT_COMMENTS) || defined(PROTO)
1947 * Backspace the cursor until the given column. Handles REPLACE and VREPLACE
1948 * modes correctly. May also be used when not in insert mode at all.
1949 * Will attempt not to go before "col" even when there is a composing
1950 * character.
1952 void
1953 backspace_until_column(col)
1954 int col;
1956 while ((int)curwin->w_cursor.col > col)
1958 curwin->w_cursor.col--;
1959 if (State & REPLACE_FLAG)
1960 replace_do_bs(col);
1961 else if (!del_char_after_col(col))
1962 break;
1965 #endif
1968 * Like del_char(), but make sure not to go before column "limit_col".
1969 * Only matters when there are composing characters.
1970 * Return TRUE when something was deleted.
1972 static int
1973 del_char_after_col(limit_col)
1974 int limit_col UNUSED;
1976 #ifdef FEAT_MBYTE
1977 if (enc_utf8 && limit_col >= 0)
1979 colnr_T ecol = curwin->w_cursor.col + 1;
1981 /* Make sure the cursor is at the start of a character, but
1982 * skip forward again when going too far back because of a
1983 * composing character. */
1984 mb_adjust_cursor();
1985 while (curwin->w_cursor.col < (colnr_T)limit_col)
1987 int l = utf_ptr2len(ml_get_cursor());
1989 if (l == 0) /* end of line */
1990 break;
1991 curwin->w_cursor.col += l;
1993 if (*ml_get_cursor() == NUL || curwin->w_cursor.col == ecol)
1994 return FALSE;
1995 del_bytes((long)((int)ecol - curwin->w_cursor.col), FALSE, TRUE);
1997 else
1998 #endif
1999 (void)del_char(FALSE);
2000 return TRUE;
2003 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
2005 * CTRL-X pressed in Insert mode.
2007 static void
2008 ins_ctrl_x()
2010 /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
2011 * CTRL-V works like CTRL-N */
2012 if (ctrl_x_mode != CTRL_X_CMDLINE)
2014 /* if the next ^X<> won't ADD nothing, then reset
2015 * compl_cont_status */
2016 if (compl_cont_status & CONT_N_ADDS)
2017 compl_cont_status |= CONT_INTRPT;
2018 else
2019 compl_cont_status = 0;
2020 /* We're not sure which CTRL-X mode it will be yet */
2021 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2022 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
2023 edit_submode_pre = NULL;
2024 showmode();
2029 * Return TRUE if the 'dict' or 'tsr' option can be used.
2031 static int
2032 has_compl_option(dict_opt)
2033 int dict_opt;
2035 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
2036 # ifdef FEAT_SPELL
2037 && !curwin->w_p_spell
2038 # endif
2040 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
2042 ctrl_x_mode = 0;
2043 edit_submode = NULL;
2044 msg_attr(dict_opt ? (char_u *)_("'dictionary' option is empty")
2045 : (char_u *)_("'thesaurus' option is empty"),
2046 hl_attr(HLF_E));
2047 if (emsg_silent == 0)
2049 vim_beep();
2050 setcursor();
2051 out_flush();
2052 ui_delay(2000L, FALSE);
2054 return FALSE;
2056 return TRUE;
2060 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
2061 * This depends on the current mode.
2064 vim_is_ctrl_x_key(c)
2065 int c;
2067 /* Always allow ^R - let it's results then be checked */
2068 if (c == Ctrl_R)
2069 return TRUE;
2071 /* Accept <PageUp> and <PageDown> if the popup menu is visible. */
2072 if (ins_compl_pum_key(c))
2073 return TRUE;
2075 switch (ctrl_x_mode)
2077 case 0: /* Not in any CTRL-X mode */
2078 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
2079 case CTRL_X_NOT_DEFINED_YET:
2080 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
2081 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
2082 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
2083 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
2084 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
2085 || c == Ctrl_S || c == 's');
2086 case CTRL_X_SCROLL:
2087 return (c == Ctrl_Y || c == Ctrl_E);
2088 case CTRL_X_WHOLE_LINE:
2089 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
2090 case CTRL_X_FILES:
2091 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
2092 case CTRL_X_DICTIONARY:
2093 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
2094 case CTRL_X_THESAURUS:
2095 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
2096 case CTRL_X_TAGS:
2097 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
2098 #ifdef FEAT_FIND_ID
2099 case CTRL_X_PATH_PATTERNS:
2100 return (c == Ctrl_P || c == Ctrl_N);
2101 case CTRL_X_PATH_DEFINES:
2102 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
2103 #endif
2104 case CTRL_X_CMDLINE:
2105 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
2106 || c == Ctrl_X);
2107 #ifdef FEAT_COMPL_FUNC
2108 case CTRL_X_FUNCTION:
2109 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
2110 case CTRL_X_OMNI:
2111 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
2112 #endif
2113 case CTRL_X_SPELL:
2114 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
2116 EMSG(_(e_internal));
2117 return FALSE;
2121 * Return TRUE when character "c" is part of the item currently being
2122 * completed. Used to decide whether to abandon complete mode when the menu
2123 * is visible.
2125 static int
2126 ins_compl_accept_char(c)
2127 int c;
2129 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
2130 /* When expanding an identifier only accept identifier chars. */
2131 return vim_isIDc(c);
2133 switch (ctrl_x_mode)
2135 case CTRL_X_FILES:
2136 /* When expanding file name only accept file name chars. But not
2137 * path separators, so that "proto/<Tab>" expands files in
2138 * "proto", not "proto/" as a whole */
2139 return vim_isfilec(c) && !vim_ispathsep(c);
2141 case CTRL_X_CMDLINE:
2142 case CTRL_X_OMNI:
2143 /* Command line and Omni completion can work with just about any
2144 * printable character, but do stop at white space. */
2145 return vim_isprintc(c) && !vim_iswhite(c);
2147 case CTRL_X_WHOLE_LINE:
2148 /* For while line completion a space can be part of the line. */
2149 return vim_isprintc(c);
2151 return vim_iswordc(c);
2155 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
2156 * case of the originally typed text is used, and the case of the completed
2157 * text is inferred, ie this tries to work out what case you probably wanted
2158 * the rest of the word to be in -- webb
2161 ins_compl_add_infercase(str, len, icase, fname, dir, flags)
2162 char_u *str;
2163 int len;
2164 int icase;
2165 char_u *fname;
2166 int dir;
2167 int flags;
2169 char_u *p;
2170 int i, c;
2171 int actual_len; /* Take multi-byte characters */
2172 int actual_compl_length; /* into account. */
2173 int min_len;
2174 int *wca; /* Wide character array. */
2175 int has_lower = FALSE;
2176 int was_letter = FALSE;
2178 if (p_ic && curbuf->b_p_inf && len > 0)
2180 /* Infer case of completed part. */
2182 /* Find actual length of completion. */
2183 #ifdef FEAT_MBYTE
2184 if (has_mbyte)
2186 p = str;
2187 actual_len = 0;
2188 while (*p != NUL)
2190 mb_ptr_adv(p);
2191 ++actual_len;
2194 else
2195 #endif
2196 actual_len = len;
2198 /* Find actual length of original text. */
2199 #ifdef FEAT_MBYTE
2200 if (has_mbyte)
2202 p = compl_orig_text;
2203 actual_compl_length = 0;
2204 while (*p != NUL)
2206 mb_ptr_adv(p);
2207 ++actual_compl_length;
2210 else
2211 #endif
2212 actual_compl_length = compl_length;
2214 /* "actual_len" may be smaller than "actual_compl_length" when using
2215 * thesaurus, only use the minimum when comparing. */
2216 min_len = actual_len < actual_compl_length
2217 ? actual_len : actual_compl_length;
2219 /* Allocate wide character array for the completion and fill it. */
2220 wca = (int *)alloc((unsigned)(actual_len * sizeof(int)));
2221 if (wca != NULL)
2223 p = str;
2224 for (i = 0; i < actual_len; ++i)
2225 #ifdef FEAT_MBYTE
2226 if (has_mbyte)
2227 wca[i] = mb_ptr2char_adv(&p);
2228 else
2229 #endif
2230 wca[i] = *(p++);
2232 /* Rule 1: Were any chars converted to lower? */
2233 p = compl_orig_text;
2234 for (i = 0; i < min_len; ++i)
2236 #ifdef FEAT_MBYTE
2237 if (has_mbyte)
2238 c = mb_ptr2char_adv(&p);
2239 else
2240 #endif
2241 c = *(p++);
2242 if (MB_ISLOWER(c))
2244 has_lower = TRUE;
2245 if (MB_ISUPPER(wca[i]))
2247 /* Rule 1 is satisfied. */
2248 for (i = actual_compl_length; i < actual_len; ++i)
2249 wca[i] = MB_TOLOWER(wca[i]);
2250 break;
2256 * Rule 2: No lower case, 2nd consecutive letter converted to
2257 * upper case.
2259 if (!has_lower)
2261 p = compl_orig_text;
2262 for (i = 0; i < min_len; ++i)
2264 #ifdef FEAT_MBYTE
2265 if (has_mbyte)
2266 c = mb_ptr2char_adv(&p);
2267 else
2268 #endif
2269 c = *(p++);
2270 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
2272 /* Rule 2 is satisfied. */
2273 for (i = actual_compl_length; i < actual_len; ++i)
2274 wca[i] = MB_TOUPPER(wca[i]);
2275 break;
2277 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
2281 /* Copy the original case of the part we typed. */
2282 p = compl_orig_text;
2283 for (i = 0; i < min_len; ++i)
2285 #ifdef FEAT_MBYTE
2286 if (has_mbyte)
2287 c = mb_ptr2char_adv(&p);
2288 else
2289 #endif
2290 c = *(p++);
2291 if (MB_ISLOWER(c))
2292 wca[i] = MB_TOLOWER(wca[i]);
2293 else if (MB_ISUPPER(c))
2294 wca[i] = MB_TOUPPER(wca[i]);
2298 * Generate encoding specific output from wide character array.
2299 * Multi-byte characters can occupy up to five bytes more than
2300 * ASCII characters, and we also need one byte for NUL, so stay
2301 * six bytes away from the edge of IObuff.
2303 p = IObuff;
2304 i = 0;
2305 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
2306 #ifdef FEAT_MBYTE
2307 if (has_mbyte)
2308 p += (*mb_char2bytes)(wca[i++], p);
2309 else
2310 #endif
2311 *(p++) = wca[i++];
2312 *p = NUL;
2314 vim_free(wca);
2317 return ins_compl_add(IObuff, len, icase, fname, NULL, dir,
2318 flags, FALSE);
2320 return ins_compl_add(str, len, icase, fname, NULL, dir, flags, FALSE);
2324 * Add a match to the list of matches.
2325 * If the given string is already in the list of completions, then return
2326 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2327 * maybe because alloc() returns NULL, then FAIL is returned.
2329 static int
2330 ins_compl_add(str, len, icase, fname, cptext, cdir, flags, adup)
2331 char_u *str;
2332 int len;
2333 int icase;
2334 char_u *fname;
2335 char_u **cptext; /* extra text for popup menu or NULL */
2336 int cdir;
2337 int flags;
2338 int adup; /* accept duplicate match */
2340 compl_T *match;
2341 int dir = (cdir == 0 ? compl_direction : cdir);
2343 ui_breakcheck();
2344 if (got_int)
2345 return FAIL;
2346 if (len < 0)
2347 len = (int)STRLEN(str);
2350 * If the same match is already present, don't add it.
2352 if (compl_first_match != NULL && !adup)
2354 match = compl_first_match;
2357 if ( !(match->cp_flags & ORIGINAL_TEXT)
2358 && STRNCMP(match->cp_str, str, len) == 0
2359 && match->cp_str[len] == NUL)
2360 return NOTDONE;
2361 match = match->cp_next;
2362 } while (match != NULL && match != compl_first_match);
2365 /* Remove any popup menu before changing the list of matches. */
2366 ins_compl_del_pum();
2369 * Allocate a new match structure.
2370 * Copy the values to the new match structure.
2372 match = (compl_T *)alloc_clear((unsigned)sizeof(compl_T));
2373 if (match == NULL)
2374 return FAIL;
2375 match->cp_number = -1;
2376 if (flags & ORIGINAL_TEXT)
2377 match->cp_number = 0;
2378 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
2380 vim_free(match);
2381 return FAIL;
2383 match->cp_icase = icase;
2385 /* match-fname is:
2386 * - compl_curr_match->cp_fname if it is a string equal to fname.
2387 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2388 * - NULL otherwise. --Acevedo */
2389 if (fname != NULL
2390 && compl_curr_match != NULL
2391 && compl_curr_match->cp_fname != NULL
2392 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
2393 match->cp_fname = compl_curr_match->cp_fname;
2394 else if (fname != NULL)
2396 match->cp_fname = vim_strsave(fname);
2397 flags |= FREE_FNAME;
2399 else
2400 match->cp_fname = NULL;
2401 match->cp_flags = flags;
2403 if (cptext != NULL)
2405 int i;
2407 for (i = 0; i < CPT_COUNT; ++i)
2408 if (cptext[i] != NULL && *cptext[i] != NUL)
2409 match->cp_text[i] = vim_strsave(cptext[i]);
2413 * Link the new match structure in the list of matches.
2415 if (compl_first_match == NULL)
2416 match->cp_next = match->cp_prev = NULL;
2417 else if (dir == FORWARD)
2419 match->cp_next = compl_curr_match->cp_next;
2420 match->cp_prev = compl_curr_match;
2422 else /* BACKWARD */
2424 match->cp_next = compl_curr_match;
2425 match->cp_prev = compl_curr_match->cp_prev;
2427 if (match->cp_next)
2428 match->cp_next->cp_prev = match;
2429 if (match->cp_prev)
2430 match->cp_prev->cp_next = match;
2431 else /* if there's nothing before, it is the first match */
2432 compl_first_match = match;
2433 compl_curr_match = match;
2436 * Find the longest common string if still doing that.
2438 if (compl_get_longest && (flags & ORIGINAL_TEXT) == 0)
2439 ins_compl_longest_match(match);
2441 return OK;
2445 * Return TRUE if "str[len]" matches with match->cp_str, considering
2446 * match->cp_icase.
2448 static int
2449 ins_compl_equal(match, str, len)
2450 compl_T *match;
2451 char_u *str;
2452 int len;
2454 if (match->cp_icase)
2455 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
2456 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
2460 * Reduce the longest common string for match "match".
2462 static void
2463 ins_compl_longest_match(match)
2464 compl_T *match;
2466 char_u *p, *s;
2467 int c1, c2;
2468 int had_match;
2470 if (compl_leader == NULL)
2472 /* First match, use it as a whole. */
2473 compl_leader = vim_strsave(match->cp_str);
2474 if (compl_leader != NULL)
2476 had_match = (curwin->w_cursor.col > compl_col);
2477 ins_compl_delete();
2478 ins_bytes(compl_leader + ins_compl_len());
2479 ins_redraw(FALSE);
2481 /* When the match isn't there (to avoid matching itself) remove it
2482 * again after redrawing. */
2483 if (!had_match)
2484 ins_compl_delete();
2485 compl_used_match = FALSE;
2488 else
2490 /* Reduce the text if this match differs from compl_leader. */
2491 p = compl_leader;
2492 s = match->cp_str;
2493 while (*p != NUL)
2495 #ifdef FEAT_MBYTE
2496 if (has_mbyte)
2498 c1 = mb_ptr2char(p);
2499 c2 = mb_ptr2char(s);
2501 else
2502 #endif
2504 c1 = *p;
2505 c2 = *s;
2507 if (match->cp_icase ? (MB_TOLOWER(c1) != MB_TOLOWER(c2))
2508 : (c1 != c2))
2509 break;
2510 #ifdef FEAT_MBYTE
2511 if (has_mbyte)
2513 mb_ptr_adv(p);
2514 mb_ptr_adv(s);
2516 else
2517 #endif
2519 ++p;
2520 ++s;
2524 if (*p != NUL)
2526 /* Leader was shortened, need to change the inserted text. */
2527 *p = NUL;
2528 had_match = (curwin->w_cursor.col > compl_col);
2529 ins_compl_delete();
2530 ins_bytes(compl_leader + ins_compl_len());
2531 ins_redraw(FALSE);
2533 /* When the match isn't there (to avoid matching itself) remove it
2534 * again after redrawing. */
2535 if (!had_match)
2536 ins_compl_delete();
2539 compl_used_match = FALSE;
2544 * Add an array of matches to the list of matches.
2545 * Frees matches[].
2547 static void
2548 ins_compl_add_matches(num_matches, matches, icase)
2549 int num_matches;
2550 char_u **matches;
2551 int icase;
2553 int i;
2554 int add_r = OK;
2555 int dir = compl_direction;
2557 for (i = 0; i < num_matches && add_r != FAIL; i++)
2558 if ((add_r = ins_compl_add(matches[i], -1, icase,
2559 NULL, NULL, dir, 0, FALSE)) == OK)
2560 /* if dir was BACKWARD then honor it just once */
2561 dir = FORWARD;
2562 FreeWild(num_matches, matches);
2565 /* Make the completion list cyclic.
2566 * Return the number of matches (excluding the original).
2568 static int
2569 ins_compl_make_cyclic()
2571 compl_T *match;
2572 int count = 0;
2574 if (compl_first_match != NULL)
2577 * Find the end of the list.
2579 match = compl_first_match;
2580 /* there's always an entry for the compl_orig_text, it doesn't count. */
2581 while (match->cp_next != NULL && match->cp_next != compl_first_match)
2583 match = match->cp_next;
2584 ++count;
2586 match->cp_next = compl_first_match;
2587 compl_first_match->cp_prev = match;
2589 return count;
2593 * Start completion for the complete() function.
2594 * "startcol" is where the matched text starts (1 is first column).
2595 * "list" is the list of matches.
2597 void
2598 set_completion(startcol, list)
2599 colnr_T startcol;
2600 list_T *list;
2602 /* If already doing completions stop it. */
2603 if (ctrl_x_mode != 0)
2604 ins_compl_prep(' ');
2605 ins_compl_clear();
2607 if (stop_arrow() == FAIL)
2608 return;
2610 if (startcol > curwin->w_cursor.col)
2611 startcol = curwin->w_cursor.col;
2612 compl_col = startcol;
2613 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2614 /* compl_pattern doesn't need to be set */
2615 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2616 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2617 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
2618 return;
2620 /* Handle like dictionary completion. */
2621 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2623 ins_compl_add_list(list);
2624 compl_matches = ins_compl_make_cyclic();
2625 compl_started = TRUE;
2626 compl_used_match = TRUE;
2627 compl_cont_status = 0;
2629 compl_curr_match = compl_first_match;
2630 ins_complete(Ctrl_N);
2631 out_flush();
2635 /* "compl_match_array" points the currently displayed list of entries in the
2636 * popup menu. It is NULL when there is no popup menu. */
2637 static pumitem_T *compl_match_array = NULL;
2638 static int compl_match_arraysize;
2641 * Update the screen and when there is any scrolling remove the popup menu.
2643 static void
2644 ins_compl_upd_pum()
2646 int h;
2648 if (compl_match_array != NULL)
2650 h = curwin->w_cline_height;
2651 update_screen(0);
2652 if (h != curwin->w_cline_height)
2653 ins_compl_del_pum();
2658 * Remove any popup menu.
2660 static void
2661 ins_compl_del_pum()
2663 if (compl_match_array != NULL)
2665 pum_undisplay();
2666 vim_free(compl_match_array);
2667 compl_match_array = NULL;
2672 * Return TRUE if the popup menu should be displayed.
2674 static int
2675 pum_wanted()
2677 /* 'completeopt' must contain "menu" or "menuone" */
2678 if (vim_strchr(p_cot, 'm') == NULL)
2679 return FALSE;
2681 /* The display looks bad on a B&W display. */
2682 if (t_colors < 8
2683 #ifdef FEAT_GUI
2684 && !gui.in_use
2685 #endif
2687 return FALSE;
2688 return TRUE;
2692 * Return TRUE if there are two or more matches to be shown in the popup menu.
2693 * One if 'completopt' contains "menuone".
2695 static int
2696 pum_enough_matches()
2698 compl_T *compl;
2699 int i;
2701 /* Don't display the popup menu if there are no matches or there is only
2702 * one (ignoring the original text). */
2703 compl = compl_first_match;
2704 i = 0;
2707 if (compl == NULL
2708 || ((compl->cp_flags & ORIGINAL_TEXT) == 0 && ++i == 2))
2709 break;
2710 compl = compl->cp_next;
2711 } while (compl != compl_first_match);
2713 if (strstr((char *)p_cot, "menuone") != NULL)
2714 return (i >= 1);
2715 return (i >= 2);
2719 * Show the popup menu for the list of matches.
2720 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
2722 void
2723 ins_compl_show_pum()
2725 compl_T *compl;
2726 compl_T *shown_compl = NULL;
2727 int did_find_shown_match = FALSE;
2728 int shown_match_ok = FALSE;
2729 int i;
2730 int cur = -1;
2731 colnr_T col;
2732 int lead_len = 0;
2734 if (!pum_wanted() || !pum_enough_matches())
2735 return;
2737 #if defined(FEAT_EVAL)
2738 /* Dirty hard-coded hack: remove any matchparen highlighting. */
2739 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
2740 #endif
2742 /* Update the screen before drawing the popup menu over it. */
2743 update_screen(0);
2745 if (compl_match_array == NULL)
2747 /* Need to build the popup menu list. */
2748 compl_match_arraysize = 0;
2749 compl = compl_first_match;
2750 if (compl_leader != NULL)
2751 lead_len = (int)STRLEN(compl_leader);
2754 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2755 && (compl_leader == NULL
2756 || ins_compl_equal(compl, compl_leader, lead_len)))
2757 ++compl_match_arraysize;
2758 compl = compl->cp_next;
2759 } while (compl != NULL && compl != compl_first_match);
2760 if (compl_match_arraysize == 0)
2761 return;
2762 compl_match_array = (pumitem_T *)alloc_clear(
2763 (unsigned)(sizeof(pumitem_T)
2764 * compl_match_arraysize));
2765 if (compl_match_array != NULL)
2767 /* If the current match is the original text don't find the first
2768 * match after it, don't highlight anything. */
2769 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
2770 shown_match_ok = TRUE;
2772 i = 0;
2773 compl = compl_first_match;
2776 if ((compl->cp_flags & ORIGINAL_TEXT) == 0
2777 && (compl_leader == NULL
2778 || ins_compl_equal(compl, compl_leader, lead_len)))
2780 if (!shown_match_ok)
2782 if (compl == compl_shown_match || did_find_shown_match)
2784 /* This item is the shown match or this is the
2785 * first displayed item after the shown match. */
2786 compl_shown_match = compl;
2787 did_find_shown_match = TRUE;
2788 shown_match_ok = TRUE;
2790 else
2791 /* Remember this displayed match for when the
2792 * shown match is just below it. */
2793 shown_compl = compl;
2794 cur = i;
2797 if (compl->cp_text[CPT_ABBR] != NULL)
2798 compl_match_array[i].pum_text =
2799 compl->cp_text[CPT_ABBR];
2800 else
2801 compl_match_array[i].pum_text = compl->cp_str;
2802 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
2803 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
2804 if (compl->cp_text[CPT_MENU] != NULL)
2805 compl_match_array[i++].pum_extra =
2806 compl->cp_text[CPT_MENU];
2807 else
2808 compl_match_array[i++].pum_extra = compl->cp_fname;
2811 if (compl == compl_shown_match)
2813 did_find_shown_match = TRUE;
2815 /* When the original text is the shown match don't set
2816 * compl_shown_match. */
2817 if (compl->cp_flags & ORIGINAL_TEXT)
2818 shown_match_ok = TRUE;
2820 if (!shown_match_ok && shown_compl != NULL)
2822 /* The shown match isn't displayed, set it to the
2823 * previously displayed match. */
2824 compl_shown_match = shown_compl;
2825 shown_match_ok = TRUE;
2828 compl = compl->cp_next;
2829 } while (compl != NULL && compl != compl_first_match);
2831 if (!shown_match_ok) /* no displayed match at all */
2832 cur = -1;
2835 else
2837 /* popup menu already exists, only need to find the current item.*/
2838 for (i = 0; i < compl_match_arraysize; ++i)
2839 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
2840 || compl_match_array[i].pum_text
2841 == compl_shown_match->cp_text[CPT_ABBR])
2843 cur = i;
2844 break;
2848 if (compl_match_array != NULL)
2850 /* Compute the screen column of the start of the completed text.
2851 * Use the cursor to get all wrapping and other settings right. */
2852 col = curwin->w_cursor.col;
2853 curwin->w_cursor.col = compl_col;
2854 pum_display(compl_match_array, compl_match_arraysize, cur);
2855 curwin->w_cursor.col = col;
2859 #define DICT_FIRST (1) /* use just first element in "dict" */
2860 #define DICT_EXACT (2) /* "dict" is the exact name of a file */
2863 * Add any identifiers that match the given pattern in the list of dictionary
2864 * files "dict_start" to the list of completions.
2866 static void
2867 ins_compl_dictionaries(dict_start, pat, flags, thesaurus)
2868 char_u *dict_start;
2869 char_u *pat;
2870 int flags; /* DICT_FIRST and/or DICT_EXACT */
2871 int thesaurus; /* Thesaurus completion */
2873 char_u *dict = dict_start;
2874 char_u *ptr;
2875 char_u *buf;
2876 regmatch_T regmatch;
2877 char_u **files;
2878 int count;
2879 int save_p_scs;
2880 int dir = compl_direction;
2882 if (*dict == NUL)
2884 #ifdef FEAT_SPELL
2885 /* When 'dictionary' is empty and spell checking is enabled use
2886 * "spell". */
2887 if (!thesaurus && curwin->w_p_spell)
2888 dict = (char_u *)"spell";
2889 else
2890 #endif
2891 return;
2894 buf = alloc(LSIZE);
2895 if (buf == NULL)
2896 return;
2897 regmatch.regprog = NULL; /* so that we can goto theend */
2899 /* If 'infercase' is set, don't use 'smartcase' here */
2900 save_p_scs = p_scs;
2901 if (curbuf->b_p_inf)
2902 p_scs = FALSE;
2904 /* When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
2905 * to only match at the start of a line. Otherwise just match the
2906 * pattern. Also need to double backslashes. */
2907 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2909 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
2910 size_t len;
2912 if (pat_esc == NULL)
2913 goto theend;
2914 len = STRLEN(pat_esc) + 10;
2915 ptr = alloc((unsigned)len);
2916 if (ptr == NULL)
2918 vim_free(pat_esc);
2919 goto theend;
2921 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
2922 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
2923 vim_free(pat_esc);
2924 vim_free(ptr);
2926 else
2928 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2929 if (regmatch.regprog == NULL)
2930 goto theend;
2933 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2934 regmatch.rm_ic = ignorecase(pat);
2935 while (*dict != NUL && !got_int && !compl_interrupted)
2937 /* copy one dictionary file name into buf */
2938 if (flags == DICT_EXACT)
2940 count = 1;
2941 files = &dict;
2943 else
2945 /* Expand wildcards in the dictionary name, but do not allow
2946 * backticks (for security, the 'dict' option may have been set in
2947 * a modeline). */
2948 copy_option_part(&dict, buf, LSIZE, ",");
2949 # ifdef FEAT_SPELL
2950 if (!thesaurus && STRCMP(buf, "spell") == 0)
2951 count = -1;
2952 else
2953 # endif
2954 if (vim_strchr(buf, '`') != NULL
2955 || expand_wildcards(1, &buf, &count, &files,
2956 EW_FILE|EW_SILENT) != OK)
2957 count = 0;
2960 # ifdef FEAT_SPELL
2961 if (count == -1)
2963 /* Complete from active spelling. Skip "\<" in the pattern, we
2964 * don't use it as a RE. */
2965 if (pat[0] == '\\' && pat[1] == '<')
2966 ptr = pat + 2;
2967 else
2968 ptr = pat;
2969 spell_dump_compl(curbuf, ptr, regmatch.rm_ic, &dir, 0);
2971 else
2972 # endif
2973 if (count > 0) /* avoid warning for using "files" uninit */
2975 ins_compl_files(count, files, thesaurus, flags,
2976 &regmatch, buf, &dir);
2977 if (flags != DICT_EXACT)
2978 FreeWild(count, files);
2980 if (flags != 0)
2981 break;
2984 theend:
2985 p_scs = save_p_scs;
2986 vim_free(regmatch.regprog);
2987 vim_free(buf);
2990 static void
2991 ins_compl_files(count, files, thesaurus, flags, regmatch, buf, dir)
2992 int count;
2993 char_u **files;
2994 int thesaurus;
2995 int flags;
2996 regmatch_T *regmatch;
2997 char_u *buf;
2998 int *dir;
3000 char_u *ptr;
3001 int i;
3002 FILE *fp;
3003 int add_r;
3005 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
3007 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
3008 if (flags != DICT_EXACT)
3010 vim_snprintf((char *)IObuff, IOSIZE,
3011 _("Scanning dictionary: %s"), (char *)files[i]);
3012 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3015 if (fp != NULL)
3018 * Read dictionary file line by line.
3019 * Check each line for a match.
3021 while (!got_int && !compl_interrupted
3022 && !vim_fgets(buf, LSIZE, fp))
3024 ptr = buf;
3025 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
3027 ptr = regmatch->startp[0];
3028 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3029 ptr = find_line_end(ptr);
3030 else
3031 ptr = find_word_end(ptr);
3032 add_r = ins_compl_add_infercase(regmatch->startp[0],
3033 (int)(ptr - regmatch->startp[0]),
3034 p_ic, files[i], *dir, 0);
3035 if (thesaurus)
3037 char_u *wstart;
3040 * Add the other matches on the line
3042 ptr = buf;
3043 while (!got_int)
3045 /* Find start of the next word. Skip white
3046 * space and punctuation. */
3047 ptr = find_word_start(ptr);
3048 if (*ptr == NUL || *ptr == NL)
3049 break;
3050 wstart = ptr;
3052 /* Find end of the word. */
3053 #ifdef FEAT_MBYTE
3054 if (has_mbyte)
3055 /* Japanese words may have characters in
3056 * different classes, only separate words
3057 * with single-byte non-word characters. */
3058 while (*ptr != NUL)
3060 int l = (*mb_ptr2len)(ptr);
3062 if (l < 2 && !vim_iswordc(*ptr))
3063 break;
3064 ptr += l;
3066 else
3067 #endif
3068 ptr = find_word_end(ptr);
3070 /* Add the word. Skip the regexp match. */
3071 if (wstart != regmatch->startp[0])
3072 add_r = ins_compl_add_infercase(wstart,
3073 (int)(ptr - wstart),
3074 p_ic, files[i], *dir, 0);
3077 if (add_r == OK)
3078 /* if dir was BACKWARD then honor it just once */
3079 *dir = FORWARD;
3080 else if (add_r == FAIL)
3081 break;
3082 /* avoid expensive call to vim_regexec() when at end
3083 * of line */
3084 if (*ptr == '\n' || got_int)
3085 break;
3087 line_breakcheck();
3088 ins_compl_check_keys(50);
3090 fclose(fp);
3096 * Find the start of the next word.
3097 * Returns a pointer to the first char of the word. Also stops at a NUL.
3099 char_u *
3100 find_word_start(ptr)
3101 char_u *ptr;
3103 #ifdef FEAT_MBYTE
3104 if (has_mbyte)
3105 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
3106 ptr += (*mb_ptr2len)(ptr);
3107 else
3108 #endif
3109 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
3110 ++ptr;
3111 return ptr;
3115 * Find the end of the word. Assumes it starts inside a word.
3116 * Returns a pointer to just after the word.
3118 char_u *
3119 find_word_end(ptr)
3120 char_u *ptr;
3122 #ifdef FEAT_MBYTE
3123 int start_class;
3125 if (has_mbyte)
3127 start_class = mb_get_class(ptr);
3128 if (start_class > 1)
3129 while (*ptr != NUL)
3131 ptr += (*mb_ptr2len)(ptr);
3132 if (mb_get_class(ptr) != start_class)
3133 break;
3136 else
3137 #endif
3138 while (vim_iswordc(*ptr))
3139 ++ptr;
3140 return ptr;
3144 * Find the end of the line, omitting CR and NL at the end.
3145 * Returns a pointer to just after the line.
3147 static char_u *
3148 find_line_end(ptr)
3149 char_u *ptr;
3151 char_u *s;
3153 s = ptr + STRLEN(ptr);
3154 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
3155 --s;
3156 return s;
3160 * Free the list of completions
3162 static void
3163 ins_compl_free()
3165 compl_T *match;
3166 int i;
3168 vim_free(compl_pattern);
3169 compl_pattern = NULL;
3170 vim_free(compl_leader);
3171 compl_leader = NULL;
3173 if (compl_first_match == NULL)
3174 return;
3176 ins_compl_del_pum();
3177 pum_clear();
3179 compl_curr_match = compl_first_match;
3182 match = compl_curr_match;
3183 compl_curr_match = compl_curr_match->cp_next;
3184 vim_free(match->cp_str);
3185 /* several entries may use the same fname, free it just once. */
3186 if (match->cp_flags & FREE_FNAME)
3187 vim_free(match->cp_fname);
3188 for (i = 0; i < CPT_COUNT; ++i)
3189 vim_free(match->cp_text[i]);
3190 vim_free(match);
3191 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
3192 compl_first_match = compl_curr_match = NULL;
3193 compl_shown_match = NULL;
3196 static void
3197 ins_compl_clear()
3199 compl_cont_status = 0;
3200 compl_started = FALSE;
3201 compl_matches = 0;
3202 vim_free(compl_pattern);
3203 compl_pattern = NULL;
3204 vim_free(compl_leader);
3205 compl_leader = NULL;
3206 edit_submode_extra = NULL;
3207 vim_free(compl_orig_text);
3208 compl_orig_text = NULL;
3209 compl_enter_selects = FALSE;
3213 * Return TRUE when Insert completion is active.
3216 ins_compl_active()
3218 return compl_started;
3222 * Delete one character before the cursor and show the subset of the matches
3223 * that match the word that is now before the cursor.
3224 * Returns the character to be used, NUL if the work is done and another char
3225 * to be got from the user.
3227 static int
3228 ins_compl_bs()
3230 char_u *line;
3231 char_u *p;
3233 line = ml_get_curline();
3234 p = line + curwin->w_cursor.col;
3235 mb_ptr_back(line, p);
3237 /* Stop completion when the whole word was deleted. For Omni completion
3238 * allow the word to be deleted, we won't match everything. */
3239 if ((int)(p - line) - (int)compl_col < 0
3240 || ((int)(p - line) - (int)compl_col == 0
3241 && (ctrl_x_mode & CTRL_X_OMNI) == 0))
3242 return K_BS;
3244 /* Deleted more than what was used to find matches or didn't finish
3245 * finding all matches: need to look for matches all over again. */
3246 if (curwin->w_cursor.col <= compl_col + compl_length
3247 || compl_was_interrupted)
3248 ins_compl_restart();
3250 vim_free(compl_leader);
3251 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
3252 if (compl_leader != NULL)
3254 ins_compl_new_leader();
3255 return NUL;
3257 return K_BS;
3261 * Called after changing "compl_leader".
3262 * Show the popup menu with a different set of matches.
3263 * May also search for matches again if the previous search was interrupted.
3265 static void
3266 ins_compl_new_leader()
3268 ins_compl_del_pum();
3269 ins_compl_delete();
3270 ins_bytes(compl_leader + ins_compl_len());
3271 compl_used_match = FALSE;
3273 if (compl_started)
3274 ins_compl_set_original_text(compl_leader);
3275 else
3277 #ifdef FEAT_SPELL
3278 spell_bad_len = 0; /* need to redetect bad word */
3279 #endif
3281 * Matches were cleared, need to search for them now. First display
3282 * the changed text before the cursor. Set "compl_restarting" to
3283 * avoid that the first match is inserted.
3285 update_screen(0);
3286 #ifdef FEAT_GUI
3287 if (gui.in_use)
3289 /* Show the cursor after the match, not after the redrawn text. */
3290 setcursor();
3291 out_flush();
3292 gui_update_cursor(FALSE, FALSE);
3294 #endif
3295 compl_restarting = TRUE;
3296 if (ins_complete(Ctrl_N) == FAIL)
3297 compl_cont_status = 0;
3298 compl_restarting = FALSE;
3301 #if 0 /* disabled, made CTRL-L, BS and typing char jump to original text. */
3302 if (!compl_used_match)
3304 /* Go to the original text, since none of the matches is inserted. */
3305 if (compl_first_match->cp_prev != NULL
3306 && (compl_first_match->cp_prev->cp_flags & ORIGINAL_TEXT))
3307 compl_shown_match = compl_first_match->cp_prev;
3308 else
3309 compl_shown_match = compl_first_match;
3310 compl_curr_match = compl_shown_match;
3311 compl_shows_dir = compl_direction;
3313 #endif
3314 compl_enter_selects = !compl_used_match;
3316 /* Show the popup menu with a different set of matches. */
3317 ins_compl_show_pum();
3319 /* Don't let Enter select the original text when there is no popup menu. */
3320 if (compl_match_array == NULL)
3321 compl_enter_selects = FALSE;
3325 * Return the length of the completion, from the completion start column to
3326 * the cursor column. Making sure it never goes below zero.
3328 static int
3329 ins_compl_len()
3331 int off = (int)curwin->w_cursor.col - (int)compl_col;
3333 if (off < 0)
3334 return 0;
3335 return off;
3339 * Append one character to the match leader. May reduce the number of
3340 * matches.
3342 static void
3343 ins_compl_addleader(c)
3344 int c;
3346 #ifdef FEAT_MBYTE
3347 int cc;
3349 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
3351 char_u buf[MB_MAXBYTES + 1];
3353 (*mb_char2bytes)(c, buf);
3354 buf[cc] = NUL;
3355 ins_char_bytes(buf, cc);
3357 else
3358 #endif
3359 ins_char(c);
3361 /* If we didn't complete finding matches we must search again. */
3362 if (compl_was_interrupted)
3363 ins_compl_restart();
3365 vim_free(compl_leader);
3366 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
3367 (int)(curwin->w_cursor.col - compl_col));
3368 if (compl_leader != NULL)
3369 ins_compl_new_leader();
3373 * Setup for finding completions again without leaving CTRL-X mode. Used when
3374 * BS or a key was typed while still searching for matches.
3376 static void
3377 ins_compl_restart()
3379 ins_compl_free();
3380 compl_started = FALSE;
3381 compl_matches = 0;
3382 compl_cont_status = 0;
3383 compl_cont_mode = 0;
3387 * Set the first match, the original text.
3389 static void
3390 ins_compl_set_original_text(str)
3391 char_u *str;
3393 char_u *p;
3395 /* Replace the original text entry. */
3396 if (compl_first_match->cp_flags & ORIGINAL_TEXT) /* safety check */
3398 p = vim_strsave(str);
3399 if (p != NULL)
3401 vim_free(compl_first_match->cp_str);
3402 compl_first_match->cp_str = p;
3408 * Append one character to the match leader. May reduce the number of
3409 * matches.
3411 static void
3412 ins_compl_addfrommatch()
3414 char_u *p;
3415 int len = (int)curwin->w_cursor.col - (int)compl_col;
3416 int c;
3417 compl_T *cp;
3419 p = compl_shown_match->cp_str;
3420 if ((int)STRLEN(p) <= len) /* the match is too short */
3422 /* When still at the original match use the first entry that matches
3423 * the leader. */
3424 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
3426 p = NULL;
3427 for (cp = compl_shown_match->cp_next; cp != NULL
3428 && cp != compl_first_match; cp = cp->cp_next)
3430 if (compl_leader == NULL
3431 || ins_compl_equal(cp, compl_leader,
3432 (int)STRLEN(compl_leader)))
3434 p = cp->cp_str;
3435 break;
3438 if (p == NULL || (int)STRLEN(p) <= len)
3439 return;
3441 else
3442 return;
3444 p += len;
3445 #ifdef FEAT_MBYTE
3446 c = mb_ptr2char(p);
3447 #else
3448 c = *p;
3449 #endif
3450 ins_compl_addleader(c);
3454 * Prepare for Insert mode completion, or stop it.
3455 * Called just after typing a character in Insert mode.
3456 * Returns TRUE when the character is not to be inserted;
3458 static int
3459 ins_compl_prep(c)
3460 int c;
3462 char_u *ptr;
3463 int want_cindent;
3464 int retval = FALSE;
3466 /* Forget any previous 'special' messages if this is actually
3467 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
3469 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
3470 edit_submode_extra = NULL;
3472 /* Ignore end of Select mode mapping and mouse scroll buttons. */
3473 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP)
3474 return retval;
3476 /* Set "compl_get_longest" when finding the first matches. */
3477 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
3478 || (ctrl_x_mode == 0 && !compl_started))
3480 compl_get_longest = (vim_strchr(p_cot, 'l') != NULL);
3481 compl_used_match = TRUE;
3484 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
3487 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3488 * it will be yet. Now we decide.
3490 switch (c)
3492 case Ctrl_E:
3493 case Ctrl_Y:
3494 ctrl_x_mode = CTRL_X_SCROLL;
3495 if (!(State & REPLACE_FLAG))
3496 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
3497 else
3498 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
3499 edit_submode_pre = NULL;
3500 showmode();
3501 break;
3502 case Ctrl_L:
3503 ctrl_x_mode = CTRL_X_WHOLE_LINE;
3504 break;
3505 case Ctrl_F:
3506 ctrl_x_mode = CTRL_X_FILES;
3507 break;
3508 case Ctrl_K:
3509 ctrl_x_mode = CTRL_X_DICTIONARY;
3510 break;
3511 case Ctrl_R:
3512 /* Simply allow ^R to happen without affecting ^X mode */
3513 break;
3514 case Ctrl_T:
3515 ctrl_x_mode = CTRL_X_THESAURUS;
3516 break;
3517 #ifdef FEAT_COMPL_FUNC
3518 case Ctrl_U:
3519 ctrl_x_mode = CTRL_X_FUNCTION;
3520 break;
3521 case Ctrl_O:
3522 ctrl_x_mode = CTRL_X_OMNI;
3523 break;
3524 #endif
3525 case 's':
3526 case Ctrl_S:
3527 ctrl_x_mode = CTRL_X_SPELL;
3528 #ifdef FEAT_SPELL
3529 ++emsg_off; /* Avoid getting the E756 error twice. */
3530 spell_back_to_badword();
3531 --emsg_off;
3532 #endif
3533 break;
3534 case Ctrl_RSB:
3535 ctrl_x_mode = CTRL_X_TAGS;
3536 break;
3537 #ifdef FEAT_FIND_ID
3538 case Ctrl_I:
3539 case K_S_TAB:
3540 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
3541 break;
3542 case Ctrl_D:
3543 ctrl_x_mode = CTRL_X_PATH_DEFINES;
3544 break;
3545 #endif
3546 case Ctrl_V:
3547 case Ctrl_Q:
3548 ctrl_x_mode = CTRL_X_CMDLINE;
3549 break;
3550 case Ctrl_P:
3551 case Ctrl_N:
3552 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
3553 * just started ^X mode, or there were enough ^X's to cancel
3554 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
3555 * do normal expansion when interrupting a different mode (say
3556 * ^X^F^X^P or ^P^X^X^P, see below)
3557 * nothing changes if interrupting mode 0, (eg, the flag
3558 * doesn't change when going to ADDING mode -- Acevedo */
3559 if (!(compl_cont_status & CONT_INTRPT))
3560 compl_cont_status |= CONT_LOCAL;
3561 else if (compl_cont_mode != 0)
3562 compl_cont_status &= ~CONT_LOCAL;
3563 /* FALLTHROUGH */
3564 default:
3565 /* If we have typed at least 2 ^X's... for modes != 0, we set
3566 * compl_cont_status = 0 (eg, as if we had just started ^X
3567 * mode).
3568 * For mode 0, we set "compl_cont_mode" to an impossible
3569 * value, in both cases ^X^X can be used to restart the same
3570 * mode (avoiding ADDING mode).
3571 * Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
3572 * 'complete' and local ^P expansions respectively.
3573 * In mode 0 an extra ^X is needed since ^X^P goes to ADDING
3574 * mode -- Acevedo */
3575 if (c == Ctrl_X)
3577 if (compl_cont_mode != 0)
3578 compl_cont_status = 0;
3579 else
3580 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
3582 ctrl_x_mode = 0;
3583 edit_submode = NULL;
3584 showmode();
3585 break;
3588 else if (ctrl_x_mode != 0)
3590 /* We're already in CTRL-X mode, do we stay in it? */
3591 if (!vim_is_ctrl_x_key(c))
3593 if (ctrl_x_mode == CTRL_X_SCROLL)
3594 ctrl_x_mode = 0;
3595 else
3596 ctrl_x_mode = CTRL_X_FINISHED;
3597 edit_submode = NULL;
3599 showmode();
3602 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3604 /* Show error message from attempted keyword completion (probably
3605 * 'Pattern not found') until another key is hit, then go back to
3606 * showing what mode we are in. */
3607 showmode();
3608 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R
3609 && !ins_compl_pum_key(c))
3610 || ctrl_x_mode == CTRL_X_FINISHED)
3612 /* Get here when we have finished typing a sequence of ^N and
3613 * ^P or other completion characters in CTRL-X mode. Free up
3614 * memory that was used, and make sure we can redo the insert. */
3615 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
3617 char_u *p;
3618 int temp = 0;
3621 * If any of the original typed text has been changed, eg when
3622 * ignorecase is set, we must add back-spaces to the redo
3623 * buffer. We add as few as necessary to delete just the part
3624 * of the original text that has changed.
3625 * When using the longest match, edited the match or used
3626 * CTRL-E then don't use the current match.
3628 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
3629 ptr = compl_curr_match->cp_str;
3630 else if (compl_leader != NULL)
3631 ptr = compl_leader;
3632 else
3633 ptr = compl_orig_text;
3634 if (compl_orig_text != NULL)
3636 p = compl_orig_text;
3637 for (temp = 0; p[temp] != NUL && p[temp] == ptr[temp];
3638 ++temp)
3640 #ifdef FEAT_MBYTE
3641 if (temp > 0)
3642 temp -= (*mb_head_off)(compl_orig_text, p + temp);
3643 #endif
3644 for (p += temp; *p != NUL; mb_ptr_adv(p))
3645 AppendCharToRedobuff(K_BS);
3647 if (ptr != NULL)
3648 AppendToRedobuffLit(ptr + temp, -1);
3651 #ifdef FEAT_CINDENT
3652 want_cindent = (can_cindent && cindent_on());
3653 #endif
3655 * When completing whole lines: fix indent for 'cindent'.
3656 * Otherwise, break line if it's too long.
3658 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
3660 #ifdef FEAT_CINDENT
3661 /* re-indent the current line */
3662 if (want_cindent)
3664 do_c_expr_indent();
3665 want_cindent = FALSE; /* don't do it again */
3667 #endif
3669 else
3671 int prev_col = curwin->w_cursor.col;
3673 /* put the cursor on the last char, for 'tw' formatting */
3674 if (prev_col > 0)
3675 dec_cursor();
3676 if (stop_arrow() == OK)
3677 insertchar(NUL, 0, -1);
3678 if (prev_col > 0
3679 && ml_get_curline()[curwin->w_cursor.col] != NUL)
3680 inc_cursor();
3683 /* If the popup menu is displayed pressing CTRL-Y means accepting
3684 * the selection without inserting anything. When
3685 * compl_enter_selects is set the Enter key does the same. */
3686 if ((c == Ctrl_Y || (compl_enter_selects
3687 && (c == CAR || c == K_KENTER || c == NL)))
3688 && pum_visible())
3689 retval = TRUE;
3691 /* CTRL-E means completion is Ended, go back to the typed text. */
3692 if (c == Ctrl_E)
3694 ins_compl_delete();
3695 if (compl_leader != NULL)
3696 ins_bytes(compl_leader + ins_compl_len());
3697 else if (compl_first_match != NULL)
3698 ins_bytes(compl_orig_text + ins_compl_len());
3699 retval = TRUE;
3702 auto_format(FALSE, TRUE);
3704 ins_compl_free();
3705 compl_started = FALSE;
3706 compl_matches = 0;
3707 msg_clr_cmdline(); /* necessary for "noshowmode" */
3708 ctrl_x_mode = 0;
3709 compl_enter_selects = FALSE;
3710 if (edit_submode != NULL)
3712 edit_submode = NULL;
3713 showmode();
3716 #ifdef FEAT_CINDENT
3718 * Indent now if a key was typed that is in 'cinkeys'.
3720 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
3721 do_c_expr_indent();
3722 #endif
3726 /* reset continue_* if we left expansion-mode, if we stay they'll be
3727 * (re)set properly in ins_complete() */
3728 if (!vim_is_ctrl_x_key(c))
3730 compl_cont_status = 0;
3731 compl_cont_mode = 0;
3734 return retval;
3738 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3739 * (depending on flag) starting from buf and looking for a non-scanned
3740 * buffer (other than curbuf). curbuf is special, if it is called with
3741 * buf=curbuf then it has to be the first call for a given flag/expansion.
3743 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3745 static buf_T *
3746 ins_compl_next_buf(buf, flag)
3747 buf_T *buf;
3748 int flag;
3750 #ifdef FEAT_WINDOWS
3751 static win_T *wp;
3752 #endif
3754 if (flag == 'w') /* just windows */
3756 #ifdef FEAT_WINDOWS
3757 if (buf == curbuf) /* first call for this flag/expansion */
3758 wp = curwin;
3759 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
3760 && wp->w_buffer->b_scanned)
3762 buf = wp->w_buffer;
3763 #else
3764 buf = curbuf;
3765 #endif
3767 else
3768 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3769 * (unlisted buffers)
3770 * When completing whole lines skip unloaded buffers. */
3771 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
3772 && ((flag == 'U'
3773 ? buf->b_p_bl
3774 : (!buf->b_p_bl
3775 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
3776 || buf->b_scanned))
3778 return buf;
3781 #ifdef FEAT_COMPL_FUNC
3782 static void expand_by_function __ARGS((int type, char_u *base));
3785 * Execute user defined complete function 'completefunc' or 'omnifunc', and
3786 * get matches in "matches".
3788 static void
3789 expand_by_function(type, base)
3790 int type; /* CTRL_X_OMNI or CTRL_X_FUNCTION */
3791 char_u *base;
3793 list_T *matchlist;
3794 char_u *args[2];
3795 char_u *funcname;
3796 pos_T pos;
3798 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3799 if (*funcname == NUL)
3800 return;
3802 /* Call 'completefunc' to obtain the list of matches. */
3803 args[0] = (char_u *)"0";
3804 args[1] = base;
3806 pos = curwin->w_cursor;
3807 matchlist = call_func_retlist(funcname, 2, args, FALSE);
3808 curwin->w_cursor = pos; /* restore the cursor position */
3809 if (matchlist == NULL)
3810 return;
3812 ins_compl_add_list(matchlist);
3813 list_unref(matchlist);
3815 #endif /* FEAT_COMPL_FUNC */
3817 #if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
3819 * Add completions from a list.
3821 static void
3822 ins_compl_add_list(list)
3823 list_T *list;
3825 listitem_T *li;
3826 int dir = compl_direction;
3828 /* Go through the List with matches and add each of them. */
3829 for (li = list->lv_first; li != NULL; li = li->li_next)
3831 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
3832 /* if dir was BACKWARD then honor it just once */
3833 dir = FORWARD;
3834 else if (did_emsg)
3835 break;
3840 * Add a match to the list of matches from a typeval_T.
3841 * If the given string is already in the list of completions, then return
3842 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3843 * maybe because alloc() returns NULL, then FAIL is returned.
3846 ins_compl_add_tv(tv, dir)
3847 typval_T *tv;
3848 int dir;
3850 char_u *word;
3851 int icase = FALSE;
3852 int adup = FALSE;
3853 char_u *(cptext[CPT_COUNT]);
3855 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3857 word = get_dict_string(tv->vval.v_dict, (char_u *)"word", FALSE);
3858 cptext[CPT_ABBR] = get_dict_string(tv->vval.v_dict,
3859 (char_u *)"abbr", FALSE);
3860 cptext[CPT_MENU] = get_dict_string(tv->vval.v_dict,
3861 (char_u *)"menu", FALSE);
3862 cptext[CPT_KIND] = get_dict_string(tv->vval.v_dict,
3863 (char_u *)"kind", FALSE);
3864 cptext[CPT_INFO] = get_dict_string(tv->vval.v_dict,
3865 (char_u *)"info", FALSE);
3866 if (get_dict_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL)
3867 icase = get_dict_number(tv->vval.v_dict, (char_u *)"icase");
3868 if (get_dict_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
3869 adup = get_dict_number(tv->vval.v_dict, (char_u *)"dup");
3871 else
3873 word = get_tv_string_chk(tv);
3874 vim_memset(cptext, 0, sizeof(cptext));
3876 if (word == NULL || *word == NUL)
3877 return FAIL;
3878 return ins_compl_add(word, -1, icase, NULL, cptext, dir, 0, adup);
3880 #endif
3883 * Get the next expansion(s), using "compl_pattern".
3884 * The search starts at position "ini" in curbuf and in the direction
3885 * compl_direction.
3886 * When "compl_started" is FALSE start at that position, otherwise continue
3887 * where we stopped searching before.
3888 * This may return before finding all the matches.
3889 * Return the total number of matches or -1 if still unknown -- Acevedo
3891 static int
3892 ins_compl_get_exp(ini)
3893 pos_T *ini;
3895 static pos_T first_match_pos;
3896 static pos_T last_match_pos;
3897 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
3898 static int found_all = FALSE; /* Found all matches of a
3899 certain type. */
3900 static buf_T *ins_buf = NULL; /* buffer being scanned */
3902 pos_T *pos;
3903 char_u **matches;
3904 int save_p_scs;
3905 int save_p_ws;
3906 int save_p_ic;
3907 int i;
3908 int num_matches;
3909 int len;
3910 int found_new_match;
3911 int type = ctrl_x_mode;
3912 char_u *ptr;
3913 char_u *dict = NULL;
3914 int dict_f = 0;
3915 compl_T *old_match;
3916 char *bname;
3918 if (!compl_started)
3920 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
3921 ins_buf->b_scanned = 0;
3922 found_all = FALSE;
3923 ins_buf = curbuf;
3924 e_cpt = (compl_cont_status & CONT_LOCAL)
3925 ? (char_u *)"." : curbuf->b_p_cpt;
3926 last_match_pos = first_match_pos = *ini;
3929 old_match = compl_curr_match; /* remember the last current match */
3930 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3931 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
3932 for (;;)
3934 found_new_match = FAIL;
3936 /* For ^N/^P pick a new entry from e_cpt if compl_started is off,
3937 * or if found_all says this entry is done. For ^X^L only use the
3938 * entries from 'complete' that look in loaded buffers. */
3939 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3940 && (!compl_started || found_all))
3942 found_all = FALSE;
3943 while (*e_cpt == ',' || *e_cpt == ' ')
3944 e_cpt++;
3945 if (*e_cpt == '.' && !curbuf->b_scanned)
3947 ins_buf = curbuf;
3948 first_match_pos = *ini;
3949 /* So that ^N can match word immediately after cursor */
3950 if (ctrl_x_mode == 0)
3951 dec(&first_match_pos);
3952 last_match_pos = first_match_pos;
3953 type = 0;
3955 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3956 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
3958 /* Scan a buffer, but not the current one. */
3959 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
3961 compl_started = TRUE;
3962 first_match_pos.col = last_match_pos.col = 0;
3963 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
3964 last_match_pos.lnum = 0;
3965 type = 0;
3967 else /* unloaded buffer, scan like dictionary */
3969 found_all = TRUE;
3970 if (ins_buf->b_fname == NULL)
3971 continue;
3972 type = CTRL_X_DICTIONARY;
3973 dict = ins_buf->b_fname;
3974 dict_f = DICT_EXACT;
3976 bname = NULL;
3977 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3978 ins_buf->b_fname == NULL
3979 ? (bname = buf_spname(ins_buf))
3980 : ins_buf->b_sfname == NULL
3981 ? (char *)ins_buf->b_fname
3982 : (char *)ins_buf->b_sfname);
3983 vim_free(bname);
3984 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
3986 else if (*e_cpt == NUL)
3987 break;
3988 else
3990 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3991 type = -1;
3992 else if (*e_cpt == 'k' || *e_cpt == 's')
3994 if (*e_cpt == 'k')
3995 type = CTRL_X_DICTIONARY;
3996 else
3997 type = CTRL_X_THESAURUS;
3998 if (*++e_cpt != ',' && *e_cpt != NUL)
4000 dict = e_cpt;
4001 dict_f = DICT_FIRST;
4004 #ifdef FEAT_FIND_ID
4005 else if (*e_cpt == 'i')
4006 type = CTRL_X_PATH_PATTERNS;
4007 else if (*e_cpt == 'd')
4008 type = CTRL_X_PATH_DEFINES;
4009 #endif
4010 else if (*e_cpt == ']' || *e_cpt == 't')
4012 type = CTRL_X_TAGS;
4013 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4014 (void)msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
4016 else
4017 type = -1;
4019 /* in any case e_cpt is advanced to the next entry */
4020 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
4022 found_all = TRUE;
4023 if (type == -1)
4024 continue;
4028 switch (type)
4030 case -1:
4031 break;
4032 #ifdef FEAT_FIND_ID
4033 case CTRL_X_PATH_PATTERNS:
4034 case CTRL_X_PATH_DEFINES:
4035 find_pattern_in_path(compl_pattern, compl_direction,
4036 (int)STRLEN(compl_pattern), FALSE, FALSE,
4037 (type == CTRL_X_PATH_DEFINES
4038 && !(compl_cont_status & CONT_SOL))
4039 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
4040 (linenr_T)1, (linenr_T)MAXLNUM);
4041 break;
4042 #endif
4044 case CTRL_X_DICTIONARY:
4045 case CTRL_X_THESAURUS:
4046 ins_compl_dictionaries(
4047 dict != NULL ? dict
4048 : (type == CTRL_X_THESAURUS
4049 ? (*curbuf->b_p_tsr == NUL
4050 ? p_tsr
4051 : curbuf->b_p_tsr)
4052 : (*curbuf->b_p_dict == NUL
4053 ? p_dict
4054 : curbuf->b_p_dict)),
4055 compl_pattern,
4056 dict != NULL ? dict_f
4057 : 0, type == CTRL_X_THESAURUS);
4058 dict = NULL;
4059 break;
4061 case CTRL_X_TAGS:
4062 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
4063 save_p_ic = p_ic;
4064 p_ic = ignorecase(compl_pattern);
4066 /* Find up to TAG_MANY matches. Avoids that an enormous number
4067 * of matches is found when compl_pattern is empty */
4068 g_tag_at_cursor = 1;
4069 if (find_tags(compl_pattern, &num_matches, &matches,
4070 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
4071 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
4072 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4074 ins_compl_add_matches(num_matches, matches, p_ic);
4076 g_tag_at_cursor = 0;
4077 p_ic = save_p_ic;
4078 break;
4080 case CTRL_X_FILES:
4081 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
4082 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
4085 /* May change home directory back to "~". */
4086 tilde_replace(compl_pattern, num_matches, matches);
4087 ins_compl_add_matches(num_matches, matches,
4088 #ifdef CASE_INSENSITIVE_FILENAME
4089 TRUE
4090 #else
4091 FALSE
4092 #endif
4095 break;
4097 case CTRL_X_CMDLINE:
4098 if (expand_cmdline(&compl_xp, compl_pattern,
4099 (int)STRLEN(compl_pattern),
4100 &num_matches, &matches) == EXPAND_OK)
4101 ins_compl_add_matches(num_matches, matches, FALSE);
4102 break;
4104 #ifdef FEAT_COMPL_FUNC
4105 case CTRL_X_FUNCTION:
4106 case CTRL_X_OMNI:
4107 expand_by_function(type, compl_pattern);
4108 break;
4109 #endif
4111 case CTRL_X_SPELL:
4112 #ifdef FEAT_SPELL
4113 num_matches = expand_spelling(first_match_pos.lnum,
4114 compl_pattern, &matches);
4115 if (num_matches > 0)
4116 ins_compl_add_matches(num_matches, matches, p_ic);
4117 #endif
4118 break;
4120 default: /* normal ^P/^N and ^X^L */
4122 * If 'infercase' is set, don't use 'smartcase' here
4124 save_p_scs = p_scs;
4125 if (ins_buf->b_p_inf)
4126 p_scs = FALSE;
4128 /* buffers other than curbuf are scanned from the beginning or the
4129 * end but never from the middle, thus setting nowrapscan in this
4130 * buffers is a good idea, on the other hand, we always set
4131 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
4132 save_p_ws = p_ws;
4133 if (ins_buf != curbuf)
4134 p_ws = FALSE;
4135 else if (*e_cpt == '.')
4136 p_ws = TRUE;
4137 for (;;)
4139 int flags = 0;
4141 ++msg_silent; /* Don't want messages for wrapscan. */
4143 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that
4144 * has added a word that was at the beginning of the line */
4145 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
4146 || (compl_cont_status & CONT_SOL))
4147 found_new_match = search_for_exact_line(ins_buf, pos,
4148 compl_direction, compl_pattern);
4149 else
4150 found_new_match = searchit(NULL, ins_buf, pos,
4151 compl_direction,
4152 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
4153 RE_LAST, (linenr_T)0, NULL);
4154 --msg_silent;
4155 if (!compl_started)
4157 /* set "compl_started" even on fail */
4158 compl_started = TRUE;
4159 first_match_pos = *pos;
4160 last_match_pos = *pos;
4162 else if (first_match_pos.lnum == last_match_pos.lnum
4163 && first_match_pos.col == last_match_pos.col)
4164 found_new_match = FAIL;
4165 if (found_new_match == FAIL)
4167 if (ins_buf == curbuf)
4168 found_all = TRUE;
4169 break;
4172 /* when ADDING, the text before the cursor matches, skip it */
4173 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
4174 && ini->lnum == pos->lnum
4175 && ini->col == pos->col)
4176 continue;
4177 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
4178 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4180 if (compl_cont_status & CONT_ADDING)
4182 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
4183 continue;
4184 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4185 if (!p_paste)
4186 ptr = skipwhite(ptr);
4188 len = (int)STRLEN(ptr);
4190 else
4192 char_u *tmp_ptr = ptr;
4194 if (compl_cont_status & CONT_ADDING)
4196 tmp_ptr += compl_length;
4197 /* Skip if already inside a word. */
4198 if (vim_iswordp(tmp_ptr))
4199 continue;
4200 /* Find start of next word. */
4201 tmp_ptr = find_word_start(tmp_ptr);
4203 /* Find end of this word. */
4204 tmp_ptr = find_word_end(tmp_ptr);
4205 len = (int)(tmp_ptr - ptr);
4207 if ((compl_cont_status & CONT_ADDING)
4208 && len == compl_length)
4210 if (pos->lnum < ins_buf->b_ml.ml_line_count)
4212 /* Try next line, if any. the new word will be
4213 * "join" as if the normal command "J" was used.
4214 * IOSIZE is always greater than
4215 * compl_length, so the next STRNCPY always
4216 * works -- Acevedo */
4217 STRNCPY(IObuff, ptr, len);
4218 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
4219 tmp_ptr = ptr = skipwhite(ptr);
4220 /* Find start of next word. */
4221 tmp_ptr = find_word_start(tmp_ptr);
4222 /* Find end of next word. */
4223 tmp_ptr = find_word_end(tmp_ptr);
4224 if (tmp_ptr > ptr)
4226 if (*ptr != ')' && IObuff[len - 1] != TAB)
4228 if (IObuff[len - 1] != ' ')
4229 IObuff[len++] = ' ';
4230 /* IObuf =~ "\k.* ", thus len >= 2 */
4231 if (p_js
4232 && (IObuff[len - 2] == '.'
4233 || (vim_strchr(p_cpo, CPO_JOINSP)
4234 == NULL
4235 && (IObuff[len - 2] == '?'
4236 || IObuff[len - 2] == '!'))))
4237 IObuff[len++] = ' ';
4239 /* copy as much as possible of the new word */
4240 if (tmp_ptr - ptr >= IOSIZE - len)
4241 tmp_ptr = ptr + IOSIZE - len - 1;
4242 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4243 len += (int)(tmp_ptr - ptr);
4244 flags |= CONT_S_IPOS;
4246 IObuff[len] = NUL;
4247 ptr = IObuff;
4249 if (len == compl_length)
4250 continue;
4253 if (ins_compl_add_infercase(ptr, len, p_ic,
4254 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
4255 0, flags) != NOTDONE)
4257 found_new_match = OK;
4258 break;
4261 p_scs = save_p_scs;
4262 p_ws = save_p_ws;
4265 /* check if compl_curr_match has changed, (e.g. other type of
4266 * expansion added something) */
4267 if (type != 0 && compl_curr_match != old_match)
4268 found_new_match = OK;
4270 /* break the loop for specialized modes (use 'complete' just for the
4271 * generic ctrl_x_mode == 0) or when we've found a new match */
4272 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4273 || found_new_match != FAIL)
4275 if (got_int)
4276 break;
4277 /* Fill the popup menu as soon as possible. */
4278 if (type != -1)
4279 ins_compl_check_keys(0);
4281 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
4282 || compl_interrupted)
4283 break;
4284 compl_started = TRUE;
4286 else
4288 /* Mark a buffer scanned when it has been scanned completely */
4289 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
4290 ins_buf->b_scanned = TRUE;
4292 compl_started = FALSE;
4295 compl_started = TRUE;
4297 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
4298 && *e_cpt == NUL) /* Got to end of 'complete' */
4299 found_new_match = FAIL;
4301 i = -1; /* total of matches, unknown */
4302 if (found_new_match == FAIL
4303 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
4304 i = ins_compl_make_cyclic();
4306 /* If several matches were added (FORWARD) or the search failed and has
4307 * just been made cyclic then we have to move compl_curr_match to the next
4308 * or previous entry (if any) -- Acevedo */
4309 compl_curr_match = compl_direction == FORWARD ? old_match->cp_next
4310 : old_match->cp_prev;
4311 if (compl_curr_match == NULL)
4312 compl_curr_match = old_match;
4313 return i;
4316 /* Delete the old text being completed. */
4317 static void
4318 ins_compl_delete()
4320 int i;
4323 * In insert mode: Delete the typed part.
4324 * In replace mode: Put the old characters back, if any.
4326 i = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
4327 backspace_until_column(i);
4328 changed_cline_bef_curs();
4331 /* Insert the new text being completed. */
4332 static void
4333 ins_compl_insert()
4335 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
4336 if (compl_shown_match->cp_flags & ORIGINAL_TEXT)
4337 compl_used_match = FALSE;
4338 else
4339 compl_used_match = TRUE;
4343 * Fill in the next completion in the current direction.
4344 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4345 * get more completions. If it is FALSE, then we just do nothing when there
4346 * are no more completions in a given direction. The latter case is used when
4347 * we are still in the middle of finding completions, to allow browsing
4348 * through the ones found so far.
4349 * Return the total number of matches, or -1 if still unknown -- webb.
4351 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4352 * compl_shown_match here.
4354 * Note that this function may be called recursively once only. First with
4355 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4356 * calls this function with "allow_get_expansion" FALSE.
4358 static int
4359 ins_compl_next(allow_get_expansion, count, insert_match)
4360 int allow_get_expansion;
4361 int count; /* repeat completion this many times; should
4362 be at least 1 */
4363 int insert_match; /* Insert the newly selected match */
4365 int num_matches = -1;
4366 int i;
4367 int todo = count;
4368 compl_T *found_compl = NULL;
4369 int found_end = FALSE;
4370 int advance;
4372 if (compl_leader != NULL
4373 && (compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0)
4375 /* Set "compl_shown_match" to the actually shown match, it may differ
4376 * when "compl_leader" is used to omit some of the matches. */
4377 while (!ins_compl_equal(compl_shown_match,
4378 compl_leader, (int)STRLEN(compl_leader))
4379 && compl_shown_match->cp_next != NULL
4380 && compl_shown_match->cp_next != compl_first_match)
4381 compl_shown_match = compl_shown_match->cp_next;
4383 /* If we didn't find it searching forward, and compl_shows_dir is
4384 * backward, find the last match. */
4385 if (compl_shows_dir == BACKWARD
4386 && !ins_compl_equal(compl_shown_match,
4387 compl_leader, (int)STRLEN(compl_leader))
4388 && (compl_shown_match->cp_next == NULL
4389 || compl_shown_match->cp_next == compl_first_match))
4391 while (!ins_compl_equal(compl_shown_match,
4392 compl_leader, (int)STRLEN(compl_leader))
4393 && compl_shown_match->cp_prev != NULL
4394 && compl_shown_match->cp_prev != compl_first_match)
4395 compl_shown_match = compl_shown_match->cp_prev;
4399 if (allow_get_expansion && insert_match
4400 && (!(compl_get_longest || compl_restarting) || compl_used_match))
4401 /* Delete old text to be replaced */
4402 ins_compl_delete();
4404 /* When finding the longest common text we stick at the original text,
4405 * don't let CTRL-N or CTRL-P move to the first match. */
4406 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4408 /* When restarting the search don't insert the first match either. */
4409 if (compl_restarting)
4411 advance = FALSE;
4412 compl_restarting = FALSE;
4415 /* Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4416 * around. */
4417 while (--todo >= 0)
4419 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
4421 compl_shown_match = compl_shown_match->cp_next;
4422 found_end = (compl_first_match != NULL
4423 && (compl_shown_match->cp_next == compl_first_match
4424 || compl_shown_match == compl_first_match));
4426 else if (compl_shows_dir == BACKWARD
4427 && compl_shown_match->cp_prev != NULL)
4429 found_end = (compl_shown_match == compl_first_match);
4430 compl_shown_match = compl_shown_match->cp_prev;
4431 found_end |= (compl_shown_match == compl_first_match);
4433 else
4435 if (!allow_get_expansion)
4437 if (advance)
4439 if (compl_shows_dir == BACKWARD)
4440 compl_pending -= todo + 1;
4441 else
4442 compl_pending += todo + 1;
4444 return -1;
4447 if (advance)
4449 if (compl_shows_dir == BACKWARD)
4450 --compl_pending;
4451 else
4452 ++compl_pending;
4455 /* Find matches. */
4456 num_matches = ins_compl_get_exp(&compl_startpos);
4458 /* handle any pending completions */
4459 while (compl_pending != 0 && compl_direction == compl_shows_dir
4460 && advance)
4462 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4464 compl_shown_match = compl_shown_match->cp_next;
4465 --compl_pending;
4467 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4469 compl_shown_match = compl_shown_match->cp_prev;
4470 ++compl_pending;
4472 else
4473 break;
4475 found_end = FALSE;
4477 if ((compl_shown_match->cp_flags & ORIGINAL_TEXT) == 0
4478 && compl_leader != NULL
4479 && !ins_compl_equal(compl_shown_match,
4480 compl_leader, (int)STRLEN(compl_leader)))
4481 ++todo;
4482 else
4483 /* Remember a matching item. */
4484 found_compl = compl_shown_match;
4486 /* Stop at the end of the list when we found a usable match. */
4487 if (found_end)
4489 if (found_compl != NULL)
4491 compl_shown_match = found_compl;
4492 break;
4494 todo = 1; /* use first usable match after wrapping around */
4498 /* Insert the text of the new completion, or the compl_leader. */
4499 if (insert_match)
4501 if (!compl_get_longest || compl_used_match)
4502 ins_compl_insert();
4503 else
4504 ins_bytes(compl_leader + ins_compl_len());
4506 else
4507 compl_used_match = FALSE;
4509 if (!allow_get_expansion)
4511 /* may undisplay the popup menu first */
4512 ins_compl_upd_pum();
4514 /* redraw to show the user what was inserted */
4515 update_screen(0);
4517 /* display the updated popup menu */
4518 ins_compl_show_pum();
4519 #ifdef FEAT_GUI
4520 if (gui.in_use)
4522 /* Show the cursor after the match, not after the redrawn text. */
4523 setcursor();
4524 out_flush();
4525 gui_update_cursor(FALSE, FALSE);
4527 #endif
4529 /* Delete old text to be replaced, since we're still searching and
4530 * don't want to match ourselves! */
4531 ins_compl_delete();
4534 /* Enter will select a match when the match wasn't inserted and the popup
4535 * menu is visible. */
4536 compl_enter_selects = !insert_match && compl_match_array != NULL;
4539 * Show the file name for the match (if any)
4540 * Truncate the file name to avoid a wait for return.
4542 if (compl_shown_match->cp_fname != NULL)
4544 STRCPY(IObuff, "match in file ");
4545 i = (vim_strsize(compl_shown_match->cp_fname) + 16) - sc_col;
4546 if (i <= 0)
4547 i = 0;
4548 else
4549 STRCAT(IObuff, "<");
4550 STRCAT(IObuff, compl_shown_match->cp_fname + i);
4551 msg(IObuff);
4552 redraw_cmdline = FALSE; /* don't overwrite! */
4555 return num_matches;
4559 * Call this while finding completions, to check whether the user has hit a key
4560 * that should change the currently displayed completion, or exit completion
4561 * mode. Also, when compl_pending is not zero, show a completion as soon as
4562 * possible. -- webb
4563 * "frequency" specifies out of how many calls we actually check.
4565 void
4566 ins_compl_check_keys(frequency)
4567 int frequency;
4569 static int count = 0;
4571 int c;
4573 /* Don't check when reading keys from a script. That would break the test
4574 * scripts */
4575 if (using_script())
4576 return;
4578 /* Only do this at regular intervals */
4579 if (++count < frequency)
4580 return;
4581 count = 0;
4583 /* Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4584 * can't do its work correctly. */
4585 c = vpeekc_any();
4586 if (c != NUL)
4588 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4590 c = safe_vgetc(); /* Eat the character */
4591 compl_shows_dir = ins_compl_key2dir(c);
4592 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4593 c != K_UP && c != K_DOWN);
4595 else
4597 /* Need to get the character to have KeyTyped set. We'll put it
4598 * back with vungetc() below. But skip K_IGNORE. */
4599 c = safe_vgetc();
4600 if (c != K_IGNORE)
4602 /* Don't interrupt completion when the character wasn't typed,
4603 * e.g., when doing @q to replay keys. */
4604 if (c != Ctrl_R && KeyTyped)
4605 compl_interrupted = TRUE;
4607 vungetc(c);
4611 if (compl_pending != 0 && !got_int)
4613 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4615 compl_pending = 0;
4616 (void)ins_compl_next(FALSE, todo, TRUE);
4621 * Decide the direction of Insert mode complete from the key typed.
4622 * Returns BACKWARD or FORWARD.
4624 static int
4625 ins_compl_key2dir(c)
4626 int c;
4628 if (c == Ctrl_P || c == Ctrl_L
4629 || (pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP
4630 || c == K_S_UP || c == K_UP)))
4631 return BACKWARD;
4632 return FORWARD;
4636 * Return TRUE for keys that are used for completion only when the popup menu
4637 * is visible.
4639 static int
4640 ins_compl_pum_key(c)
4641 int c;
4643 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4644 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4645 || c == K_UP || c == K_DOWN);
4649 * Decide the number of completions to move forward.
4650 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4652 static int
4653 ins_compl_key2count(c)
4654 int c;
4656 int h;
4658 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4660 h = pum_get_height();
4661 if (h > 3)
4662 h -= 2; /* keep some context */
4663 return h;
4665 return 1;
4669 * Return TRUE if completion with "c" should insert the match, FALSE if only
4670 * to change the currently selected completion.
4672 static int
4673 ins_compl_use_match(c)
4674 int c;
4676 switch (c)
4678 case K_UP:
4679 case K_DOWN:
4680 case K_PAGEDOWN:
4681 case K_KPAGEDOWN:
4682 case K_S_DOWN:
4683 case K_PAGEUP:
4684 case K_KPAGEUP:
4685 case K_S_UP:
4686 return FALSE;
4688 return TRUE;
4692 * Do Insert mode completion.
4693 * Called when character "c" was typed, which has a meaning for completion.
4694 * Returns OK if completion was done, FAIL if something failed (out of mem).
4696 static int
4697 ins_complete(c)
4698 int c;
4700 char_u *line;
4701 int startcol = 0; /* column where searched text starts */
4702 colnr_T curs_col; /* cursor column */
4703 int n;
4704 int save_w_wrow;
4706 compl_direction = ins_compl_key2dir(c);
4707 if (!compl_started)
4709 /* First time we hit ^N or ^P (in a row, I mean) */
4711 did_ai = FALSE;
4712 #ifdef FEAT_SMARTINDENT
4713 did_si = FALSE;
4714 can_si = FALSE;
4715 can_si_back = FALSE;
4716 #endif
4717 if (stop_arrow() == FAIL)
4718 return FAIL;
4720 line = ml_get(curwin->w_cursor.lnum);
4721 curs_col = curwin->w_cursor.col;
4722 compl_pending = 0;
4724 /* If this same ctrl_x_mode has been interrupted use the text from
4725 * "compl_startpos" to the cursor as a pattern to add a new word
4726 * instead of expand the one before the cursor, in word-wise if
4727 * "compl_startpos" is not in the same line as the cursor then fix it
4728 * (the line has been split because it was longer than 'tw'). if SOL
4729 * is set then skip the previous pattern, a word at the beginning of
4730 * the line has been inserted, we'll look for that -- Acevedo. */
4731 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4732 && compl_cont_mode == ctrl_x_mode)
4735 * it is a continued search
4737 compl_cont_status &= ~CONT_INTRPT; /* remove INTRPT */
4738 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4739 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4741 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4743 /* line (probably) wrapped, set compl_startpos to the
4744 * first non_blank in the line, if it is not a wordchar
4745 * include it to get a better pattern, but then we don't
4746 * want the "\\<" prefix, check it bellow */
4747 compl_col = (colnr_T)(skipwhite(line) - line);
4748 compl_startpos.col = compl_col;
4749 compl_startpos.lnum = curwin->w_cursor.lnum;
4750 compl_cont_status &= ~CONT_SOL; /* clear SOL if present */
4752 else
4754 /* S_IPOS was set when we inserted a word that was at the
4755 * beginning of the line, which means that we'll go to SOL
4756 * mode but first we need to redefine compl_startpos */
4757 if (compl_cont_status & CONT_S_IPOS)
4759 compl_cont_status |= CONT_SOL;
4760 compl_startpos.col = (colnr_T)(skipwhite(
4761 line + compl_length
4762 + compl_startpos.col) - line);
4764 compl_col = compl_startpos.col;
4766 compl_length = curwin->w_cursor.col - (int)compl_col;
4767 /* IObuff is used to add a "word from the next line" would we
4768 * have enough space? just being paranoid */
4769 #define MIN_SPACE 75
4770 if (compl_length > (IOSIZE - MIN_SPACE))
4772 compl_cont_status &= ~CONT_SOL;
4773 compl_length = (IOSIZE - MIN_SPACE);
4774 compl_col = curwin->w_cursor.col - compl_length;
4776 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4777 if (compl_length < 1)
4778 compl_cont_status &= CONT_LOCAL;
4780 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4781 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4782 else
4783 compl_cont_status = 0;
4785 else
4786 compl_cont_status &= CONT_LOCAL;
4788 if (!(compl_cont_status & CONT_ADDING)) /* normal expansion */
4790 compl_cont_mode = ctrl_x_mode;
4791 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
4792 compl_cont_status = 0;
4793 compl_cont_status |= CONT_N_ADDS;
4794 compl_startpos = curwin->w_cursor;
4795 startcol = (int)curs_col;
4796 compl_col = 0;
4799 /* Work out completion pattern and original text -- webb */
4800 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
4802 if ((compl_cont_status & CONT_SOL)
4803 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4805 if (!(compl_cont_status & CONT_ADDING))
4807 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4809 compl_col += ++startcol;
4810 compl_length = curs_col - startcol;
4812 if (p_ic)
4813 compl_pattern = str_foldcase(line + compl_col,
4814 compl_length, NULL, 0);
4815 else
4816 compl_pattern = vim_strnsave(line + compl_col,
4817 compl_length);
4818 if (compl_pattern == NULL)
4819 return FAIL;
4821 else if (compl_cont_status & CONT_ADDING)
4823 char_u *prefix = (char_u *)"\\<";
4825 /* we need up to 2 extra chars for the prefix */
4826 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4827 compl_length) + 2);
4828 if (compl_pattern == NULL)
4829 return FAIL;
4830 if (!vim_iswordp(line + compl_col)
4831 || (compl_col > 0
4832 && (
4833 #ifdef FEAT_MBYTE
4834 vim_iswordp(mb_prevptr(line, line + compl_col))
4835 #else
4836 vim_iswordc(line[compl_col - 1])
4837 #endif
4839 prefix = (char_u *)"";
4840 STRCPY((char *)compl_pattern, prefix);
4841 (void)quote_meta(compl_pattern + STRLEN(prefix),
4842 line + compl_col, compl_length);
4844 else if (--startcol < 0 ||
4845 #ifdef FEAT_MBYTE
4846 !vim_iswordp(mb_prevptr(line, line + startcol + 1))
4847 #else
4848 !vim_iswordc(line[startcol])
4849 #endif
4852 /* Match any word of at least two chars */
4853 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4854 if (compl_pattern == NULL)
4855 return FAIL;
4856 compl_col += curs_col;
4857 compl_length = 0;
4859 else
4861 #ifdef FEAT_MBYTE
4862 /* Search the point of change class of multibyte character
4863 * or not a word single byte character backward. */
4864 if (has_mbyte)
4866 int base_class;
4867 int head_off;
4869 startcol -= (*mb_head_off)(line, line + startcol);
4870 base_class = mb_get_class(line + startcol);
4871 while (--startcol >= 0)
4873 head_off = (*mb_head_off)(line, line + startcol);
4874 if (base_class != mb_get_class(line + startcol
4875 - head_off))
4876 break;
4877 startcol -= head_off;
4880 else
4881 #endif
4882 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4884 compl_col += ++startcol;
4885 compl_length = (int)curs_col - startcol;
4886 if (compl_length == 1)
4888 /* Only match word with at least two chars -- webb
4889 * there's no need to call quote_meta,
4890 * alloc(7) is enough -- Acevedo
4892 compl_pattern = alloc(7);
4893 if (compl_pattern == NULL)
4894 return FAIL;
4895 STRCPY((char *)compl_pattern, "\\<");
4896 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4897 STRCAT((char *)compl_pattern, "\\k");
4899 else
4901 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4902 compl_length) + 2);
4903 if (compl_pattern == NULL)
4904 return FAIL;
4905 STRCPY((char *)compl_pattern, "\\<");
4906 (void)quote_meta(compl_pattern + 2, line + compl_col,
4907 compl_length);
4911 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
4913 compl_col = (colnr_T)(skipwhite(line) - line);
4914 compl_length = (int)curs_col - (int)compl_col;
4915 if (compl_length < 0) /* cursor in indent: empty pattern */
4916 compl_length = 0;
4917 if (p_ic)
4918 compl_pattern = str_foldcase(line + compl_col, compl_length,
4919 NULL, 0);
4920 else
4921 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4922 if (compl_pattern == NULL)
4923 return FAIL;
4925 else if (ctrl_x_mode == CTRL_X_FILES)
4927 while (--startcol >= 0 && vim_isfilec(line[startcol]))
4929 compl_col += ++startcol;
4930 compl_length = (int)curs_col - startcol;
4931 compl_pattern = addstar(line + compl_col, compl_length,
4932 EXPAND_FILES);
4933 if (compl_pattern == NULL)
4934 return FAIL;
4936 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4938 compl_pattern = vim_strnsave(line, curs_col);
4939 if (compl_pattern == NULL)
4940 return FAIL;
4941 set_cmd_context(&compl_xp, compl_pattern,
4942 (int)STRLEN(compl_pattern), curs_col);
4943 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4944 || compl_xp.xp_context == EXPAND_NOTHING)
4945 /* No completion possible, use an empty pattern to get a
4946 * "pattern not found" message. */
4947 compl_col = curs_col;
4948 else
4949 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4950 compl_length = curs_col - compl_col;
4952 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
4954 #ifdef FEAT_COMPL_FUNC
4956 * Call user defined function 'completefunc' with "a:findstart"
4957 * set to 1 to obtain the length of text to use for completion.
4959 char_u *args[2];
4960 int col;
4961 char_u *funcname;
4962 pos_T pos;
4964 /* Call 'completefunc' or 'omnifunc' and get pattern length as a
4965 * string */
4966 funcname = ctrl_x_mode == CTRL_X_FUNCTION
4967 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
4968 if (*funcname == NUL)
4970 EMSG2(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4971 ? "completefunc" : "omnifunc");
4972 return FAIL;
4975 args[0] = (char_u *)"1";
4976 args[1] = NULL;
4977 pos = curwin->w_cursor;
4978 col = call_func_retnr(funcname, 2, args, FALSE);
4979 curwin->w_cursor = pos; /* restore the cursor position */
4981 if (col < 0)
4982 col = curs_col;
4983 compl_col = col;
4984 if (compl_col > curs_col)
4985 compl_col = curs_col;
4987 /* Setup variables for completion. Need to obtain "line" again,
4988 * it may have become invalid. */
4989 line = ml_get(curwin->w_cursor.lnum);
4990 compl_length = curs_col - compl_col;
4991 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4992 if (compl_pattern == NULL)
4993 #endif
4994 return FAIL;
4996 else if (ctrl_x_mode == CTRL_X_SPELL)
4998 #ifdef FEAT_SPELL
4999 if (spell_bad_len > 0)
5000 compl_col = curs_col - spell_bad_len;
5001 else
5002 compl_col = spell_word_start(startcol);
5003 if (compl_col >= (colnr_T)startcol)
5005 compl_length = 0;
5006 compl_col = curs_col;
5008 else
5010 spell_expand_check_cap(compl_col);
5011 compl_length = (int)curs_col - compl_col;
5013 /* Need to obtain "line" again, it may have become invalid. */
5014 line = ml_get(curwin->w_cursor.lnum);
5015 compl_pattern = vim_strnsave(line + compl_col, compl_length);
5016 if (compl_pattern == NULL)
5017 #endif
5018 return FAIL;
5020 else
5022 EMSG2(_(e_intern2), "ins_complete()");
5023 return FAIL;
5026 if (compl_cont_status & CONT_ADDING)
5028 edit_submode_pre = (char_u *)_(" Adding");
5029 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
5031 /* Insert a new line, keep indentation but ignore 'comments' */
5032 #ifdef FEAT_COMMENTS
5033 char_u *old = curbuf->b_p_com;
5035 curbuf->b_p_com = (char_u *)"";
5036 #endif
5037 compl_startpos.lnum = curwin->w_cursor.lnum;
5038 compl_startpos.col = compl_col;
5039 ins_eol('\r');
5040 #ifdef FEAT_COMMENTS
5041 curbuf->b_p_com = old;
5042 #endif
5043 compl_length = 0;
5044 compl_col = curwin->w_cursor.col;
5047 else
5049 edit_submode_pre = NULL;
5050 compl_startpos.col = compl_col;
5053 if (compl_cont_status & CONT_LOCAL)
5054 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5055 else
5056 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5058 /* Always add completion for the original text. */
5059 vim_free(compl_orig_text);
5060 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5061 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5062 -1, p_ic, NULL, NULL, 0, ORIGINAL_TEXT, FALSE) != OK)
5064 vim_free(compl_pattern);
5065 compl_pattern = NULL;
5066 vim_free(compl_orig_text);
5067 compl_orig_text = NULL;
5068 return FAIL;
5071 /* showmode might reset the internal line pointers, so it must
5072 * be called before line = ml_get(), or when this address is no
5073 * longer needed. -- Acevedo.
5075 edit_submode_extra = (char_u *)_("-- Searching...");
5076 edit_submode_highl = HLF_COUNT;
5077 showmode();
5078 edit_submode_extra = NULL;
5079 out_flush();
5082 compl_shown_match = compl_curr_match;
5083 compl_shows_dir = compl_direction;
5086 * Find next match (and following matches).
5088 save_w_wrow = curwin->w_wrow;
5089 n = ins_compl_next(TRUE, ins_compl_key2count(c), ins_compl_use_match(c));
5091 /* may undisplay the popup menu */
5092 ins_compl_upd_pum();
5094 if (n > 1) /* all matches have been found */
5095 compl_matches = n;
5096 compl_curr_match = compl_shown_match;
5097 compl_direction = compl_shows_dir;
5099 /* Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5100 * mode. */
5101 if (got_int && !global_busy)
5103 (void)vgetc();
5104 got_int = FALSE;
5107 /* we found no match if the list has only the "compl_orig_text"-entry */
5108 if (compl_first_match == compl_first_match->cp_next)
5110 edit_submode_extra = (compl_cont_status & CONT_ADDING)
5111 && compl_length > 1
5112 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
5113 edit_submode_highl = HLF_E;
5114 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5115 * because we couldn't expand anything at first place, but if we used
5116 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5117 * (such as M in M'exico) if not tried already. -- Acevedo */
5118 if ( compl_length > 1
5119 || (compl_cont_status & CONT_ADDING)
5120 || (ctrl_x_mode != 0
5121 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
5122 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
5123 compl_cont_status &= ~CONT_N_ADDS;
5126 if (compl_curr_match->cp_flags & CONT_S_IPOS)
5127 compl_cont_status |= CONT_S_IPOS;
5128 else
5129 compl_cont_status &= ~CONT_S_IPOS;
5131 if (edit_submode_extra == NULL)
5133 if (compl_curr_match->cp_flags & ORIGINAL_TEXT)
5135 edit_submode_extra = (char_u *)_("Back at original");
5136 edit_submode_highl = HLF_W;
5138 else if (compl_cont_status & CONT_S_IPOS)
5140 edit_submode_extra = (char_u *)_("Word from other line");
5141 edit_submode_highl = HLF_COUNT;
5143 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5145 edit_submode_extra = (char_u *)_("The only match");
5146 edit_submode_highl = HLF_COUNT;
5148 else
5150 /* Update completion sequence number when needed. */
5151 if (compl_curr_match->cp_number == -1)
5153 int number = 0;
5154 compl_T *match;
5156 if (compl_direction == FORWARD)
5158 /* search backwards for the first valid (!= -1) number.
5159 * This should normally succeed already at the first loop
5160 * cycle, so it's fast! */
5161 for (match = compl_curr_match->cp_prev; match != NULL
5162 && match != compl_first_match;
5163 match = match->cp_prev)
5164 if (match->cp_number != -1)
5166 number = match->cp_number;
5167 break;
5169 if (match != NULL)
5170 /* go up and assign all numbers which are not assigned
5171 * yet */
5172 for (match = match->cp_next;
5173 match != NULL && match->cp_number == -1;
5174 match = match->cp_next)
5175 match->cp_number = ++number;
5177 else /* BACKWARD */
5179 /* search forwards (upwards) for the first valid (!= -1)
5180 * number. This should normally succeed already at the
5181 * first loop cycle, so it's fast! */
5182 for (match = compl_curr_match->cp_next; match != NULL
5183 && match != compl_first_match;
5184 match = match->cp_next)
5185 if (match->cp_number != -1)
5187 number = match->cp_number;
5188 break;
5190 if (match != NULL)
5191 /* go down and assign all numbers which are not
5192 * assigned yet */
5193 for (match = match->cp_prev; match
5194 && match->cp_number == -1;
5195 match = match->cp_prev)
5196 match->cp_number = ++number;
5200 /* The match should always have a sequence number now, this is
5201 * just a safety check. */
5202 if (compl_curr_match->cp_number != -1)
5204 /* Space for 10 text chars. + 2x10-digit no.s = 31.
5205 * Translations may need more than twice that. */
5206 static char_u match_ref[81];
5208 if (compl_matches > 0)
5209 vim_snprintf((char *)match_ref, sizeof(match_ref),
5210 _("match %d of %d"),
5211 compl_curr_match->cp_number, compl_matches);
5212 else
5213 vim_snprintf((char *)match_ref, sizeof(match_ref),
5214 _("match %d"),
5215 compl_curr_match->cp_number);
5216 edit_submode_extra = match_ref;
5217 edit_submode_highl = HLF_R;
5218 if (dollar_vcol)
5219 curs_columns(FALSE);
5224 /* Show a message about what (completion) mode we're in. */
5225 showmode();
5226 if (edit_submode_extra != NULL)
5228 if (!p_smd)
5229 msg_attr(edit_submode_extra,
5230 edit_submode_highl < HLF_COUNT
5231 ? hl_attr(edit_submode_highl) : 0);
5233 else
5234 msg_clr_cmdline(); /* necessary for "noshowmode" */
5236 /* Show the popup menu, unless we got interrupted. */
5237 if (!compl_interrupted)
5239 /* RedrawingDisabled may be set when invoked through complete(). */
5240 n = RedrawingDisabled;
5241 RedrawingDisabled = 0;
5243 /* If the cursor moved we need to remove the pum first. */
5244 setcursor();
5245 if (save_w_wrow != curwin->w_wrow)
5246 ins_compl_del_pum();
5248 ins_compl_show_pum();
5249 setcursor();
5250 RedrawingDisabled = n;
5252 compl_was_interrupted = compl_interrupted;
5253 compl_interrupted = FALSE;
5255 return OK;
5259 * Looks in the first "len" chars. of "src" for search-metachars.
5260 * If dest is not NULL the chars. are copied there quoting (with
5261 * a backslash) the metachars, and dest would be NUL terminated.
5262 * Returns the length (needed) of dest
5264 static unsigned
5265 quote_meta(dest, src, len)
5266 char_u *dest;
5267 char_u *src;
5268 int len;
5270 unsigned m = (unsigned)len + 1; /* one extra for the NUL */
5272 for ( ; --len >= 0; src++)
5274 switch (*src)
5276 case '.':
5277 case '*':
5278 case '[':
5279 if (ctrl_x_mode == CTRL_X_DICTIONARY
5280 || ctrl_x_mode == CTRL_X_THESAURUS)
5281 break;
5282 case '~':
5283 if (!p_magic) /* quote these only if magic is set */
5284 break;
5285 case '\\':
5286 if (ctrl_x_mode == CTRL_X_DICTIONARY
5287 || ctrl_x_mode == CTRL_X_THESAURUS)
5288 break;
5289 case '^': /* currently it's not needed. */
5290 case '$':
5291 m++;
5292 if (dest != NULL)
5293 *dest++ = '\\';
5294 break;
5296 if (dest != NULL)
5297 *dest++ = *src;
5298 # ifdef FEAT_MBYTE
5299 /* Copy remaining bytes of a multibyte character. */
5300 if (has_mbyte)
5302 int i, mb_len;
5304 mb_len = (*mb_ptr2len)(src) - 1;
5305 if (mb_len > 0 && len >= mb_len)
5306 for (i = 0; i < mb_len; ++i)
5308 --len;
5309 ++src;
5310 if (dest != NULL)
5311 *dest++ = *src;
5314 # endif
5316 if (dest != NULL)
5317 *dest = NUL;
5319 return m;
5321 #endif /* FEAT_INS_EXPAND */
5324 * Next character is interpreted literally.
5325 * A one, two or three digit decimal number is interpreted as its byte value.
5326 * If one or two digits are entered, the next character is given to vungetc().
5327 * For Unicode a character > 255 may be returned.
5330 get_literal()
5332 int cc;
5333 int nc;
5334 int i;
5335 int hex = FALSE;
5336 int octal = FALSE;
5337 #ifdef FEAT_MBYTE
5338 int unicode = 0;
5339 #endif
5341 if (got_int)
5342 return Ctrl_C;
5344 #ifdef FEAT_GUI
5346 * In GUI there is no point inserting the internal code for a special key.
5347 * It is more useful to insert the string "<KEY>" instead. This would
5348 * probably be useful in a text window too, but it would not be
5349 * vi-compatible (maybe there should be an option for it?) -- webb
5351 if (gui.in_use)
5352 ++allow_keys;
5353 #endif
5354 #ifdef USE_ON_FLY_SCROLL
5355 dont_scroll = TRUE; /* disallow scrolling here */
5356 #endif
5357 ++no_mapping; /* don't map the next key hits */
5358 cc = 0;
5359 i = 0;
5360 for (;;)
5362 nc = plain_vgetc();
5363 #ifdef FEAT_CMDL_INFO
5364 if (!(State & CMDLINE)
5365 # ifdef FEAT_MBYTE
5366 && MB_BYTE2LEN_CHECK(nc) == 1
5367 # endif
5369 add_to_showcmd(nc);
5370 #endif
5371 if (nc == 'x' || nc == 'X')
5372 hex = TRUE;
5373 else if (nc == 'o' || nc == 'O')
5374 octal = TRUE;
5375 #ifdef FEAT_MBYTE
5376 else if (nc == 'u' || nc == 'U')
5377 unicode = nc;
5378 #endif
5379 else
5381 if (hex
5382 #ifdef FEAT_MBYTE
5383 || unicode != 0
5384 #endif
5387 if (!vim_isxdigit(nc))
5388 break;
5389 cc = cc * 16 + hex2nr(nc);
5391 else if (octal)
5393 if (nc < '0' || nc > '7')
5394 break;
5395 cc = cc * 8 + nc - '0';
5397 else
5399 if (!VIM_ISDIGIT(nc))
5400 break;
5401 cc = cc * 10 + nc - '0';
5404 ++i;
5407 if (cc > 255
5408 #ifdef FEAT_MBYTE
5409 && unicode == 0
5410 #endif
5412 cc = 255; /* limit range to 0-255 */
5413 nc = 0;
5415 if (hex) /* hex: up to two chars */
5417 if (i >= 2)
5418 break;
5420 #ifdef FEAT_MBYTE
5421 else if (unicode) /* Unicode: up to four or eight chars */
5423 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
5424 break;
5426 #endif
5427 else if (i >= 3) /* decimal or octal: up to three chars */
5428 break;
5430 if (i == 0) /* no number entered */
5432 if (nc == K_ZERO) /* NUL is stored as NL */
5434 cc = '\n';
5435 nc = 0;
5437 else
5439 cc = nc;
5440 nc = 0;
5444 if (cc == 0) /* NUL is stored as NL */
5445 cc = '\n';
5446 #ifdef FEAT_MBYTE
5447 if (enc_dbcs && (cc & 0xff) == 0)
5448 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
5449 second byte will cause trouble! */
5450 #endif
5452 --no_mapping;
5453 #ifdef FEAT_GUI
5454 if (gui.in_use)
5455 --allow_keys;
5456 #endif
5457 if (nc)
5458 vungetc(nc);
5459 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
5460 return cc;
5464 * Insert character, taking care of special keys and mod_mask
5466 static void
5467 insert_special(c, allow_modmask, ctrlv)
5468 int c;
5469 int allow_modmask;
5470 int ctrlv; /* c was typed after CTRL-V */
5472 char_u *p;
5473 int len;
5476 * Special function key, translate into "<Key>". Up to the last '>' is
5477 * inserted with ins_str(), so as not to replace characters in replace
5478 * mode.
5479 * Only use mod_mask for special keys, to avoid things like <S-Space>,
5480 * unless 'allow_modmask' is TRUE.
5482 #ifdef MACOS
5483 /* Command-key never produces a normal key */
5484 if (mod_mask & MOD_MASK_CMD)
5485 allow_modmask = TRUE;
5486 #endif
5487 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
5489 p = get_special_key_name(c, mod_mask);
5490 len = (int)STRLEN(p);
5491 c = p[len - 1];
5492 if (len > 2)
5494 if (stop_arrow() == FAIL)
5495 return;
5496 p[len - 1] = NUL;
5497 ins_str(p);
5498 AppendToRedobuffLit(p, -1);
5499 ctrlv = FALSE;
5502 if (stop_arrow() == OK)
5503 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
5507 * Special characters in this context are those that need processing other
5508 * than the simple insertion that can be performed here. This includes ESC
5509 * which terminates the insert, and CR/NL which need special processing to
5510 * open up a new line. This routine tries to optimize insertions performed by
5511 * the "redo", "undo" or "put" commands, so it needs to know when it should
5512 * stop and defer processing to the "normal" mechanism.
5513 * '0' and '^' are special, because they can be followed by CTRL-D.
5515 #ifdef EBCDIC
5516 # define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
5517 #else
5518 # define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
5519 #endif
5521 #ifdef FEAT_MBYTE
5522 # define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
5523 #else
5524 # define WHITECHAR(cc) vim_iswhite(cc)
5525 #endif
5527 void
5528 insertchar(c, flags, second_indent)
5529 int c; /* character to insert or NUL */
5530 int flags; /* INSCHAR_FORMAT, etc. */
5531 int second_indent; /* indent for second line if >= 0 */
5533 int textwidth;
5534 #ifdef FEAT_COMMENTS
5535 char_u *p;
5536 #endif
5537 int fo_ins_blank;
5539 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
5540 fo_ins_blank = has_format_option(FO_INS_BLANK);
5543 * Try to break the line in two or more pieces when:
5544 * - Always do this if we have been called to do formatting only.
5545 * - Always do this when 'formatoptions' has the 'a' flag and the line
5546 * ends in white space.
5547 * - Otherwise:
5548 * - Don't do this if inserting a blank
5549 * - Don't do this if an existing character is being replaced, unless
5550 * we're in VREPLACE mode.
5551 * - Do this if the cursor is not on the line where insert started
5552 * or - 'formatoptions' doesn't have 'l' or the line was not too long
5553 * before the insert.
5554 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
5555 * before 'textwidth'
5557 if (textwidth > 0
5558 && ((flags & INSCHAR_FORMAT)
5559 || (!vim_iswhite(c)
5560 && !((State & REPLACE_FLAG)
5561 #ifdef FEAT_VREPLACE
5562 && !(State & VREPLACE_FLAG)
5563 #endif
5564 && *ml_get_cursor() != NUL)
5565 && (curwin->w_cursor.lnum != Insstart.lnum
5566 || ((!has_format_option(FO_INS_LONG)
5567 || Insstart_textlen <= (colnr_T)textwidth)
5568 && (!fo_ins_blank
5569 || Insstart_blank_vcol <= (colnr_T)textwidth
5570 ))))))
5572 /* Format with 'formatexpr' when it's set. Use internal formatting
5573 * when 'formatexpr' isn't set or it returns non-zero. */
5574 #if defined(FEAT_EVAL)
5575 int do_internal = TRUE;
5577 if (*curbuf->b_p_fex != NUL && (flags & INSCHAR_NO_FEX) == 0)
5579 do_internal = (fex_format(curwin->w_cursor.lnum, 1L, c) != 0);
5580 /* It may be required to save for undo again, e.g. when setline()
5581 * was called. */
5582 ins_need_undo = TRUE;
5584 if (do_internal)
5585 #endif
5586 internal_format(textwidth, second_indent, flags, c == NUL, c);
5589 if (c == NUL) /* only formatting was wanted */
5590 return;
5592 #ifdef FEAT_COMMENTS
5593 /* Check whether this character should end a comment. */
5594 if (did_ai && (int)c == end_comment_pending)
5596 char_u *line;
5597 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5598 int middle_len, end_len;
5599 int i;
5602 * Need to remove existing (middle) comment leader and insert end
5603 * comment leader. First, check what comment leader we can find.
5605 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
5606 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
5608 /* Skip middle-comment string */
5609 while (*p && p[-1] != ':') /* find end of middle flags */
5610 ++p;
5611 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5612 /* Don't count trailing white space for middle_len */
5613 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
5614 --middle_len;
5616 /* Find the end-comment string */
5617 while (*p && p[-1] != ':') /* find end of end flags */
5618 ++p;
5619 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5621 /* Skip white space before the cursor */
5622 i = curwin->w_cursor.col;
5623 while (--i >= 0 && vim_iswhite(line[i]))
5625 i++;
5627 /* Skip to before the middle leader */
5628 i -= middle_len;
5630 /* Check some expected things before we go on */
5631 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
5633 /* Backspace over all the stuff we want to replace */
5634 backspace_until_column(i);
5637 * Insert the end-comment string, except for the last
5638 * character, which will get inserted as normal later.
5640 ins_bytes_len(lead_end, end_len - 1);
5644 end_comment_pending = NUL;
5645 #endif
5647 did_ai = FALSE;
5648 #ifdef FEAT_SMARTINDENT
5649 did_si = FALSE;
5650 can_si = FALSE;
5651 can_si_back = FALSE;
5652 #endif
5655 * If there's any pending input, grab up to INPUT_BUFLEN at once.
5656 * This speeds up normal text input considerably.
5657 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
5658 * need to re-indent at a ':', or any other character (but not what
5659 * 'paste' is set)..
5661 #ifdef USE_ON_FLY_SCROLL
5662 dont_scroll = FALSE; /* allow scrolling here */
5663 #endif
5665 if ( !ISSPECIAL(c)
5666 #ifdef FEAT_MBYTE
5667 && (!has_mbyte || (*mb_char2len)(c) == 1)
5668 #endif
5669 && vpeekc() != NUL
5670 && !(State & REPLACE_FLAG)
5671 #ifdef FEAT_CINDENT
5672 && !cindent_on()
5673 #endif
5674 #ifdef FEAT_RIGHTLEFT
5675 && !p_ri
5676 #endif
5679 #define INPUT_BUFLEN 100
5680 char_u buf[INPUT_BUFLEN + 1];
5681 int i;
5682 colnr_T virtcol = 0;
5684 buf[0] = c;
5685 i = 1;
5686 if (textwidth > 0)
5687 virtcol = get_nolist_virtcol();
5689 * Stop the string when:
5690 * - no more chars available
5691 * - finding a special character (command key)
5692 * - buffer is full
5693 * - running into the 'textwidth' boundary
5694 * - need to check for abbreviation: A non-word char after a word-char
5696 while ( (c = vpeekc()) != NUL
5697 && !ISSPECIAL(c)
5698 #ifdef FEAT_MBYTE
5699 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
5700 #endif
5701 && i < INPUT_BUFLEN
5702 && (textwidth == 0
5703 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
5704 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
5706 #ifdef FEAT_RIGHTLEFT
5707 c = vgetc();
5708 if (p_hkmap && KeyTyped)
5709 c = hkmap(c); /* Hebrew mode mapping */
5710 # ifdef FEAT_FKMAP
5711 if (p_fkmap && KeyTyped)
5712 c = fkmap(c); /* Farsi mode mapping */
5713 # endif
5714 buf[i++] = c;
5715 #else
5716 buf[i++] = vgetc();
5717 #endif
5720 #ifdef FEAT_DIGRAPHS
5721 do_digraph(-1); /* clear digraphs */
5722 do_digraph(buf[i-1]); /* may be the start of a digraph */
5723 #endif
5724 buf[i] = NUL;
5725 ins_str(buf);
5726 if (flags & INSCHAR_CTRLV)
5728 redo_literal(*buf);
5729 i = 1;
5731 else
5732 i = 0;
5733 if (buf[i] != NUL)
5734 AppendToRedobuffLit(buf + i, -1);
5736 else
5738 #ifdef FEAT_MBYTE
5739 int cc;
5741 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
5743 char_u buf[MB_MAXBYTES + 1];
5745 (*mb_char2bytes)(c, buf);
5746 buf[cc] = NUL;
5747 ins_char_bytes(buf, cc);
5748 AppendCharToRedobuff(c);
5750 else
5751 #endif
5753 ins_char(c);
5754 if (flags & INSCHAR_CTRLV)
5755 redo_literal(c);
5756 else
5757 AppendCharToRedobuff(c);
5763 * Format text at the current insert position.
5765 static void
5766 internal_format(textwidth, second_indent, flags, format_only, c)
5767 int textwidth;
5768 int second_indent;
5769 int flags;
5770 int format_only;
5771 int c; /* character to be inserted (can be NUL) */
5773 int cc;
5774 int save_char = NUL;
5775 int haveto_redraw = FALSE;
5776 int fo_ins_blank = has_format_option(FO_INS_BLANK);
5777 #ifdef FEAT_MBYTE
5778 int fo_multibyte = has_format_option(FO_MBYTE_BREAK);
5779 #endif
5780 int fo_white_par = has_format_option(FO_WHITE_PAR);
5781 int first_line = TRUE;
5782 #ifdef FEAT_COMMENTS
5783 colnr_T leader_len;
5784 int no_leader = FALSE;
5785 int do_comments = (flags & INSCHAR_DO_COM);
5786 #endif
5789 * When 'ai' is off we don't want a space under the cursor to be
5790 * deleted. Replace it with an 'x' temporarily.
5792 if (!curbuf->b_p_ai
5793 #ifdef FEAT_VREPLACE
5794 && !(State & VREPLACE_FLAG)
5795 #endif
5798 cc = gchar_cursor();
5799 if (vim_iswhite(cc))
5801 save_char = cc;
5802 pchar_cursor('x');
5807 * Repeat breaking lines, until the current line is not too long.
5809 while (!got_int)
5811 int startcol; /* Cursor column at entry */
5812 int wantcol; /* column at textwidth border */
5813 int foundcol; /* column for start of spaces */
5814 int end_foundcol = 0; /* column for start of word */
5815 colnr_T len;
5816 colnr_T virtcol;
5817 #ifdef FEAT_VREPLACE
5818 int orig_col = 0;
5819 char_u *saved_text = NULL;
5820 #endif
5821 colnr_T col;
5822 colnr_T end_col;
5824 virtcol = get_nolist_virtcol()
5825 + char2cells(c != NUL ? c : gchar_cursor());
5826 if (virtcol <= (colnr_T)textwidth)
5827 break;
5829 #ifdef FEAT_COMMENTS
5830 if (no_leader)
5831 do_comments = FALSE;
5832 else if (!(flags & INSCHAR_FORMAT)
5833 && has_format_option(FO_WRAP_COMS))
5834 do_comments = TRUE;
5836 /* Don't break until after the comment leader */
5837 if (do_comments)
5838 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
5839 else
5840 leader_len = 0;
5842 /* If the line doesn't start with a comment leader, then don't
5843 * start one in a following broken line. Avoids that a %word
5844 * moved to the start of the next line causes all following lines
5845 * to start with %. */
5846 if (leader_len == 0)
5847 no_leader = TRUE;
5848 #endif
5849 if (!(flags & INSCHAR_FORMAT)
5850 #ifdef FEAT_COMMENTS
5851 && leader_len == 0
5852 #endif
5853 && !has_format_option(FO_WRAP))
5855 break;
5856 if ((startcol = curwin->w_cursor.col) == 0)
5857 break;
5859 /* find column of textwidth border */
5860 coladvance((colnr_T)textwidth);
5861 wantcol = curwin->w_cursor.col;
5863 curwin->w_cursor.col = startcol;
5864 foundcol = 0;
5867 * Find position to break at.
5868 * Stop at first entered white when 'formatoptions' has 'v'
5870 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
5871 || curwin->w_cursor.lnum != Insstart.lnum
5872 || curwin->w_cursor.col >= Insstart.col)
5874 if (curwin->w_cursor.col == startcol && c != NUL)
5875 cc = c;
5876 else
5877 cc = gchar_cursor();
5878 if (WHITECHAR(cc))
5880 /* remember position of blank just before text */
5881 end_col = curwin->w_cursor.col;
5883 /* find start of sequence of blanks */
5884 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
5886 dec_cursor();
5887 cc = gchar_cursor();
5889 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
5890 break; /* only spaces in front of text */
5891 #ifdef FEAT_COMMENTS
5892 /* Don't break until after the comment leader */
5893 if (curwin->w_cursor.col < leader_len)
5894 break;
5895 #endif
5896 if (has_format_option(FO_ONE_LETTER))
5898 /* do not break after one-letter words */
5899 if (curwin->w_cursor.col == 0)
5900 break; /* one-letter word at begin */
5901 #ifdef FEAT_COMMENTS
5902 /* do not break "#a b" when 'tw' is 2 */
5903 if (curwin->w_cursor.col <= leader_len)
5904 break;
5905 #endif
5906 col = curwin->w_cursor.col;
5907 dec_cursor();
5908 cc = gchar_cursor();
5910 if (WHITECHAR(cc))
5911 continue; /* one-letter, continue */
5912 curwin->w_cursor.col = col;
5915 inc_cursor();
5917 end_foundcol = end_col + 1;
5918 foundcol = curwin->w_cursor.col;
5919 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5920 break;
5922 #ifdef FEAT_MBYTE
5923 else if (cc >= 0x100 && fo_multibyte)
5925 /* Break after or before a multi-byte character. */
5926 if (curwin->w_cursor.col != startcol)
5928 #ifdef FEAT_COMMENTS
5929 /* Don't break until after the comment leader */
5930 if (curwin->w_cursor.col < leader_len)
5931 break;
5932 #endif
5933 col = curwin->w_cursor.col;
5934 inc_cursor();
5935 /* Don't change end_foundcol if already set. */
5936 if (foundcol != curwin->w_cursor.col)
5938 foundcol = curwin->w_cursor.col;
5939 end_foundcol = foundcol;
5940 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5941 break;
5943 curwin->w_cursor.col = col;
5946 if (curwin->w_cursor.col == 0)
5947 break;
5949 col = curwin->w_cursor.col;
5951 dec_cursor();
5952 cc = gchar_cursor();
5954 if (WHITECHAR(cc))
5955 continue; /* break with space */
5956 #ifdef FEAT_COMMENTS
5957 /* Don't break until after the comment leader */
5958 if (curwin->w_cursor.col < leader_len)
5959 break;
5960 #endif
5962 curwin->w_cursor.col = col;
5964 foundcol = curwin->w_cursor.col;
5965 end_foundcol = foundcol;
5966 if (curwin->w_cursor.col <= (colnr_T)wantcol)
5967 break;
5969 #endif
5970 if (curwin->w_cursor.col == 0)
5971 break;
5972 dec_cursor();
5975 if (foundcol == 0) /* no spaces, cannot break line */
5977 curwin->w_cursor.col = startcol;
5978 break;
5981 /* Going to break the line, remove any "$" now. */
5982 undisplay_dollar();
5985 * Offset between cursor position and line break is used by replace
5986 * stack functions. VREPLACE does not use this, and backspaces
5987 * over the text instead.
5989 #ifdef FEAT_VREPLACE
5990 if (State & VREPLACE_FLAG)
5991 orig_col = startcol; /* Will start backspacing from here */
5992 else
5993 #endif
5994 replace_offset = startcol - end_foundcol;
5997 * adjust startcol for spaces that will be deleted and
5998 * characters that will remain on top line
6000 curwin->w_cursor.col = foundcol;
6001 while ((cc = gchar_cursor(), WHITECHAR(cc))
6002 && (!fo_white_par || curwin->w_cursor.col < startcol))
6003 inc_cursor();
6004 startcol -= curwin->w_cursor.col;
6005 if (startcol < 0)
6006 startcol = 0;
6008 #ifdef FEAT_VREPLACE
6009 if (State & VREPLACE_FLAG)
6012 * In VREPLACE mode, we will backspace over the text to be
6013 * wrapped, so save a copy now to put on the next line.
6015 saved_text = vim_strsave(ml_get_cursor());
6016 curwin->w_cursor.col = orig_col;
6017 if (saved_text == NULL)
6018 break; /* Can't do it, out of memory */
6019 saved_text[startcol] = NUL;
6021 /* Backspace over characters that will move to the next line */
6022 if (!fo_white_par)
6023 backspace_until_column(foundcol);
6025 else
6026 #endif
6028 /* put cursor after pos. to break line */
6029 if (!fo_white_par)
6030 curwin->w_cursor.col = foundcol;
6034 * Split the line just before the margin.
6035 * Only insert/delete lines, but don't really redraw the window.
6037 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
6038 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
6039 #ifdef FEAT_COMMENTS
6040 + (do_comments ? OPENLINE_DO_COM : 0)
6041 #endif
6042 , old_indent);
6043 old_indent = 0;
6045 replace_offset = 0;
6046 if (first_line)
6048 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
6049 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
6050 if (second_indent >= 0)
6052 #ifdef FEAT_VREPLACE
6053 if (State & VREPLACE_FLAG)
6054 change_indent(INDENT_SET, second_indent, FALSE, NUL, TRUE);
6055 else
6056 #endif
6057 (void)set_indent(second_indent, SIN_CHANGED);
6059 first_line = FALSE;
6062 #ifdef FEAT_VREPLACE
6063 if (State & VREPLACE_FLAG)
6066 * In VREPLACE mode we have backspaced over the text to be
6067 * moved, now we re-insert it into the new line.
6069 ins_bytes(saved_text);
6070 vim_free(saved_text);
6072 else
6073 #endif
6076 * Check if cursor is not past the NUL off the line, cindent
6077 * may have added or removed indent.
6079 curwin->w_cursor.col += startcol;
6080 len = (colnr_T)STRLEN(ml_get_curline());
6081 if (curwin->w_cursor.col > len)
6082 curwin->w_cursor.col = len;
6085 haveto_redraw = TRUE;
6086 #ifdef FEAT_CINDENT
6087 can_cindent = TRUE;
6088 #endif
6089 /* moved the cursor, don't autoindent or cindent now */
6090 did_ai = FALSE;
6091 #ifdef FEAT_SMARTINDENT
6092 did_si = FALSE;
6093 can_si = FALSE;
6094 can_si_back = FALSE;
6095 #endif
6096 line_breakcheck();
6099 if (save_char != NUL) /* put back space after cursor */
6100 pchar_cursor(save_char);
6102 if (!format_only && haveto_redraw)
6104 update_topline();
6105 redraw_curbuf_later(VALID);
6110 * Called after inserting or deleting text: When 'formatoptions' includes the
6111 * 'a' flag format from the current line until the end of the paragraph.
6112 * Keep the cursor at the same position relative to the text.
6113 * The caller must have saved the cursor line for undo, following ones will be
6114 * saved here.
6116 void
6117 auto_format(trailblank, prev_line)
6118 int trailblank; /* when TRUE also format with trailing blank */
6119 int prev_line; /* may start in previous line */
6121 pos_T pos;
6122 colnr_T len;
6123 char_u *old;
6124 char_u *new, *pnew;
6125 int wasatend;
6126 int cc;
6128 if (!has_format_option(FO_AUTO))
6129 return;
6131 pos = curwin->w_cursor;
6132 old = ml_get_curline();
6134 /* may remove added space */
6135 check_auto_format(FALSE);
6137 /* Don't format in Insert mode when the cursor is on a trailing blank, the
6138 * user might insert normal text next. Also skip formatting when "1" is
6139 * in 'formatoptions' and there is a single character before the cursor.
6140 * Otherwise the line would be broken and when typing another non-white
6141 * next they are not joined back together. */
6142 wasatend = (pos.col == (colnr_T)STRLEN(old));
6143 if (*old != NUL && !trailblank && wasatend)
6145 dec_cursor();
6146 cc = gchar_cursor();
6147 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
6148 && has_format_option(FO_ONE_LETTER))
6149 dec_cursor();
6150 cc = gchar_cursor();
6151 if (WHITECHAR(cc))
6153 curwin->w_cursor = pos;
6154 return;
6156 curwin->w_cursor = pos;
6159 #ifdef FEAT_COMMENTS
6160 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
6161 * comments. */
6162 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
6163 && get_leader_len(old, NULL, FALSE) == 0)
6164 return;
6165 #endif
6168 * May start formatting in a previous line, so that after "x" a word is
6169 * moved to the previous line if it fits there now. Only when this is not
6170 * the start of a paragraph.
6172 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
6174 --curwin->w_cursor.lnum;
6175 if (u_save_cursor() == FAIL)
6176 return;
6180 * Do the formatting and restore the cursor position. "saved_cursor" will
6181 * be adjusted for the text formatting.
6183 saved_cursor = pos;
6184 format_lines((linenr_T)-1, FALSE);
6185 curwin->w_cursor = saved_cursor;
6186 saved_cursor.lnum = 0;
6188 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
6190 /* "cannot happen" */
6191 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6192 coladvance((colnr_T)MAXCOL);
6194 else
6195 check_cursor_col();
6197 /* Insert mode: If the cursor is now after the end of the line while it
6198 * previously wasn't, the line was broken. Because of the rule above we
6199 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
6200 * formatted. */
6201 if (!wasatend && has_format_option(FO_WHITE_PAR))
6203 new = ml_get_curline();
6204 len = (colnr_T)STRLEN(new);
6205 if (curwin->w_cursor.col == len)
6207 pnew = vim_strnsave(new, len + 2);
6208 pnew[len] = ' ';
6209 pnew[len + 1] = NUL;
6210 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
6211 /* remove the space later */
6212 did_add_space = TRUE;
6214 else
6215 /* may remove added space */
6216 check_auto_format(FALSE);
6219 check_cursor();
6223 * When an extra space was added to continue a paragraph for auto-formatting,
6224 * delete it now. The space must be under the cursor, just after the insert
6225 * position.
6227 static void
6228 check_auto_format(end_insert)
6229 int end_insert; /* TRUE when ending Insert mode */
6231 int c = ' ';
6232 int cc;
6234 if (did_add_space)
6236 cc = gchar_cursor();
6237 if (!WHITECHAR(cc))
6238 /* Somehow the space was removed already. */
6239 did_add_space = FALSE;
6240 else
6242 if (!end_insert)
6244 inc_cursor();
6245 c = gchar_cursor();
6246 dec_cursor();
6248 if (c != NUL)
6250 /* The space is no longer at the end of the line, delete it. */
6251 del_char(FALSE);
6252 did_add_space = FALSE;
6259 * Find out textwidth to be used for formatting:
6260 * if 'textwidth' option is set, use it
6261 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
6262 * if invalid value, use 0.
6263 * Set default to window width (maximum 79) for "gq" operator.
6266 comp_textwidth(ff)
6267 int ff; /* force formatting (for "gq" command) */
6269 int textwidth;
6271 textwidth = curbuf->b_p_tw;
6272 if (textwidth == 0 && curbuf->b_p_wm)
6274 /* The width is the window width minus 'wrapmargin' minus all the
6275 * things that add to the margin. */
6276 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
6277 #ifdef FEAT_CMDWIN
6278 if (cmdwin_type != 0)
6279 textwidth -= 1;
6280 #endif
6281 #ifdef FEAT_FOLDING
6282 textwidth -= curwin->w_p_fdc;
6283 #endif
6284 #ifdef FEAT_SIGNS
6285 if (curwin->w_buffer->b_signlist != NULL
6286 # ifdef FEAT_NETBEANS_INTG
6287 || usingNetbeans
6288 # endif
6290 textwidth -= 1;
6291 #endif
6292 if (curwin->w_p_nu || curwin->w_p_rnu)
6293 textwidth -= 8;
6295 if (textwidth < 0)
6296 textwidth = 0;
6297 if (ff && textwidth == 0)
6299 textwidth = W_WIDTH(curwin) - 1;
6300 if (textwidth > 79)
6301 textwidth = 79;
6303 return textwidth;
6307 * Put a character in the redo buffer, for when just after a CTRL-V.
6309 static void
6310 redo_literal(c)
6311 int c;
6313 char_u buf[10];
6315 /* Only digits need special treatment. Translate them into a string of
6316 * three digits. */
6317 if (VIM_ISDIGIT(c))
6319 vim_snprintf((char *)buf, sizeof(buf), "%03d", c);
6320 AppendToRedobuff(buf);
6322 else
6323 AppendCharToRedobuff(c);
6327 * start_arrow() is called when an arrow key is used in insert mode.
6328 * For undo/redo it resembles hitting the <ESC> key.
6330 static void
6331 start_arrow(end_insert_pos)
6332 pos_T *end_insert_pos; /* can be NULL */
6334 if (!arrow_used) /* something has been inserted */
6336 AppendToRedobuff(ESC_STR);
6337 stop_insert(end_insert_pos, FALSE);
6338 arrow_used = TRUE; /* this means we stopped the current insert */
6340 #ifdef FEAT_SPELL
6341 check_spell_redraw();
6342 #endif
6345 #ifdef FEAT_SPELL
6347 * If we skipped highlighting word at cursor, do it now.
6348 * It may be skipped again, thus reset spell_redraw_lnum first.
6350 static void
6351 check_spell_redraw()
6353 if (spell_redraw_lnum != 0)
6355 linenr_T lnum = spell_redraw_lnum;
6357 spell_redraw_lnum = 0;
6358 redrawWinline(lnum, FALSE);
6363 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6364 * spelled word, if there is one.
6366 static void
6367 spell_back_to_badword()
6369 pos_T tpos = curwin->w_cursor;
6371 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
6372 if (curwin->w_cursor.col != tpos.col)
6373 start_arrow(&tpos);
6375 #endif
6378 * stop_arrow() is called before a change is made in insert mode.
6379 * If an arrow key has been used, start a new insertion.
6380 * Returns FAIL if undo is impossible, shouldn't insert then.
6383 stop_arrow()
6385 if (arrow_used)
6387 if (u_save_cursor() == OK)
6389 arrow_used = FALSE;
6390 ins_need_undo = FALSE;
6392 Insstart = curwin->w_cursor; /* new insertion starts here */
6393 Insstart_textlen = (colnr_T)linetabsize(ml_get_curline(),curwin->w_cursor.lnum);
6394 ai_col = 0;
6395 #ifdef FEAT_VREPLACE
6396 if (State & VREPLACE_FLAG)
6398 orig_line_count = curbuf->b_ml.ml_line_count;
6399 vr_lines_changed = 1;
6401 #endif
6402 ResetRedobuff();
6403 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
6404 new_insert_skip = 2;
6406 else if (ins_need_undo)
6408 if (u_save_cursor() == OK)
6409 ins_need_undo = FALSE;
6412 #ifdef FEAT_FOLDING
6413 /* Always open fold at the cursor line when inserting something. */
6414 foldOpenCursor();
6415 #endif
6417 return (arrow_used || ins_need_undo ? FAIL : OK);
6421 * Do a few things to stop inserting.
6422 * "end_insert_pos" is where insert ended. It is NULL when we already jumped
6423 * to another window/buffer.
6425 static void
6426 stop_insert(end_insert_pos, esc)
6427 pos_T *end_insert_pos;
6428 int esc; /* called by ins_esc() */
6430 int cc;
6431 char_u *ptr;
6433 stop_redo_ins();
6434 replace_flush(); /* abandon replace stack */
6437 * Save the inserted text for later redo with ^@ and CTRL-A.
6438 * Don't do it when "restart_edit" was set and nothing was inserted,
6439 * otherwise CTRL-O w and then <Left> will clear "last_insert".
6441 ptr = get_inserted();
6442 if (did_restart_edit == 0 || (ptr != NULL
6443 && (int)STRLEN(ptr) > new_insert_skip))
6445 vim_free(last_insert);
6446 last_insert = ptr;
6447 last_insert_skip = new_insert_skip;
6449 else
6450 vim_free(ptr);
6452 if (!arrow_used && end_insert_pos != NULL)
6454 /* Auto-format now. It may seem strange to do this when stopping an
6455 * insertion (or moving the cursor), but it's required when appending
6456 * a line and having it end in a space. But only do it when something
6457 * was actually inserted, otherwise undo won't work. */
6458 if (!ins_need_undo && has_format_option(FO_AUTO))
6460 pos_T tpos = curwin->w_cursor;
6462 /* When the cursor is at the end of the line after a space the
6463 * formatting will move it to the following word. Avoid that by
6464 * moving the cursor onto the space. */
6465 cc = 'x';
6466 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
6468 dec_cursor();
6469 cc = gchar_cursor();
6470 if (!vim_iswhite(cc))
6471 curwin->w_cursor = tpos;
6474 auto_format(TRUE, FALSE);
6476 if (vim_iswhite(cc))
6478 if (gchar_cursor() != NUL)
6479 inc_cursor();
6480 #ifdef FEAT_VIRTUALEDIT
6481 /* If the cursor is still at the same character, also keep
6482 * the "coladd". */
6483 if (gchar_cursor() == NUL
6484 && curwin->w_cursor.lnum == tpos.lnum
6485 && curwin->w_cursor.col == tpos.col)
6486 curwin->w_cursor.coladd = tpos.coladd;
6487 #endif
6491 /* If a space was inserted for auto-formatting, remove it now. */
6492 check_auto_format(TRUE);
6494 /* If we just did an auto-indent, remove the white space from the end
6495 * of the line, and put the cursor back.
6496 * Do this when ESC was used or moving the cursor up/down.
6497 * Check for the old position still being valid, just in case the text
6498 * got changed unexpectedly. */
6499 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
6500 && curwin->w_cursor.lnum != end_insert_pos->lnum))
6501 && end_insert_pos->lnum <= curbuf->b_ml.ml_line_count)
6503 pos_T tpos = curwin->w_cursor;
6505 curwin->w_cursor = *end_insert_pos;
6506 check_cursor_col(); /* make sure it is not past the line */
6507 for (;;)
6509 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
6510 --curwin->w_cursor.col;
6511 cc = gchar_cursor();
6512 if (!vim_iswhite(cc))
6513 break;
6514 if (del_char(TRUE) == FAIL)
6515 break; /* should not happen */
6517 if (curwin->w_cursor.lnum != tpos.lnum)
6518 curwin->w_cursor = tpos;
6519 else if (cc != NUL)
6520 ++curwin->w_cursor.col; /* put cursor back on the NUL */
6522 #ifdef FEAT_VISUAL
6523 /* <C-S-Right> may have started Visual mode, adjust the position for
6524 * deleted characters. */
6525 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
6527 int len = (int)STRLEN(ml_get_curline());
6529 if (VIsual.col > len)
6531 VIsual.col = len;
6532 # ifdef FEAT_VIRTUALEDIT
6533 VIsual.coladd = 0;
6534 # endif
6537 #endif
6540 did_ai = FALSE;
6541 #ifdef FEAT_SMARTINDENT
6542 did_si = FALSE;
6543 can_si = FALSE;
6544 can_si_back = FALSE;
6545 #endif
6547 /* Set '[ and '] to the inserted text. When end_insert_pos is NULL we are
6548 * now in a different buffer. */
6549 if (end_insert_pos != NULL)
6551 curbuf->b_op_start = Insstart;
6552 curbuf->b_op_end = *end_insert_pos;
6557 * Set the last inserted text to a single character.
6558 * Used for the replace command.
6560 void
6561 set_last_insert(c)
6562 int c;
6564 char_u *s;
6566 vim_free(last_insert);
6567 #ifdef FEAT_MBYTE
6568 last_insert = alloc(MB_MAXBYTES * 3 + 5);
6569 #else
6570 last_insert = alloc(6);
6571 #endif
6572 if (last_insert != NULL)
6574 s = last_insert;
6575 /* Use the CTRL-V only when entering a special char */
6576 if (c < ' ' || c == DEL)
6577 *s++ = Ctrl_V;
6578 s = add_char2buf(c, s);
6579 *s++ = ESC;
6580 *s++ = NUL;
6581 last_insert_skip = 0;
6585 #if defined(EXITFREE) || defined(PROTO)
6586 void
6587 free_last_insert()
6589 vim_free(last_insert);
6590 last_insert = NULL;
6591 # ifdef FEAT_INS_EXPAND
6592 vim_free(compl_orig_text);
6593 compl_orig_text = NULL;
6594 # endif
6596 #endif
6599 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
6600 * and CSI. Handle multi-byte characters.
6601 * Returns a pointer to after the added bytes.
6603 char_u *
6604 add_char2buf(c, s)
6605 int c;
6606 char_u *s;
6608 #ifdef FEAT_MBYTE
6609 char_u temp[MB_MAXBYTES];
6610 int i;
6611 int len;
6613 len = (*mb_char2bytes)(c, temp);
6614 for (i = 0; i < len; ++i)
6616 c = temp[i];
6617 #endif
6618 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
6619 if (c == K_SPECIAL)
6621 *s++ = K_SPECIAL;
6622 *s++ = KS_SPECIAL;
6623 *s++ = KE_FILLER;
6625 #ifdef FEAT_GUI
6626 else if (c == CSI)
6628 *s++ = CSI;
6629 *s++ = KS_EXTRA;
6630 *s++ = (int)KE_CSI;
6632 #endif
6633 else
6634 *s++ = c;
6635 #ifdef FEAT_MBYTE
6637 #endif
6638 return s;
6642 * move cursor to start of line
6643 * if flags & BL_WHITE move to first non-white
6644 * if flags & BL_SOL move to first non-white if startofline is set,
6645 * otherwise keep "curswant" column
6646 * if flags & BL_FIX don't leave the cursor on a NUL.
6648 void
6649 beginline(flags)
6650 int flags;
6652 if ((flags & BL_SOL) && !p_sol)
6653 coladvance(curwin->w_curswant);
6654 else
6656 curwin->w_cursor.col = 0;
6657 #ifdef FEAT_VIRTUALEDIT
6658 curwin->w_cursor.coladd = 0;
6659 #endif
6661 if (flags & (BL_WHITE | BL_SOL))
6663 char_u *ptr;
6665 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
6666 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
6667 ++curwin->w_cursor.col;
6669 curwin->w_set_curswant = TRUE;
6674 * oneright oneleft cursor_down cursor_up
6676 * Move one char {right,left,down,up}.
6677 * Doesn't move onto the NUL past the end of the line, unless it is allowed.
6678 * Return OK when successful, FAIL when we hit a line of file boundary.
6682 oneright()
6684 char_u *ptr;
6685 int l;
6687 #ifdef FEAT_VIRTUALEDIT
6688 if (virtual_active())
6690 pos_T prevpos = curwin->w_cursor;
6692 /* Adjust for multi-wide char (excluding TAB) */
6693 ptr = ml_get_cursor();
6694 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
6695 # ifdef FEAT_MBYTE
6696 (*mb_ptr2char)(ptr)
6697 # else
6698 *ptr
6699 # endif
6701 ? ptr2cells(ptr) : 1));
6702 curwin->w_set_curswant = TRUE;
6703 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
6704 return (prevpos.col != curwin->w_cursor.col
6705 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
6707 #endif
6709 ptr = ml_get_cursor();
6710 if (*ptr == NUL)
6711 return FAIL; /* already at the very end */
6713 #ifdef FEAT_MBYTE
6714 if (has_mbyte)
6715 l = (*mb_ptr2len)(ptr);
6716 else
6717 #endif
6718 l = 1;
6720 /* move "l" bytes right, but don't end up on the NUL, unless 'virtualedit'
6721 * contains "onemore". */
6722 if (ptr[l] == NUL
6723 #ifdef FEAT_VIRTUALEDIT
6724 && (ve_flags & VE_ONEMORE) == 0
6725 #endif
6727 return FAIL;
6728 curwin->w_cursor.col += l;
6730 curwin->w_set_curswant = TRUE;
6731 return OK;
6735 oneleft()
6737 #ifdef FEAT_VIRTUALEDIT
6738 if (virtual_active())
6740 int width;
6741 int v = getviscol();
6743 if (v == 0)
6744 return FAIL;
6746 # ifdef FEAT_LINEBREAK
6747 /* We might get stuck on 'showbreak', skip over it. */
6748 width = 1;
6749 for (;;)
6751 coladvance(v - width);
6752 /* getviscol() is slow, skip it when 'showbreak' is empty,
6753 * 'breakindent' is not set and there are no multi-byte
6754 * characters */
6755 if ((*p_sbr == NUL && !curwin->w_p_bri
6756 # ifdef FEAT_MBYTE
6757 && !has_mbyte
6758 # endif
6759 ) || getviscol() < v)
6760 break;
6761 ++width;
6763 # else
6764 coladvance(v - 1);
6765 # endif
6767 if (curwin->w_cursor.coladd == 1)
6769 char_u *ptr;
6771 /* Adjust for multi-wide char (not a TAB) */
6772 ptr = ml_get_cursor();
6773 if (*ptr != TAB && vim_isprintc(
6774 # ifdef FEAT_MBYTE
6775 (*mb_ptr2char)(ptr)
6776 # else
6777 *ptr
6778 # endif
6779 ) && ptr2cells(ptr) > 1)
6780 curwin->w_cursor.coladd = 0;
6783 curwin->w_set_curswant = TRUE;
6784 return OK;
6786 #endif
6788 if (curwin->w_cursor.col == 0)
6789 return FAIL;
6791 curwin->w_set_curswant = TRUE;
6792 --curwin->w_cursor.col;
6794 #ifdef FEAT_MBYTE
6795 /* if the character on the left of the current cursor is a multi-byte
6796 * character, move to its first byte */
6797 if (has_mbyte)
6798 mb_adjust_cursor();
6799 #endif
6800 return OK;
6804 cursor_up(n, upd_topline)
6805 long n;
6806 int upd_topline; /* When TRUE: update topline */
6808 linenr_T lnum;
6810 if (n > 0)
6812 lnum = curwin->w_cursor.lnum;
6813 /* This fails if the cursor is already in the first line or the count
6814 * is larger than the line number and '-' is in 'cpoptions' */
6815 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6816 return FAIL;
6817 if (n >= lnum)
6818 lnum = 1;
6819 else
6820 #ifdef FEAT_FOLDING
6821 if (hasAnyFolding(curwin))
6824 * Count each sequence of folded lines as one logical line.
6826 /* go to the the start of the current fold */
6827 (void)hasFolding(lnum, &lnum, NULL);
6829 while (n--)
6831 /* move up one line */
6832 --lnum;
6833 if (lnum <= 1)
6834 break;
6835 /* If we entered a fold, move to the beginning, unless in
6836 * Insert mode or when 'foldopen' contains "all": it will open
6837 * in a moment. */
6838 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
6839 (void)hasFolding(lnum, &lnum, NULL);
6841 if (lnum < 1)
6842 lnum = 1;
6844 else
6845 #endif
6846 lnum -= n;
6847 curwin->w_cursor.lnum = lnum;
6850 /* try to advance to the column we want to be at */
6851 coladvance(curwin->w_curswant);
6853 if (upd_topline)
6854 update_topline(); /* make sure curwin->w_topline is valid */
6856 return OK;
6860 * Cursor down a number of logical lines.
6863 cursor_down(n, upd_topline)
6864 long n;
6865 int upd_topline; /* When TRUE: update topline */
6867 linenr_T lnum;
6869 if (n > 0)
6871 lnum = curwin->w_cursor.lnum;
6872 #ifdef FEAT_FOLDING
6873 /* Move to last line of fold, will fail if it's the end-of-file. */
6874 (void)hasFolding(lnum, NULL, &lnum);
6875 #endif
6876 /* This fails if the cursor is already in the last line or would move
6877 * beyound the last line and '-' is in 'cpoptions' */
6878 if (lnum >= curbuf->b_ml.ml_line_count
6879 || (lnum + n > curbuf->b_ml.ml_line_count
6880 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
6881 return FAIL;
6882 if (lnum + n >= curbuf->b_ml.ml_line_count)
6883 lnum = curbuf->b_ml.ml_line_count;
6884 else
6885 #ifdef FEAT_FOLDING
6886 if (hasAnyFolding(curwin))
6888 linenr_T last;
6890 /* count each sequence of folded lines as one logical line */
6891 while (n--)
6893 if (hasFolding(lnum, NULL, &last))
6894 lnum = last + 1;
6895 else
6896 ++lnum;
6897 if (lnum >= curbuf->b_ml.ml_line_count)
6898 break;
6900 if (lnum > curbuf->b_ml.ml_line_count)
6901 lnum = curbuf->b_ml.ml_line_count;
6903 else
6904 #endif
6905 lnum += n;
6906 curwin->w_cursor.lnum = lnum;
6909 /* try to advance to the column we want to be at */
6910 coladvance(curwin->w_curswant);
6912 if (upd_topline)
6913 update_topline(); /* make sure curwin->w_topline is valid */
6915 return OK;
6919 * Stuff the last inserted text in the read buffer.
6920 * Last_insert actually is a copy of the redo buffer, so we
6921 * first have to remove the command.
6924 stuff_inserted(c, count, no_esc)
6925 int c; /* Command character to be inserted */
6926 long count; /* Repeat this many times */
6927 int no_esc; /* Don't add an ESC at the end */
6929 char_u *esc_ptr;
6930 char_u *ptr;
6931 char_u *last_ptr;
6932 char_u last = NUL;
6934 ptr = get_last_insert();
6935 if (ptr == NULL)
6937 EMSG(_(e_noinstext));
6938 return FAIL;
6941 /* may want to stuff the command character, to start Insert mode */
6942 if (c != NUL)
6943 stuffcharReadbuff(c);
6944 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
6945 *esc_ptr = NUL; /* remove the ESC */
6947 /* when the last char is either "0" or "^" it will be quoted if no ESC
6948 * comes after it OR if it will inserted more than once and "ptr"
6949 * starts with ^D. -- Acevedo
6951 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
6952 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
6953 && (no_esc || (*ptr == Ctrl_D && count > 1)))
6955 last = *last_ptr;
6956 *last_ptr = NUL;
6961 stuffReadbuff(ptr);
6962 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
6963 if (last)
6964 stuffReadbuff((char_u *)(last == '0'
6965 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
6966 : IF_EB("\026^", CTRL_V_STR "^")));
6968 while (--count > 0);
6970 if (last)
6971 *last_ptr = last;
6973 if (esc_ptr != NULL)
6974 *esc_ptr = ESC; /* put the ESC back */
6976 /* may want to stuff a trailing ESC, to get out of Insert mode */
6977 if (!no_esc)
6978 stuffcharReadbuff(ESC);
6980 return OK;
6983 char_u *
6984 get_last_insert()
6986 if (last_insert == NULL)
6987 return NULL;
6988 return last_insert + last_insert_skip;
6992 * Get last inserted string, and remove trailing <Esc>.
6993 * Returns pointer to allocated memory (must be freed) or NULL.
6995 char_u *
6996 get_last_insert_save()
6998 char_u *s;
6999 int len;
7001 if (last_insert == NULL)
7002 return NULL;
7003 s = vim_strsave(last_insert + last_insert_skip);
7004 if (s != NULL)
7006 len = (int)STRLEN(s);
7007 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
7008 s[len - 1] = NUL;
7010 return s;
7014 * Check the word in front of the cursor for an abbreviation.
7015 * Called when the non-id character "c" has been entered.
7016 * When an abbreviation is recognized it is removed from the text and
7017 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
7019 static int
7020 echeck_abbr(c)
7021 int c;
7023 /* Don't check for abbreviation in paste mode, when disabled and just
7024 * after moving around with cursor keys. */
7025 if (p_paste || no_abbr || arrow_used)
7026 return FALSE;
7028 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
7029 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
7033 * replace-stack functions
7035 * When replacing characters, the replaced characters are remembered for each
7036 * new character. This is used to re-insert the old text when backspacing.
7038 * There is a NUL headed list of characters for each character that is
7039 * currently in the file after the insertion point. When BS is used, one NUL
7040 * headed list is put back for the deleted character.
7042 * For a newline, there are two NUL headed lists. One contains the characters
7043 * that the NL replaced. The extra one stores the characters after the cursor
7044 * that were deleted (always white space).
7046 * Replace_offset is normally 0, in which case replace_push will add a new
7047 * character at the end of the stack. If replace_offset is not 0, that many
7048 * characters will be left on the stack above the newly inserted character.
7051 static char_u *replace_stack = NULL;
7052 static long replace_stack_nr = 0; /* next entry in replace stack */
7053 static long replace_stack_len = 0; /* max. number of entries */
7055 void
7056 replace_push(c)
7057 int c; /* character that is replaced (NUL is none) */
7059 char_u *p;
7061 if (replace_stack_nr < replace_offset) /* nothing to do */
7062 return;
7063 if (replace_stack_len <= replace_stack_nr)
7065 replace_stack_len += 50;
7066 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
7067 if (p == NULL) /* out of memory */
7069 replace_stack_len -= 50;
7070 return;
7072 if (replace_stack != NULL)
7074 mch_memmove(p, replace_stack,
7075 (size_t)(replace_stack_nr * sizeof(char_u)));
7076 vim_free(replace_stack);
7078 replace_stack = p;
7080 p = replace_stack + replace_stack_nr - replace_offset;
7081 if (replace_offset)
7082 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
7083 *p = c;
7084 ++replace_stack_nr;
7087 #if defined(FEAT_MBYTE) || defined(PROTO)
7089 * Push a character onto the replace stack. Handles a multi-byte character in
7090 * reverse byte order, so that the first byte is popped off first.
7091 * Return the number of bytes done (includes composing characters).
7094 replace_push_mb(p)
7095 char_u *p;
7097 int l = (*mb_ptr2len)(p);
7098 int j;
7100 for (j = l - 1; j >= 0; --j)
7101 replace_push(p[j]);
7102 return l;
7104 #endif
7106 #if 0
7108 * call replace_push(c) with replace_offset set to the first NUL.
7110 static void
7111 replace_push_off(c)
7112 int c;
7114 char_u *p;
7116 p = replace_stack + replace_stack_nr;
7117 for (replace_offset = 1; replace_offset < replace_stack_nr;
7118 ++replace_offset)
7119 if (*--p == NUL)
7120 break;
7121 replace_push(c);
7122 replace_offset = 0;
7124 #endif
7127 * Pop one item from the replace stack.
7128 * return -1 if stack empty
7129 * return replaced character or NUL otherwise
7131 static int
7132 replace_pop()
7134 if (replace_stack_nr == 0)
7135 return -1;
7136 return (int)replace_stack[--replace_stack_nr];
7140 * Join the top two items on the replace stack. This removes to "off"'th NUL
7141 * encountered.
7143 static void
7144 replace_join(off)
7145 int off; /* offset for which NUL to remove */
7147 int i;
7149 for (i = replace_stack_nr; --i >= 0; )
7150 if (replace_stack[i] == NUL && off-- <= 0)
7152 --replace_stack_nr;
7153 mch_memmove(replace_stack + i, replace_stack + i + 1,
7154 (size_t)(replace_stack_nr - i));
7155 return;
7160 * Pop bytes from the replace stack until a NUL is found, and insert them
7161 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
7163 static void
7164 replace_pop_ins()
7166 int cc;
7167 int oldState = State;
7169 State = NORMAL; /* don't want REPLACE here */
7170 while ((cc = replace_pop()) > 0)
7172 #ifdef FEAT_MBYTE
7173 mb_replace_pop_ins(cc);
7174 #else
7175 ins_char(cc);
7176 #endif
7177 dec_cursor();
7179 State = oldState;
7182 #ifdef FEAT_MBYTE
7184 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
7185 * indicates a multi-byte char, pop the other bytes too.
7187 static void
7188 mb_replace_pop_ins(cc)
7189 int cc;
7191 int n;
7192 char_u buf[MB_MAXBYTES];
7193 int i;
7194 int c;
7196 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
7198 buf[0] = cc;
7199 for (i = 1; i < n; ++i)
7200 buf[i] = replace_pop();
7201 ins_bytes_len(buf, n);
7203 else
7204 ins_char(cc);
7206 if (enc_utf8)
7207 /* Handle composing chars. */
7208 for (;;)
7210 c = replace_pop();
7211 if (c == -1) /* stack empty */
7212 break;
7213 if ((n = MB_BYTE2LEN(c)) == 1)
7215 /* Not a multi-byte char, put it back. */
7216 replace_push(c);
7217 break;
7219 else
7221 buf[0] = c;
7222 for (i = 1; i < n; ++i)
7223 buf[i] = replace_pop();
7224 if (utf_iscomposing(utf_ptr2char(buf)))
7225 ins_bytes_len(buf, n);
7226 else
7228 /* Not a composing char, put it back. */
7229 for (i = n - 1; i >= 0; --i)
7230 replace_push(buf[i]);
7231 break;
7236 #endif
7239 * make the replace stack empty
7240 * (called when exiting replace mode)
7242 static void
7243 replace_flush()
7245 vim_free(replace_stack);
7246 replace_stack = NULL;
7247 replace_stack_len = 0;
7248 replace_stack_nr = 0;
7252 * Handle doing a BS for one character.
7253 * cc < 0: replace stack empty, just move cursor
7254 * cc == 0: character was inserted, delete it
7255 * cc > 0: character was replaced, put cc (first byte of original char) back
7256 * and check for more characters to be put back
7257 * When "limit_col" is >= 0, don't delete before this column. Matters when
7258 * using composing characters, use del_char_after_col() instead of del_char().
7260 static void
7261 replace_do_bs(limit_col)
7262 int limit_col;
7264 int cc;
7265 #ifdef FEAT_VREPLACE
7266 int orig_len = 0;
7267 int ins_len;
7268 int orig_vcols = 0;
7269 colnr_T start_vcol;
7270 char_u *p;
7271 int i;
7272 int vcol;
7273 #endif
7275 cc = replace_pop();
7276 if (cc > 0)
7278 #ifdef FEAT_VREPLACE
7279 if (State & VREPLACE_FLAG)
7281 /* Get the number of screen cells used by the character we are
7282 * going to delete. */
7283 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
7284 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
7286 #endif
7287 #ifdef FEAT_MBYTE
7288 if (has_mbyte)
7290 (void)del_char_after_col(limit_col);
7291 # ifdef FEAT_VREPLACE
7292 if (State & VREPLACE_FLAG)
7293 orig_len = (int)STRLEN(ml_get_cursor());
7294 # endif
7295 replace_push(cc);
7297 else
7298 #endif
7300 pchar_cursor(cc);
7301 #ifdef FEAT_VREPLACE
7302 if (State & VREPLACE_FLAG)
7303 orig_len = (int)STRLEN(ml_get_cursor()) - 1;
7304 #endif
7306 replace_pop_ins();
7308 #ifdef FEAT_VREPLACE
7309 if (State & VREPLACE_FLAG)
7311 /* Get the number of screen cells used by the inserted characters */
7312 p = ml_get_cursor();
7313 ins_len = (int)STRLEN(p) - orig_len;
7314 vcol = start_vcol;
7315 for (i = 0; i < ins_len; ++i)
7317 vcol += chartabsize(p + i, vcol);
7318 #ifdef FEAT_MBYTE
7319 i += (*mb_ptr2len)(p) - 1;
7320 #endif
7322 vcol -= start_vcol;
7324 /* Delete spaces that were inserted after the cursor to keep the
7325 * text aligned. */
7326 curwin->w_cursor.col += ins_len;
7327 while (vcol > orig_vcols && gchar_cursor() == ' ')
7329 del_char(FALSE);
7330 ++orig_vcols;
7332 curwin->w_cursor.col -= ins_len;
7334 #endif
7336 /* mark the buffer as changed and prepare for displaying */
7337 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
7339 else if (cc == 0)
7340 (void)del_char_after_col(limit_col);
7343 #ifdef FEAT_CINDENT
7345 * Return TRUE if C-indenting is on.
7347 static int
7348 cindent_on()
7350 return (!p_paste && (curbuf->b_p_cin
7351 # ifdef FEAT_EVAL
7352 || *curbuf->b_p_inde != NUL
7353 # endif
7356 #endif
7358 #if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
7360 * Re-indent the current line, based on the current contents of it and the
7361 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
7362 * confused what all the part that handles Control-T is doing that I'm not.
7363 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
7366 void
7367 fixthisline(get_the_indent)
7368 int (*get_the_indent) __ARGS((void));
7370 change_indent(INDENT_SET, get_the_indent(), FALSE, 0, TRUE);
7371 if (linewhite(curwin->w_cursor.lnum))
7372 did_ai = TRUE; /* delete the indent if the line stays empty */
7375 void
7376 fix_indent()
7378 if (p_paste)
7379 return;
7380 # ifdef FEAT_LISP
7381 if (curbuf->b_p_lisp && curbuf->b_p_ai)
7382 fixthisline(get_lisp_indent);
7383 # endif
7384 # if defined(FEAT_LISP) && defined(FEAT_CINDENT)
7385 else
7386 # endif
7387 # ifdef FEAT_CINDENT
7388 if (cindent_on())
7389 do_c_expr_indent();
7390 # endif
7393 #endif
7395 #ifdef FEAT_CINDENT
7397 * return TRUE if 'cinkeys' contains the key "keytyped",
7398 * when == '*': Only if key is preceded with '*' (indent before insert)
7399 * when == '!': Only if key is prededed with '!' (don't insert)
7400 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
7402 * "keytyped" can have a few special values:
7403 * KEY_OPEN_FORW
7404 * KEY_OPEN_BACK
7405 * KEY_COMPLETE just finished completion.
7407 * If line_is_empty is TRUE accept keys with '0' before them.
7410 in_cinkeys(keytyped, when, line_is_empty)
7411 int keytyped;
7412 int when;
7413 int line_is_empty;
7415 char_u *look;
7416 int try_match;
7417 int try_match_word;
7418 char_u *p;
7419 char_u *line;
7420 int icase;
7421 int i;
7423 if (keytyped == NUL)
7424 /* Can happen with CTRL-Y and CTRL-E on a short line. */
7425 return FALSE;
7427 #ifdef FEAT_EVAL
7428 if (*curbuf->b_p_inde != NUL)
7429 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
7430 else
7431 #endif
7432 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
7433 while (*look)
7436 * Find out if we want to try a match with this key, depending on
7437 * 'when' and a '*' or '!' before the key.
7439 switch (when)
7441 case '*': try_match = (*look == '*'); break;
7442 case '!': try_match = (*look == '!'); break;
7443 default: try_match = (*look != '*'); break;
7445 if (*look == '*' || *look == '!')
7446 ++look;
7449 * If there is a '0', only accept a match if the line is empty.
7450 * But may still match when typing last char of a word.
7452 if (*look == '0')
7454 try_match_word = try_match;
7455 if (!line_is_empty)
7456 try_match = FALSE;
7457 ++look;
7459 else
7460 try_match_word = FALSE;
7463 * does it look like a control character?
7465 if (*look == '^'
7466 #ifdef EBCDIC
7467 && (Ctrl_chr(look[1]) != 0)
7468 #else
7469 && look[1] >= '?' && look[1] <= '_'
7470 #endif
7473 if (try_match && keytyped == Ctrl_chr(look[1]))
7474 return TRUE;
7475 look += 2;
7478 * 'o' means "o" command, open forward.
7479 * 'O' means "O" command, open backward.
7481 else if (*look == 'o')
7483 if (try_match && keytyped == KEY_OPEN_FORW)
7484 return TRUE;
7485 ++look;
7487 else if (*look == 'O')
7489 if (try_match && keytyped == KEY_OPEN_BACK)
7490 return TRUE;
7491 ++look;
7495 * 'e' means to check for "else" at start of line and just before the
7496 * cursor.
7498 else if (*look == 'e')
7500 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
7502 p = ml_get_curline();
7503 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
7504 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
7505 return TRUE;
7507 ++look;
7511 * ':' only causes an indent if it is at the end of a label or case
7512 * statement, or when it was before typing the ':' (to fix
7513 * class::method for C++).
7515 else if (*look == ':')
7517 if (try_match && keytyped == ':')
7519 p = ml_get_curline();
7520 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
7521 return TRUE;
7522 /* Need to get the line again after cin_islabel(). */
7523 p = ml_get_curline();
7524 if (curwin->w_cursor.col > 2
7525 && p[curwin->w_cursor.col - 1] == ':'
7526 && p[curwin->w_cursor.col - 2] == ':')
7528 p[curwin->w_cursor.col - 1] = ' ';
7529 i = (cin_iscase(p) || cin_isscopedecl(p)
7530 || cin_islabel(30));
7531 p = ml_get_curline();
7532 p[curwin->w_cursor.col - 1] = ':';
7533 if (i)
7534 return TRUE;
7537 ++look;
7542 * Is it a key in <>, maybe?
7544 else if (*look == '<')
7546 if (try_match)
7549 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
7550 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
7551 * >, *, : and ! keys if they really really want to.
7553 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
7554 && keytyped == look[1])
7555 return TRUE;
7557 if (keytyped == get_special_key_code(look + 1))
7558 return TRUE;
7560 while (*look && *look != '>')
7561 look++;
7562 while (*look == '>')
7563 look++;
7567 * Is it a word: "=word"?
7569 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
7571 ++look;
7572 if (*look == '~')
7574 icase = TRUE;
7575 ++look;
7577 else
7578 icase = FALSE;
7579 p = vim_strchr(look, ',');
7580 if (p == NULL)
7581 p = look + STRLEN(look);
7582 if ((try_match || try_match_word)
7583 && curwin->w_cursor.col >= (colnr_T)(p - look))
7585 int match = FALSE;
7587 #ifdef FEAT_INS_EXPAND
7588 if (keytyped == KEY_COMPLETE)
7590 char_u *s;
7592 /* Just completed a word, check if it starts with "look".
7593 * search back for the start of a word. */
7594 line = ml_get_curline();
7595 # ifdef FEAT_MBYTE
7596 if (has_mbyte)
7598 char_u *n;
7600 for (s = line + curwin->w_cursor.col; s > line; s = n)
7602 n = mb_prevptr(line, s);
7603 if (!vim_iswordp(n))
7604 break;
7607 else
7608 # endif
7609 for (s = line + curwin->w_cursor.col; s > line; --s)
7610 if (!vim_iswordc(s[-1]))
7611 break;
7612 if (s + (p - look) <= line + curwin->w_cursor.col
7613 && (icase
7614 ? MB_STRNICMP(s, look, p - look)
7615 : STRNCMP(s, look, p - look)) == 0)
7616 match = TRUE;
7618 else
7619 #endif
7620 /* TODO: multi-byte */
7621 if (keytyped == (int)p[-1] || (icase && keytyped < 256
7622 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
7624 line = ml_get_cursor();
7625 if ((curwin->w_cursor.col == (colnr_T)(p - look)
7626 || !vim_iswordc(line[-(p - look) - 1]))
7627 && (icase
7628 ? MB_STRNICMP(line - (p - look), look, p - look)
7629 : STRNCMP(line - (p - look), look, p - look))
7630 == 0)
7631 match = TRUE;
7633 if (match && try_match_word && !try_match)
7635 /* "0=word": Check if there are only blanks before the
7636 * word. */
7637 line = ml_get_curline();
7638 if ((int)(skipwhite(line) - line) !=
7639 (int)(curwin->w_cursor.col - (p - look)))
7640 match = FALSE;
7642 if (match)
7643 return TRUE;
7645 look = p;
7649 * ok, it's a boring generic character.
7651 else
7653 if (try_match && *look == keytyped)
7654 return TRUE;
7655 ++look;
7659 * Skip over ", ".
7661 look = skip_to_option_part(look);
7663 return FALSE;
7665 #endif /* FEAT_CINDENT */
7667 #if defined(FEAT_RIGHTLEFT) || defined(PROTO)
7669 * Map Hebrew keyboard when in hkmap mode.
7672 hkmap(c)
7673 int c;
7675 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
7677 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
7678 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
7679 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
7680 static char_u map[26] =
7681 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
7682 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
7683 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
7684 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
7685 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
7686 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
7687 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
7688 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
7689 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
7691 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
7692 return (int)(map[CharOrd(c)] - 1 + p_aleph);
7693 /* '-1'='sofit' */
7694 else if (c == 'x')
7695 return 'X';
7696 else if (c == 'q')
7697 return '\''; /* {geresh}={'} */
7698 else if (c == 246)
7699 return ' '; /* \"o --> ' ' for a german keyboard */
7700 else if (c == 228)
7701 return ' '; /* \"a --> ' ' -- / -- */
7702 else if (c == 252)
7703 return ' '; /* \"u --> ' ' -- / -- */
7704 #ifdef EBCDIC
7705 else if (islower(c))
7706 #else
7707 /* NOTE: islower() does not do the right thing for us on Linux so we
7708 * do this the same was as 5.7 and previous, so it works correctly on
7709 * all systems. Specifically, the e.g. Delete and Arrow keys are
7710 * munged and won't work if e.g. searching for Hebrew text.
7712 else if (c >= 'a' && c <= 'z')
7713 #endif
7714 return (int)(map[CharOrdLow(c)] + p_aleph);
7715 else
7716 return c;
7718 else
7720 switch (c)
7722 case '`': return ';';
7723 case '/': return '.';
7724 case '\'': return ',';
7725 case 'q': return '/';
7726 case 'w': return '\'';
7728 /* Hebrew letters - set offset from 'a' */
7729 case ',': c = '{'; break;
7730 case '.': c = 'v'; break;
7731 case ';': c = 't'; break;
7732 default: {
7733 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
7735 #ifdef EBCDIC
7736 /* see note about islower() above */
7737 if (!islower(c))
7738 #else
7739 if (c < 'a' || c > 'z')
7740 #endif
7741 return c;
7742 c = str[CharOrdLow(c)];
7743 break;
7747 return (int)(CharOrdLow(c) + p_aleph);
7750 #endif
7752 static void
7753 ins_reg()
7755 int need_redraw = FALSE;
7756 int regname;
7757 int literally = 0;
7758 #ifdef FEAT_VISUAL
7759 int vis_active = VIsual_active;
7760 #endif
7763 * If we are going to wait for a character, show a '"'.
7765 pc_status = PC_STATUS_UNSET;
7766 if (redrawing() && !char_avail())
7768 /* may need to redraw when no more chars available now */
7769 ins_redraw(FALSE);
7771 edit_putchar('"', TRUE);
7772 #ifdef FEAT_CMDL_INFO
7773 add_to_showcmd_c(Ctrl_R);
7774 #endif
7777 #ifdef USE_ON_FLY_SCROLL
7778 dont_scroll = TRUE; /* disallow scrolling here */
7779 #endif
7782 * Don't map the register name. This also prevents the mode message to be
7783 * deleted when ESC is hit.
7785 ++no_mapping;
7786 regname = plain_vgetc();
7787 LANGMAP_ADJUST(regname, TRUE);
7788 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
7790 /* Get a third key for literal register insertion */
7791 literally = regname;
7792 #ifdef FEAT_CMDL_INFO
7793 add_to_showcmd_c(literally);
7794 #endif
7795 regname = plain_vgetc();
7796 LANGMAP_ADJUST(regname, TRUE);
7798 --no_mapping;
7800 #ifdef FEAT_EVAL
7802 * Don't call u_sync() while getting the expression,
7803 * evaluating it or giving an error message for it!
7805 ++no_u_sync;
7806 if (regname == '=')
7808 # ifdef USE_IM_CONTROL
7809 int im_on = im_get_status();
7810 # endif
7811 regname = get_expr_register();
7812 # ifdef USE_IM_CONTROL
7813 /* Restore the Input Method. */
7814 if (im_on)
7815 im_set_active(TRUE);
7816 # endif
7818 if (regname == NUL || !valid_yank_reg(regname, FALSE))
7820 vim_beep();
7821 need_redraw = TRUE; /* remove the '"' */
7823 else
7825 #endif
7826 if (literally == Ctrl_O || literally == Ctrl_P)
7828 /* Append the command to the redo buffer. */
7829 AppendCharToRedobuff(Ctrl_R);
7830 AppendCharToRedobuff(literally);
7831 AppendCharToRedobuff(regname);
7833 do_put(regname, BACKWARD, 1L,
7834 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
7836 else if (insert_reg(regname, literally) == FAIL)
7838 vim_beep();
7839 need_redraw = TRUE; /* remove the '"' */
7841 else if (stop_insert_mode)
7842 /* When the '=' register was used and a function was invoked that
7843 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
7844 * insert anything, need to remove the '"' */
7845 need_redraw = TRUE;
7847 #ifdef FEAT_EVAL
7849 --no_u_sync;
7850 #endif
7851 #ifdef FEAT_CMDL_INFO
7852 clear_showcmd();
7853 #endif
7855 /* If the inserted register is empty, we need to remove the '"' */
7856 if (need_redraw || stuff_empty())
7857 edit_unputchar();
7859 #ifdef FEAT_VISUAL
7860 /* Disallow starting Visual mode here, would get a weird mode. */
7861 if (!vis_active && VIsual_active)
7862 end_visual_mode();
7863 #endif
7867 * CTRL-G commands in Insert mode.
7869 static void
7870 ins_ctrl_g()
7872 int c;
7874 #ifdef FEAT_INS_EXPAND
7875 /* Right after CTRL-X the cursor will be after the ruler. */
7876 setcursor();
7877 #endif
7880 * Don't map the second key. This also prevents the mode message to be
7881 * deleted when ESC is hit.
7883 ++no_mapping;
7884 c = plain_vgetc();
7885 --no_mapping;
7886 switch (c)
7888 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
7889 case K_UP:
7890 case Ctrl_K:
7891 case 'k': ins_up(TRUE);
7892 break;
7894 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
7895 case K_DOWN:
7896 case Ctrl_J:
7897 case 'j': ins_down(TRUE);
7898 break;
7900 /* CTRL-G u: start new undoable edit */
7901 case 'u': u_sync(TRUE);
7902 ins_need_undo = TRUE;
7904 /* Need to reset Insstart, esp. because a BS that joins
7905 * a line to the previous one must save for undo. */
7906 Insstart = curwin->w_cursor;
7907 break;
7909 /* Unknown CTRL-G command, reserved for future expansion. */
7910 default: vim_beep();
7915 * CTRL-^ in Insert mode.
7917 static void
7918 ins_ctrl_hat()
7920 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
7922 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
7923 if (State & LANGMAP)
7925 curbuf->b_p_iminsert = B_IMODE_NONE;
7926 State &= ~LANGMAP;
7928 else
7930 curbuf->b_p_iminsert = B_IMODE_LMAP;
7931 State |= LANGMAP;
7932 #ifdef USE_IM_CONTROL
7933 im_set_active(FALSE);
7934 #endif
7937 #ifdef USE_IM_CONTROL
7938 else
7940 /* There are no ":lmap" mappings, toggle IM */
7941 if (im_get_status())
7943 curbuf->b_p_iminsert = B_IMODE_NONE;
7944 im_set_active(FALSE);
7946 else
7948 curbuf->b_p_iminsert = B_IMODE_IM;
7949 State &= ~LANGMAP;
7950 im_set_active(TRUE);
7953 #endif
7954 set_iminsert_global();
7955 showmode();
7956 #ifdef FEAT_GUI
7957 /* may show different cursor shape or color */
7958 if (gui.in_use)
7959 gui_update_cursor(TRUE, FALSE);
7960 #endif
7961 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
7962 /* Show/unshow value of 'keymap' in status lines. */
7963 status_redraw_curbuf();
7964 #endif
7968 * Handle ESC in insert mode.
7969 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
7970 * insert.
7972 static int
7973 ins_esc(count, cmdchar, nomove)
7974 long *count;
7975 int cmdchar;
7976 int nomove; /* don't move cursor */
7978 int temp;
7979 static int disabled_redraw = FALSE;
7981 #ifdef FEAT_SPELL
7982 check_spell_redraw();
7983 #endif
7984 #if defined(FEAT_HANGULIN)
7985 # if defined(ESC_CHG_TO_ENG_MODE)
7986 hangul_input_state_set(0);
7987 # endif
7988 if (composing_hangul)
7990 push_raw_key(composing_hangul_buffer, 2);
7991 composing_hangul = 0;
7993 #endif
7995 temp = curwin->w_cursor.col;
7996 if (disabled_redraw)
7998 --RedrawingDisabled;
7999 disabled_redraw = FALSE;
8001 if (!arrow_used)
8004 * Don't append the ESC for "r<CR>" and "grx".
8005 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
8006 * when "count" is non-zero.
8008 if (cmdchar != 'r' && cmdchar != 'v')
8009 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
8012 * Repeating insert may take a long time. Check for
8013 * interrupt now and then.
8015 if (*count > 0)
8017 line_breakcheck();
8018 if (got_int)
8019 *count = 0;
8022 if (--*count > 0) /* repeat what was typed */
8024 /* Vi repeats the insert without replacing characters. */
8025 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
8026 State &= ~REPLACE_FLAG;
8028 (void)start_redo_ins();
8029 if (cmdchar == 'r' || cmdchar == 'v')
8030 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
8031 ++RedrawingDisabled;
8032 disabled_redraw = TRUE;
8033 return FALSE; /* repeat the insert */
8035 stop_insert(&curwin->w_cursor, TRUE);
8036 undisplay_dollar();
8039 /* When an autoindent was removed, curswant stays after the
8040 * indent */
8041 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
8042 curwin->w_set_curswant = TRUE;
8044 /* Remember the last Insert position in the '^ mark. */
8045 if (!cmdmod.keepjumps)
8046 curbuf->b_last_insert = curwin->w_cursor;
8049 * The cursor should end up on the last inserted character.
8050 * Don't do it for CTRL-O, unless past the end of the line.
8052 if (!nomove
8053 && (curwin->w_cursor.col != 0
8054 #ifdef FEAT_VIRTUALEDIT
8055 || curwin->w_cursor.coladd > 0
8056 #endif
8058 && (restart_edit == NUL
8059 || (gchar_cursor() == NUL
8060 #ifdef FEAT_VISUAL
8061 && !VIsual_active
8062 #endif
8064 #ifdef FEAT_RIGHTLEFT
8065 && !revins_on
8066 #endif
8069 #ifdef FEAT_VIRTUALEDIT
8070 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
8072 oneleft();
8073 if (restart_edit != NUL)
8074 ++curwin->w_cursor.coladd;
8076 else
8077 #endif
8079 --curwin->w_cursor.col;
8080 #ifdef FEAT_MBYTE
8081 /* Correct cursor for multi-byte character. */
8082 if (has_mbyte)
8083 mb_adjust_cursor();
8084 #endif
8088 #ifdef USE_IM_CONTROL
8089 /* Disable IM to allow typing English directly for Normal mode commands.
8090 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
8091 * well). */
8092 if (!(State & LANGMAP))
8093 im_save_status(&curbuf->b_p_iminsert);
8094 im_set_active(FALSE);
8095 #endif
8097 State = NORMAL;
8098 /* need to position cursor again (e.g. when on a TAB ) */
8099 changed_cline_bef_curs();
8101 #ifdef FEAT_MOUSE
8102 setmouse();
8103 #endif
8104 #ifdef CURSOR_SHAPE
8105 ui_cursor_shape(); /* may show different cursor shape */
8106 #endif
8109 * When recording or for CTRL-O, need to display the new mode.
8110 * Otherwise remove the mode message.
8112 if (Recording || restart_edit != NUL)
8113 showmode();
8114 else if (p_smd)
8115 MSG("");
8117 return TRUE; /* exit Insert mode */
8120 #ifdef FEAT_RIGHTLEFT
8122 * Toggle language: hkmap and revins_on.
8123 * Move to end of reverse inserted text.
8125 static void
8126 ins_ctrl_()
8128 if (revins_on && revins_chars && revins_scol >= 0)
8130 while (gchar_cursor() != NUL && revins_chars--)
8131 ++curwin->w_cursor.col;
8133 p_ri = !p_ri;
8134 revins_on = (State == INSERT && p_ri);
8135 if (revins_on)
8137 revins_scol = curwin->w_cursor.col;
8138 revins_legal++;
8139 revins_chars = 0;
8140 undisplay_dollar();
8142 else
8143 revins_scol = -1;
8144 #ifdef FEAT_FKMAP
8145 if (p_altkeymap)
8148 * to be consistent also for redo command, using '.'
8149 * set arrow_used to true and stop it - causing to redo
8150 * characters entered in one mode (normal/reverse insert).
8152 arrow_used = TRUE;
8153 (void)stop_arrow();
8154 p_fkmap = curwin->w_p_rl ^ p_ri;
8155 if (p_fkmap && p_ri)
8156 State = INSERT;
8158 else
8159 #endif
8160 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
8161 showmode();
8163 #endif
8165 #ifdef FEAT_VISUAL
8167 * If 'keymodel' contains "startsel", may start selection.
8168 * Returns TRUE when a CTRL-O and other keys stuffed.
8170 static int
8171 ins_start_select(c)
8172 int c;
8174 if (km_startsel)
8175 switch (c)
8177 case K_KHOME:
8178 case K_KEND:
8179 case K_PAGEUP:
8180 case K_KPAGEUP:
8181 case K_PAGEDOWN:
8182 case K_KPAGEDOWN:
8183 # ifdef MACOS
8184 case K_LEFT:
8185 case K_RIGHT:
8186 case K_UP:
8187 case K_DOWN:
8188 case K_END:
8189 case K_HOME:
8190 # endif
8191 if (!(mod_mask & MOD_MASK_SHIFT))
8192 break;
8193 /* FALLTHROUGH */
8194 case K_S_LEFT:
8195 case K_S_RIGHT:
8196 case K_S_UP:
8197 case K_S_DOWN:
8198 case K_S_END:
8199 case K_S_HOME:
8200 /* Start selection right away, the cursor can move with
8201 * CTRL-O when beyond the end of the line. */
8202 start_selection();
8204 /* Execute the key in (insert) Select mode. */
8205 stuffcharReadbuff(Ctrl_O);
8206 if (mod_mask)
8208 char_u buf[4];
8210 buf[0] = K_SPECIAL;
8211 buf[1] = KS_MODIFIER;
8212 buf[2] = mod_mask;
8213 buf[3] = NUL;
8214 stuffReadbuff(buf);
8216 stuffcharReadbuff(c);
8217 return TRUE;
8219 return FALSE;
8221 #endif
8224 * <Insert> key in Insert mode: toggle insert/remplace mode.
8226 static void
8227 ins_insert(replaceState)
8228 int replaceState;
8230 #ifdef FEAT_FKMAP
8231 if (p_fkmap && p_ri)
8233 beep_flush();
8234 EMSG(farsi_text_3); /* encoded in Farsi */
8235 return;
8237 #endif
8239 #ifdef FEAT_AUTOCMD
8240 # ifdef FEAT_EVAL
8241 set_vim_var_string(VV_INSERTMODE,
8242 (char_u *)((State & REPLACE_FLAG) ? "i" :
8243 # ifdef FEAT_VREPLACE
8244 replaceState == VREPLACE ? "v" :
8245 # endif
8246 "r"), 1);
8247 # endif
8248 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
8249 #endif
8250 if (State & REPLACE_FLAG)
8251 State = INSERT | (State & LANGMAP);
8252 else
8253 State = replaceState | (State & LANGMAP);
8254 AppendCharToRedobuff(K_INS);
8255 showmode();
8256 #ifdef CURSOR_SHAPE
8257 ui_cursor_shape(); /* may show different cursor shape */
8258 #endif
8262 * Pressed CTRL-O in Insert mode.
8264 static void
8265 ins_ctrl_o()
8267 #ifdef FEAT_VREPLACE
8268 if (State & VREPLACE_FLAG)
8269 restart_edit = 'V';
8270 else
8271 #endif
8272 if (State & REPLACE_FLAG)
8273 restart_edit = 'R';
8274 else
8275 restart_edit = 'I';
8276 #ifdef FEAT_VIRTUALEDIT
8277 if (virtual_active())
8278 ins_at_eol = FALSE; /* cursor always keeps its column */
8279 else
8280 #endif
8281 ins_at_eol = (gchar_cursor() == NUL);
8285 * If the cursor is on an indent, ^T/^D insert/delete one
8286 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
8287 * Always round the indent to 'shiftwidth', this is compatible
8288 * with vi. But vi only supports ^T and ^D after an
8289 * autoindent, we support it everywhere.
8291 static void
8292 ins_shift(c, lastc)
8293 int c;
8294 int lastc;
8296 if (stop_arrow() == FAIL)
8297 return;
8298 AppendCharToRedobuff(c);
8301 * 0^D and ^^D: remove all indent.
8303 if (c == Ctrl_D && (lastc == '0' || lastc == '^')
8304 && curwin->w_cursor.col > 0)
8306 --curwin->w_cursor.col;
8307 (void)del_char(FALSE); /* delete the '^' or '0' */
8308 /* In Replace mode, restore the characters that '^' or '0' replaced. */
8309 if (State & REPLACE_FLAG)
8310 replace_pop_ins();
8311 if (lastc == '^')
8312 old_indent = get_indent(); /* remember curr. indent */
8313 change_indent(INDENT_SET, 0, TRUE, 0, TRUE);
8315 else
8316 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0, TRUE);
8318 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
8319 did_ai = FALSE;
8320 #ifdef FEAT_SMARTINDENT
8321 did_si = FALSE;
8322 can_si = FALSE;
8323 can_si_back = FALSE;
8324 #endif
8325 #ifdef FEAT_CINDENT
8326 can_cindent = FALSE; /* no cindenting after ^D or ^T */
8327 #endif
8330 static void
8331 ins_del()
8333 int temp;
8335 if (stop_arrow() == FAIL)
8336 return;
8337 if (gchar_cursor() == NUL) /* delete newline */
8339 temp = curwin->w_cursor.col;
8340 if (!can_bs(BS_EOL) /* only if "eol" included */
8341 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
8342 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
8343 || do_join(2,FALSE) == FAIL)
8344 vim_beep();
8345 else
8346 curwin->w_cursor.col = temp;
8348 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
8349 vim_beep();
8350 did_ai = FALSE;
8351 #ifdef FEAT_SMARTINDENT
8352 did_si = FALSE;
8353 can_si = FALSE;
8354 can_si_back = FALSE;
8355 #endif
8356 AppendCharToRedobuff(K_DEL);
8359 static void ins_bs_one __ARGS((colnr_T *vcolp));
8362 * Delete one character for ins_bs().
8364 static void
8365 ins_bs_one(vcolp)
8366 colnr_T *vcolp;
8368 dec_cursor();
8369 getvcol(curwin, &curwin->w_cursor, vcolp, NULL, NULL);
8370 if (State & REPLACE_FLAG)
8372 /* Don't delete characters before the insert point when in
8373 * Replace mode */
8374 if (curwin->w_cursor.lnum != Insstart.lnum
8375 || curwin->w_cursor.col >= Insstart.col)
8376 replace_do_bs(-1);
8378 else
8379 (void)del_char(FALSE);
8383 * Handle Backspace, delete-word and delete-line in Insert mode.
8384 * Return TRUE when backspace was actually used.
8386 static int
8387 ins_bs(c, mode, inserted_space_p)
8388 int c;
8389 int mode;
8390 int *inserted_space_p;
8392 linenr_T lnum;
8393 int cc;
8394 int temp = 0; /* init for GCC */
8395 colnr_T save_col;
8396 colnr_T mincol;
8397 int did_backspace = FALSE;
8398 int in_indent;
8399 int oldState;
8400 #ifdef FEAT_MBYTE
8401 int cpc[MAX_MCO]; /* composing characters */
8402 #endif
8405 * can't delete anything in an empty file
8406 * can't backup past first character in buffer
8407 * can't backup past starting point unless 'backspace' > 1
8408 * can backup to a previous line if 'backspace' == 0
8410 if ( bufempty()
8411 || (
8412 #ifdef FEAT_RIGHTLEFT
8413 !revins_on &&
8414 #endif
8415 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
8416 || (!can_bs(BS_START)
8417 && (arrow_used
8418 || (curwin->w_cursor.lnum == Insstart.lnum
8419 && curwin->w_cursor.col <= Insstart.col)))
8420 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
8421 && curwin->w_cursor.col <= ai_col)
8422 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
8424 vim_beep();
8425 return FALSE;
8428 if (stop_arrow() == FAIL)
8429 return FALSE;
8430 in_indent = inindent(0);
8431 #ifdef FEAT_CINDENT
8432 if (in_indent)
8433 can_cindent = FALSE;
8434 #endif
8435 #ifdef FEAT_COMMENTS
8436 end_comment_pending = NUL; /* After BS, don't auto-end comment */
8437 #endif
8438 #ifdef FEAT_RIGHTLEFT
8439 if (revins_on) /* put cursor after last inserted char */
8440 inc_cursor();
8441 #endif
8443 #ifdef FEAT_VIRTUALEDIT
8444 /* Virtualedit:
8445 * BACKSPACE_CHAR eats a virtual space
8446 * BACKSPACE_WORD eats all coladd
8447 * BACKSPACE_LINE eats all coladd and keeps going
8449 if (curwin->w_cursor.coladd > 0)
8451 if (mode == BACKSPACE_CHAR)
8453 --curwin->w_cursor.coladd;
8454 return TRUE;
8456 if (mode == BACKSPACE_WORD)
8458 curwin->w_cursor.coladd = 0;
8459 return TRUE;
8461 curwin->w_cursor.coladd = 0;
8463 #endif
8466 * delete newline!
8468 if (curwin->w_cursor.col == 0)
8470 lnum = Insstart.lnum;
8471 if (curwin->w_cursor.lnum == Insstart.lnum
8472 #ifdef FEAT_RIGHTLEFT
8473 || revins_on
8474 #endif
8477 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
8478 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
8479 return FALSE;
8480 --Insstart.lnum;
8481 Insstart.col = MAXCOL;
8484 * In replace mode:
8485 * cc < 0: NL was inserted, delete it
8486 * cc >= 0: NL was replaced, put original characters back
8488 cc = -1;
8489 if (State & REPLACE_FLAG)
8490 cc = replace_pop(); /* returns -1 if NL was inserted */
8492 * In replace mode, in the line we started replacing, we only move the
8493 * cursor.
8495 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
8497 dec_cursor();
8499 else
8501 #ifdef FEAT_VREPLACE
8502 if (!(State & VREPLACE_FLAG)
8503 || curwin->w_cursor.lnum > orig_line_count)
8504 #endif
8506 temp = gchar_cursor(); /* remember current char */
8507 --curwin->w_cursor.lnum;
8509 /* When "aw" is in 'formatoptions' we must delete the space at
8510 * the end of the line, otherwise the line will be broken
8511 * again when auto-formatting. */
8512 if (has_format_option(FO_AUTO)
8513 && has_format_option(FO_WHITE_PAR))
8515 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
8516 TRUE);
8517 int len;
8519 len = (int)STRLEN(ptr);
8520 if (len > 0 && ptr[len - 1] == ' ')
8521 ptr[len - 1] = NUL;
8524 (void)do_join(2,FALSE);
8525 if (temp == NUL && gchar_cursor() != NUL)
8526 inc_cursor();
8528 #ifdef FEAT_VREPLACE
8529 else
8530 dec_cursor();
8531 #endif
8534 * In REPLACE mode we have to put back the text that was replaced
8535 * by the NL. On the replace stack is first a NUL-terminated
8536 * sequence of characters that were deleted and then the
8537 * characters that NL replaced.
8539 if (State & REPLACE_FLAG)
8542 * Do the next ins_char() in NORMAL state, to
8543 * prevent ins_char() from replacing characters and
8544 * avoiding showmatch().
8546 oldState = State;
8547 State = NORMAL;
8549 * restore characters (blanks) deleted after cursor
8551 while (cc > 0)
8553 save_col = curwin->w_cursor.col;
8554 #ifdef FEAT_MBYTE
8555 mb_replace_pop_ins(cc);
8556 #else
8557 ins_char(cc);
8558 #endif
8559 curwin->w_cursor.col = save_col;
8560 cc = replace_pop();
8562 /* restore the characters that NL replaced */
8563 replace_pop_ins();
8564 State = oldState;
8567 did_ai = FALSE;
8569 else
8572 * Delete character(s) before the cursor.
8574 #ifdef FEAT_RIGHTLEFT
8575 if (revins_on) /* put cursor on last inserted char */
8576 dec_cursor();
8577 #endif
8578 mincol = 0;
8579 /* keep indent */
8580 if (mode == BACKSPACE_LINE
8581 && (curbuf->b_p_ai
8582 #ifdef FEAT_CINDENT
8583 || cindent_on()
8584 #endif
8586 #ifdef FEAT_RIGHTLEFT
8587 && !revins_on
8588 #endif
8591 save_col = curwin->w_cursor.col;
8592 beginline(BL_WHITE);
8593 if (curwin->w_cursor.col < save_col)
8594 mincol = curwin->w_cursor.col;
8595 curwin->w_cursor.col = save_col;
8599 * Handle deleting one 'shiftwidth' or 'softtabstop'.
8601 if ( mode == BACKSPACE_CHAR
8602 && ((p_sta && in_indent)
8603 || (
8604 #ifdef FEAT_VARTABS
8605 (tabstop_count(curbuf->b_p_vsts_ary) != 0
8606 || curbuf->b_p_sts != 0)
8607 #else
8608 curbuf->b_p_sts != 0
8609 #endif
8610 && curwin->w_cursor.col > 0
8611 && (*(ml_get_cursor() - 1) == TAB
8612 || (*(ml_get_cursor() - 1) == ' '
8613 && (!*inserted_space_p
8614 || arrow_used))))))
8616 #ifndef FEAT_VARTABS
8617 int ts;
8618 #endif
8619 colnr_T vcol;
8620 colnr_T want_vcol;
8621 colnr_T start_vcol;
8623 *inserted_space_p = FALSE;
8624 #ifndef FEAT_VARTABS
8625 if (p_sta && in_indent)
8626 ts = curbuf->b_p_sw;
8627 else
8628 ts = curbuf->b_p_sts;
8629 #endif
8630 /* Compute the virtual column where we want to be. Since
8631 * 'showbreak' may get in the way, need to get the last column of
8632 * the previous character. */
8633 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8634 start_vcol = vcol;
8635 dec_cursor();
8636 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
8637 inc_cursor();
8638 #ifdef FEAT_VARTABS
8639 if (p_sta && in_indent)
8640 want_vcol = (want_vcol / curbuf->b_p_sw) * curbuf->b_p_sw;
8641 else
8642 want_vcol = tabstop_start(want_vcol, curbuf->b_p_sts,
8643 curbuf->b_p_vsts_ary);
8644 #else
8645 want_vcol = (want_vcol / ts) * ts;
8646 #endif
8648 /* delete characters until we are at or before want_vcol */
8649 while (vcol > want_vcol
8650 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
8651 ins_bs_one(&vcol);
8653 /* insert extra spaces until we are at want_vcol */
8654 while (vcol < want_vcol)
8656 /* Remember the first char we inserted */
8657 if (curwin->w_cursor.lnum == Insstart.lnum
8658 && curwin->w_cursor.col < Insstart.col)
8659 Insstart.col = curwin->w_cursor.col;
8661 #ifdef FEAT_VREPLACE
8662 if (State & VREPLACE_FLAG)
8663 ins_char(' ');
8664 else
8665 #endif
8667 ins_str((char_u *)" ");
8668 if ((State & REPLACE_FLAG))
8669 replace_push(NUL);
8671 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
8674 /* If we are now back where we started delete one character. Can
8675 * happen when using 'sts' and 'linebreak'. */
8676 if (vcol >= start_vcol)
8677 ins_bs_one(&vcol);
8681 * Delete upto starting point, start of line or previous word.
8683 else do
8685 #ifdef FEAT_RIGHTLEFT
8686 if (!revins_on) /* put cursor on char to be deleted */
8687 #endif
8688 dec_cursor();
8690 /* start of word? */
8691 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
8693 mode = BACKSPACE_WORD_NOT_SPACE;
8694 temp = vim_iswordc(gchar_cursor());
8696 /* end of word? */
8697 else if (mode == BACKSPACE_WORD_NOT_SPACE
8698 && (vim_isspace(cc = gchar_cursor())
8699 || vim_iswordc(cc) != temp))
8701 #ifdef FEAT_RIGHTLEFT
8702 if (!revins_on)
8703 #endif
8704 inc_cursor();
8705 #ifdef FEAT_RIGHTLEFT
8706 else if (State & REPLACE_FLAG)
8707 dec_cursor();
8708 #endif
8709 break;
8711 if (State & REPLACE_FLAG)
8712 replace_do_bs(-1);
8713 else
8715 #ifdef FEAT_MBYTE
8716 if (enc_utf8 && p_deco)
8717 (void)utfc_ptr2char(ml_get_cursor(), cpc);
8718 #endif
8719 (void)del_char(FALSE);
8720 #ifdef FEAT_MBYTE
8722 * If there are combining characters and 'delcombine' is set
8723 * move the cursor back. Don't back up before the base
8724 * character.
8726 if (enc_utf8 && p_deco && cpc[0] != NUL)
8727 inc_cursor();
8728 #endif
8729 #ifdef FEAT_RIGHTLEFT
8730 if (revins_chars)
8732 revins_chars--;
8733 revins_legal++;
8735 if (revins_on && gchar_cursor() == NUL)
8736 break;
8737 #endif
8739 /* Just a single backspace?: */
8740 if (mode == BACKSPACE_CHAR)
8741 break;
8742 } while (
8743 #ifdef FEAT_RIGHTLEFT
8744 revins_on ||
8745 #endif
8746 (curwin->w_cursor.col > mincol
8747 && (curwin->w_cursor.lnum != Insstart.lnum
8748 || curwin->w_cursor.col != Insstart.col)));
8749 did_backspace = TRUE;
8751 #ifdef FEAT_SMARTINDENT
8752 did_si = FALSE;
8753 can_si = FALSE;
8754 can_si_back = FALSE;
8755 #endif
8756 if (curwin->w_cursor.col <= 1)
8757 did_ai = FALSE;
8759 * It's a little strange to put backspaces into the redo
8760 * buffer, but it makes auto-indent a lot easier to deal
8761 * with.
8763 AppendCharToRedobuff(c);
8765 /* If deleted before the insertion point, adjust it */
8766 if (curwin->w_cursor.lnum == Insstart.lnum
8767 && curwin->w_cursor.col < Insstart.col)
8768 Insstart.col = curwin->w_cursor.col;
8770 /* vi behaviour: the cursor moves backward but the character that
8771 * was there remains visible
8772 * Vim behaviour: the cursor moves backward and the character that
8773 * was there is erased from the screen.
8774 * We can emulate the vi behaviour by pretending there is a dollar
8775 * displayed even when there isn't.
8776 * --pkv Sun Jan 19 01:56:40 EST 2003 */
8777 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
8778 dollar_vcol = curwin->w_virtcol;
8780 #ifdef FEAT_FOLDING
8781 /* When deleting a char the cursor line must never be in a closed fold.
8782 * E.g., when 'foldmethod' is indent and deleting the first non-white
8783 * char before a Tab. */
8784 if (did_backspace)
8785 foldOpenCursor();
8786 #endif
8788 return did_backspace;
8791 #ifdef FEAT_MOUSE
8792 static void
8793 ins_mouse(c)
8794 int c;
8796 pos_T tpos;
8797 win_T *old_curwin = curwin;
8799 # ifdef FEAT_GUI
8800 /* When GUI is active, also move/paste when 'mouse' is empty */
8801 if (!gui.in_use)
8802 # endif
8803 if (!mouse_has(MOUSE_INSERT))
8804 return;
8806 undisplay_dollar();
8807 tpos = curwin->w_cursor;
8808 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
8810 #ifdef FEAT_WINDOWS
8811 win_T *new_curwin = curwin;
8813 if (curwin != old_curwin && win_valid(old_curwin))
8815 /* Mouse took us to another window. We need to go back to the
8816 * previous one to stop insert there properly. */
8817 curwin = old_curwin;
8818 curbuf = curwin->w_buffer;
8820 #endif
8821 start_arrow(curwin == old_curwin ? &tpos : NULL);
8822 #ifdef FEAT_WINDOWS
8823 if (curwin != new_curwin && win_valid(new_curwin))
8825 curwin = new_curwin;
8826 curbuf = curwin->w_buffer;
8828 #endif
8829 # ifdef FEAT_CINDENT
8830 can_cindent = TRUE;
8831 # endif
8834 #ifdef FEAT_WINDOWS
8835 /* redraw status lines (in case another window became active) */
8836 redraw_statuslines();
8837 #endif
8840 static void
8841 ins_mousescroll(up)
8842 int up;
8844 pos_T tpos;
8845 # if defined(FEAT_WINDOWS)
8846 win_T *old_curwin = curwin;
8847 # endif
8848 # ifdef FEAT_INS_EXPAND
8849 int did_scroll = FALSE;
8850 # endif
8852 tpos = curwin->w_cursor;
8854 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8855 /* Currently the mouse coordinates are only known in the GUI. */
8856 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
8858 int row, col;
8860 row = mouse_row;
8861 col = mouse_col;
8863 /* find the window at the pointer coordinates */
8864 curwin = mouse_find_win(&row, &col);
8865 curbuf = curwin->w_buffer;
8867 if (curwin == old_curwin)
8868 # endif
8869 undisplay_dollar();
8871 # ifdef FEAT_INS_EXPAND
8872 /* Don't scroll the window in which completion is being done. */
8873 if (!pum_visible()
8874 # if defined(FEAT_WINDOWS)
8875 || curwin != old_curwin
8876 # endif
8878 # endif
8880 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
8881 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
8882 else
8883 scroll_redraw(up, 3L);
8884 # ifdef FEAT_INS_EXPAND
8885 did_scroll = TRUE;
8886 # endif
8889 # if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
8890 curwin->w_redr_status = TRUE;
8892 curwin = old_curwin;
8893 curbuf = curwin->w_buffer;
8894 # endif
8896 # ifdef FEAT_INS_EXPAND
8897 /* The popup menu may overlay the window, need to redraw it.
8898 * TODO: Would be more efficient to only redraw the windows that are
8899 * overlapped by the popup menu. */
8900 if (pum_visible() && did_scroll)
8902 redraw_all_later(NOT_VALID);
8903 ins_compl_show_pum();
8905 # endif
8907 if (!equalpos(curwin->w_cursor, tpos))
8909 start_arrow(&tpos);
8910 # ifdef FEAT_CINDENT
8911 can_cindent = TRUE;
8912 # endif
8915 #endif
8917 #if defined(FEAT_GUI_TABLINE) || defined(PROTO)
8918 static void
8919 ins_tabline(c)
8920 int c;
8922 /* We will be leaving the current window, unless closing another tab. */
8923 if (c != K_TABMENU || current_tabmenu != TABLINE_MENU_CLOSE
8924 || (current_tab != 0 && current_tab != tabpage_index(curtab)))
8926 undisplay_dollar();
8927 start_arrow(&curwin->w_cursor);
8928 # ifdef FEAT_CINDENT
8929 can_cindent = TRUE;
8930 # endif
8933 if (c == K_TABLINE)
8934 goto_tabpage(current_tab);
8935 else
8937 handle_tabmenu();
8938 redraw_statuslines(); /* will redraw the tabline when needed */
8941 #endif
8943 #if defined(FEAT_GUI) || defined(PROTO)
8944 void
8945 ins_scroll()
8947 pos_T tpos;
8949 undisplay_dollar();
8950 tpos = curwin->w_cursor;
8951 if (gui_do_scroll())
8953 start_arrow(&tpos);
8954 # ifdef FEAT_CINDENT
8955 can_cindent = TRUE;
8956 # endif
8960 void
8961 ins_horscroll()
8963 pos_T tpos;
8965 undisplay_dollar();
8966 tpos = curwin->w_cursor;
8967 if (gui_do_horiz_scroll())
8969 start_arrow(&tpos);
8970 # ifdef FEAT_CINDENT
8971 can_cindent = TRUE;
8972 # endif
8975 #endif
8977 static void
8978 ins_left()
8980 pos_T tpos;
8982 #ifdef FEAT_FOLDING
8983 if ((fdo_flags & FDO_HOR) && KeyTyped)
8984 foldOpenCursor();
8985 #endif
8986 undisplay_dollar();
8987 tpos = curwin->w_cursor;
8988 if (oneleft() == OK)
8990 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
8991 /* Only call start_arrow() when not busy with preediting, it will
8992 * break undo. K_LEFT is inserted in im_correct_cursor(). */
8993 if (!im_is_preediting())
8994 #endif
8995 start_arrow(&tpos);
8996 #ifdef FEAT_RIGHTLEFT
8997 /* If exit reversed string, position is fixed */
8998 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
8999 revins_legal++;
9000 revins_chars++;
9001 #endif
9005 * if 'whichwrap' set for cursor in insert mode may go to
9006 * previous line
9008 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
9010 start_arrow(&tpos);
9011 --(curwin->w_cursor.lnum);
9012 coladvance((colnr_T)MAXCOL);
9013 curwin->w_set_curswant = TRUE; /* so we stay at the end */
9015 else
9016 vim_beep();
9019 static void
9020 ins_home(c)
9021 int c;
9023 pos_T tpos;
9025 #ifdef FEAT_FOLDING
9026 if ((fdo_flags & FDO_HOR) && KeyTyped)
9027 foldOpenCursor();
9028 #endif
9029 undisplay_dollar();
9030 tpos = curwin->w_cursor;
9031 if (c == K_C_HOME)
9032 curwin->w_cursor.lnum = 1;
9033 curwin->w_cursor.col = 0;
9034 #ifdef FEAT_VIRTUALEDIT
9035 curwin->w_cursor.coladd = 0;
9036 #endif
9037 curwin->w_curswant = 0;
9038 start_arrow(&tpos);
9041 static void
9042 ins_end(c)
9043 int c;
9045 pos_T tpos;
9047 #ifdef FEAT_FOLDING
9048 if ((fdo_flags & FDO_HOR) && KeyTyped)
9049 foldOpenCursor();
9050 #endif
9051 undisplay_dollar();
9052 tpos = curwin->w_cursor;
9053 if (c == K_C_END)
9054 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
9055 coladvance((colnr_T)MAXCOL);
9056 curwin->w_curswant = MAXCOL;
9058 start_arrow(&tpos);
9061 static void
9062 ins_s_left()
9064 #ifdef FEAT_FOLDING
9065 if ((fdo_flags & FDO_HOR) && KeyTyped)
9066 foldOpenCursor();
9067 #endif
9068 undisplay_dollar();
9069 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
9071 start_arrow(&curwin->w_cursor);
9072 (void)bck_word(1L, FALSE, FALSE);
9073 curwin->w_set_curswant = TRUE;
9075 else
9076 vim_beep();
9079 static void
9080 ins_right()
9082 #ifdef FEAT_FOLDING
9083 if ((fdo_flags & FDO_HOR) && KeyTyped)
9084 foldOpenCursor();
9085 #endif
9086 undisplay_dollar();
9087 if (gchar_cursor() != NUL
9088 #ifdef FEAT_VIRTUALEDIT
9089 || virtual_active()
9090 #endif
9093 start_arrow(&curwin->w_cursor);
9094 curwin->w_set_curswant = TRUE;
9095 #ifdef FEAT_VIRTUALEDIT
9096 if (virtual_active())
9097 oneright();
9098 else
9099 #endif
9101 #ifdef FEAT_MBYTE
9102 if (has_mbyte)
9103 curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
9104 else
9105 #endif
9106 ++curwin->w_cursor.col;
9109 #ifdef FEAT_RIGHTLEFT
9110 revins_legal++;
9111 if (revins_chars)
9112 revins_chars--;
9113 #endif
9115 /* if 'whichwrap' set for cursor in insert mode, may move the
9116 * cursor to the next line */
9117 else if (vim_strchr(p_ww, ']') != NULL
9118 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
9120 start_arrow(&curwin->w_cursor);
9121 curwin->w_set_curswant = TRUE;
9122 ++curwin->w_cursor.lnum;
9123 curwin->w_cursor.col = 0;
9125 else
9126 vim_beep();
9129 static void
9130 ins_s_right()
9132 #ifdef FEAT_FOLDING
9133 if ((fdo_flags & FDO_HOR) && KeyTyped)
9134 foldOpenCursor();
9135 #endif
9136 undisplay_dollar();
9137 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
9138 || gchar_cursor() != NUL)
9140 start_arrow(&curwin->w_cursor);
9141 (void)fwd_word(1L, FALSE, 0);
9142 curwin->w_set_curswant = TRUE;
9144 else
9145 vim_beep();
9148 static void
9149 ins_up(startcol)
9150 int startcol; /* when TRUE move to Insstart.col */
9152 pos_T tpos;
9153 linenr_T old_topline = curwin->w_topline;
9154 #ifdef FEAT_DIFF
9155 int old_topfill = curwin->w_topfill;
9156 #endif
9158 undisplay_dollar();
9159 tpos = curwin->w_cursor;
9160 if (cursor_up(1L, TRUE) == OK)
9162 if (startcol)
9163 coladvance(getvcol_nolist(&Insstart));
9164 if (old_topline != curwin->w_topline
9165 #ifdef FEAT_DIFF
9166 || old_topfill != curwin->w_topfill
9167 #endif
9169 redraw_later(VALID);
9170 start_arrow(&tpos);
9171 #ifdef FEAT_CINDENT
9172 can_cindent = TRUE;
9173 #endif
9175 else
9176 vim_beep();
9179 static void
9180 ins_pageup()
9182 pos_T tpos;
9184 undisplay_dollar();
9186 #ifdef FEAT_WINDOWS
9187 if (mod_mask & MOD_MASK_CTRL)
9189 /* <C-PageUp>: tab page back */
9190 if (first_tabpage->tp_next != NULL)
9192 start_arrow(&curwin->w_cursor);
9193 goto_tabpage(-1);
9195 return;
9197 #endif
9199 tpos = curwin->w_cursor;
9200 if (onepage(BACKWARD, 1L) == OK)
9202 start_arrow(&tpos);
9203 #ifdef FEAT_CINDENT
9204 can_cindent = TRUE;
9205 #endif
9207 else
9208 vim_beep();
9211 static void
9212 ins_down(startcol)
9213 int startcol; /* when TRUE move to Insstart.col */
9215 pos_T tpos;
9216 linenr_T old_topline = curwin->w_topline;
9217 #ifdef FEAT_DIFF
9218 int old_topfill = curwin->w_topfill;
9219 #endif
9221 undisplay_dollar();
9222 tpos = curwin->w_cursor;
9223 if (cursor_down(1L, TRUE) == OK)
9225 if (startcol)
9226 coladvance(getvcol_nolist(&Insstart));
9227 if (old_topline != curwin->w_topline
9228 #ifdef FEAT_DIFF
9229 || old_topfill != curwin->w_topfill
9230 #endif
9232 redraw_later(VALID);
9233 start_arrow(&tpos);
9234 #ifdef FEAT_CINDENT
9235 can_cindent = TRUE;
9236 #endif
9238 else
9239 vim_beep();
9242 static void
9243 ins_pagedown()
9245 pos_T tpos;
9247 undisplay_dollar();
9249 #ifdef FEAT_WINDOWS
9250 if (mod_mask & MOD_MASK_CTRL)
9252 /* <C-PageDown>: tab page forward */
9253 if (first_tabpage->tp_next != NULL)
9255 start_arrow(&curwin->w_cursor);
9256 goto_tabpage(0);
9258 return;
9260 #endif
9262 tpos = curwin->w_cursor;
9263 if (onepage(FORWARD, 1L) == OK)
9265 start_arrow(&tpos);
9266 #ifdef FEAT_CINDENT
9267 can_cindent = TRUE;
9268 #endif
9270 else
9271 vim_beep();
9274 #ifdef FEAT_DND
9275 static void
9276 ins_drop()
9278 do_put('~', BACKWARD, 1L, PUT_CURSEND);
9280 #endif
9283 * Handle TAB in Insert or Replace mode.
9284 * Return TRUE when the TAB needs to be inserted like a normal character.
9286 static int
9287 ins_tab()
9289 int ind;
9290 int i;
9291 int temp;
9293 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
9294 Insstart_blank_vcol = get_nolist_virtcol();
9295 if (echeck_abbr(TAB + ABBR_OFF))
9296 return FALSE;
9298 ind = inindent(0);
9299 #ifdef FEAT_CINDENT
9300 if (ind)
9301 can_cindent = FALSE;
9302 #endif
9305 * When nothing special, insert TAB like a normal character
9307 if (!curbuf->b_p_et
9308 #ifdef FEAT_VARTABS
9309 && !(p_sta && ind
9310 /* These five lines mean 'tabstop' != 'shiftwidth' */
9311 && ((tabstop_count(curbuf->b_p_vts_ary) > 1)
9312 || (tabstop_count(curbuf->b_p_vts_ary) == 1
9313 && tabstop_first(curbuf->b_p_vts_ary) != curbuf->b_p_sw)
9314 || (tabstop_count(curbuf->b_p_vts_ary) == 0
9315 && curbuf->b_p_ts != curbuf->b_p_sw)))
9316 && tabstop_count(curbuf->b_p_vsts_ary) == 0
9317 && curbuf->b_p_sts == 0
9318 #else
9319 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
9320 && curbuf->b_p_sts == 0
9321 #endif
9323 return TRUE;
9325 if (stop_arrow() == FAIL)
9326 return TRUE;
9328 did_ai = FALSE;
9329 #ifdef FEAT_SMARTINDENT
9330 did_si = FALSE;
9331 can_si = FALSE;
9332 can_si_back = FALSE;
9333 #endif
9334 AppendToRedobuff((char_u *)"\t");
9336 #ifdef FEAT_VARTABS
9337 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9339 temp = (int)curbuf->b_p_sw;
9340 temp -= get_nolist_virtcol() % temp;
9342 else if (tabstop_count(curbuf->b_p_vsts_ary) > 0 || curbuf->b_p_sts > 0)
9343 /* use 'softtabstop' when set */
9344 temp = tabstop_padding(get_nolist_virtcol(), curbuf->b_p_sts,
9345 curbuf->b_p_vsts_ary);
9346 else /* otherwise use 'tabstop' */
9347 temp = tabstop_padding(get_nolist_virtcol(), curbuf->b_p_ts,
9348 curbuf->b_p_vts_ary);
9349 #else
9350 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
9351 temp = (int)curbuf->b_p_sw;
9352 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
9353 temp = (int)curbuf->b_p_sts;
9354 else /* otherwise use 'tabstop' */
9355 temp = (int)curbuf->b_p_ts;
9356 temp -= get_nolist_virtcol() % temp;
9357 #endif
9360 * Insert the first space with ins_char(). It will delete one char in
9361 * replace mode. Insert the rest with ins_str(); it will not delete any
9362 * chars. For VREPLACE mode, we use ins_char() for all characters.
9364 ins_char(' ');
9365 while (--temp > 0)
9367 #ifdef FEAT_VREPLACE
9368 if (State & VREPLACE_FLAG)
9369 ins_char(' ');
9370 else
9371 #endif
9373 ins_str((char_u *)" ");
9374 if (State & REPLACE_FLAG) /* no char replaced */
9375 replace_push(NUL);
9380 * When 'expandtab' not set: Replace spaces by TABs where possible.
9382 #ifdef FEAT_VARTABS
9383 if (!curbuf->b_p_et && (tabstop_count(curbuf->b_p_vsts_ary) > 0
9384 || curbuf->b_p_sts > 0
9385 || (p_sta && ind)))
9386 #else
9387 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
9388 #endif
9390 char_u *ptr;
9391 #ifdef FEAT_VREPLACE
9392 char_u *saved_line = NULL; /* init for GCC */
9393 pos_T pos;
9394 #endif
9395 pos_T fpos;
9396 pos_T *cursor;
9397 colnr_T want_vcol, vcol;
9398 int change_col = -1;
9399 int save_list = curwin->w_p_list;
9402 * Get the current line. For VREPLACE mode, don't make real changes
9403 * yet, just work on a copy of the line.
9405 #ifdef FEAT_VREPLACE
9406 if (State & VREPLACE_FLAG)
9408 pos = curwin->w_cursor;
9409 cursor = &pos;
9410 saved_line = vim_strsave(ml_get_curline());
9411 if (saved_line == NULL)
9412 return FALSE;
9413 ptr = saved_line + pos.col;
9415 else
9416 #endif
9418 ptr = ml_get_cursor();
9419 cursor = &curwin->w_cursor;
9422 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
9423 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9424 curwin->w_p_list = FALSE;
9426 /* Find first white before the cursor */
9427 fpos = curwin->w_cursor;
9428 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
9430 --fpos.col;
9431 --ptr;
9434 /* In Replace mode, don't change characters before the insert point. */
9435 if ((State & REPLACE_FLAG)
9436 && fpos.lnum == Insstart.lnum
9437 && fpos.col < Insstart.col)
9439 ptr += Insstart.col - fpos.col;
9440 fpos.col = Insstart.col;
9443 /* compute virtual column numbers of first white and cursor */
9444 getvcol(curwin, &fpos, &vcol, NULL, NULL);
9445 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
9447 /* Use as many TABs as possible. Beware of 'breakindent', 'showbreak' and
9448 * 'linebreak' adding extra virtual columns. */
9449 while (vim_iswhite(*ptr))
9451 i = lbr_chartabsize((char_u *)"\t", vcol, cursor->lnum);
9452 if (vcol + i > want_vcol)
9453 break;
9454 if (*ptr != TAB)
9456 *ptr = TAB;
9457 if (change_col < 0)
9459 change_col = fpos.col; /* Column of first change */
9460 /* May have to adjust Insstart */
9461 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
9462 Insstart.col = fpos.col;
9465 ++fpos.col;
9466 ++ptr;
9467 vcol += i;
9470 if (change_col >= 0)
9472 int repl_off = 0;
9474 /* Skip over the spaces we need. */
9475 while (vcol < want_vcol && *ptr == ' ')
9477 vcol += lbr_chartabsize(ptr, vcol, cursor->lnum);
9478 ++ptr;
9479 ++repl_off;
9481 if (vcol > want_vcol)
9483 /* Must have a char with 'showbreak' just before it. */
9484 --ptr;
9485 --repl_off;
9487 fpos.col += repl_off;
9489 /* Delete following spaces. */
9490 i = cursor->col - fpos.col;
9491 if (i > 0)
9493 STRMOVE(ptr, ptr + i);
9494 /* correct replace stack. */
9495 if ((State & REPLACE_FLAG)
9496 #ifdef FEAT_VREPLACE
9497 && !(State & VREPLACE_FLAG)
9498 #endif
9500 for (temp = i; --temp >= 0; )
9501 replace_join(repl_off);
9503 #ifdef FEAT_NETBEANS_INTG
9504 if (usingNetbeans)
9506 netbeans_removed(curbuf, fpos.lnum, cursor->col,
9507 (long)(i + 1));
9508 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
9509 (char_u *)"\t", 1);
9511 #endif
9512 cursor->col -= i;
9514 #ifdef FEAT_VREPLACE
9516 * In VREPLACE mode, we haven't changed anything yet. Do it now by
9517 * backspacing over the changed spacing and then inserting the new
9518 * spacing.
9520 if (State & VREPLACE_FLAG)
9522 /* Backspace from real cursor to change_col */
9523 backspace_until_column(change_col);
9525 /* Insert each char in saved_line from changed_col to
9526 * ptr-cursor */
9527 ins_bytes_len(saved_line + change_col,
9528 cursor->col - change_col);
9530 #endif
9533 #ifdef FEAT_VREPLACE
9534 if (State & VREPLACE_FLAG)
9535 vim_free(saved_line);
9536 #endif
9537 curwin->w_p_list = save_list;
9540 return FALSE;
9544 * Handle CR or NL in insert mode.
9545 * Return TRUE when out of memory or can't undo.
9547 static int
9548 ins_eol(c)
9549 int c;
9551 int i;
9553 if (echeck_abbr(c + ABBR_OFF))
9554 return FALSE;
9555 if (stop_arrow() == FAIL)
9556 return TRUE;
9557 undisplay_dollar();
9560 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
9561 * character under the cursor. Only push a NUL on the replace stack,
9562 * nothing to put back when the NL is deleted.
9564 if ((State & REPLACE_FLAG)
9565 #ifdef FEAT_VREPLACE
9566 && !(State & VREPLACE_FLAG)
9567 #endif
9569 replace_push(NUL);
9572 * In VREPLACE mode, a NL replaces the rest of the line, and starts
9573 * replacing the next line, so we push all of the characters left on the
9574 * line onto the replace stack. This is not done here though, it is done
9575 * in open_line().
9578 #ifdef FEAT_VIRTUALEDIT
9579 /* Put cursor on NUL if on the last char and coladd is 1 (happens after
9580 * CTRL-O). */
9581 if (virtual_active() && curwin->w_cursor.coladd > 0)
9582 coladvance(getviscol());
9583 #endif
9585 #ifdef FEAT_RIGHTLEFT
9586 # ifdef FEAT_FKMAP
9587 if (p_altkeymap && p_fkmap)
9588 fkmap(NL);
9589 # endif
9590 /* NL in reverse insert will always start in the end of
9591 * current line. */
9592 if (revins_on)
9593 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
9594 #endif
9596 AppendToRedobuff(NL_STR);
9597 i = open_line(FORWARD,
9598 #ifdef FEAT_COMMENTS
9599 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
9600 #endif
9601 0, old_indent);
9602 old_indent = 0;
9603 #ifdef FEAT_CINDENT
9604 can_cindent = TRUE;
9605 #endif
9606 #ifdef FEAT_FOLDING
9607 /* When inserting a line the cursor line must never be in a closed fold. */
9608 foldOpenCursor();
9609 #endif
9611 return (!i);
9614 #ifdef FEAT_DIGRAPHS
9616 * Handle digraph in insert mode.
9617 * Returns character still to be inserted, or NUL when nothing remaining to be
9618 * done.
9620 static int
9621 ins_digraph()
9623 int c;
9624 int cc;
9626 pc_status = PC_STATUS_UNSET;
9627 if (redrawing() && !char_avail())
9629 /* may need to redraw when no more chars available now */
9630 ins_redraw(FALSE);
9632 edit_putchar('?', TRUE);
9633 #ifdef FEAT_CMDL_INFO
9634 add_to_showcmd_c(Ctrl_K);
9635 #endif
9638 #ifdef USE_ON_FLY_SCROLL
9639 dont_scroll = TRUE; /* disallow scrolling here */
9640 #endif
9642 /* don't map the digraph chars. This also prevents the
9643 * mode message to be deleted when ESC is hit */
9644 ++no_mapping;
9645 ++allow_keys;
9646 c = plain_vgetc();
9647 --no_mapping;
9648 --allow_keys;
9649 if (IS_SPECIAL(c) || mod_mask) /* special key */
9651 #ifdef FEAT_CMDL_INFO
9652 clear_showcmd();
9653 #endif
9654 insert_special(c, TRUE, FALSE);
9655 return NUL;
9657 if (c != ESC)
9659 if (redrawing() && !char_avail())
9661 /* may need to redraw when no more chars available now */
9662 ins_redraw(FALSE);
9664 if (char2cells(c) == 1)
9666 /* first remove the '?', otherwise it's restored when typing
9667 * an ESC next */
9668 edit_unputchar();
9669 ins_redraw(FALSE);
9670 edit_putchar(c, TRUE);
9672 #ifdef FEAT_CMDL_INFO
9673 add_to_showcmd_c(c);
9674 #endif
9676 ++no_mapping;
9677 ++allow_keys;
9678 cc = plain_vgetc();
9679 --no_mapping;
9680 --allow_keys;
9681 if (cc != ESC)
9683 AppendToRedobuff((char_u *)CTRL_V_STR);
9684 c = getdigraph(c, cc, TRUE);
9685 #ifdef FEAT_CMDL_INFO
9686 clear_showcmd();
9687 #endif
9688 return c;
9691 edit_unputchar();
9692 #ifdef FEAT_CMDL_INFO
9693 clear_showcmd();
9694 #endif
9695 return NUL;
9697 #endif
9700 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
9701 * Returns the char to be inserted, or NUL if none found.
9703 static int
9704 ins_copychar(lnum)
9705 linenr_T lnum;
9707 int c;
9708 int temp;
9709 char_u *ptr, *prev_ptr;
9711 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
9713 vim_beep();
9714 return NUL;
9717 /* try to advance to the cursor column */
9718 temp = 0;
9719 ptr = ml_get(lnum);
9720 prev_ptr = ptr;
9721 validate_virtcol();
9722 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
9724 prev_ptr = ptr;
9725 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp, lnum);
9727 if ((colnr_T)temp > curwin->w_virtcol)
9728 ptr = prev_ptr;
9730 #ifdef FEAT_MBYTE
9731 c = (*mb_ptr2char)(ptr);
9732 #else
9733 c = *ptr;
9734 #endif
9735 if (c == NUL)
9736 vim_beep();
9737 return c;
9741 * CTRL-Y or CTRL-E typed in Insert mode.
9743 static int
9744 ins_ctrl_ey(tc)
9745 int tc;
9747 int c = tc;
9749 #ifdef FEAT_INS_EXPAND
9750 if (ctrl_x_mode == CTRL_X_SCROLL)
9752 if (c == Ctrl_Y)
9753 scrolldown_clamp();
9754 else
9755 scrollup_clamp();
9756 redraw_later(VALID);
9758 else
9759 #endif
9761 c = ins_copychar(curwin->w_cursor.lnum + (c == Ctrl_Y ? -1 : 1));
9762 if (c != NUL)
9764 long tw_save;
9766 /* The character must be taken literally, insert like it
9767 * was typed after a CTRL-V, and pretend 'textwidth'
9768 * wasn't set. Digits, 'o' and 'x' are special after a
9769 * CTRL-V, don't use it for these. */
9770 if (c < 256 && !isalnum(c))
9771 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
9772 tw_save = curbuf->b_p_tw;
9773 curbuf->b_p_tw = -1;
9774 insert_special(c, TRUE, FALSE);
9775 curbuf->b_p_tw = tw_save;
9776 #ifdef FEAT_RIGHTLEFT
9777 revins_chars++;
9778 revins_legal++;
9779 #endif
9780 c = Ctrl_V; /* pretend CTRL-V is last character */
9781 auto_format(FALSE, TRUE);
9784 return c;
9787 #ifdef FEAT_SMARTINDENT
9789 * Try to do some very smart auto-indenting.
9790 * Used when inserting a "normal" character.
9792 static void
9793 ins_try_si(c)
9794 int c;
9796 pos_T *pos, old_pos;
9797 char_u *ptr;
9798 int i;
9799 int temp;
9802 * do some very smart indenting when entering '{' or '}'
9804 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
9807 * for '}' set indent equal to indent of line containing matching '{'
9809 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
9811 old_pos = curwin->w_cursor;
9813 * If the matching '{' has a ')' immediately before it (ignoring
9814 * white-space), then line up with the start of the line
9815 * containing the matching '(' if there is one. This handles the
9816 * case where an "if (..\n..) {" statement continues over multiple
9817 * lines -- webb
9819 ptr = ml_get(pos->lnum);
9820 i = pos->col;
9821 if (i > 0) /* skip blanks before '{' */
9822 while (--i > 0 && vim_iswhite(ptr[i]))
9824 curwin->w_cursor.lnum = pos->lnum;
9825 curwin->w_cursor.col = i;
9826 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
9827 curwin->w_cursor = *pos;
9828 i = get_indent();
9829 curwin->w_cursor = old_pos;
9830 #ifdef FEAT_VREPLACE
9831 if (State & VREPLACE_FLAG)
9832 change_indent(INDENT_SET, i, FALSE, NUL, TRUE);
9833 else
9834 #endif
9835 (void)set_indent(i, SIN_CHANGED);
9837 else if (curwin->w_cursor.col > 0)
9840 * when inserting '{' after "O" reduce indent, but not
9841 * more than indent of previous line
9843 temp = TRUE;
9844 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
9846 old_pos = curwin->w_cursor;
9847 i = get_indent();
9848 while (curwin->w_cursor.lnum > 1)
9850 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
9852 /* ignore empty lines and lines starting with '#'. */
9853 if (*ptr != '#' && *ptr != NUL)
9854 break;
9856 if (get_indent() >= i)
9857 temp = FALSE;
9858 curwin->w_cursor = old_pos;
9860 if (temp)
9861 shift_line(TRUE, FALSE, 1, TRUE);
9866 * set indent of '#' always to 0
9868 if (curwin->w_cursor.col > 0 && can_si && c == '#')
9870 /* remember current indent for next line */
9871 old_indent = get_indent();
9872 (void)set_indent(0, SIN_CHANGED);
9875 /* Adjust ai_col, the char at this position can be deleted. */
9876 if (ai_col > curwin->w_cursor.col)
9877 ai_col = curwin->w_cursor.col;
9879 #endif
9882 * Get the value that w_virtcol would have when 'list' is off.
9883 * Unless 'cpo' contains the 'L' flag.
9885 static colnr_T
9886 get_nolist_virtcol()
9888 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
9889 return getvcol_nolist(&curwin->w_cursor);
9890 validate_virtcol();
9891 return curwin->w_virtcol;