blob: c91170215dcc08c189ff1facecfb32016fff567d [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
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 */
9
10/*
11 * edit.c: functions for Insert mode
12 */
13
14#include "vim.h"
15
16#ifdef FEAT_INS_EXPAND
17/*
18 * definitions used for CTRL-X submode
19 */
20#define CTRL_X_WANT_IDENT 0x100
21
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
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +000033#define CTRL_X_FUNCTION 12
Bram Moolenaar071d4272004-06-13 20:20:40 +000034
35#define CHECK_KEYS_TIME 30
36
37#define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
38
39static char *ctrl_x_msgs[] =
40{
41 N_(" Keyword completion (^N^P)"), /* ctrl_x_mode == 0, ^P/^N compl. */
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +000042 N_(" ^X mode (^E^Y^L^]^F^I^K^D^U^V^N^P)"),
Bram Moolenaar071d4272004-06-13 20:20:40 +000043 /* Scroll has it's own msgs, in it's place there is the msg for local
44 * ctrl_x_mode = 0 (eg continue_status & CONT_LOCAL) -- Acevedo */
45 N_(" Keyword Local completion (^N^P)"),
46 N_(" Whole line completion (^L^N^P)"),
47 N_(" File name completion (^F^N^P)"),
48 N_(" Tag completion (^]^N^P)"),
49 N_(" Path pattern completion (^N^P)"),
50 N_(" Definition completion (^D^N^P)"),
51 NULL,
52 N_(" Dictionary completion (^K^N^P)"),
53 N_(" Thesaurus completion (^T^N^P)"),
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +000054 N_(" Command-line completion (^V^N^P)"),
55 N_(" User defined completion (^U^N^P)"),
Bram Moolenaar071d4272004-06-13 20:20:40 +000056};
57
58static char_u e_hitend[] = N_("Hit end of paragraph");
59
60/*
61 * Structure used to store one match for insert completion.
62 */
63struct Completion
64{
65 struct Completion *next;
66 struct Completion *prev;
67 char_u *str; /* matched text */
68 char_u *fname; /* file containing the match */
69 int original; /* ORIGINAL_TEXT, CONT_S_IPOS or FREE_FNAME */
70 int number; /* sequence number */
71};
72
73/* the original text when the expansion begun */
74#define ORIGINAL_TEXT (1)
75#define FREE_FNAME (2)
76
77/*
78 * All the current matches are stored in a list.
79 * "first_match" points to the start of the list.
80 * "curr_match" points to the currently selected entry.
81 * "shown_match" is different from curr_match during ins_compl_get_exp().
82 */
83static struct Completion *first_match = NULL;
84static struct Completion *curr_match = NULL;
85static struct Completion *shown_match = NULL;
86
87static int started_completion = FALSE;
88static int completion_matches = 0;
89static char_u *complete_pat = NULL;
90static int complete_direction = FORWARD;
91static int shown_direction = FORWARD;
92static int completion_pending = FALSE;
93static pos_T initial_pos;
94static colnr_T complete_col = 0; /* column where the text starts
95 that is being completed */
96static int save_sm;
97static char_u *original_text = NULL; /* text before completion */
98static int continue_mode = 0;
99static expand_T complete_xp;
100
101static int ins_compl_add __ARGS((char_u *str, int len, char_u *, int dir, int reuse));
102static void ins_compl_add_matches __ARGS((int num_matches, char_u **matches, int dir));
103static int ins_compl_make_cyclic __ARGS((void));
104static void ins_compl_dictionaries __ARGS((char_u *dict, char_u *pat, int dir, int flags, int thesaurus));
105static void ins_compl_free __ARGS((void));
106static void ins_compl_clear __ARGS((void));
107static void ins_compl_prep __ARGS((int c));
108static buf_T *ins_compl_next_buf __ARGS((buf_T *buf, int flag));
109static int ins_compl_get_exp __ARGS((pos_T *ini, int dir));
110static void ins_compl_delete __ARGS((void));
111static void ins_compl_insert __ARGS((void));
112static int ins_compl_next __ARGS((int allow_get_expansion));
113static int ins_complete __ARGS((int c));
114static int quote_meta __ARGS((char_u *dest, char_u *str, int len));
115#endif /* FEAT_INS_EXPAND */
116
117#define BACKSPACE_CHAR 1
118#define BACKSPACE_WORD 2
119#define BACKSPACE_WORD_NOT_SPACE 3
120#define BACKSPACE_LINE 4
121
122static void ins_redraw __ARGS((void));
123static void ins_ctrl_v __ARGS((void));
124static void undisplay_dollar __ARGS((void));
125static void insert_special __ARGS((int, int, int));
126static void check_auto_format __ARGS((int));
127static void redo_literal __ARGS((int c));
128static void start_arrow __ARGS((pos_T *end_insert_pos));
Bram Moolenaar217ad922005-03-20 22:37:15 +0000129#ifdef FEAT_SYN_HL
130static void check_spell_redraw __ARGS((void));
131#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000132static void stop_insert __ARGS((pos_T *end_insert_pos, int esc));
133static int echeck_abbr __ARGS((int));
134static void replace_push_off __ARGS((int c));
135static int replace_pop __ARGS((void));
136static void replace_join __ARGS((int off));
137static void replace_pop_ins __ARGS((void));
138#ifdef FEAT_MBYTE
139static void mb_replace_pop_ins __ARGS((int cc));
140#endif
141static void replace_flush __ARGS((void));
142static void replace_do_bs __ARGS((void));
143#ifdef FEAT_CINDENT
144static int cindent_on __ARGS((void));
145#endif
146static void ins_reg __ARGS((void));
147static void ins_ctrl_g __ARGS((void));
148static int ins_esc __ARGS((long *count, int cmdchar));
149#ifdef FEAT_RIGHTLEFT
150static void ins_ctrl_ __ARGS((void));
151#endif
152#ifdef FEAT_VISUAL
153static int ins_start_select __ARGS((int c));
154#endif
155static void ins_shift __ARGS((int c, int lastc));
156static void ins_del __ARGS((void));
157static int ins_bs __ARGS((int c, int mode, int *inserted_space_p));
158#ifdef FEAT_MOUSE
159static void ins_mouse __ARGS((int c));
160static void ins_mousescroll __ARGS((int up));
161#endif
162static void ins_left __ARGS((void));
163static void ins_home __ARGS((int c));
164static void ins_end __ARGS((int c));
165static void ins_s_left __ARGS((void));
166static void ins_right __ARGS((void));
167static void ins_s_right __ARGS((void));
168static void ins_up __ARGS((int startcol));
169static void ins_pageup __ARGS((void));
170static void ins_down __ARGS((int startcol));
171static void ins_pagedown __ARGS((void));
172#ifdef FEAT_DND
173static void ins_drop __ARGS((void));
174#endif
175static int ins_tab __ARGS((void));
176static int ins_eol __ARGS((int c));
177#ifdef FEAT_DIGRAPHS
178static int ins_digraph __ARGS((void));
179#endif
180static int ins_copychar __ARGS((linenr_T lnum));
181#ifdef FEAT_SMARTINDENT
182static void ins_try_si __ARGS((int c));
183#endif
184static colnr_T get_nolist_virtcol __ARGS((void));
185
186static colnr_T Insstart_textlen; /* length of line when insert started */
187static colnr_T Insstart_blank_vcol; /* vcol for first inserted blank */
188
189static char_u *last_insert = NULL; /* the text of the previous insert,
190 K_SPECIAL and CSI are escaped */
191static int last_insert_skip; /* nr of chars in front of previous insert */
192static int new_insert_skip; /* nr of chars in front of current insert */
193
194#ifdef FEAT_CINDENT
195static int can_cindent; /* may do cindenting on this line */
196#endif
197
198static int old_indent = 0; /* for ^^D command in insert mode */
199
200#ifdef FEAT_RIGHTLEFT
Bram Moolenaar6c0b44b2005-06-01 21:56:33 +0000201static int revins_on; /* reverse insert mode on */
202static int revins_chars; /* how much to skip after edit */
203static int revins_legal; /* was the last char 'legal'? */
204static int revins_scol; /* start column of revins session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#endif
206
207#if defined(FEAT_MBYTE) && defined(MACOS_CLASSIC)
208static short previous_script = smRoman;
209#endif
210
211static int ins_need_undo; /* call u_save() before inserting a
212 char. Set when edit() is called.
213 after that arrow_used is used. */
214
215static int did_add_space = FALSE; /* auto_format() added an extra space
216 under the cursor */
217
218/*
219 * edit(): Start inserting text.
220 *
221 * "cmdchar" can be:
222 * 'i' normal insert command
223 * 'a' normal append command
224 * 'R' replace command
225 * 'r' "r<CR>" command: insert one <CR>. Note: count can be > 1, for redo,
226 * but still only one <CR> is inserted. The <Esc> is not used for redo.
227 * 'g' "gI" command.
228 * 'V' "gR" command for Virtual Replace mode.
229 * 'v' "gr" command for single character Virtual Replace mode.
230 *
231 * This function is not called recursively. For CTRL-O commands, it returns
232 * and lets the caller handle the Normal-mode command.
233 *
234 * Return TRUE if a CTRL-O command caused the return (insert mode pending).
235 */
236 int
237edit(cmdchar, startln, count)
238 int cmdchar;
239 int startln; /* if set, insert at start of line */
240 long count;
241{
242 int c = 0;
243 char_u *ptr;
244 int lastc;
245 colnr_T mincol;
246 static linenr_T o_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 int i;
248 int did_backspace = TRUE; /* previous char was backspace */
249#ifdef FEAT_CINDENT
250 int line_is_white = FALSE; /* line is empty before insert */
251#endif
252 linenr_T old_topline = 0; /* topline before insertion */
253#ifdef FEAT_DIFF
254 int old_topfill = -1;
255#endif
256 int inserted_space = FALSE; /* just inserted a space */
257 int replaceState = REPLACE;
258 int did_restart_edit = restart_edit;
259
260 /* sleep before redrawing, needed for "CTRL-O :" that results in an
261 * error message */
262 check_for_delay(TRUE);
263
264#ifdef HAVE_SANDBOX
265 /* Don't allow inserting in the sandbox. */
266 if (sandbox != 0)
267 {
268 EMSG(_(e_sandbox));
269 return FALSE;
270 }
271#endif
272
273#ifdef FEAT_INS_EXPAND
274 ins_compl_clear(); /* clear stuff for CTRL-X mode */
275#endif
276
Bram Moolenaar843ee412004-06-30 16:16:41 +0000277#ifdef FEAT_AUTOCMD
278 /*
279 * Trigger InsertEnter autocommands. Do not do this for "r<CR>" or "grx".
280 */
281 if (cmdchar != 'r' && cmdchar != 'v')
282 {
283 if (cmdchar == 'R')
284 ptr = (char_u *)"r";
285 else if (cmdchar == 'V')
286 ptr = (char_u *)"v";
287 else
288 ptr = (char_u *)"i";
289 set_vim_var_string(VV_INSERTMODE, ptr, 1);
290 apply_autocmds(EVENT_INSERTENTER, NULL, NULL, FALSE, curbuf);
291 }
292#endif
293
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294#ifdef FEAT_MOUSE
295 /*
296 * When doing a paste with the middle mouse button, Insstart is set to
297 * where the paste started.
298 */
299 if (where_paste_started.lnum != 0)
300 Insstart = where_paste_started;
301 else
302#endif
303 {
304 Insstart = curwin->w_cursor;
305 if (startln)
306 Insstart.col = 0;
307 }
308 Insstart_textlen = linetabsize(ml_get_curline());
309 Insstart_blank_vcol = MAXCOL;
310 if (!did_ai)
311 ai_col = 0;
312
313 if (cmdchar != NUL && restart_edit == 0)
314 {
315 ResetRedobuff();
316 AppendNumberToRedobuff(count);
317#ifdef FEAT_VREPLACE
318 if (cmdchar == 'V' || cmdchar == 'v')
319 {
320 /* "gR" or "gr" command */
321 AppendCharToRedobuff('g');
322 AppendCharToRedobuff((cmdchar == 'v') ? 'r' : 'R');
323 }
324 else
325#endif
326 {
327 AppendCharToRedobuff(cmdchar);
328 if (cmdchar == 'g') /* "gI" command */
329 AppendCharToRedobuff('I');
330 else if (cmdchar == 'r') /* "r<CR>" command */
331 count = 1; /* insert only one <CR> */
332 }
333 }
334
335 if (cmdchar == 'R')
336 {
337#ifdef FEAT_FKMAP
338 if (p_fkmap && p_ri)
339 {
340 beep_flush();
341 EMSG(farsi_text_3); /* encoded in Farsi */
342 State = INSERT;
343 }
344 else
345#endif
346 State = REPLACE;
347 }
348#ifdef FEAT_VREPLACE
349 else if (cmdchar == 'V' || cmdchar == 'v')
350 {
351 State = VREPLACE;
352 replaceState = VREPLACE;
353 orig_line_count = curbuf->b_ml.ml_line_count;
354 vr_lines_changed = 1;
355 }
356#endif
357 else
358 State = INSERT;
359
360 stop_insert_mode = FALSE;
361
362 /*
363 * Need to recompute the cursor position, it might move when the cursor is
364 * on a TAB or special character.
365 */
366 curs_columns(TRUE);
367
368 /*
369 * Enable langmap or IME, indicated by 'iminsert'.
370 * Note that IME may enabled/disabled without us noticing here, thus the
371 * 'iminsert' value may not reflect what is actually used. It is updated
372 * when hitting <Esc>.
373 */
374 if (curbuf->b_p_iminsert == B_IMODE_LMAP)
375 State |= LANGMAP;
376#ifdef USE_IM_CONTROL
377 im_set_active(curbuf->b_p_iminsert == B_IMODE_IM);
378#endif
379
380#if defined(FEAT_MBYTE) && defined(MACOS_CLASSIC)
381 KeyScript(previous_script);
382#endif
383
384#ifdef FEAT_MOUSE
385 setmouse();
386#endif
387#ifdef FEAT_CMDL_INFO
388 clear_showcmd();
389#endif
390#ifdef FEAT_RIGHTLEFT
391 /* there is no reverse replace mode */
392 revins_on = (State == INSERT && p_ri);
393 if (revins_on)
394 undisplay_dollar();
395 revins_chars = 0;
396 revins_legal = 0;
397 revins_scol = -1;
398#endif
399
400 /*
401 * Handle restarting Insert mode.
402 * Don't do this for "CTRL-O ." (repeat an insert): we get here with
403 * restart_edit non-zero, and something in the stuff buffer.
404 */
405 if (restart_edit != 0 && stuff_empty())
406 {
407#ifdef FEAT_MOUSE
408 /*
409 * After a paste we consider text typed to be part of the insert for
410 * the pasted text. You can backspace over the pasted text too.
411 */
412 if (where_paste_started.lnum)
413 arrow_used = FALSE;
414 else
415#endif
416 arrow_used = TRUE;
417 restart_edit = 0;
418
419 /*
420 * If the cursor was after the end-of-line before the CTRL-O and it is
421 * now at the end-of-line, put it after the end-of-line (this is not
422 * correct in very rare cases).
423 * Also do this if curswant is greater than the current virtual
424 * column. Eg after "^O$" or "^O80|".
425 */
426 validate_virtcol();
427 update_curswant();
Bram Moolenaar68b76a62005-03-25 21:53:48 +0000428 if (((ins_at_eol && curwin->w_cursor.lnum == o_lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 || curwin->w_curswant > curwin->w_virtcol)
430 && *(ptr = ml_get_curline() + curwin->w_cursor.col) != NUL)
431 {
432 if (ptr[1] == NUL)
433 ++curwin->w_cursor.col;
434#ifdef FEAT_MBYTE
435 else if (has_mbyte)
436 {
437 i = (*mb_ptr2len_check)(ptr);
438 if (ptr[i] == NUL)
439 curwin->w_cursor.col += i;
440 }
441#endif
442 }
Bram Moolenaar68b76a62005-03-25 21:53:48 +0000443 ins_at_eol = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444 }
445 else
446 arrow_used = FALSE;
447
448 /* we are in insert mode now, don't need to start it anymore */
449 need_start_insertmode = FALSE;
450
451 /* Need to save the line for undo before inserting the first char. */
452 ins_need_undo = TRUE;
453
454#ifdef FEAT_MOUSE
455 where_paste_started.lnum = 0;
456#endif
457#ifdef FEAT_CINDENT
458 can_cindent = TRUE;
459#endif
460#ifdef FEAT_FOLDING
461 /* The cursor line is not in a closed fold, unless 'insertmode' is set or
462 * restarting. */
463 if (!p_im && did_restart_edit == 0)
464 foldOpenCursor();
465#endif
466
467 /*
468 * If 'showmode' is set, show the current (insert/replace/..) mode.
469 * A warning message for changing a readonly file is given here, before
470 * actually changing anything. It's put after the mode, if any.
471 */
472 i = 0;
473 if (p_smd)
474 i = showmode();
475
476 if (!p_im && did_restart_edit == 0)
477 change_warning(i + 1);
478
479#ifdef CURSOR_SHAPE
480 ui_cursor_shape(); /* may show different cursor shape */
481#endif
482#ifdef FEAT_DIGRAPHS
483 do_digraph(-1); /* clear digraphs */
484#endif
485
486/*
487 * Get the current length of the redo buffer, those characters have to be
488 * skipped if we want to get to the inserted characters.
489 */
490 ptr = get_inserted();
491 if (ptr == NULL)
492 new_insert_skip = 0;
493 else
494 {
495 new_insert_skip = (int)STRLEN(ptr);
496 vim_free(ptr);
497 }
498
499 old_indent = 0;
500
501 /*
502 * Main loop in Insert mode: repeat until Insert mode is left.
503 */
504 for (;;)
505 {
506#ifdef FEAT_RIGHTLEFT
507 if (!revins_legal)
508 revins_scol = -1; /* reset on illegal motions */
509 else
510 revins_legal = 0;
511#endif
512 if (arrow_used) /* don't repeat insert when arrow key used */
513 count = 0;
514
515 if (stop_insert_mode)
516 {
517 /* ":stopinsert" used or 'insertmode' reset */
518 count = 0;
519 goto doESCkey;
520 }
521
522 /* set curwin->w_curswant for next K_DOWN or K_UP */
523 if (!arrow_used)
524 curwin->w_set_curswant = TRUE;
525
526 /* If there is no typeahead may check for timestamps (e.g., for when a
527 * menu invoked a shell command). */
528 if (stuff_empty())
529 {
530 did_check_timestamps = FALSE;
531 if (need_check_timestamps)
532 check_timestamps(FALSE);
533 }
534
535 /*
536 * When emsg() was called msg_scroll will have been set.
537 */
538 msg_scroll = FALSE;
539
540#ifdef FEAT_GUI
541 /* When 'mousefocus' is set a mouse movement may have taken us to
542 * another window. "need_mouse_correct" may then be set because of an
543 * autocommand. */
544 if (need_mouse_correct)
545 gui_mouse_correct();
546#endif
547
548#ifdef FEAT_FOLDING
549 /* Open fold at the cursor line, according to 'foldopen'. */
550 if (fdo_flags & FDO_INSERT)
551 foldOpenCursor();
552 /* Close folds where the cursor isn't, according to 'foldclose' */
553 if (!char_avail())
554 foldCheckClose();
555#endif
556
557 /*
558 * If we inserted a character at the last position of the last line in
559 * the window, scroll the window one line up. This avoids an extra
560 * redraw.
561 * This is detected when the cursor column is smaller after inserting
562 * something.
563 * Don't do this when the topline changed already, it has
564 * already been adjusted (by insertchar() calling open_line())).
565 */
566 if (curbuf->b_mod_set
567 && curwin->w_p_wrap
568 && !did_backspace
569 && curwin->w_topline == old_topline
570#ifdef FEAT_DIFF
571 && curwin->w_topfill == old_topfill
572#endif
573 )
574 {
575 mincol = curwin->w_wcol;
576 validate_cursor_col();
577
578 if ((int)curwin->w_wcol < (int)mincol - curbuf->b_p_ts
579 && curwin->w_wrow == W_WINROW(curwin)
580 + curwin->w_height - 1 - p_so
581 && (curwin->w_cursor.lnum != curwin->w_topline
582#ifdef FEAT_DIFF
583 || curwin->w_topfill > 0
584#endif
585 ))
586 {
587#ifdef FEAT_DIFF
588 if (curwin->w_topfill > 0)
589 --curwin->w_topfill;
590 else
591#endif
592#ifdef FEAT_FOLDING
593 if (hasFolding(curwin->w_topline, NULL, &old_topline))
594 set_topline(curwin, old_topline + 1);
595 else
596#endif
597 set_topline(curwin, curwin->w_topline + 1);
598 }
599 }
600
601 /* May need to adjust w_topline to show the cursor. */
602 update_topline();
603
604 did_backspace = FALSE;
605
606 validate_cursor(); /* may set must_redraw */
607
608 /*
609 * Redraw the display when no characters are waiting.
610 * Also shows mode, ruler and positions cursor.
611 */
612 ins_redraw();
613
614#ifdef FEAT_SCROLLBIND
615 if (curwin->w_p_scb)
616 do_check_scrollbind(TRUE);
617#endif
618
619 update_curswant();
620 old_topline = curwin->w_topline;
621#ifdef FEAT_DIFF
622 old_topfill = curwin->w_topfill;
623#endif
624
625#ifdef USE_ON_FLY_SCROLL
626 dont_scroll = FALSE; /* allow scrolling here */
627#endif
628
629 /*
630 * Get a character for Insert mode.
631 */
632 lastc = c; /* remember previous char for CTRL-D */
633 c = safe_vgetc();
634
635#ifdef FEAT_RIGHTLEFT
636 if (p_hkmap && KeyTyped)
637 c = hkmap(c); /* Hebrew mode mapping */
638#endif
639#ifdef FEAT_FKMAP
640 if (p_fkmap && KeyTyped)
641 c = fkmap(c); /* Farsi mode mapping */
642#endif
643
644#ifdef FEAT_INS_EXPAND
645 /* Prepare for or stop CTRL-X mode. This doesn't do completion, but
646 * it does fix up the text when finishing completion. */
647 ins_compl_prep(c);
648#endif
649
650 /* CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to mode
651 * selected with 'insertmode'. */
652 if (c == Ctrl_BSL)
653 {
654 /* may need to redraw when no more chars available now */
655 ins_redraw();
656 ++no_mapping;
657 ++allow_keys;
658 c = safe_vgetc();
659 --no_mapping;
660 --allow_keys;
661 if (c != Ctrl_N && c != Ctrl_G) /* it's something else */
662 {
663 vungetc(c);
664 c = Ctrl_BSL;
665 }
666 else if (c == Ctrl_G && p_im)
667 continue;
668 else
669 {
670 count = 0;
671 goto doESCkey;
672 }
673 }
674
675#ifdef FEAT_DIGRAPHS
676 c = do_digraph(c);
677#endif
678
679#ifdef FEAT_INS_EXPAND
680 if ((c == Ctrl_V || c == Ctrl_Q) && ctrl_x_mode == CTRL_X_CMDLINE)
681 goto docomplete;
682#endif
683 if (c == Ctrl_V || c == Ctrl_Q)
684 {
685 ins_ctrl_v();
686 c = Ctrl_V; /* pretend CTRL-V is last typed character */
687 continue;
688 }
689
690#ifdef FEAT_CINDENT
691 if (cindent_on()
692# ifdef FEAT_INS_EXPAND
693 && ctrl_x_mode == 0
694# endif
695 )
696 {
697 /* A key name preceded by a bang means this key is not to be
698 * inserted. Skip ahead to the re-indenting below.
699 * A key name preceded by a star means that indenting has to be
700 * done before inserting the key. */
701 line_is_white = inindent(0);
702 if (in_cinkeys(c, '!', line_is_white))
703 goto force_cindent;
704 if (can_cindent && in_cinkeys(c, '*', line_is_white)
705 && stop_arrow() == OK)
706 do_c_expr_indent();
707 }
708#endif
709
710#ifdef FEAT_RIGHTLEFT
711 if (curwin->w_p_rl)
712 switch (c)
713 {
714 case K_LEFT: c = K_RIGHT; break;
715 case K_S_LEFT: c = K_S_RIGHT; break;
716 case K_C_LEFT: c = K_C_RIGHT; break;
717 case K_RIGHT: c = K_LEFT; break;
718 case K_S_RIGHT: c = K_S_LEFT; break;
719 case K_C_RIGHT: c = K_C_LEFT; break;
720 }
721#endif
722
723#ifdef FEAT_VISUAL
724 /*
725 * If 'keymodel' contains "startsel", may start selection. If it
726 * does, a CTRL-O and c will be stuffed, we need to get these
727 * characters.
728 */
729 if (ins_start_select(c))
730 continue;
731#endif
732
733 /*
734 * The big switch to handle a character in insert mode.
735 */
736 switch (c)
737 {
738 /* toggle insert/replace mode */
739 case K_INS:
740 case K_KINS:
741#ifdef FEAT_FKMAP
742 if (p_fkmap && p_ri)
743 {
744 beep_flush();
745 EMSG(farsi_text_3); /* encoded in Farsi */
746 break;
747 }
748#endif
Bram Moolenaar843ee412004-06-30 16:16:41 +0000749#ifdef FEAT_AUTOCMD
750 set_vim_var_string(VV_INSERTMODE,
751 (char_u *)((State & REPLACE_FLAG) ? "i" :
752 replaceState == VREPLACE ? "v" : "r"), 1);
753 apply_autocmds(EVENT_INSERTCHANGE, NULL, NULL, FALSE, curbuf);
754#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 if (State & REPLACE_FLAG)
756 State = INSERT | (State & LANGMAP);
757 else
758 State = replaceState | (State & LANGMAP);
759 AppendCharToRedobuff(K_INS);
760 showmode();
761#ifdef CURSOR_SHAPE
762 ui_cursor_shape(); /* may show different cursor shape */
763#endif
764 break;
765
766#ifdef FEAT_INS_EXPAND
767 /* Enter CTRL-X mode */
768 case Ctrl_X:
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +0000769 /* CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770 * CTRL-V works like CTRL-N */
771 if (ctrl_x_mode != CTRL_X_CMDLINE)
772 {
773 /* if the next ^X<> won't ADD nothing, then reset
774 * continue_status */
775 if (continue_status & CONT_N_ADDS)
776 continue_status = (continue_status | CONT_INTRPT);
777 else
778 continue_status = 0;
779 /* We're not sure which CTRL-X mode it will be yet */
780 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
781 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
782 edit_submode_pre = NULL;
783 showmode();
784 }
785 break;
786#endif
787
788 /* end of Select mode mapping - ignore */
789 case K_SELECT:
790 break;
791
792 /* suspend when 'insertmode' set */
793 case Ctrl_Z:
794 if (!p_im)
795 goto normalchar; /* insert CTRL-Z as normal char */
796 stuffReadbuff((char_u *)":st\r");
797 c = Ctrl_O;
798 /*FALLTHROUGH*/
799
800 /* execute one command */
801 case Ctrl_O:
802 if (echeck_abbr(Ctrl_O + ABBR_OFF))
803 break;
804 count = 0;
805#ifdef FEAT_VREPLACE
806 if (State & VREPLACE_FLAG)
807 restart_edit = 'V';
808 else
809#endif
810 if (State & REPLACE_FLAG)
811 restart_edit = 'R';
812 else
813 restart_edit = 'I';
814#ifdef FEAT_VIRTUALEDIT
815 if (virtual_active())
Bram Moolenaar68b76a62005-03-25 21:53:48 +0000816 ins_at_eol = FALSE; /* cursor always keeps its column */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817 else
818#endif
Bram Moolenaar68b76a62005-03-25 21:53:48 +0000819 ins_at_eol = (gchar_cursor() == NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 goto doESCkey;
821
822#ifdef FEAT_SNIFF
823 case K_SNIFF:
824 stuffcharReadbuff(K_SNIFF);
825 goto doESCkey;
826#endif
827
828 /* Hitting the help key in insert mode is like <ESC> <Help> */
829 case K_HELP:
830 case K_F1:
831 case K_XF1:
832 stuffcharReadbuff(K_HELP);
833 if (p_im)
834 need_start_insertmode = TRUE;
835 goto doESCkey;
836
837#ifdef FEAT_NETBEANS_INTG
838 case K_F21:
839 ++no_mapping; /* don't map the next key hits */
840 i = safe_vgetc();
841 --no_mapping;
842 netbeans_keycommand(i);
843 break;
844#endif
845
846 /* an escape ends input mode */
847 case ESC:
848 if (echeck_abbr(ESC + ABBR_OFF))
849 break;
850 /*FALLTHROUGH*/
851
852 case Ctrl_C:
853#ifdef FEAT_CMDWIN
854 if (c == Ctrl_C && cmdwin_type != 0)
855 {
856 /* Close the cmdline window. */
857 cmdwin_result = K_IGNORE;
858 got_int = FALSE; /* don't stop executing autocommands et al. */
859 goto doESCkey;
860 }
861#endif
862
863#ifdef UNIX
864do_intr:
865#endif
866 /* when 'insertmode' set, and not halfway a mapping, don't leave
867 * Insert mode */
868 if (goto_im())
869 {
870 if (got_int)
871 {
872 (void)vgetc(); /* flush all buffers */
873 got_int = FALSE;
874 }
875 else
876 vim_beep();
877 break;
878 }
879doESCkey:
880 /*
881 * This is the ONLY return from edit()!
882 */
Bram Moolenaar217ad922005-03-20 22:37:15 +0000883#ifdef FEAT_SYN_HL
884 check_spell_redraw();
885#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886 /* Always update o_lnum, so that a "CTRL-O ." that adds a line
887 * still puts the cursor back after the inserted text. */
Bram Moolenaar68b76a62005-03-25 21:53:48 +0000888 if (ins_at_eol && gchar_cursor() == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889 o_lnum = curwin->w_cursor.lnum;
890
891 if (ins_esc(&count, cmdchar))
Bram Moolenaar843ee412004-06-30 16:16:41 +0000892 {
893#ifdef FEAT_AUTOCMD
894 if (cmdchar != 'r' && cmdchar != 'v')
895 apply_autocmds(EVENT_INSERTLEAVE, NULL, NULL,
896 FALSE, curbuf);
897#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 return (c == Ctrl_O);
Bram Moolenaar843ee412004-06-30 16:16:41 +0000899 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900 continue;
901
902 /*
903 * Insert the previously inserted text.
904 * For ^@ the trailing ESC will end the insert, unless there is an
905 * error.
906 */
907 case K_ZERO:
908 case NUL:
909 case Ctrl_A:
910 if (stuff_inserted(NUL, 1L, (c == Ctrl_A)) == FAIL
911 && c != Ctrl_A && !p_im)
912 goto doESCkey; /* quit insert mode */
913 inserted_space = FALSE;
914 break;
915
916 /* insert the contents of a register */
917 case Ctrl_R:
918 ins_reg();
919 auto_format(FALSE, TRUE);
920 inserted_space = FALSE;
921 break;
922
923 case Ctrl_G:
924 ins_ctrl_g();
925 break;
926
927 case Ctrl_HAT:
928 if (map_to_exists_mode((char_u *)"", LANGMAP))
929 {
930 /* ":lmap" mappings exists, Toggle use of ":lmap" mappings. */
931 if (State & LANGMAP)
932 {
933 curbuf->b_p_iminsert = B_IMODE_NONE;
934 State &= ~LANGMAP;
935 }
936 else
937 {
938 curbuf->b_p_iminsert = B_IMODE_LMAP;
939 State |= LANGMAP;
940#ifdef USE_IM_CONTROL
941 im_set_active(FALSE);
942#endif
943 }
944 }
945#ifdef USE_IM_CONTROL
946 else
947 {
948 /* There are no ":lmap" mappings, toggle IM */
949 if (im_get_status())
950 {
951 curbuf->b_p_iminsert = B_IMODE_NONE;
952 im_set_active(FALSE);
953 }
954 else
955 {
956 curbuf->b_p_iminsert = B_IMODE_IM;
957 State &= ~LANGMAP;
958 im_set_active(TRUE);
959 }
960 }
961#endif
962 set_iminsert_global();
963 showmode();
964#ifdef FEAT_GUI
965 /* may show different cursor shape or color */
966 if (gui.in_use)
967 gui_update_cursor(TRUE, FALSE);
968#endif
969#if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
970 /* Show/unshow value of 'keymap' in status lines. */
971 status_redraw_curbuf();
972#endif
973 break;
974
975#ifdef FEAT_RIGHTLEFT
976 case Ctrl__:
977 if (!p_ari)
978 goto normalchar;
979 ins_ctrl_();
980 break;
981#endif
982
983 /* Make indent one shiftwidth smaller. */
984 case Ctrl_D:
985#if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
986 if (ctrl_x_mode == CTRL_X_PATH_DEFINES)
987 goto docomplete;
988#endif
989 /* FALLTHROUGH */
990
991 /* Make indent one shiftwidth greater. */
992 case Ctrl_T:
993# ifdef FEAT_INS_EXPAND
994 if (c == Ctrl_T && ctrl_x_mode == CTRL_X_THESAURUS)
995 {
996 if (*curbuf->b_p_tsr == NUL && *p_tsr == NUL)
997 {
998 ctrl_x_mode = 0;
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +0000999 edit_submode = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 msg_attr((char_u *)_("'thesaurus' option is empty"),
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00001001 hl_attr(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001002 if (emsg_silent == 0)
1003 {
1004 vim_beep();
1005 setcursor();
1006 out_flush();
1007 ui_delay(2000L, FALSE);
1008 }
1009 break;
1010 }
1011 goto docomplete;
1012 }
1013# endif
1014 ins_shift(c, lastc);
1015 auto_format(FALSE, TRUE);
1016 inserted_space = FALSE;
1017 break;
1018
1019 /* delete character under the cursor */
1020 case K_DEL:
1021 case K_KDEL:
1022 ins_del();
1023 auto_format(FALSE, TRUE);
1024 break;
1025
1026 /* delete character before the cursor */
1027 case K_BS:
1028 case Ctrl_H:
1029 did_backspace = ins_bs(c, BACKSPACE_CHAR, &inserted_space);
1030 auto_format(FALSE, TRUE);
1031 break;
1032
1033 /* delete word before the cursor */
1034 case Ctrl_W:
1035 did_backspace = ins_bs(c, BACKSPACE_WORD, &inserted_space);
1036 auto_format(FALSE, TRUE);
1037 break;
1038
1039 /* delete all inserted text in current line */
1040 case Ctrl_U:
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00001041# ifdef FEAT_COMPL_FUNC
1042 /* CTRL-X CTRL-U completes with 'completefunc'. */
1043 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
1044 || ctrl_x_mode == CTRL_X_FUNCTION)
1045 goto docomplete;
1046# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 did_backspace = ins_bs(c, BACKSPACE_LINE, &inserted_space);
1048 auto_format(FALSE, TRUE);
1049 inserted_space = FALSE;
1050 break;
1051
1052#ifdef FEAT_MOUSE
1053 case K_LEFTMOUSE:
1054 case K_LEFTMOUSE_NM:
1055 case K_LEFTDRAG:
1056 case K_LEFTRELEASE:
1057 case K_LEFTRELEASE_NM:
1058 case K_MIDDLEMOUSE:
1059 case K_MIDDLEDRAG:
1060 case K_MIDDLERELEASE:
1061 case K_RIGHTMOUSE:
1062 case K_RIGHTDRAG:
1063 case K_RIGHTRELEASE:
1064 case K_X1MOUSE:
1065 case K_X1DRAG:
1066 case K_X1RELEASE:
1067 case K_X2MOUSE:
1068 case K_X2DRAG:
1069 case K_X2RELEASE:
1070 ins_mouse(c);
1071 break;
1072
1073 /* Default action for scroll wheel up: scroll up */
1074 case K_MOUSEDOWN:
1075 ins_mousescroll(FALSE);
1076 break;
1077
1078 /* Default action for scroll wheel down: scroll down */
1079 case K_MOUSEUP:
1080 ins_mousescroll(TRUE);
1081 break;
1082#endif
1083
1084 case K_IGNORE:
1085 break;
1086
1087#ifdef FEAT_GUI
1088 case K_VER_SCROLLBAR:
1089 ins_scroll();
1090 break;
1091
1092 case K_HOR_SCROLLBAR:
1093 ins_horscroll();
1094 break;
1095#endif
1096
1097 case K_HOME:
1098 case K_KHOME:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 case K_S_HOME:
1100 case K_C_HOME:
1101 ins_home(c);
1102 break;
1103
1104 case K_END:
1105 case K_KEND:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 case K_S_END:
1107 case K_C_END:
1108 ins_end(c);
1109 break;
1110
1111 case K_LEFT:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001112 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1113 ins_s_left();
1114 else
1115 ins_left();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 break;
1117
1118 case K_S_LEFT:
1119 case K_C_LEFT:
1120 ins_s_left();
1121 break;
1122
1123 case K_RIGHT:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001124 if (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL))
1125 ins_s_right();
1126 else
1127 ins_right();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128 break;
1129
1130 case K_S_RIGHT:
1131 case K_C_RIGHT:
1132 ins_s_right();
1133 break;
1134
1135 case K_UP:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001136 if (mod_mask & MOD_MASK_SHIFT)
1137 ins_pageup();
1138 else
1139 ins_up(FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 break;
1141
1142 case K_S_UP:
1143 case K_PAGEUP:
1144 case K_KPAGEUP:
1145 ins_pageup();
1146 break;
1147
1148 case K_DOWN:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001149 if (mod_mask & MOD_MASK_SHIFT)
1150 ins_pagedown();
1151 else
1152 ins_down(FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153 break;
1154
1155 case K_S_DOWN:
1156 case K_PAGEDOWN:
1157 case K_KPAGEDOWN:
1158 ins_pagedown();
1159 break;
1160
1161#ifdef FEAT_DND
1162 case K_DROP:
1163 ins_drop();
1164 break;
1165#endif
1166
1167 /* When <S-Tab> isn't mapped, use it like a normal TAB */
1168 case K_S_TAB:
1169 c = TAB;
1170 /* FALLTHROUGH */
1171
1172 /* TAB or Complete patterns along path */
1173 case TAB:
1174#if defined(FEAT_INS_EXPAND) && defined(FEAT_FIND_ID)
1175 if (ctrl_x_mode == CTRL_X_PATH_PATTERNS)
1176 goto docomplete;
1177#endif
1178 inserted_space = FALSE;
1179 if (ins_tab())
1180 goto normalchar; /* insert TAB as a normal char */
1181 auto_format(FALSE, TRUE);
1182 break;
1183
1184 case K_KENTER:
1185 c = CAR;
1186 /* FALLTHROUGH */
1187 case CAR:
1188 case NL:
1189#if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
1190 /* In a quickfix window a <CR> jumps to the error under the
1191 * cursor. */
1192 if (bt_quickfix(curbuf) && c == CAR)
1193 {
1194 do_cmdline_cmd((char_u *)".cc");
1195 break;
1196 }
1197#endif
1198#ifdef FEAT_CMDWIN
1199 if (cmdwin_type != 0)
1200 {
1201 /* Execute the command in the cmdline window. */
1202 cmdwin_result = CAR;
1203 goto doESCkey;
1204 }
1205#endif
1206 if (ins_eol(c) && !p_im)
1207 goto doESCkey; /* out of memory */
1208 auto_format(FALSE, FALSE);
1209 inserted_space = FALSE;
1210 break;
1211
1212#if defined(FEAT_DIGRAPHS) || defined (FEAT_INS_EXPAND)
1213 case Ctrl_K:
1214# ifdef FEAT_INS_EXPAND
1215 if (ctrl_x_mode == CTRL_X_DICTIONARY)
1216 {
1217 if (*curbuf->b_p_dict == NUL && *p_dict == NUL)
1218 {
1219 ctrl_x_mode = 0;
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00001220 edit_submode = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221 msg_attr((char_u *)_("'dictionary' option is empty"),
Bram Moolenaar13fcaaf2005-04-15 21:13:42 +00001222 hl_attr(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223 if (emsg_silent == 0)
1224 {
1225 vim_beep();
1226 setcursor();
1227 out_flush();
1228 ui_delay(2000L, FALSE);
1229 }
1230 break;
1231 }
1232 goto docomplete;
1233 }
1234# endif
1235# ifdef FEAT_DIGRAPHS
1236 c = ins_digraph();
1237 if (c == NUL)
1238 break;
1239# endif
1240 goto normalchar;
1241#endif /* FEAT_DIGRAPHS || FEAT_INS_EXPAND */
1242
1243#ifdef FEAT_INS_EXPAND
1244 case Ctrl_RSB: /* Tag name completion after ^X */
1245 if (ctrl_x_mode != CTRL_X_TAGS)
1246 goto normalchar;
1247 goto docomplete;
1248
1249 case Ctrl_F: /* File name completion after ^X */
1250 if (ctrl_x_mode != CTRL_X_FILES)
1251 goto normalchar;
1252 goto docomplete;
1253#endif
1254
1255 case Ctrl_L: /* Whole line completion after ^X */
1256#ifdef FEAT_INS_EXPAND
1257 if (ctrl_x_mode != CTRL_X_WHOLE_LINE)
1258#endif
1259 {
1260 /* CTRL-L with 'insertmode' set: Leave Insert mode */
1261 if (p_im)
1262 {
1263 if (echeck_abbr(Ctrl_L + ABBR_OFF))
1264 break;
1265 goto doESCkey;
1266 }
1267 goto normalchar;
1268 }
1269#ifdef FEAT_INS_EXPAND
1270 /* FALLTHROUGH */
1271
1272 /* Do previous/next pattern completion */
1273 case Ctrl_P:
1274 case Ctrl_N:
1275 /* if 'complete' is empty then plain ^P is no longer special,
1276 * but it is under other ^X modes */
1277 if (*curbuf->b_p_cpt == NUL
1278 && ctrl_x_mode != 0
1279 && !(continue_status & CONT_LOCAL))
1280 goto normalchar;
1281
1282docomplete:
1283 if (ins_complete(c) == FAIL)
1284 continue_status = 0;
1285 break;
1286#endif /* FEAT_INS_EXPAND */
1287
1288 case Ctrl_Y: /* copy from previous line or scroll down */
1289 case Ctrl_E: /* copy from next line or scroll up */
1290#ifdef FEAT_INS_EXPAND
1291 if (ctrl_x_mode == CTRL_X_SCROLL)
1292 {
1293 if (c == Ctrl_Y)
1294 scrolldown_clamp();
1295 else
1296 scrollup_clamp();
1297 redraw_later(VALID);
1298 }
1299 else
1300#endif
1301 {
1302 c = ins_copychar(curwin->w_cursor.lnum
1303 + (c == Ctrl_Y ? -1 : 1));
1304 if (c != NUL)
1305 {
1306 long tw_save;
1307
1308 /* The character must be taken literally, insert like it
1309 * was typed after a CTRL-V, and pretend 'textwidth'
1310 * wasn't set. Digits, 'o' and 'x' are special after a
1311 * CTRL-V, don't use it for these. */
1312 if (c < 256 && !isalnum(c))
1313 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1314 tw_save = curbuf->b_p_tw;
1315 curbuf->b_p_tw = -1;
1316 insert_special(c, TRUE, FALSE);
1317 curbuf->b_p_tw = tw_save;
1318#ifdef FEAT_RIGHTLEFT
1319 revins_chars++;
1320 revins_legal++;
1321#endif
1322 c = Ctrl_V; /* pretend CTRL-V is last character */
1323 auto_format(FALSE, TRUE);
1324 }
1325 }
1326 break;
1327
1328 default:
1329#ifdef UNIX
1330 if (c == intr_char) /* special interrupt char */
1331 goto do_intr;
1332#endif
1333
1334 /*
1335 * Insert a nomal character.
1336 */
1337normalchar:
1338#ifdef FEAT_SMARTINDENT
1339 /* Try to perform smart-indenting. */
1340 ins_try_si(c);
1341#endif
1342
1343 if (c == ' ')
1344 {
1345 inserted_space = TRUE;
1346#ifdef FEAT_CINDENT
1347 if (inindent(0))
1348 can_cindent = FALSE;
1349#endif
1350 if (Insstart_blank_vcol == MAXCOL
1351 && curwin->w_cursor.lnum == Insstart.lnum)
1352 Insstart_blank_vcol = get_nolist_virtcol();
1353 }
1354
1355 if (vim_iswordc(c) || !echeck_abbr(
1356#ifdef FEAT_MBYTE
1357 /* Add ABBR_OFF for characters above 0x100, this is
1358 * what check_abbr() expects. */
1359 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1360#endif
1361 c))
1362 {
1363 insert_special(c, FALSE, FALSE);
1364#ifdef FEAT_RIGHTLEFT
1365 revins_legal++;
1366 revins_chars++;
1367#endif
1368 }
1369
1370 auto_format(FALSE, TRUE);
1371
1372#ifdef FEAT_FOLDING
1373 /* When inserting a character the cursor line must never be in a
1374 * closed fold. */
1375 foldOpenCursor();
1376#endif
1377 break;
1378 } /* end of switch (c) */
1379
1380 /* If the cursor was moved we didn't just insert a space */
1381 if (arrow_used)
1382 inserted_space = FALSE;
1383
1384#ifdef FEAT_CINDENT
1385 if (can_cindent && cindent_on()
1386# ifdef FEAT_INS_EXPAND
1387 && ctrl_x_mode == 0
1388# endif
1389 )
1390 {
1391force_cindent:
1392 /*
1393 * Indent now if a key was typed that is in 'cinkeys'.
1394 */
1395 if (in_cinkeys(c, ' ', line_is_white))
1396 {
1397 if (stop_arrow() == OK)
1398 /* re-indent the current line */
1399 do_c_expr_indent();
1400 }
1401 }
1402#endif /* FEAT_CINDENT */
1403
1404 } /* for (;;) */
1405 /* NOTREACHED */
1406}
1407
1408/*
1409 * Redraw for Insert mode.
1410 * This is postponed until getting the next character to make '$' in the 'cpo'
1411 * option work correctly.
1412 * Only redraw when there are no characters available. This speeds up
1413 * inserting sequences of characters (e.g., for CTRL-R).
1414 */
1415 static void
1416ins_redraw()
1417{
1418 if (!char_avail())
1419 {
1420 if (must_redraw)
1421 update_screen(0);
1422 else if (clear_cmdline || redraw_cmdline)
1423 showmode(); /* clear cmdline and show mode */
1424 showruler(FALSE);
1425 setcursor();
1426 emsg_on_display = FALSE; /* may remove error message now */
1427 }
1428}
1429
1430/*
1431 * Handle a CTRL-V or CTRL-Q typed in Insert mode.
1432 */
1433 static void
1434ins_ctrl_v()
1435{
1436 int c;
1437
1438 /* may need to redraw when no more chars available now */
1439 ins_redraw();
1440
1441 if (redrawing() && !char_avail())
1442 edit_putchar('^', TRUE);
1443 AppendToRedobuff((char_u *)CTRL_V_STR); /* CTRL-V */
1444
1445#ifdef FEAT_CMDL_INFO
1446 add_to_showcmd_c(Ctrl_V);
1447#endif
1448
1449 c = get_literal();
1450#ifdef FEAT_CMDL_INFO
1451 clear_showcmd();
1452#endif
1453 insert_special(c, FALSE, TRUE);
1454#ifdef FEAT_RIGHTLEFT
1455 revins_chars++;
1456 revins_legal++;
1457#endif
1458}
1459
1460/*
1461 * Put a character directly onto the screen. It's not stored in a buffer.
1462 * Used while handling CTRL-K, CTRL-V, etc. in Insert mode.
1463 */
1464static int pc_status;
1465#define PC_STATUS_UNSET 0 /* pc_bytes was not set */
1466#define PC_STATUS_RIGHT 1 /* right halve of double-wide char */
1467#define PC_STATUS_LEFT 2 /* left halve of double-wide char */
1468#define PC_STATUS_SET 3 /* pc_bytes was filled */
1469#ifdef FEAT_MBYTE
1470static char_u pc_bytes[MB_MAXBYTES + 1]; /* saved bytes */
1471#else
1472static char_u pc_bytes[2]; /* saved bytes */
1473#endif
1474static int pc_attr;
1475static int pc_row;
1476static int pc_col;
1477
1478 void
1479edit_putchar(c, highlight)
1480 int c;
1481 int highlight;
1482{
1483 int attr;
1484
1485 if (ScreenLines != NULL)
1486 {
1487 update_topline(); /* just in case w_topline isn't valid */
1488 validate_cursor();
1489 if (highlight)
1490 attr = hl_attr(HLF_8);
1491 else
1492 attr = 0;
1493 pc_row = W_WINROW(curwin) + curwin->w_wrow;
1494 pc_col = W_WINCOL(curwin);
1495#if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1496 pc_status = PC_STATUS_UNSET;
1497#endif
1498#ifdef FEAT_RIGHTLEFT
1499 if (curwin->w_p_rl)
1500 {
1501 pc_col += W_WIDTH(curwin) - 1 - curwin->w_wcol;
1502# ifdef FEAT_MBYTE
1503 if (has_mbyte)
1504 {
1505 int fix_col = mb_fix_col(pc_col, pc_row);
1506
1507 if (fix_col != pc_col)
1508 {
1509 screen_putchar(' ', pc_row, fix_col, attr);
1510 --curwin->w_wcol;
1511 pc_status = PC_STATUS_RIGHT;
1512 }
1513 }
1514# endif
1515 }
1516 else
1517#endif
1518 {
1519 pc_col += curwin->w_wcol;
1520#ifdef FEAT_MBYTE
1521 if (mb_lefthalve(pc_row, pc_col))
1522 pc_status = PC_STATUS_LEFT;
1523#endif
1524 }
1525
1526 /* save the character to be able to put it back */
1527#if defined(FEAT_RIGHTLEFT) || defined(FEAT_MBYTE)
1528 if (pc_status == PC_STATUS_UNSET)
1529#endif
1530 {
1531 screen_getbytes(pc_row, pc_col, pc_bytes, &pc_attr);
1532 pc_status = PC_STATUS_SET;
1533 }
1534 screen_putchar(c, pc_row, pc_col, attr);
1535 }
1536}
1537
1538/*
1539 * Undo the previous edit_putchar().
1540 */
1541 void
1542edit_unputchar()
1543{
1544 if (pc_status != PC_STATUS_UNSET && pc_row >= msg_scrolled)
1545 {
1546#if defined(FEAT_MBYTE)
1547 if (pc_status == PC_STATUS_RIGHT)
1548 ++curwin->w_wcol;
1549 if (pc_status == PC_STATUS_RIGHT || pc_status == PC_STATUS_LEFT)
1550 redrawWinline(curwin->w_cursor.lnum, FALSE);
1551 else
1552#endif
1553 screen_puts(pc_bytes, pc_row - msg_scrolled, pc_col, pc_attr);
1554 }
1555}
1556
1557/*
1558 * Called when p_dollar is set: display a '$' at the end of the changed text
1559 * Only works when cursor is in the line that changes.
1560 */
1561 void
1562display_dollar(col)
1563 colnr_T col;
1564{
1565 colnr_T save_col;
1566
1567 if (!redrawing())
1568 return;
1569
1570 cursor_off();
1571 save_col = curwin->w_cursor.col;
1572 curwin->w_cursor.col = col;
1573#ifdef FEAT_MBYTE
1574 if (has_mbyte)
1575 {
1576 char_u *p;
1577
1578 /* If on the last byte of a multi-byte move to the first byte. */
1579 p = ml_get_curline();
1580 curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
1581 }
1582#endif
1583 curs_columns(FALSE); /* recompute w_wrow and w_wcol */
1584 if (curwin->w_wcol < W_WIDTH(curwin))
1585 {
1586 edit_putchar('$', FALSE);
1587 dollar_vcol = curwin->w_virtcol;
1588 }
1589 curwin->w_cursor.col = save_col;
1590}
1591
1592/*
1593 * Call this function before moving the cursor from the normal insert position
1594 * in insert mode.
1595 */
1596 static void
1597undisplay_dollar()
1598{
1599 if (dollar_vcol)
1600 {
1601 dollar_vcol = 0;
1602 redrawWinline(curwin->w_cursor.lnum, FALSE);
1603 }
1604}
1605
1606/*
1607 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1608 * Keep the cursor on the same character.
1609 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1610 * type == INDENT_DEC decrease indent (for CTRL-D)
1611 * type == INDENT_SET set indent to "amount"
1612 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1613 */
1614 void
1615change_indent(type, amount, round, replaced)
1616 int type;
1617 int amount;
1618 int round;
1619 int replaced; /* replaced character, put on replace stack */
1620{
1621 int vcol;
1622 int last_vcol;
1623 int insstart_less; /* reduction for Insstart.col */
1624 int new_cursor_col;
1625 int i;
1626 char_u *ptr;
1627 int save_p_list;
1628 int start_col;
1629 colnr_T vc;
1630#ifdef FEAT_VREPLACE
1631 colnr_T orig_col = 0; /* init for GCC */
1632 char_u *new_line, *orig_line = NULL; /* init for GCC */
1633
1634 /* VREPLACE mode needs to know what the line was like before changing */
1635 if (State & VREPLACE_FLAG)
1636 {
1637 orig_line = vim_strsave(ml_get_curline()); /* Deal with NULL below */
1638 orig_col = curwin->w_cursor.col;
1639 }
1640#endif
1641
1642 /* for the following tricks we don't want list mode */
1643 save_p_list = curwin->w_p_list;
1644 curwin->w_p_list = FALSE;
1645 vc = getvcol_nolist(&curwin->w_cursor);
1646 vcol = vc;
1647
1648 /*
1649 * For Replace mode we need to fix the replace stack later, which is only
1650 * possible when the cursor is in the indent. Remember the number of
1651 * characters before the cursor if it's possible.
1652 */
1653 start_col = curwin->w_cursor.col;
1654
1655 /* determine offset from first non-blank */
1656 new_cursor_col = curwin->w_cursor.col;
1657 beginline(BL_WHITE);
1658 new_cursor_col -= curwin->w_cursor.col;
1659
1660 insstart_less = curwin->w_cursor.col;
1661
1662 /*
1663 * If the cursor is in the indent, compute how many screen columns the
1664 * cursor is to the left of the first non-blank.
1665 */
1666 if (new_cursor_col < 0)
1667 vcol = get_indent() - vcol;
1668
1669 if (new_cursor_col > 0) /* can't fix replace stack */
1670 start_col = -1;
1671
1672 /*
1673 * Set the new indent. The cursor will be put on the first non-blank.
1674 */
1675 if (type == INDENT_SET)
1676 (void)set_indent(amount, SIN_CHANGED);
1677 else
1678 {
1679#ifdef FEAT_VREPLACE
1680 int save_State = State;
1681
1682 /* Avoid being called recursively. */
1683 if (State & VREPLACE_FLAG)
1684 State = INSERT;
1685#endif
1686 shift_line(type == INDENT_DEC, round, 1);
1687#ifdef FEAT_VREPLACE
1688 State = save_State;
1689#endif
1690 }
1691 insstart_less -= curwin->w_cursor.col;
1692
1693 /*
1694 * Try to put cursor on same character.
1695 * If the cursor is at or after the first non-blank in the line,
1696 * compute the cursor column relative to the column of the first
1697 * non-blank character.
1698 * If we are not in insert mode, leave the cursor on the first non-blank.
1699 * If the cursor is before the first non-blank, position it relative
1700 * to the first non-blank, counted in screen columns.
1701 */
1702 if (new_cursor_col >= 0)
1703 {
1704 /*
1705 * When changing the indent while the cursor is touching it, reset
1706 * Insstart_col to 0.
1707 */
1708 if (new_cursor_col == 0)
1709 insstart_less = MAXCOL;
1710 new_cursor_col += curwin->w_cursor.col;
1711 }
1712 else if (!(State & INSERT))
1713 new_cursor_col = curwin->w_cursor.col;
1714 else
1715 {
1716 /*
1717 * Compute the screen column where the cursor should be.
1718 */
1719 vcol = get_indent() - vcol;
1720 curwin->w_virtcol = (vcol < 0) ? 0 : vcol;
1721
1722 /*
1723 * Advance the cursor until we reach the right screen column.
1724 */
1725 vcol = last_vcol = 0;
1726 new_cursor_col = -1;
1727 ptr = ml_get_curline();
1728 while (vcol <= (int)curwin->w_virtcol)
1729 {
1730 last_vcol = vcol;
1731#ifdef FEAT_MBYTE
1732 if (has_mbyte && new_cursor_col >= 0)
1733 new_cursor_col += (*mb_ptr2len_check)(ptr + new_cursor_col);
1734 else
1735#endif
1736 ++new_cursor_col;
1737 vcol += lbr_chartabsize(ptr + new_cursor_col, (colnr_T)vcol);
1738 }
1739 vcol = last_vcol;
1740
1741 /*
1742 * May need to insert spaces to be able to position the cursor on
1743 * the right screen column.
1744 */
1745 if (vcol != (int)curwin->w_virtcol)
1746 {
1747 curwin->w_cursor.col = new_cursor_col;
1748 i = (int)curwin->w_virtcol - vcol;
1749 ptr = alloc(i + 1);
1750 if (ptr != NULL)
1751 {
1752 new_cursor_col += i;
1753 ptr[i] = NUL;
1754 while (--i >= 0)
1755 ptr[i] = ' ';
1756 ins_str(ptr);
1757 vim_free(ptr);
1758 }
1759 }
1760
1761 /*
1762 * When changing the indent while the cursor is in it, reset
1763 * Insstart_col to 0.
1764 */
1765 insstart_less = MAXCOL;
1766 }
1767
1768 curwin->w_p_list = save_p_list;
1769
1770 if (new_cursor_col <= 0)
1771 curwin->w_cursor.col = 0;
1772 else
1773 curwin->w_cursor.col = new_cursor_col;
1774 curwin->w_set_curswant = TRUE;
1775 changed_cline_bef_curs();
1776
1777 /*
1778 * May have to adjust the start of the insert.
1779 */
1780 if (State & INSERT)
1781 {
1782 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1783 {
1784 if ((int)Insstart.col <= insstart_less)
1785 Insstart.col = 0;
1786 else
1787 Insstart.col -= insstart_less;
1788 }
1789 if ((int)ai_col <= insstart_less)
1790 ai_col = 0;
1791 else
1792 ai_col -= insstart_less;
1793 }
1794
1795 /*
1796 * For REPLACE mode, may have to fix the replace stack, if it's possible.
1797 * If the number of characters before the cursor decreased, need to pop a
1798 * few characters from the replace stack.
1799 * If the number of characters before the cursor increased, need to push a
1800 * few NULs onto the replace stack.
1801 */
1802 if (REPLACE_NORMAL(State) && start_col >= 0)
1803 {
1804 while (start_col > (int)curwin->w_cursor.col)
1805 {
1806 replace_join(0); /* remove a NUL from the replace stack */
1807 --start_col;
1808 }
1809 while (start_col < (int)curwin->w_cursor.col || replaced)
1810 {
1811 replace_push(NUL);
1812 if (replaced)
1813 {
1814 replace_push(replaced);
1815 replaced = NUL;
1816 }
1817 ++start_col;
1818 }
1819 }
1820
1821#ifdef FEAT_VREPLACE
1822 /*
1823 * For VREPLACE mode, we also have to fix the replace stack. In this case
1824 * it is always possible because we backspace over the whole line and then
1825 * put it back again the way we wanted it.
1826 */
1827 if (State & VREPLACE_FLAG)
1828 {
1829 /* If orig_line didn't allocate, just return. At least we did the job,
1830 * even if you can't backspace. */
1831 if (orig_line == NULL)
1832 return;
1833
1834 /* Save new line */
1835 new_line = vim_strsave(ml_get_curline());
1836 if (new_line == NULL)
1837 return;
1838
1839 /* We only put back the new line up to the cursor */
1840 new_line[curwin->w_cursor.col] = NUL;
1841
1842 /* Put back original line */
1843 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1844 curwin->w_cursor.col = orig_col;
1845
1846 /* Backspace from cursor to start of line */
1847 backspace_until_column(0);
1848
1849 /* Insert new stuff into line again */
1850 ins_bytes(new_line);
1851
1852 vim_free(new_line);
1853 }
1854#endif
1855}
1856
1857/*
1858 * Truncate the space at the end of a line. This is to be used only in an
1859 * insert mode. It handles fixing the replace stack for REPLACE and VREPLACE
1860 * modes.
1861 */
1862 void
1863truncate_spaces(line)
1864 char_u *line;
1865{
1866 int i;
1867
1868 /* find start of trailing white space */
1869 for (i = (int)STRLEN(line) - 1; i >= 0 && vim_iswhite(line[i]); i--)
1870 {
1871 if (State & REPLACE_FLAG)
1872 replace_join(0); /* remove a NUL from the replace stack */
1873 }
1874 line[i + 1] = NUL;
1875}
1876
1877#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1878 || defined(FEAT_COMMENTS) || defined(PROTO)
1879/*
1880 * Backspace the cursor until the given column. Handles REPLACE and VREPLACE
1881 * modes correctly. May also be used when not in insert mode at all.
1882 */
1883 void
1884backspace_until_column(col)
1885 int col;
1886{
1887 while ((int)curwin->w_cursor.col > col)
1888 {
1889 curwin->w_cursor.col--;
1890 if (State & REPLACE_FLAG)
1891 replace_do_bs();
1892 else
1893 (void)del_char(FALSE);
1894 }
1895}
1896#endif
1897
1898#if defined(FEAT_INS_EXPAND) || defined(PROTO)
1899/*
1900 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
1901 * This depends on the current mode.
1902 */
1903 int
1904vim_is_ctrl_x_key(c)
1905 int c;
1906{
1907 /* Always allow ^R - let it's results then be checked */
1908 if (c == Ctrl_R)
1909 return TRUE;
1910
1911 switch (ctrl_x_mode)
1912 {
1913 case 0: /* Not in any CTRL-X mode */
1914 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
1915 case CTRL_X_NOT_DEFINED_YET:
1916 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
1917 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
1918 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
1919 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
1920 || c == Ctrl_Q);
1921 case CTRL_X_SCROLL:
1922 return (c == Ctrl_Y || c == Ctrl_E);
1923 case CTRL_X_WHOLE_LINE:
1924 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
1925 case CTRL_X_FILES:
1926 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
1927 case CTRL_X_DICTIONARY:
1928 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
1929 case CTRL_X_THESAURUS:
1930 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
1931 case CTRL_X_TAGS:
1932 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
1933#ifdef FEAT_FIND_ID
1934 case CTRL_X_PATH_PATTERNS:
1935 return (c == Ctrl_P || c == Ctrl_N);
1936 case CTRL_X_PATH_DEFINES:
1937 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
1938#endif
1939 case CTRL_X_CMDLINE:
1940 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
1941 || c == Ctrl_X);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00001942#ifdef FEAT_COMPL_FUNC
1943 case CTRL_X_FUNCTION:
1944 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N || c == Ctrl_X);
1945#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 }
1947 EMSG(_(e_internal));
1948 return FALSE;
1949}
1950
1951/*
1952 * This is like ins_compl_add(), but if ic and inf are set, then the
1953 * case of the originally typed text is used, and the case of the completed
1954 * text is infered, ie this tries to work out what case you probably wanted
1955 * the rest of the word to be in -- webb
1956 */
1957 int
1958ins_compl_add_infercase(str, len, fname, dir, reuse)
1959 char_u *str;
1960 int len;
1961 char_u *fname;
1962 int dir;
1963 int reuse;
1964{
1965 int has_lower = FALSE;
1966 int was_letter = FALSE;
1967 int idx;
1968
1969 if (p_ic && curbuf->b_p_inf && len < IOSIZE)
1970 {
1971 /* Infer case of completed part -- webb */
1972 /* Use IObuff, str would change text in buffer! */
1973 STRNCPY(IObuff, str, len);
1974 IObuff[len] = NUL;
1975
1976 /* Rule 1: Were any chars converted to lower? */
1977 for (idx = 0; idx < completion_length; ++idx)
1978 {
1979 if (islower(original_text[idx]))
1980 {
1981 has_lower = TRUE;
1982 if (isupper(IObuff[idx]))
1983 {
1984 /* Rule 1 is satisfied */
1985 for (idx = completion_length; idx < len; ++idx)
1986 IObuff[idx] = TOLOWER_LOC(IObuff[idx]);
1987 break;
1988 }
1989 }
1990 }
1991
1992 /*
1993 * Rule 2: No lower case, 2nd consecutive letter converted to
1994 * upper case.
1995 */
1996 if (!has_lower)
1997 {
1998 for (idx = 0; idx < completion_length; ++idx)
1999 {
2000 if (was_letter && isupper(original_text[idx])
2001 && islower(IObuff[idx]))
2002 {
2003 /* Rule 2 is satisfied */
2004 for (idx = completion_length; idx < len; ++idx)
2005 IObuff[idx] = TOUPPER_LOC(IObuff[idx]);
2006 break;
2007 }
2008 was_letter = isalpha(original_text[idx]);
2009 }
2010 }
2011
2012 /* Copy the original case of the part we typed */
2013 STRNCPY(IObuff, original_text, completion_length);
2014
2015 return ins_compl_add(IObuff, len, fname, dir, reuse);
2016 }
2017 return ins_compl_add(str, len, fname, dir, reuse);
2018}
2019
2020/*
2021 * Add a match to the list of matches.
2022 * If the given string is already in the list of completions, then return
2023 * FAIL, otherwise add it to the list and return OK. If there is an error,
2024 * maybe because alloc returns NULL, then RET_ERROR is returned -- webb.
2025 */
2026 static int
2027ins_compl_add(str, len, fname, dir, reuse)
2028 char_u *str;
2029 int len;
2030 char_u *fname;
2031 int dir;
2032 int reuse;
2033{
2034 struct Completion *match;
2035
2036 ui_breakcheck();
2037 if (got_int)
2038 return RET_ERROR;
2039 if (len < 0)
2040 len = (int)STRLEN(str);
2041
2042 /*
2043 * If the same match is already present, don't add it.
2044 */
2045 if (first_match != NULL)
2046 {
2047 match = first_match;
2048 do
2049 {
2050 if ( !(match->original & ORIGINAL_TEXT)
2051 && STRNCMP(match->str, str, (size_t)len) == 0
2052 && match->str[len] == NUL)
2053 return FAIL;
2054 match = match->next;
2055 } while (match != NULL && match != first_match);
2056 }
2057
2058 /*
2059 * Allocate a new match structure.
2060 * Copy the values to the new match structure.
2061 */
2062 match = (struct Completion *)alloc((unsigned)sizeof(struct Completion));
2063 if (match == NULL)
2064 return RET_ERROR;
2065 match->number = -1;
2066 if (reuse & ORIGINAL_TEXT)
2067 {
2068 match->number = 0;
2069 match->str = original_text;
2070 }
2071 else if ((match->str = vim_strnsave(str, len)) == NULL)
2072 {
2073 vim_free(match);
2074 return RET_ERROR;
2075 }
2076 /* match-fname is:
2077 * - curr_match->fname if it is a string equal to fname.
2078 * - a copy of fname, FREE_FNAME is set to free later THE allocated mem.
2079 * - NULL otherwise. --Acevedo */
2080 if (fname && curr_match && curr_match->fname
2081 && STRCMP(fname, curr_match->fname) == 0)
2082 match->fname = curr_match->fname;
2083 else if (fname && (match->fname = vim_strsave(fname)) != NULL)
2084 reuse |= FREE_FNAME;
2085 else
2086 match->fname = NULL;
2087 match->original = reuse;
2088
2089 /*
2090 * Link the new match structure in the list of matches.
2091 */
2092 if (first_match == NULL)
2093 match->next = match->prev = NULL;
2094 else if (dir == FORWARD)
2095 {
2096 match->next = curr_match->next;
2097 match->prev = curr_match;
2098 }
2099 else /* BACKWARD */
2100 {
2101 match->next = curr_match;
2102 match->prev = curr_match->prev;
2103 }
2104 if (match->next)
2105 match->next->prev = match;
2106 if (match->prev)
2107 match->prev->next = match;
2108 else /* if there's nothing before, it is the first match */
2109 first_match = match;
2110 curr_match = match;
2111
2112 return OK;
2113}
2114
2115/*
2116 * Add an array of matches to the list of matches.
2117 * Frees matches[].
2118 */
2119 static void
2120ins_compl_add_matches(num_matches, matches, dir)
2121 int num_matches;
2122 char_u **matches;
2123 int dir;
2124{
2125 int i;
2126 int add_r = OK;
2127 int ldir = dir;
2128
2129 for (i = 0; i < num_matches && add_r != RET_ERROR; i++)
2130 if ((add_r = ins_compl_add(matches[i], -1, NULL, ldir, 0)) == OK)
2131 /* if dir was BACKWARD then honor it just once */
2132 ldir = FORWARD;
2133 FreeWild(num_matches, matches);
2134}
2135
2136/* Make the completion list cyclic.
2137 * Return the number of matches (excluding the original).
2138 */
2139 static int
2140ins_compl_make_cyclic()
2141{
2142 struct Completion *match;
2143 int count = 0;
2144
2145 if (first_match != NULL)
2146 {
2147 /*
2148 * Find the end of the list.
2149 */
2150 match = first_match;
2151 /* there's always an entry for the original_text, it doesn't count. */
2152 while (match->next != NULL && match->next != first_match)
2153 {
2154 match = match->next;
2155 ++count;
2156 }
2157 match->next = first_match;
2158 first_match->prev = match;
2159 }
2160 return count;
2161}
2162
2163#define DICT_FIRST (1) /* use just first element in "dict" */
2164#define DICT_EXACT (2) /* "dict" is the exact name of a file */
2165/*
2166 * Add any identifiers that match the given pattern to the list of
2167 * completions.
2168 */
2169 static void
2170ins_compl_dictionaries(dict, pat, dir, flags, thesaurus)
2171 char_u *dict;
2172 char_u *pat;
2173 int dir;
2174 int flags;
2175 int thesaurus;
2176{
2177 char_u *ptr;
2178 char_u *buf;
2179 FILE *fp;
2180 regmatch_T regmatch;
2181 int add_r;
2182 char_u **files;
2183 int count;
2184 int i;
2185 int save_p_scs;
2186
2187 buf = alloc(LSIZE);
2188 /* If 'infercase' is set, don't use 'smartcase' here */
2189 save_p_scs = p_scs;
2190 if (curbuf->b_p_inf)
2191 p_scs = FALSE;
2192 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2193 /* ignore case depends on 'ignorecase', 'smartcase' and "pat" */
2194 regmatch.rm_ic = ignorecase(pat);
2195 while (buf != NULL && regmatch.regprog != NULL && *dict != NUL
2196 && !got_int && !completion_interrupted)
2197 {
2198 /* copy one dictionary file name into buf */
2199 if (flags == DICT_EXACT)
2200 {
2201 count = 1;
2202 files = &dict;
2203 }
2204 else
2205 {
2206 /* Expand wildcards in the dictionary name, but do not allow
2207 * backticks (for security, the 'dict' option may have been set in
2208 * a modeline). */
2209 copy_option_part(&dict, buf, LSIZE, ",");
2210 if (vim_strchr(buf, '`') != NULL
2211 || expand_wildcards(1, &buf, &count, &files,
2212 EW_FILE|EW_SILENT) != OK)
2213 count = 0;
2214 }
2215
2216 for (i = 0; i < count && !got_int && !completion_interrupted; i++)
2217 {
2218 fp = mch_fopen((char *)files[i], "r"); /* open dictionary file */
2219 if (flags != DICT_EXACT)
2220 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00002221 vim_snprintf((char *)IObuff, IOSIZE,
2222 _("Scanning dictionary: %s"), (char *)files[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
2224 }
2225
2226 if (fp != NULL)
2227 {
2228 /*
2229 * Read dictionary file line by line.
2230 * Check each line for a match.
2231 */
2232 while (!got_int && !completion_interrupted
2233 && !vim_fgets(buf, LSIZE, fp))
2234 {
2235 ptr = buf;
2236 while (vim_regexec(&regmatch, buf, (colnr_T)(ptr - buf)))
2237 {
2238 ptr = regmatch.startp[0];
2239 ptr = find_word_end(ptr);
2240 add_r = ins_compl_add_infercase(regmatch.startp[0],
2241 (int)(ptr - regmatch.startp[0]),
2242 files[i], dir, 0);
2243 if (thesaurus)
2244 {
2245 char_u *wstart;
2246
2247 /*
2248 * Add the other matches on the line
2249 */
2250 while (!got_int)
2251 {
2252 /* Find start of the next word. Skip white
2253 * space and punctuation. */
2254 ptr = find_word_start(ptr);
2255 if (*ptr == NUL || *ptr == NL)
2256 break;
2257 wstart = ptr;
2258
2259 /* Find end of the word and add it. */
2260#ifdef FEAT_MBYTE
2261 if (has_mbyte)
2262 /* Japanese words may have characters in
2263 * different classes, only separate words
2264 * with single-byte non-word characters. */
2265 while (*ptr != NUL)
2266 {
2267 int l = (*mb_ptr2len_check)(ptr);
2268
2269 if (l < 2 && !vim_iswordc(*ptr))
2270 break;
2271 ptr += l;
2272 }
2273 else
2274#endif
2275 ptr = find_word_end(ptr);
2276 add_r = ins_compl_add_infercase(wstart,
2277 (int)(ptr - wstart), files[i], dir, 0);
2278 }
2279 }
2280 if (add_r == OK)
2281 /* if dir was BACKWARD then honor it just once */
2282 dir = FORWARD;
2283 else if (add_r == RET_ERROR)
2284 break;
2285 /* avoid expensive call to vim_regexec() when at end
2286 * of line */
2287 if (*ptr == '\n' || got_int)
2288 break;
2289 }
2290 line_breakcheck();
2291 ins_compl_check_keys();
2292 }
2293 fclose(fp);
2294 }
2295 }
2296 if (flags != DICT_EXACT)
2297 FreeWild(count, files);
2298 if (flags)
2299 break;
2300 }
2301 p_scs = save_p_scs;
2302 vim_free(regmatch.regprog);
2303 vim_free(buf);
2304}
2305
2306/*
2307 * Find the start of the next word.
2308 * Returns a pointer to the first char of the word. Also stops at a NUL.
2309 */
2310 char_u *
2311find_word_start(ptr)
2312 char_u *ptr;
2313{
2314#ifdef FEAT_MBYTE
2315 if (has_mbyte)
2316 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2317 ptr += (*mb_ptr2len_check)(ptr);
2318 else
2319#endif
2320 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2321 ++ptr;
2322 return ptr;
2323}
2324
2325/*
2326 * Find the end of the word. Assumes it starts inside a word.
2327 * Returns a pointer to just after the word.
2328 */
2329 char_u *
2330find_word_end(ptr)
2331 char_u *ptr;
2332{
2333#ifdef FEAT_MBYTE
2334 int start_class;
2335
2336 if (has_mbyte)
2337 {
2338 start_class = mb_get_class(ptr);
2339 if (start_class > 1)
2340 while (*ptr != NUL)
2341 {
2342 ptr += (*mb_ptr2len_check)(ptr);
2343 if (mb_get_class(ptr) != start_class)
2344 break;
2345 }
2346 }
2347 else
2348#endif
2349 while (vim_iswordc(*ptr))
2350 ++ptr;
2351 return ptr;
2352}
2353
2354/*
2355 * Free the list of completions
2356 */
2357 static void
2358ins_compl_free()
2359{
2360 struct Completion *match;
2361
2362 vim_free(complete_pat);
2363 complete_pat = NULL;
2364
2365 if (first_match == NULL)
2366 return;
2367 curr_match = first_match;
2368 do
2369 {
2370 match = curr_match;
2371 curr_match = curr_match->next;
2372 vim_free(match->str);
2373 /* several entries may use the same fname, free it just once. */
2374 if (match->original & FREE_FNAME)
2375 vim_free(match->fname);
2376 vim_free(match);
2377 } while (curr_match != NULL && curr_match != first_match);
2378 first_match = curr_match = NULL;
2379}
2380
2381 static void
2382ins_compl_clear()
2383{
2384 continue_status = 0;
2385 started_completion = FALSE;
2386 completion_matches = 0;
2387 vim_free(complete_pat);
2388 complete_pat = NULL;
2389 save_sm = -1;
2390 edit_submode_extra = NULL;
2391}
2392
2393/*
2394 * Prepare for Insert mode completion, or stop it.
2395 */
2396 static void
2397ins_compl_prep(c)
2398 int c;
2399{
2400 char_u *ptr;
2401 char_u *tmp_ptr;
2402 int temp;
2403 int want_cindent;
2404
2405 /* Forget any previous 'special' messages if this is actually
2406 * a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2407 */
2408 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2409 edit_submode_extra = NULL;
2410
2411 /* Ignore end of Select mode mapping */
2412 if (c == K_SELECT)
2413 return;
2414
2415 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
2416 {
2417 /*
2418 * We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2419 * it will be yet. Now we decide.
2420 */
2421 switch (c)
2422 {
2423 case Ctrl_E:
2424 case Ctrl_Y:
2425 ctrl_x_mode = CTRL_X_SCROLL;
2426 if (!(State & REPLACE_FLAG))
2427 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2428 else
2429 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2430 edit_submode_pre = NULL;
2431 showmode();
2432 break;
2433 case Ctrl_L:
2434 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2435 break;
2436 case Ctrl_F:
2437 ctrl_x_mode = CTRL_X_FILES;
2438 break;
2439 case Ctrl_K:
2440 ctrl_x_mode = CTRL_X_DICTIONARY;
2441 break;
2442 case Ctrl_R:
2443 /* Simply allow ^R to happen without affecting ^X mode */
2444 break;
2445 case Ctrl_T:
2446 ctrl_x_mode = CTRL_X_THESAURUS;
2447 break;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002448#ifdef FEAT_COMPL_FUNC
2449 case Ctrl_U:
2450 ctrl_x_mode = CTRL_X_FUNCTION;
2451 break;
2452#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 case Ctrl_RSB:
2454 ctrl_x_mode = CTRL_X_TAGS;
2455 break;
2456#ifdef FEAT_FIND_ID
2457 case Ctrl_I:
2458 case K_S_TAB:
2459 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2460 break;
2461 case Ctrl_D:
2462 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2463 break;
2464#endif
2465 case Ctrl_V:
2466 case Ctrl_Q:
2467 ctrl_x_mode = CTRL_X_CMDLINE;
2468 break;
2469 case Ctrl_P:
2470 case Ctrl_N:
2471 /* ^X^P means LOCAL expansion if nothing interrupted (eg we
2472 * just started ^X mode, or there were enough ^X's to cancel
2473 * the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2474 * do normal expansion when interrupting a different mode (say
2475 * ^X^F^X^P or ^P^X^X^P, see below)
2476 * nothing changes if interrupting mode 0, (eg, the flag
2477 * doesn't change when going to ADDING mode -- Acevedo */
2478 if (!(continue_status & CONT_INTRPT))
2479 continue_status |= CONT_LOCAL;
2480 else if (continue_mode != 0)
2481 continue_status &= ~CONT_LOCAL;
2482 /* FALLTHROUGH */
2483 default:
2484 /* if we have typed at least 2 ^X's... for modes != 0, we set
2485 * continue_status = 0 (eg, as if we had just started ^X mode)
2486 * for mode 0, we set continue_mode to an impossible value, in
2487 * both cases ^X^X can be used to restart the same mode
2488 * (avoiding ADDING mode). Undocumented feature:
2489 * In a mode != 0 ^X^P and ^X^X^P start 'complete' and local
2490 * ^P expansions respectively. In mode 0 an extra ^X is
2491 * needed since ^X^P goes to ADDING mode -- Acevedo */
2492 if (c == Ctrl_X)
2493 {
2494 if (continue_mode != 0)
2495 continue_status = 0;
2496 else
2497 continue_mode = CTRL_X_NOT_DEFINED_YET;
2498 }
2499 ctrl_x_mode = 0;
2500 edit_submode = NULL;
2501 showmode();
2502 break;
2503 }
2504 }
2505 else if (ctrl_x_mode != 0)
2506 {
2507 /* We're already in CTRL-X mode, do we stay in it? */
2508 if (!vim_is_ctrl_x_key(c))
2509 {
2510 if (ctrl_x_mode == CTRL_X_SCROLL)
2511 ctrl_x_mode = 0;
2512 else
2513 ctrl_x_mode = CTRL_X_FINISHED;
2514 edit_submode = NULL;
2515 }
2516 showmode();
2517 }
2518
2519 if (started_completion || ctrl_x_mode == CTRL_X_FINISHED)
2520 {
2521 /* Show error message from attempted keyword completion (probably
2522 * 'Pattern not found') until another key is hit, then go back to
2523 * showing what mode we are in.
2524 */
2525 showmode();
2526 if ((ctrl_x_mode == 0 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_R)
2527 || ctrl_x_mode == CTRL_X_FINISHED)
2528 {
2529 /* Get here when we have finished typing a sequence of ^N and
2530 * ^P or other completion characters in CTRL-X mode. Free up
2531 * memory that was used, and make sure we can redo the insert.
2532 */
2533 if (curr_match != NULL)
2534 {
2535 /*
2536 * If any of the original typed text has been changed,
2537 * eg when ignorecase is set, we must add back-spaces to
2538 * the redo buffer. We add as few as necessary to delete
2539 * just the part of the original text that has changed.
2540 */
2541 ptr = curr_match->str;
2542 tmp_ptr = original_text;
2543 while (*tmp_ptr && *tmp_ptr == *ptr)
2544 {
2545 ++tmp_ptr;
2546 ++ptr;
2547 }
2548 for (temp = 0; tmp_ptr[temp]; ++temp)
2549 AppendCharToRedobuff(K_BS);
2550 AppendToRedobuffLit(ptr);
2551 }
2552
2553#ifdef FEAT_CINDENT
2554 want_cindent = (can_cindent && cindent_on());
2555#endif
2556 /*
2557 * When completing whole lines: fix indent for 'cindent'.
2558 * Otherwise, break line if it's too long.
2559 */
2560 if (continue_mode == CTRL_X_WHOLE_LINE)
2561 {
2562#ifdef FEAT_CINDENT
2563 /* re-indent the current line */
2564 if (want_cindent)
2565 {
2566 do_c_expr_indent();
2567 want_cindent = FALSE; /* don't do it again */
2568 }
2569#endif
2570 }
2571 else
2572 {
2573 /* put the cursor on the last char, for 'tw' formatting */
2574 curwin->w_cursor.col--;
2575 if (stop_arrow() == OK)
2576 insertchar(NUL, 0, -1);
2577 curwin->w_cursor.col++;
2578 }
2579
2580 auto_format(FALSE, TRUE);
2581
2582 ins_compl_free();
2583 started_completion = FALSE;
2584 completion_matches = 0;
2585 msg_clr_cmdline(); /* necessary for "noshowmode" */
2586 ctrl_x_mode = 0;
2587 p_sm = save_sm;
2588 if (edit_submode != NULL)
2589 {
2590 edit_submode = NULL;
2591 showmode();
2592 }
2593
2594#ifdef FEAT_CINDENT
2595 /*
2596 * Indent now if a key was typed that is in 'cinkeys'.
2597 */
2598 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2599 do_c_expr_indent();
2600#endif
2601 }
2602 }
2603
2604 /* reset continue_* if we left expansion-mode, if we stay they'll be
2605 * (re)set properly in ins_complete() */
2606 if (!vim_is_ctrl_x_key(c))
2607 {
2608 continue_status = 0;
2609 continue_mode = 0;
2610 }
2611}
2612
2613/*
2614 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2615 * (depending on flag) starting from buf and looking for a non-scanned
2616 * buffer (other than curbuf). curbuf is special, if it is called with
2617 * buf=curbuf then it has to be the first call for a given flag/expansion.
2618 *
2619 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2620 */
2621 static buf_T *
2622ins_compl_next_buf(buf, flag)
2623 buf_T *buf;
2624 int flag;
2625{
2626#ifdef FEAT_WINDOWS
2627 static win_T *wp;
2628#endif
2629
2630 if (flag == 'w') /* just windows */
2631 {
2632#ifdef FEAT_WINDOWS
2633 if (buf == curbuf) /* first call for this flag/expansion */
2634 wp = curwin;
2635 while ((wp = wp->w_next != NULL ? wp->w_next : firstwin) != curwin
2636 && wp->w_buffer->b_scanned)
2637 ;
2638 buf = wp->w_buffer;
2639#else
2640 buf = curbuf;
2641#endif
2642 }
2643 else
2644 /* 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2645 * (unlisted buffers)
2646 * When completing whole lines skip unloaded buffers. */
2647 while ((buf = buf->b_next != NULL ? buf->b_next : firstbuf) != curbuf
2648 && ((flag == 'U'
2649 ? buf->b_p_bl
2650 : (!buf->b_p_bl
2651 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2652 || buf->b_scanned
2653 || (buf->b_ml.ml_mfp == NULL
2654 && ctrl_x_mode == CTRL_X_WHOLE_LINE)))
2655 ;
2656 return buf;
2657}
2658
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002659#ifdef FEAT_COMPL_FUNC
2660static char_u *call_completefunc __ARGS((char_u *line, char_u *base, int col, int preproc));
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002661static int expand_by_function __ARGS((linenr_T lnum, int col, char_u *base, char_u ***matches));
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002662
2663/*
2664 * Execute user defined complete function 'completefunc'.
2665 * Return NULL if some error occurs.
2666 */
2667 static char_u *
2668call_completefunc(line, base, col, preproc)
2669 char_u *line;
2670 char_u *base;
2671 int col;
2672 int preproc;
2673{
2674 char_u colbuf[30];
2675 char_u *args[4];
2676
2677 /* Return NULL when 'completefunc' isn't set. */
2678 if (*curbuf->b_p_cfu == NUL)
2679 return NULL;
2680
2681 sprintf((char *)colbuf, "%d", col + (base ? (int)STRLEN(base) : 0));
2682 args[0] = line;
2683 args[1] = base;
2684 args[2] = colbuf;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002685 args[3] = (char_u *)(preproc ? "1" : "0");
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002686 return call_vim_function(curbuf->b_p_cfu, 4, args, FALSE);
2687}
2688
2689/*
2690 * Execute user defined complete function 'completefunc', and get candidates
2691 * are separeted with "\n". Return value is number of candidates and array
2692 * of candidates as "matches".
2693 */
2694 static int
2695expand_by_function(lnum, col, base, matches)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00002696 linenr_T lnum;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002697 int col;
2698 char_u *base;
2699 char_u ***matches;
2700{
2701 char_u *matchstr = NULL;
2702
2703 /* Execute 'completefunc' and get the result */
2704 matchstr = call_completefunc(ml_get_buf(curbuf, lnum, FALSE), base, col, 0);
2705
2706 /* Parse returned string */
2707 if (matchstr != NULL)
2708 {
2709 garray_T ga;
2710 char_u *p, *pnext;
2711
2712 ga_init2(&ga, (int)sizeof(char*), 8);
2713 for (p = matchstr; *p != NUL; p = pnext)
2714 {
2715 int len;
2716
2717 pnext = vim_strchr(p, '\n');
2718 if (pnext == NULL)
2719 pnext = p + STRLEN(p);
2720 len = pnext - p;
2721 if (len > 0)
2722 {
2723 if (ga_grow(&ga, 1) == FAIL)
2724 break;
2725 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(p, len);
2726 ++ga.ga_len;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002727 }
2728 if (*pnext != NUL)
2729 ++pnext;
2730 }
2731 vim_free(matchstr);
2732 if (ga.ga_len > 0)
2733 *matches = (char_u**)ga.ga_data;
2734 return ga.ga_len;
2735 }
2736 return 0;
2737}
2738#endif /* FEAT_COMPL_FUNC */
2739
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740/*
2741 * Get the next expansion(s) for the text starting at the initial curbuf
2742 * position "ini" and in the direction dir.
2743 * Return the total of matches or -1 if still unknown -- Acevedo
2744 */
2745 static int
2746ins_compl_get_exp(ini, dir)
2747 pos_T *ini;
2748 int dir;
2749{
2750 static pos_T first_match_pos;
2751 static pos_T last_match_pos;
2752 static char_u *e_cpt = (char_u *)""; /* curr. entry in 'complete' */
2753 static int found_all = FALSE; /* Found all matches. */
2754 static buf_T *ins_buf = NULL;
2755
2756 pos_T *pos;
2757 char_u **matches;
2758 int save_p_scs;
2759 int save_p_ws;
2760 int save_p_ic;
2761 int i;
2762 int num_matches;
2763 int len;
2764 int found_new_match;
2765 int type = ctrl_x_mode;
2766 char_u *ptr;
2767 char_u *tmp_ptr;
2768 char_u *dict = NULL;
2769 int dict_f = 0;
2770 struct Completion *old_match;
2771
2772 if (!started_completion)
2773 {
2774 for (ins_buf = firstbuf; ins_buf != NULL; ins_buf = ins_buf->b_next)
2775 ins_buf->b_scanned = 0;
2776 found_all = FALSE;
2777 ins_buf = curbuf;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002778 e_cpt = (continue_status & CONT_LOCAL)
2779 ? (char_u *)"." : curbuf->b_p_cpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 last_match_pos = first_match_pos = *ini;
2781 }
2782
2783 old_match = curr_match; /* remember the last current match */
2784 pos = (dir == FORWARD) ? &last_match_pos : &first_match_pos;
2785 /* For ^N/^P loop over all the flags/windows/buffers in 'complete' */
2786 for (;;)
2787 {
2788 found_new_match = FAIL;
2789
2790 /* For ^N/^P pick a new entry from e_cpt if started_completion is off,
2791 * or if found_all says this entry is done. For ^X^L only use the
2792 * entries from 'complete' that look in loaded buffers. */
2793 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
2794 && (!started_completion || found_all))
2795 {
2796 found_all = FALSE;
2797 while (*e_cpt == ',' || *e_cpt == ' ')
2798 e_cpt++;
2799 if (*e_cpt == '.' && !curbuf->b_scanned)
2800 {
2801 ins_buf = curbuf;
2802 first_match_pos = *ini;
2803 /* So that ^N can match word immediately after cursor */
2804 if (ctrl_x_mode == 0)
2805 dec(&first_match_pos);
2806 last_match_pos = first_match_pos;
2807 type = 0;
2808 }
2809 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
2810 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
2811 {
2812 /* Scan a buffer, but not the current one. */
2813 if (ins_buf->b_ml.ml_mfp != NULL) /* loaded buffer */
2814 {
2815 started_completion = TRUE;
2816 first_match_pos.col = last_match_pos.col = 0;
2817 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
2818 last_match_pos.lnum = 0;
2819 type = 0;
2820 }
2821 else /* unloaded buffer, scan like dictionary */
2822 {
2823 found_all = TRUE;
2824 if (ins_buf->b_fname == NULL)
2825 continue;
2826 type = CTRL_X_DICTIONARY;
2827 dict = ins_buf->b_fname;
2828 dict_f = DICT_EXACT;
2829 }
Bram Moolenaar555b2802005-05-19 21:08:39 +00002830 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 ins_buf->b_fname == NULL
2832 ? buf_spname(ins_buf)
2833 : ins_buf->b_sfname == NULL
2834 ? (char *)ins_buf->b_fname
2835 : (char *)ins_buf->b_sfname);
2836 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
2837 }
2838 else if (*e_cpt == NUL)
2839 break;
2840 else
2841 {
2842 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
2843 type = -1;
2844 else if (*e_cpt == 'k' || *e_cpt == 's')
2845 {
2846 if (*e_cpt == 'k')
2847 type = CTRL_X_DICTIONARY;
2848 else
2849 type = CTRL_X_THESAURUS;
2850 if (*++e_cpt != ',' && *e_cpt != NUL)
2851 {
2852 dict = e_cpt;
2853 dict_f = DICT_FIRST;
2854 }
2855 }
2856#ifdef FEAT_FIND_ID
2857 else if (*e_cpt == 'i')
2858 type = CTRL_X_PATH_PATTERNS;
2859 else if (*e_cpt == 'd')
2860 type = CTRL_X_PATH_DEFINES;
2861#endif
2862 else if (*e_cpt == ']' || *e_cpt == 't')
2863 {
2864 type = CTRL_X_TAGS;
2865 sprintf((char*)IObuff, _("Scanning tags."));
2866 msg_trunc_attr(IObuff, TRUE, hl_attr(HLF_R));
2867 }
2868 else
2869 type = -1;
2870
2871 /* in any case e_cpt is advanced to the next entry */
2872 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
2873
2874 found_all = TRUE;
2875 if (type == -1)
2876 continue;
2877 }
2878 }
2879
2880 switch (type)
2881 {
2882 case -1:
2883 break;
2884#ifdef FEAT_FIND_ID
2885 case CTRL_X_PATH_PATTERNS:
2886 case CTRL_X_PATH_DEFINES:
2887 find_pattern_in_path(complete_pat, dir,
2888 (int)STRLEN(complete_pat), FALSE, FALSE,
2889 (type == CTRL_X_PATH_DEFINES
2890 && !(continue_status & CONT_SOL))
2891 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
2892 (linenr_T)1, (linenr_T)MAXLNUM);
2893 break;
2894#endif
2895
2896 case CTRL_X_DICTIONARY:
2897 case CTRL_X_THESAURUS:
2898 ins_compl_dictionaries(
2899 dict ? dict
2900 : (type == CTRL_X_THESAURUS
2901 ? (*curbuf->b_p_tsr == NUL
2902 ? p_tsr
2903 : curbuf->b_p_tsr)
2904 : (*curbuf->b_p_dict == NUL
2905 ? p_dict
2906 : curbuf->b_p_dict)),
2907 complete_pat, dir,
2908 dict ? dict_f : 0, type == CTRL_X_THESAURUS);
2909 dict = NULL;
2910 break;
2911
2912 case CTRL_X_TAGS:
2913 /* set p_ic according to p_ic, p_scs and pat for find_tags(). */
2914 save_p_ic = p_ic;
2915 p_ic = ignorecase(complete_pat);
2916
2917 /* Find up to TAG_MANY matches. Avoids that an enourmous number
2918 * of matches is found when complete_pat is empty */
2919 if (find_tags(complete_pat, &num_matches, &matches,
2920 TAG_REGEXP | TAG_NAMES | TAG_NOIC |
2921 TAG_INS_COMP | (ctrl_x_mode ? TAG_VERBOSE : 0),
2922 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
2923 {
2924 ins_compl_add_matches(num_matches, matches, dir);
2925 }
2926 p_ic = save_p_ic;
2927 break;
2928
2929 case CTRL_X_FILES:
2930 if (expand_wildcards(1, &complete_pat, &num_matches, &matches,
2931 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
2932 {
2933
2934 /* May change home directory back to "~". */
2935 tilde_replace(complete_pat, num_matches, matches);
2936 ins_compl_add_matches(num_matches, matches, dir);
2937 }
2938 break;
2939
2940 case CTRL_X_CMDLINE:
2941 if (expand_cmdline(&complete_xp, complete_pat,
2942 (int)STRLEN(complete_pat),
2943 &num_matches, &matches) == EXPAND_OK)
2944 ins_compl_add_matches(num_matches, matches, dir);
2945 break;
2946
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00002947#ifdef FEAT_COMPL_FUNC
2948 case CTRL_X_FUNCTION:
2949 num_matches = expand_by_function(first_match_pos.lnum,
2950 first_match_pos.col, complete_pat, &matches);
2951 if (num_matches > 0)
2952 ins_compl_add_matches(num_matches, matches, dir);
2953 break;
2954#endif
2955
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 default: /* normal ^P/^N and ^X^L */
2957 /*
2958 * If 'infercase' is set, don't use 'smartcase' here
2959 */
2960 save_p_scs = p_scs;
2961 if (ins_buf->b_p_inf)
2962 p_scs = FALSE;
2963 /* buffers other than curbuf are scanned from the beginning or the
2964 * end but never from the middle, thus setting nowrapscan in this
2965 * buffers is a good idea, on the other hand, we always set
2966 * wrapscan for curbuf to avoid missing matches -- Acevedo,Webb */
2967 save_p_ws = p_ws;
2968 if (ins_buf != curbuf)
2969 p_ws = FALSE;
2970 else if (*e_cpt == '.')
2971 p_ws = TRUE;
2972 for (;;)
2973 {
2974 int reuse = 0;
2975
2976 /* ctrl_x_mode == CTRL_X_WHOLE_LINE || word-wise search that has
2977 * added a word that was at the beginning of the line */
2978 if ( ctrl_x_mode == CTRL_X_WHOLE_LINE
2979 || (continue_status & CONT_SOL))
2980 found_new_match = search_for_exact_line(ins_buf, pos,
2981 dir, complete_pat);
2982 else
2983 found_new_match = searchit(NULL, ins_buf, pos, dir,
2984 complete_pat, 1L, SEARCH_KEEP + SEARCH_NFMSG,
2985 RE_LAST);
2986 if (!started_completion)
2987 {
2988 /* set started_completion even on fail */
2989 started_completion = TRUE;
2990 first_match_pos = *pos;
2991 last_match_pos = *pos;
2992 }
2993 else if (first_match_pos.lnum == last_match_pos.lnum
2994 && first_match_pos.col == last_match_pos.col)
2995 found_new_match = FAIL;
2996 if (found_new_match == FAIL)
2997 {
2998 if (ins_buf == curbuf)
2999 found_all = TRUE;
3000 break;
3001 }
3002
3003 /* when ADDING, the text before the cursor matches, skip it */
3004 if ( (continue_status & CONT_ADDING) && ins_buf == curbuf
3005 && ini->lnum == pos->lnum
3006 && ini->col == pos->col)
3007 continue;
3008 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
3009 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3010 {
3011 if (continue_status & CONT_ADDING)
3012 {
3013 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
3014 continue;
3015 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3016 if (!p_paste)
3017 ptr = skipwhite(ptr);
3018 }
3019 len = (int)STRLEN(ptr);
3020 }
3021 else
3022 {
3023 tmp_ptr = ptr;
3024 if (continue_status & CONT_ADDING)
3025 {
3026 tmp_ptr += completion_length;
3027 /* Skip if already inside a word. */
3028 if (vim_iswordp(tmp_ptr))
3029 continue;
3030 /* Find start of next word. */
3031 tmp_ptr = find_word_start(tmp_ptr);
3032 }
3033 /* Find end of this word. */
3034 tmp_ptr = find_word_end(tmp_ptr);
3035 len = (int)(tmp_ptr - ptr);
3036
3037 if ((continue_status & CONT_ADDING)
3038 && len == completion_length)
3039 {
3040 if (pos->lnum < ins_buf->b_ml.ml_line_count)
3041 {
3042 /* Try next line, if any. the new word will be
3043 * "join" as if the normal command "J" was used.
3044 * IOSIZE is always greater than
3045 * completion_length, so the next STRNCPY always
3046 * works -- Acevedo */
3047 STRNCPY(IObuff, ptr, len);
3048 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3049 tmp_ptr = ptr = skipwhite(ptr);
3050 /* Find start of next word. */
3051 tmp_ptr = find_word_start(tmp_ptr);
3052 /* Find end of next word. */
3053 tmp_ptr = find_word_end(tmp_ptr);
3054 if (tmp_ptr > ptr)
3055 {
3056 if (*ptr != ')' && IObuff[len-1] != TAB)
3057 {
3058 if (IObuff[len-1] != ' ')
3059 IObuff[len++] = ' ';
3060 /* IObuf =~ "\k.* ", thus len >= 2 */
3061 if (p_js
3062 && (IObuff[len-2] == '.'
3063 || (vim_strchr(p_cpo, CPO_JOINSP)
3064 == NULL
3065 && (IObuff[len-2] == '?'
3066 || IObuff[len-2] == '!'))))
3067 IObuff[len++] = ' ';
3068 }
3069 /* copy as much as posible of the new word */
3070 if (tmp_ptr - ptr >= IOSIZE - len)
3071 tmp_ptr = ptr + IOSIZE - len - 1;
3072 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3073 len += (int)(tmp_ptr - ptr);
3074 reuse |= CONT_S_IPOS;
3075 }
3076 IObuff[len] = NUL;
3077 ptr = IObuff;
3078 }
3079 if (len == completion_length)
3080 continue;
3081 }
3082 }
3083 if (ins_compl_add_infercase(ptr, len,
3084 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
3085 dir, reuse) != FAIL)
3086 {
3087 found_new_match = OK;
3088 break;
3089 }
3090 }
3091 p_scs = save_p_scs;
3092 p_ws = save_p_ws;
3093 }
3094 /* check if curr_match has changed, (e.g. other type of expansion
3095 * added somenthing) */
3096 if (curr_match != old_match)
3097 found_new_match = OK;
3098
3099 /* break the loop for specialized modes (use 'complete' just for the
3100 * generic ctrl_x_mode == 0) or when we've found a new match */
3101 if ((ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE)
3102 || found_new_match != FAIL)
3103 break;
3104
3105 /* Mark a buffer scanned when it has been scanned completely */
3106 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3107 ins_buf->b_scanned = TRUE;
3108
3109 started_completion = FALSE;
3110 }
3111 started_completion = TRUE;
3112
3113 if ((ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_WHOLE_LINE)
3114 && *e_cpt == NUL) /* Got to end of 'complete' */
3115 found_new_match = FAIL;
3116
3117 i = -1; /* total of matches, unknown */
3118 if (found_new_match == FAIL
3119 || (ctrl_x_mode != 0 && ctrl_x_mode != CTRL_X_WHOLE_LINE))
3120 i = ins_compl_make_cyclic();
3121
3122 /* If several matches were added (FORWARD) or the search failed and has
3123 * just been made cyclic then we have to move curr_match to the next or
3124 * previous entry (if any) -- Acevedo */
3125 curr_match = dir == FORWARD ? old_match->next : old_match->prev;
3126 if (curr_match == NULL)
3127 curr_match = old_match;
3128 return i;
3129}
3130
3131/* Delete the old text being completed. */
3132 static void
3133ins_compl_delete()
3134{
3135 int i;
3136
3137 /*
3138 * In insert mode: Delete the typed part.
3139 * In replace mode: Put the old characters back, if any.
3140 */
3141 i = complete_col + (continue_status & CONT_ADDING ? completion_length : 0);
3142 backspace_until_column(i);
3143 changed_cline_bef_curs();
3144}
3145
3146/* Insert the new text being completed. */
3147 static void
3148ins_compl_insert()
3149{
3150 ins_bytes(shown_match->str + curwin->w_cursor.col - complete_col);
3151}
3152
3153/*
3154 * Fill in the next completion in the current direction.
3155 * If allow_get_expansion is TRUE, then we may call ins_compl_get_exp() to get
3156 * more completions. If it is FALSE, then we just do nothing when there are
3157 * no more completions in a given direction. The latter case is used when we
3158 * are still in the middle of finding completions, to allow browsing through
3159 * the ones found so far.
3160 * Return the total number of matches, or -1 if still unknown -- webb.
3161 *
3162 * curr_match is currently being used by ins_compl_get_exp(), so we use
3163 * shown_match here.
3164 *
3165 * Note that this function may be called recursively once only. First with
3166 * allow_get_expansion TRUE, which calls ins_compl_get_exp(), which in turn
3167 * calls this function with allow_get_expansion FALSE.
3168 */
3169 static int
3170ins_compl_next(allow_get_expansion)
3171 int allow_get_expansion;
3172{
3173 int num_matches = -1;
3174 int i;
3175
3176 if (allow_get_expansion)
3177 {
3178 /* Delete old text to be replaced */
3179 ins_compl_delete();
3180 }
3181 completion_pending = FALSE;
3182 if (shown_direction == FORWARD && shown_match->next != NULL)
3183 shown_match = shown_match->next;
3184 else if (shown_direction == BACKWARD && shown_match->prev != NULL)
3185 shown_match = shown_match->prev;
3186 else
3187 {
3188 completion_pending = TRUE;
3189 if (allow_get_expansion)
3190 {
3191 num_matches = ins_compl_get_exp(&initial_pos, complete_direction);
3192 if (completion_pending)
3193 {
3194 if (complete_direction == shown_direction)
3195 shown_match = curr_match;
3196 }
3197 }
3198 else
3199 return -1;
3200 }
3201
3202 /* Insert the text of the new completion */
3203 ins_compl_insert();
3204
3205 if (!allow_get_expansion)
3206 {
3207 /* Display the current match. */
3208 update_screen(0);
3209
3210 /* Delete old text to be replaced, since we're still searching and
3211 * don't want to match ourselves! */
3212 ins_compl_delete();
3213 }
3214
3215 /*
3216 * Show the file name for the match (if any)
3217 * Truncate the file name to avoid a wait for return.
3218 */
3219 if (shown_match->fname != NULL)
3220 {
3221 STRCPY(IObuff, "match in file ");
3222 i = (vim_strsize(shown_match->fname) + 16) - sc_col;
3223 if (i <= 0)
3224 i = 0;
3225 else
3226 STRCAT(IObuff, "<");
3227 STRCAT(IObuff, shown_match->fname + i);
3228 msg(IObuff);
3229 redraw_cmdline = FALSE; /* don't overwrite! */
3230 }
3231
3232 return num_matches;
3233}
3234
3235/*
3236 * Call this while finding completions, to check whether the user has hit a key
3237 * that should change the currently displayed completion, or exit completion
3238 * mode. Also, when completion_pending is TRUE, show a completion as soon as
3239 * possible. -- webb
3240 */
3241 void
3242ins_compl_check_keys()
3243{
3244 static int count = 0;
3245
3246 int c;
3247
3248 /* Don't check when reading keys from a script. That would break the test
3249 * scripts */
3250 if (using_script())
3251 return;
3252
3253 /* Only do this at regular intervals */
3254 if (++count < CHECK_KEYS_TIME)
3255 return;
3256 count = 0;
3257
3258 ++no_mapping;
3259 c = vpeekc_any();
3260 --no_mapping;
3261 if (c != NUL)
3262 {
3263 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
3264 {
3265 c = safe_vgetc(); /* Eat the character */
3266 if (c == Ctrl_P || c == Ctrl_L)
3267 shown_direction = BACKWARD;
3268 else
3269 shown_direction = FORWARD;
3270 (void)ins_compl_next(FALSE);
3271 }
3272 else if (c != Ctrl_R)
3273 completion_interrupted = TRUE;
3274 }
3275 if (completion_pending && !got_int)
3276 (void)ins_compl_next(FALSE);
3277}
3278
3279/*
3280 * Do Insert mode completion.
3281 * Called when character "c" was typed, which has a meaning for completion.
3282 * Returns OK if completion was done, FAIL if something failed (out of mem).
3283 */
3284 static int
3285ins_complete(c)
3286 int c;
3287{
3288 char_u *line;
3289 char_u *tmp_ptr = NULL; /* init for gcc */
3290 int temp = 0;
3291
3292 if (c == Ctrl_P || c == Ctrl_L)
3293 complete_direction = BACKWARD;
3294 else
3295 complete_direction = FORWARD;
3296 if (!started_completion)
3297 {
3298 /* First time we hit ^N or ^P (in a row, I mean) */
3299
3300 /* Turn off 'sm' so we don't show matches with ^X^L */
3301 save_sm = p_sm;
3302 p_sm = FALSE;
3303
3304 did_ai = FALSE;
3305#ifdef FEAT_SMARTINDENT
3306 did_si = FALSE;
3307 can_si = FALSE;
3308 can_si_back = FALSE;
3309#endif
3310 if (stop_arrow() == FAIL)
3311 return FAIL;
3312
3313 line = ml_get(curwin->w_cursor.lnum);
3314 complete_col = curwin->w_cursor.col;
3315
3316 /* if this same ctrl_x_mode has been interrupted use the text from
3317 * "initial_pos" to the cursor as a pattern to add a new word instead
3318 * of expand the one before the cursor, in word-wise if "initial_pos"
3319 * is not in the same line as the cursor then fix it (the line has
3320 * been split because it was longer than 'tw'). if SOL is set then
3321 * skip the previous pattern, a word at the beginning of the line has
3322 * been inserted, we'll look for that -- Acevedo. */
3323 if ((continue_status & CONT_INTRPT) && continue_mode == ctrl_x_mode)
3324 {
3325 /*
3326 * it is a continued search
3327 */
3328 continue_status &= ~CONT_INTRPT; /* remove INTRPT */
3329 if (ctrl_x_mode == 0 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
3330 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3331 {
3332 if (initial_pos.lnum != curwin->w_cursor.lnum)
3333 {
3334 /* line (probably) wrapped, set initial_pos to the first
3335 * non_blank in the line, if it is not a wordchar include
3336 * it to get a better pattern, but then we don't want the
3337 * "\\<" prefix, check it bellow */
3338 tmp_ptr = skipwhite(line);
3339 initial_pos.col = (colnr_T) (tmp_ptr - line);
3340 initial_pos.lnum = curwin->w_cursor.lnum;
3341 continue_status &= ~CONT_SOL; /* clear SOL if present */
3342 }
3343 else
3344 {
3345 /* S_IPOS was set when we inserted a word that was at the
3346 * beginning of the line, which means that we'll go to SOL
3347 * mode but first we need to redefine initial_pos */
3348 if (continue_status & CONT_S_IPOS)
3349 {
3350 continue_status |= CONT_SOL;
3351 initial_pos.col = (colnr_T) (skipwhite(line + completion_length +
3352 initial_pos.col) - line);
3353 }
3354 tmp_ptr = line + initial_pos.col;
3355 }
3356 temp = curwin->w_cursor.col - (int)(tmp_ptr - line);
3357 /* IObuf is used to add a "word from the next line" would we
3358 * have enough space? just being paranoic */
3359#define MIN_SPACE 75
3360 if (temp > (IOSIZE - MIN_SPACE))
3361 {
3362 continue_status &= ~CONT_SOL;
3363 temp = (IOSIZE - MIN_SPACE);
3364 tmp_ptr = line + curwin->w_cursor.col - temp;
3365 }
3366 continue_status |= CONT_ADDING | CONT_N_ADDS;
3367 if (temp < 1)
3368 continue_status &= CONT_LOCAL;
3369 }
3370 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3371 continue_status = CONT_ADDING | CONT_N_ADDS;
3372 else
3373 continue_status = 0;
3374 }
3375 else
3376 continue_status &= CONT_LOCAL;
3377
3378 if (!(continue_status & CONT_ADDING)) /* normal expansion */
3379 {
3380 continue_mode = ctrl_x_mode;
3381 if (ctrl_x_mode != 0) /* Remove LOCAL if ctrl_x_mode != 0 */
3382 continue_status = 0;
3383 continue_status |= CONT_N_ADDS;
3384 initial_pos = curwin->w_cursor;
3385 temp = (int)complete_col;
3386 tmp_ptr = line;
3387 }
3388
3389 /* Work out completion pattern and original text -- webb */
3390 if (ctrl_x_mode == 0 || (ctrl_x_mode & CTRL_X_WANT_IDENT))
3391 {
3392 if ( (continue_status & CONT_SOL)
3393 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3394 {
3395 if (!(continue_status & CONT_ADDING))
3396 {
3397 while (--temp >= 0 && vim_isIDc(line[temp]))
3398 ;
3399 tmp_ptr += ++temp;
3400 temp = complete_col - temp;
3401 }
3402 if (p_ic)
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003403 complete_pat = str_foldcase(tmp_ptr, temp, NULL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003404 else
3405 complete_pat = vim_strnsave(tmp_ptr, temp);
3406 if (complete_pat == NULL)
3407 return FAIL;
3408 }
3409 else if (continue_status & CONT_ADDING)
3410 {
3411 char_u *prefix = (char_u *)"\\<";
3412
3413 /* we need 3 extra chars, 1 for the NUL and
3414 * 2 >= strlen(prefix) -- Acevedo */
3415 complete_pat = alloc(quote_meta(NULL, tmp_ptr, temp) + 3);
3416 if (complete_pat == NULL)
3417 return FAIL;
3418 if (!vim_iswordp(tmp_ptr)
3419 || (tmp_ptr > line
3420 && (
3421#ifdef FEAT_MBYTE
3422 vim_iswordp(mb_prevptr(line, tmp_ptr))
3423#else
3424 vim_iswordc(*(tmp_ptr - 1))
3425#endif
3426 )))
3427 prefix = (char_u *)"";
3428 STRCPY((char *)complete_pat, prefix);
3429 (void)quote_meta(complete_pat + STRLEN(prefix), tmp_ptr, temp);
3430 }
3431 else if (
3432#ifdef FEAT_MBYTE
3433 --temp < 0 || !vim_iswordp(mb_prevptr(line,
3434 line + temp + 1))
3435#else
3436 --temp < 0 || !vim_iswordc(line[temp])
3437#endif
3438 )
3439 {
3440 /* Match any word of at least two chars */
3441 complete_pat = vim_strsave((char_u *)"\\<\\k\\k");
3442 if (complete_pat == NULL)
3443 return FAIL;
3444 tmp_ptr += complete_col;
3445 temp = 0;
3446 }
3447 else
3448 {
3449#ifdef FEAT_MBYTE
3450 /* Search the point of change class of multibyte character
3451 * or not a word single byte character backward. */
3452 if (has_mbyte)
3453 {
3454 int base_class;
3455 int head_off;
3456
3457 temp -= (*mb_head_off)(line, line + temp);
3458 base_class = mb_get_class(line + temp);
3459 while (--temp >= 0)
3460 {
3461 head_off = (*mb_head_off)(line, line + temp);
3462 if (base_class != mb_get_class(line + temp - head_off))
3463 break;
3464 temp -= head_off;
3465 }
3466 }
3467 else
3468#endif
3469 while (--temp >= 0 && vim_iswordc(line[temp]))
3470 ;
3471 tmp_ptr += ++temp;
3472 if ((temp = (int)complete_col - temp) == 1)
3473 {
3474 /* Only match word with at least two chars -- webb
3475 * there's no need to call quote_meta,
3476 * alloc(7) is enough -- Acevedo
3477 */
3478 complete_pat = alloc(7);
3479 if (complete_pat == NULL)
3480 return FAIL;
3481 STRCPY((char *)complete_pat, "\\<");
3482 (void)quote_meta(complete_pat + 2, tmp_ptr, 1);
3483 STRCAT((char *)complete_pat, "\\k");
3484 }
3485 else
3486 {
3487 complete_pat = alloc(quote_meta(NULL, tmp_ptr, temp) + 3);
3488 if (complete_pat == NULL)
3489 return FAIL;
3490 STRCPY((char *)complete_pat, "\\<");
3491 (void)quote_meta(complete_pat + 2, tmp_ptr, temp);
3492 }
3493 }
3494 }
3495 else if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3496 {
3497 tmp_ptr = skipwhite(line);
3498 temp = (int)complete_col - (int)(tmp_ptr - line);
3499 if (temp < 0) /* cursor in indent: empty pattern */
3500 temp = 0;
3501 if (p_ic)
Bram Moolenaar8f999f12005-01-25 22:12:55 +00003502 complete_pat = str_foldcase(tmp_ptr, temp, NULL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 else
3504 complete_pat = vim_strnsave(tmp_ptr, temp);
3505 if (complete_pat == NULL)
3506 return FAIL;
3507 }
3508 else if (ctrl_x_mode == CTRL_X_FILES)
3509 {
3510 while (--temp >= 0 && vim_isfilec(line[temp]))
3511 ;
3512 tmp_ptr += ++temp;
3513 temp = (int)complete_col - temp;
3514 complete_pat = addstar(tmp_ptr, temp, EXPAND_FILES);
3515 if (complete_pat == NULL)
3516 return FAIL;
3517 }
3518 else if (ctrl_x_mode == CTRL_X_CMDLINE)
3519 {
3520 complete_pat = vim_strnsave(line, complete_col);
3521 if (complete_pat == NULL)
3522 return FAIL;
3523 set_cmd_context(&complete_xp, complete_pat,
3524 (int)STRLEN(complete_pat), complete_col);
3525 if (complete_xp.xp_context == EXPAND_UNSUCCESSFUL
3526 || complete_xp.xp_context == EXPAND_NOTHING)
3527 return FAIL;
3528 temp = (int)(complete_xp.xp_pattern - complete_pat);
3529 tmp_ptr = line + temp;
3530 temp = complete_col - temp;
3531 }
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00003532#ifdef FEAT_COMPL_FUNC
3533 else if (ctrl_x_mode == CTRL_X_FUNCTION)
3534 {
3535 /*
3536 * Call user defined function 'completefunc' with line content,
3537 * cursor column number and preproc is 1. Obtain length of text
3538 * to use for completion.
3539 */
3540 char_u *lenstr;
3541 int keeplen = 0;
3542
3543 /* Call 'completefunc' and get pattern length as a string */
3544 lenstr = call_completefunc(line, NULL, complete_col, 1);
3545 if (lenstr == NULL)
3546 return FAIL;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003547 keeplen = atoi((char *)lenstr);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00003548 vim_free(lenstr);
3549 if (keeplen < 0)
3550 return FAIL;
3551 if ((colnr_T)keeplen > complete_col)
3552 keeplen = complete_col;
3553
3554 /* Setup variables for completion */
3555 tmp_ptr = line + keeplen;
3556 temp = complete_col - keeplen;
3557 complete_pat = vim_strnsave(tmp_ptr, temp);
3558 if (complete_pat == NULL)
3559 return FAIL;
3560 }
3561#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562 complete_col = (colnr_T) (tmp_ptr - line);
3563
3564 if (continue_status & CONT_ADDING)
3565 {
3566 edit_submode_pre = (char_u *)_(" Adding");
3567 if (ctrl_x_mode == CTRL_X_WHOLE_LINE)
3568 {
3569 /* Insert a new line, keep indentation but ignore 'comments' */
3570#ifdef FEAT_COMMENTS
3571 char_u *old = curbuf->b_p_com;
3572
3573 curbuf->b_p_com = (char_u *)"";
3574#endif
3575 initial_pos.lnum = curwin->w_cursor.lnum;
3576 initial_pos.col = complete_col;
3577 ins_eol('\r');
3578#ifdef FEAT_COMMENTS
3579 curbuf->b_p_com = old;
3580#endif
3581 tmp_ptr = (char_u *)"";
3582 temp = 0;
3583 complete_col = curwin->w_cursor.col;
3584 }
3585 }
3586 else
3587 {
3588 edit_submode_pre = NULL;
3589 initial_pos.col = complete_col;
3590 }
3591
3592 if (continue_status & CONT_LOCAL)
3593 edit_submode = (char_u *)_(ctrl_x_msgs[2]);
3594 else
3595 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
3596
3597 completion_length = temp;
3598
3599 /* Always add completion for the original text. Note that
3600 * "original_text" itself (not a copy) is added, it will be freed when
3601 * the list of matches is freed. */
3602 if ((original_text = vim_strnsave(tmp_ptr, temp)) == NULL
3603 || ins_compl_add(original_text, -1, NULL, 0, ORIGINAL_TEXT) != OK)
3604 {
3605 vim_free(complete_pat);
3606 complete_pat = NULL;
3607 vim_free(original_text);
3608 return FAIL;
3609 }
3610
3611 /* showmode might reset the internal line pointers, so it must
3612 * be called before line = ml_get(), or when this address is no
3613 * longer needed. -- Acevedo.
3614 */
3615 edit_submode_extra = (char_u *)_("-- Searching...");
3616 edit_submode_highl = HLF_COUNT;
3617 showmode();
3618 edit_submode_extra = NULL;
3619 out_flush();
3620 }
3621
3622 shown_match = curr_match;
3623 shown_direction = complete_direction;
3624
3625 /*
3626 * Find next match.
3627 */
3628 temp = ins_compl_next(TRUE);
3629
3630 if (temp > 1) /* all matches have been found */
3631 completion_matches = temp;
3632 curr_match = shown_match;
3633 complete_direction = shown_direction;
3634 completion_interrupted = FALSE;
3635
3636 /* eat the ESC to avoid leaving insert mode */
3637 if (got_int && !global_busy)
3638 {
3639 (void)vgetc();
3640 got_int = FALSE;
3641 }
3642
3643 /* we found no match if the list has only the original_text-entry */
3644 if (first_match == first_match->next)
3645 {
3646 edit_submode_extra = (continue_status & CONT_ADDING)
3647 && completion_length > 1
3648 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
3649 edit_submode_highl = HLF_E;
3650 /* remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
3651 * because we couldn't expand anything at first place, but if we used
3652 * ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
3653 * (such as M in M'exico) if not tried already. -- Acevedo */
3654 if ( completion_length > 1
3655 || (continue_status & CONT_ADDING)
3656 || (ctrl_x_mode != 0
3657 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
3658 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
3659 continue_status &= ~CONT_N_ADDS;
3660 }
3661
3662 if (curr_match->original & CONT_S_IPOS)
3663 continue_status |= CONT_S_IPOS;
3664 else
3665 continue_status &= ~CONT_S_IPOS;
3666
3667 if (edit_submode_extra == NULL)
3668 {
3669 if (curr_match->original & ORIGINAL_TEXT)
3670 {
3671 edit_submode_extra = (char_u *)_("Back at original");
3672 edit_submode_highl = HLF_W;
3673 }
3674 else if (continue_status & CONT_S_IPOS)
3675 {
3676 edit_submode_extra = (char_u *)_("Word from other line");
3677 edit_submode_highl = HLF_COUNT;
3678 }
3679 else if (curr_match->next == curr_match->prev)
3680 {
3681 edit_submode_extra = (char_u *)_("The only match");
3682 edit_submode_highl = HLF_COUNT;
3683 }
3684 else
3685 {
3686 /* Update completion sequence number when needed. */
3687 if (curr_match->number == -1)
3688 {
3689 int number = 0;
3690 struct Completion *match;
3691
3692 if (complete_direction == FORWARD)
3693 {
3694 /* search backwards for the first valid (!= -1) number.
3695 * This should normally succeed already at the first loop
3696 * cycle, so it's fast! */
3697 for (match = curr_match->prev; match != NULL
3698 && match != first_match; match = match->prev)
3699 if (match->number != -1)
3700 {
3701 number = match->number;
3702 break;
3703 }
3704 if (match != NULL)
3705 /* go up and assign all numbers which are not assigned
3706 * yet */
3707 for (match = match->next; match
3708 && match->number == -1; match = match->next)
3709 match->number = ++number;
3710 }
3711 else /* BACKWARD */
3712 {
3713 /* search forwards (upwards) for the first valid (!= -1)
3714 * number. This should normally succeed already at the
3715 * first loop cycle, so it's fast! */
3716 for (match = curr_match->next; match != NULL
3717 && match != first_match; match = match->next)
3718 if (match->number != -1)
3719 {
3720 number = match->number;
3721 break;
3722 }
3723 if (match != NULL)
3724 /* go down and assign all numbers which are not
3725 * assigned yet */
3726 for (match = match->prev; match
3727 && match->number == -1; match = match->prev)
3728 match->number = ++number;
3729 }
3730 }
3731
3732 /* The match should always have a sequnce number now, this is just
3733 * a safety check. */
3734 if (curr_match->number != -1)
3735 {
3736 /* Space for 10 text chars. + 2x10-digit no.s */
3737 static char_u match_ref[31];
3738
3739 if (completion_matches > 0)
3740 sprintf((char *)IObuff, _("match %d of %d"),
3741 curr_match->number, completion_matches);
3742 else
3743 sprintf((char *)IObuff, _("match %d"), curr_match->number);
3744 STRNCPY(match_ref, IObuff, 30 );
3745 match_ref[30] = '\0';
3746 edit_submode_extra = match_ref;
3747 edit_submode_highl = HLF_R;
3748 if (dollar_vcol)
3749 curs_columns(FALSE);
3750 }
3751 }
3752 }
3753
3754 /* Show a message about what (completion) mode we're in. */
3755 showmode();
3756 if (edit_submode_extra != NULL)
3757 {
3758 if (!p_smd)
3759 msg_attr(edit_submode_extra,
3760 edit_submode_highl < HLF_COUNT
3761 ? hl_attr(edit_submode_highl) : 0);
3762 }
3763 else
3764 msg_clr_cmdline(); /* necessary for "noshowmode" */
3765
3766 return OK;
3767}
3768
3769/*
3770 * Looks in the first "len" chars. of "src" for search-metachars.
3771 * If dest is not NULL the chars. are copied there quoting (with
3772 * a backslash) the metachars, and dest would be NUL terminated.
3773 * Returns the length (needed) of dest
3774 */
3775 static int
3776quote_meta(dest, src, len)
3777 char_u *dest;
3778 char_u *src;
3779 int len;
3780{
3781 int m;
3782
3783 for (m = len; --len >= 0; src++)
3784 {
3785 switch (*src)
3786 {
3787 case '.':
3788 case '*':
3789 case '[':
3790 if (ctrl_x_mode == CTRL_X_DICTIONARY
3791 || ctrl_x_mode == CTRL_X_THESAURUS)
3792 break;
3793 case '~':
3794 if (!p_magic) /* quote these only if magic is set */
3795 break;
3796 case '\\':
3797 if (ctrl_x_mode == CTRL_X_DICTIONARY
3798 || ctrl_x_mode == CTRL_X_THESAURUS)
3799 break;
3800 case '^': /* currently it's not needed. */
3801 case '$':
3802 m++;
3803 if (dest != NULL)
3804 *dest++ = '\\';
3805 break;
3806 }
3807 if (dest != NULL)
3808 *dest++ = *src;
3809#ifdef FEAT_MBYTE
3810 /* Copy remaining bytes of a multibyte character. */
3811 if (has_mbyte)
3812 {
3813 int i, mb_len;
3814
3815 mb_len = (*mb_ptr2len_check)(src) - 1;
3816 if (mb_len > 0 && len >= mb_len)
3817 for (i = 0; i < mb_len; ++i)
3818 {
3819 --len;
3820 ++src;
3821 if (dest != NULL)
3822 *dest++ = *src;
3823 }
3824 }
3825#endif
3826 }
3827 if (dest != NULL)
3828 *dest = NUL;
3829
3830 return m;
3831}
3832#endif /* FEAT_INS_EXPAND */
3833
3834/*
3835 * Next character is interpreted literally.
3836 * A one, two or three digit decimal number is interpreted as its byte value.
3837 * If one or two digits are entered, the next character is given to vungetc().
3838 * For Unicode a character > 255 may be returned.
3839 */
3840 int
3841get_literal()
3842{
3843 int cc;
3844 int nc;
3845 int i;
3846 int hex = FALSE;
3847 int octal = FALSE;
3848#ifdef FEAT_MBYTE
3849 int unicode = 0;
3850#endif
3851
3852 if (got_int)
3853 return Ctrl_C;
3854
3855#ifdef FEAT_GUI
3856 /*
3857 * In GUI there is no point inserting the internal code for a special key.
3858 * It is more useful to insert the string "<KEY>" instead. This would
3859 * probably be useful in a text window too, but it would not be
3860 * vi-compatible (maybe there should be an option for it?) -- webb
3861 */
3862 if (gui.in_use)
3863 ++allow_keys;
3864#endif
3865#ifdef USE_ON_FLY_SCROLL
3866 dont_scroll = TRUE; /* disallow scrolling here */
3867#endif
3868 ++no_mapping; /* don't map the next key hits */
3869 cc = 0;
3870 i = 0;
3871 for (;;)
3872 {
3873 do
3874 nc = safe_vgetc();
3875 while (nc == K_IGNORE || nc == K_VER_SCROLLBAR
3876 || nc == K_HOR_SCROLLBAR);
3877#ifdef FEAT_CMDL_INFO
3878 if (!(State & CMDLINE)
3879# ifdef FEAT_MBYTE
3880 && MB_BYTE2LEN_CHECK(nc) == 1
3881# endif
3882 )
3883 add_to_showcmd(nc);
3884#endif
3885 if (nc == 'x' || nc == 'X')
3886 hex = TRUE;
3887 else if (nc == 'o' || nc == 'O')
3888 octal = TRUE;
3889#ifdef FEAT_MBYTE
3890 else if (nc == 'u' || nc == 'U')
3891 unicode = nc;
3892#endif
3893 else
3894 {
3895 if (hex
3896#ifdef FEAT_MBYTE
3897 || unicode != 0
3898#endif
3899 )
3900 {
3901 if (!vim_isxdigit(nc))
3902 break;
3903 cc = cc * 16 + hex2nr(nc);
3904 }
3905 else if (octal)
3906 {
3907 if (nc < '0' || nc > '7')
3908 break;
3909 cc = cc * 8 + nc - '0';
3910 }
3911 else
3912 {
3913 if (!VIM_ISDIGIT(nc))
3914 break;
3915 cc = cc * 10 + nc - '0';
3916 }
3917
3918 ++i;
3919 }
3920
3921 if (cc > 255
3922#ifdef FEAT_MBYTE
3923 && unicode == 0
3924#endif
3925 )
3926 cc = 255; /* limit range to 0-255 */
3927 nc = 0;
3928
3929 if (hex) /* hex: up to two chars */
3930 {
3931 if (i >= 2)
3932 break;
3933 }
3934#ifdef FEAT_MBYTE
3935 else if (unicode) /* Unicode: up to four or eight chars */
3936 {
3937 if ((unicode == 'u' && i >= 4) || (unicode == 'U' && i >= 8))
3938 break;
3939 }
3940#endif
3941 else if (i >= 3) /* decimal or octal: up to three chars */
3942 break;
3943 }
3944 if (i == 0) /* no number entered */
3945 {
3946 if (nc == K_ZERO) /* NUL is stored as NL */
3947 {
3948 cc = '\n';
3949 nc = 0;
3950 }
3951 else
3952 {
3953 cc = nc;
3954 nc = 0;
3955 }
3956 }
3957
3958 if (cc == 0) /* NUL is stored as NL */
3959 cc = '\n';
Bram Moolenaar217ad922005-03-20 22:37:15 +00003960#ifdef FEAT_MBYTE
3961 if (enc_dbcs && (cc & 0xff) == 0)
3962 cc = '?'; /* don't accept an illegal DBCS char, the NUL in the
3963 second byte will cause trouble! */
3964#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965
3966 --no_mapping;
3967#ifdef FEAT_GUI
3968 if (gui.in_use)
3969 --allow_keys;
3970#endif
3971 if (nc)
3972 vungetc(nc);
3973 got_int = FALSE; /* CTRL-C typed after CTRL-V is not an interrupt */
3974 return cc;
3975}
3976
3977/*
3978 * Insert character, taking care of special keys and mod_mask
3979 */
3980 static void
3981insert_special(c, allow_modmask, ctrlv)
3982 int c;
3983 int allow_modmask;
3984 int ctrlv; /* c was typed after CTRL-V */
3985{
3986 char_u *p;
3987 int len;
3988
3989 /*
3990 * Special function key, translate into "<Key>". Up to the last '>' is
3991 * inserted with ins_str(), so as not to replace characters in replace
3992 * mode.
3993 * Only use mod_mask for special keys, to avoid things like <S-Space>,
3994 * unless 'allow_modmask' is TRUE.
3995 */
3996#ifdef MACOS
3997 /* Command-key never produces a normal key */
3998 if (mod_mask & MOD_MASK_CMD)
3999 allow_modmask = TRUE;
4000#endif
4001 if (IS_SPECIAL(c) || (mod_mask && allow_modmask))
4002 {
4003 p = get_special_key_name(c, mod_mask);
4004 len = (int)STRLEN(p);
4005 c = p[len - 1];
4006 if (len > 2)
4007 {
4008 if (stop_arrow() == FAIL)
4009 return;
4010 p[len - 1] = NUL;
4011 ins_str(p);
4012 AppendToRedobuffLit(p);
4013 ctrlv = FALSE;
4014 }
4015 }
4016 if (stop_arrow() == OK)
4017 insertchar(c, ctrlv ? INSCHAR_CTRLV : 0, -1);
4018}
4019
4020/*
4021 * Special characters in this context are those that need processing other
4022 * than the simple insertion that can be performed here. This includes ESC
4023 * which terminates the insert, and CR/NL which need special processing to
4024 * open up a new line. This routine tries to optimize insertions performed by
4025 * the "redo", "undo" or "put" commands, so it needs to know when it should
4026 * stop and defer processing to the "normal" mechanism.
4027 * '0' and '^' are special, because they can be followed by CTRL-D.
4028 */
4029#ifdef EBCDIC
4030# define ISSPECIAL(c) ((c) < ' ' || (c) == '0' || (c) == '^')
4031#else
4032# define ISSPECIAL(c) ((c) < ' ' || (c) >= DEL || (c) == '0' || (c) == '^')
4033#endif
4034
4035#ifdef FEAT_MBYTE
4036# define WHITECHAR(cc) (vim_iswhite(cc) && (!enc_utf8 || !utf_iscomposing(utf_ptr2char(ml_get_cursor() + 1))))
4037#else
4038# define WHITECHAR(cc) vim_iswhite(cc)
4039#endif
4040
4041 void
4042insertchar(c, flags, second_indent)
4043 int c; /* character to insert or NUL */
4044 int flags; /* INSCHAR_FORMAT, etc. */
4045 int second_indent; /* indent for second line if >= 0 */
4046{
4047 int haveto_redraw = FALSE;
4048 int textwidth;
4049#ifdef FEAT_COMMENTS
4050 colnr_T leader_len;
4051 char_u *p;
4052 int no_leader = FALSE;
4053 int do_comments = (flags & INSCHAR_DO_COM);
4054#endif
4055 int fo_white_par;
4056 int first_line = TRUE;
4057 int fo_ins_blank;
4058#ifdef FEAT_MBYTE
4059 int fo_multibyte;
4060#endif
4061 int save_char = NUL;
4062 int cc;
4063
4064 textwidth = comp_textwidth(flags & INSCHAR_FORMAT);
4065 fo_ins_blank = has_format_option(FO_INS_BLANK);
4066#ifdef FEAT_MBYTE
4067 fo_multibyte = has_format_option(FO_MBYTE_BREAK);
4068#endif
4069 fo_white_par = has_format_option(FO_WHITE_PAR);
4070
4071 /*
4072 * Try to break the line in two or more pieces when:
4073 * - Always do this if we have been called to do formatting only.
4074 * - Always do this when 'formatoptions' has the 'a' flag and the line
4075 * ends in white space.
4076 * - Otherwise:
4077 * - Don't do this if inserting a blank
4078 * - Don't do this if an existing character is being replaced, unless
4079 * we're in VREPLACE mode.
4080 * - Do this if the cursor is not on the line where insert started
4081 * or - 'formatoptions' doesn't have 'l' or the line was not too long
4082 * before the insert.
4083 * - 'formatoptions' doesn't have 'b' or a blank was inserted at or
4084 * before 'textwidth'
4085 */
4086 if (textwidth
4087 && ((flags & INSCHAR_FORMAT)
4088 || (!vim_iswhite(c)
4089 && !((State & REPLACE_FLAG)
4090#ifdef FEAT_VREPLACE
4091 && !(State & VREPLACE_FLAG)
4092#endif
4093 && *ml_get_cursor() != NUL)
4094 && (curwin->w_cursor.lnum != Insstart.lnum
4095 || ((!has_format_option(FO_INS_LONG)
4096 || Insstart_textlen <= (colnr_T)textwidth)
4097 && (!fo_ins_blank
4098 || Insstart_blank_vcol <= (colnr_T)textwidth
4099 ))))))
4100 {
4101 /*
4102 * When 'ai' is off we don't want a space under the cursor to be
4103 * deleted. Replace it with an 'x' temporarily.
4104 */
4105 if (!curbuf->b_p_ai)
4106 {
4107 cc = gchar_cursor();
4108 if (vim_iswhite(cc))
4109 {
4110 save_char = cc;
4111 pchar_cursor('x');
4112 }
4113 }
4114
4115 /*
4116 * Repeat breaking lines, until the current line is not too long.
4117 */
4118 while (!got_int)
4119 {
4120 int startcol; /* Cursor column at entry */
4121 int wantcol; /* column at textwidth border */
4122 int foundcol; /* column for start of spaces */
4123 int end_foundcol = 0; /* column for start of word */
4124 colnr_T len;
4125 colnr_T virtcol;
4126#ifdef FEAT_VREPLACE
4127 int orig_col = 0;
4128 char_u *saved_text = NULL;
4129#endif
4130 colnr_T col;
4131
4132 virtcol = get_nolist_virtcol();
4133 if (virtcol < (colnr_T)textwidth)
4134 break;
4135
4136#ifdef FEAT_COMMENTS
4137 if (no_leader)
4138 do_comments = FALSE;
4139 else if (!(flags & INSCHAR_FORMAT)
4140 && has_format_option(FO_WRAP_COMS))
4141 do_comments = TRUE;
4142
4143 /* Don't break until after the comment leader */
4144 if (do_comments)
4145 leader_len = get_leader_len(ml_get_curline(), NULL, FALSE);
4146 else
4147 leader_len = 0;
4148
4149 /* If the line doesn't start with a comment leader, then don't
4150 * start one in a following broken line. Avoids that a %word
4151 * moved to the start of the next line causes all following lines
4152 * to start with %. */
4153 if (leader_len == 0)
4154 no_leader = TRUE;
4155#endif
4156 if (!(flags & INSCHAR_FORMAT)
4157#ifdef FEAT_COMMENTS
4158 && leader_len == 0
4159#endif
4160 && !has_format_option(FO_WRAP))
4161
4162 {
4163 textwidth = 0;
4164 break;
4165 }
4166 if ((startcol = curwin->w_cursor.col) == 0)
4167 break;
4168
4169 /* find column of textwidth border */
4170 coladvance((colnr_T)textwidth);
4171 wantcol = curwin->w_cursor.col;
4172
4173 curwin->w_cursor.col = startcol - 1;
4174#ifdef FEAT_MBYTE
4175 /* Correct cursor for multi-byte character. */
4176 if (has_mbyte)
4177 mb_adjust_cursor();
4178#endif
4179 foundcol = 0;
4180
4181 /*
4182 * Find position to break at.
4183 * Stop at first entered white when 'formatoptions' has 'v'
4184 */
4185 while ((!fo_ins_blank && !has_format_option(FO_INS_VI))
4186 || curwin->w_cursor.lnum != Insstart.lnum
4187 || curwin->w_cursor.col >= Insstart.col)
4188 {
4189 cc = gchar_cursor();
4190 if (WHITECHAR(cc))
4191 {
4192 /* remember position of blank just before text */
4193 end_foundcol = curwin->w_cursor.col;
4194
4195 /* find start of sequence of blanks */
4196 while (curwin->w_cursor.col > 0 && WHITECHAR(cc))
4197 {
4198 dec_cursor();
4199 cc = gchar_cursor();
4200 }
4201 if (curwin->w_cursor.col == 0 && WHITECHAR(cc))
4202 break; /* only spaces in front of text */
4203#ifdef FEAT_COMMENTS
4204 /* Don't break until after the comment leader */
4205 if (curwin->w_cursor.col < leader_len)
4206 break;
4207#endif
4208 if (has_format_option(FO_ONE_LETTER))
4209 {
4210 /* do not break after one-letter words */
4211 if (curwin->w_cursor.col == 0)
4212 break; /* one-letter word at begin */
4213
4214 col = curwin->w_cursor.col;
4215 dec_cursor();
4216 cc = gchar_cursor();
4217
4218 if (WHITECHAR(cc))
4219 continue; /* one-letter, continue */
4220 curwin->w_cursor.col = col;
4221 }
4222#ifdef FEAT_MBYTE
4223 if (has_mbyte)
4224 foundcol = curwin->w_cursor.col
4225 + (*mb_ptr2len_check)(ml_get_cursor());
4226 else
4227#endif
4228 foundcol = curwin->w_cursor.col + 1;
4229 if (curwin->w_cursor.col < (colnr_T)wantcol)
4230 break;
4231 }
4232#ifdef FEAT_MBYTE
4233 else if (cc >= 0x100 && fo_multibyte
4234 && curwin->w_cursor.col <= (colnr_T)wantcol)
4235 {
4236 /* Break after or before a multi-byte character. */
4237 foundcol = curwin->w_cursor.col;
4238 if (curwin->w_cursor.col < (colnr_T)wantcol)
4239 foundcol += (*mb_char2len)(cc);
4240 end_foundcol = foundcol;
4241 break;
4242 }
4243#endif
4244 if (curwin->w_cursor.col == 0)
4245 break;
4246 dec_cursor();
4247 }
4248
4249 if (foundcol == 0) /* no spaces, cannot break line */
4250 {
4251 curwin->w_cursor.col = startcol;
4252 break;
4253 }
4254
4255 /* Going to break the line, remove any "$" now. */
4256 undisplay_dollar();
4257
4258 /*
4259 * Offset between cursor position and line break is used by replace
4260 * stack functions. VREPLACE does not use this, and backspaces
4261 * over the text instead.
4262 */
4263#ifdef FEAT_VREPLACE
4264 if (State & VREPLACE_FLAG)
4265 orig_col = startcol; /* Will start backspacing from here */
4266 else
4267#endif
4268 replace_offset = startcol - end_foundcol - 1;
4269
4270 /*
4271 * adjust startcol for spaces that will be deleted and
4272 * characters that will remain on top line
4273 */
4274 curwin->w_cursor.col = foundcol;
4275 while (cc = gchar_cursor(), WHITECHAR(cc))
4276 inc_cursor();
4277 startcol -= curwin->w_cursor.col;
4278 if (startcol < 0)
4279 startcol = 0;
4280
4281#ifdef FEAT_VREPLACE
4282 if (State & VREPLACE_FLAG)
4283 {
4284 /*
4285 * In VREPLACE mode, we will backspace over the text to be
4286 * wrapped, so save a copy now to put on the next line.
4287 */
4288 saved_text = vim_strsave(ml_get_cursor());
4289 curwin->w_cursor.col = orig_col;
4290 if (saved_text == NULL)
4291 break; /* Can't do it, out of memory */
4292 saved_text[startcol] = NUL;
4293
4294 /* Backspace over characters that will move to the next line */
4295 if (!fo_white_par)
4296 backspace_until_column(foundcol);
4297 }
4298 else
4299#endif
4300 {
4301 /* put cursor after pos. to break line */
4302 if (!fo_white_par)
4303 curwin->w_cursor.col = foundcol;
4304 }
4305
4306 /*
4307 * Split the line just before the margin.
4308 * Only insert/delete lines, but don't really redraw the window.
4309 */
4310 open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
4311 + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
4312#ifdef FEAT_COMMENTS
4313 + (do_comments ? OPENLINE_DO_COM : 0)
4314#endif
4315 , old_indent);
4316 old_indent = 0;
4317
4318 replace_offset = 0;
4319 if (first_line)
4320 {
4321 if (second_indent < 0 && has_format_option(FO_Q_NUMBER))
4322 second_indent = get_number_indent(curwin->w_cursor.lnum -1);
4323 if (second_indent >= 0)
4324 {
4325#ifdef FEAT_VREPLACE
4326 if (State & VREPLACE_FLAG)
4327 change_indent(INDENT_SET, second_indent, FALSE, NUL);
4328 else
4329#endif
4330 (void)set_indent(second_indent, SIN_CHANGED);
4331 }
4332 first_line = FALSE;
4333 }
4334
4335#ifdef FEAT_VREPLACE
4336 if (State & VREPLACE_FLAG)
4337 {
4338 /*
4339 * In VREPLACE mode we have backspaced over the text to be
4340 * moved, now we re-insert it into the new line.
4341 */
4342 ins_bytes(saved_text);
4343 vim_free(saved_text);
4344 }
4345 else
4346#endif
4347 {
4348 /*
4349 * Check if cursor is not past the NUL off the line, cindent
4350 * may have added or removed indent.
4351 */
4352 curwin->w_cursor.col += startcol;
4353 len = (colnr_T)STRLEN(ml_get_curline());
4354 if (curwin->w_cursor.col > len)
4355 curwin->w_cursor.col = len;
4356 }
4357
4358 haveto_redraw = TRUE;
4359#ifdef FEAT_CINDENT
4360 can_cindent = TRUE;
4361#endif
4362 /* moved the cursor, don't autoindent or cindent now */
4363 did_ai = FALSE;
4364#ifdef FEAT_SMARTINDENT
4365 did_si = FALSE;
4366 can_si = FALSE;
4367 can_si_back = FALSE;
4368#endif
4369 line_breakcheck();
4370 }
4371
4372 if (save_char) /* put back space after cursor */
4373 pchar_cursor(save_char);
4374
4375 if (c == NUL) /* formatting only */
4376 return;
4377 if (haveto_redraw)
4378 {
4379 update_topline();
4380 redraw_curbuf_later(VALID);
4381 }
4382 }
4383 if (c == NUL) /* only formatting was wanted */
4384 return;
4385
4386#ifdef FEAT_COMMENTS
4387 /* Check whether this character should end a comment. */
4388 if (did_ai && (int)c == end_comment_pending)
4389 {
4390 char_u *line;
4391 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
4392 int middle_len, end_len;
4393 int i;
4394
4395 /*
4396 * Need to remove existing (middle) comment leader and insert end
4397 * comment leader. First, check what comment leader we can find.
4398 */
4399 i = get_leader_len(line = ml_get_curline(), &p, FALSE);
4400 if (i > 0 && vim_strchr(p, COM_MIDDLE) != NULL) /* Just checking */
4401 {
4402 /* Skip middle-comment string */
4403 while (*p && p[-1] != ':') /* find end of middle flags */
4404 ++p;
4405 middle_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
4406 /* Don't count trailing white space for middle_len */
4407 while (middle_len > 0 && vim_iswhite(lead_end[middle_len - 1]))
4408 --middle_len;
4409
4410 /* Find the end-comment string */
4411 while (*p && p[-1] != ':') /* find end of end flags */
4412 ++p;
4413 end_len = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
4414
4415 /* Skip white space before the cursor */
4416 i = curwin->w_cursor.col;
4417 while (--i >= 0 && vim_iswhite(line[i]))
4418 ;
4419 i++;
4420
4421 /* Skip to before the middle leader */
4422 i -= middle_len;
4423
4424 /* Check some expected things before we go on */
4425 if (i >= 0 && lead_end[end_len - 1] == end_comment_pending)
4426 {
4427 /* Backspace over all the stuff we want to replace */
4428 backspace_until_column(i);
4429
4430 /*
4431 * Insert the end-comment string, except for the last
4432 * character, which will get inserted as normal later.
4433 */
4434 ins_bytes_len(lead_end, end_len - 1);
4435 }
4436 }
4437 }
4438 end_comment_pending = NUL;
4439#endif
4440
4441 did_ai = FALSE;
4442#ifdef FEAT_SMARTINDENT
4443 did_si = FALSE;
4444 can_si = FALSE;
4445 can_si_back = FALSE;
4446#endif
4447
4448 /*
4449 * If there's any pending input, grab up to INPUT_BUFLEN at once.
4450 * This speeds up normal text input considerably.
4451 * Don't do this when 'cindent' or 'indentexpr' is set, because we might
4452 * need to re-indent at a ':', or any other character (but not what
4453 * 'paste' is set)..
4454 */
4455#ifdef USE_ON_FLY_SCROLL
4456 dont_scroll = FALSE; /* allow scrolling here */
4457#endif
4458
4459 if ( !ISSPECIAL(c)
4460#ifdef FEAT_MBYTE
4461 && (!has_mbyte || (*mb_char2len)(c) == 1)
4462#endif
4463 && vpeekc() != NUL
4464 && !(State & REPLACE_FLAG)
4465#ifdef FEAT_CINDENT
4466 && !cindent_on()
4467#endif
4468#ifdef FEAT_RIGHTLEFT
4469 && !p_ri
4470#endif
4471 )
4472 {
4473#define INPUT_BUFLEN 100
4474 char_u buf[INPUT_BUFLEN + 1];
4475 int i;
4476 colnr_T virtcol = 0;
4477
4478 buf[0] = c;
4479 i = 1;
4480 if (textwidth)
4481 virtcol = get_nolist_virtcol();
4482 /*
4483 * Stop the string when:
4484 * - no more chars available
4485 * - finding a special character (command key)
4486 * - buffer is full
4487 * - running into the 'textwidth' boundary
4488 * - need to check for abbreviation: A non-word char after a word-char
4489 */
4490 while ( (c = vpeekc()) != NUL
4491 && !ISSPECIAL(c)
4492#ifdef FEAT_MBYTE
4493 && (!has_mbyte || MB_BYTE2LEN_CHECK(c) == 1)
4494#endif
4495 && i < INPUT_BUFLEN
4496 && (textwidth == 0
4497 || (virtcol += byte2cells(buf[i - 1])) < (colnr_T)textwidth)
4498 && !(!no_abbr && !vim_iswordc(c) && vim_iswordc(buf[i - 1])))
4499 {
4500#ifdef FEAT_RIGHTLEFT
4501 c = vgetc();
4502 if (p_hkmap && KeyTyped)
4503 c = hkmap(c); /* Hebrew mode mapping */
4504# ifdef FEAT_FKMAP
4505 if (p_fkmap && KeyTyped)
4506 c = fkmap(c); /* Farsi mode mapping */
4507# endif
4508 buf[i++] = c;
4509#else
4510 buf[i++] = vgetc();
4511#endif
4512 }
4513
4514#ifdef FEAT_DIGRAPHS
4515 do_digraph(-1); /* clear digraphs */
4516 do_digraph(buf[i-1]); /* may be the start of a digraph */
4517#endif
4518 buf[i] = NUL;
4519 ins_str(buf);
4520 if (flags & INSCHAR_CTRLV)
4521 {
4522 redo_literal(*buf);
4523 i = 1;
4524 }
4525 else
4526 i = 0;
4527 if (buf[i] != NUL)
4528 AppendToRedobuffLit(buf + i);
4529 }
4530 else
4531 {
4532#ifdef FEAT_MBYTE
4533 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
4534 {
4535 char_u buf[MB_MAXBYTES + 1];
4536
4537 (*mb_char2bytes)(c, buf);
4538 buf[cc] = NUL;
4539 ins_char_bytes(buf, cc);
4540 AppendCharToRedobuff(c);
4541 }
4542 else
4543#endif
4544 {
4545 ins_char(c);
4546 if (flags & INSCHAR_CTRLV)
4547 redo_literal(c);
4548 else
4549 AppendCharToRedobuff(c);
4550 }
4551 }
4552}
4553
4554/*
4555 * Called after inserting or deleting text: When 'formatoptions' includes the
4556 * 'a' flag format from the current line until the end of the paragraph.
4557 * Keep the cursor at the same position relative to the text.
4558 * The caller must have saved the cursor line for undo, following ones will be
4559 * saved here.
4560 */
4561 void
4562auto_format(trailblank, prev_line)
4563 int trailblank; /* when TRUE also format with trailing blank */
4564 int prev_line; /* may start in previous line */
4565{
4566 pos_T pos;
4567 colnr_T len;
4568 char_u *old;
4569 char_u *new, *pnew;
4570 int wasatend;
Bram Moolenaar75c50c42005-06-04 22:06:24 +00004571 int cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572
4573 if (!has_format_option(FO_AUTO))
4574 return;
4575
4576 pos = curwin->w_cursor;
4577 old = ml_get_curline();
4578
4579 /* may remove added space */
4580 check_auto_format(FALSE);
4581
4582 /* Don't format in Insert mode when the cursor is on a trailing blank, the
4583 * user might insert normal text next. Also skip formatting when "1" is
4584 * in 'formatoptions' and there is a single character before the cursor.
4585 * Otherwise the line would be broken and when typing another non-white
4586 * next they are not joined back together. */
4587 wasatend = (pos.col == STRLEN(old));
4588 if (*old != NUL && !trailblank && wasatend)
4589 {
4590 dec_cursor();
Bram Moolenaar75c50c42005-06-04 22:06:24 +00004591 cc = gchar_cursor();
4592 if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
4593 && has_format_option(FO_ONE_LETTER))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004594 dec_cursor();
Bram Moolenaar75c50c42005-06-04 22:06:24 +00004595 cc = gchar_cursor();
4596 if (WHITECHAR(cc))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597 {
4598 curwin->w_cursor = pos;
4599 return;
4600 }
4601 curwin->w_cursor = pos;
4602 }
4603
4604#ifdef FEAT_COMMENTS
4605 /* With the 'c' flag in 'formatoptions' and 't' missing: only format
4606 * comments. */
4607 if (has_format_option(FO_WRAP_COMS) && !has_format_option(FO_WRAP)
4608 && get_leader_len(old, NULL, FALSE) == 0)
4609 return;
4610#endif
4611
4612 /*
4613 * May start formatting in a previous line, so that after "x" a word is
4614 * moved to the previous line if it fits there now. Only when this is not
4615 * the start of a paragraph.
4616 */
4617 if (prev_line && !paragraph_start(curwin->w_cursor.lnum))
4618 {
4619 --curwin->w_cursor.lnum;
4620 if (u_save_cursor() == FAIL)
4621 return;
4622 }
4623
4624 /*
4625 * Do the formatting and restore the cursor position. "saved_cursor" will
4626 * be adjusted for the text formatting.
4627 */
4628 saved_cursor = pos;
4629 format_lines((linenr_T)-1);
4630 curwin->w_cursor = saved_cursor;
4631 saved_cursor.lnum = 0;
4632
4633 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
4634 {
4635 /* "cannot happen" */
4636 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4637 coladvance((colnr_T)MAXCOL);
4638 }
4639 else
4640 check_cursor_col();
4641
4642 /* Insert mode: If the cursor is now after the end of the line while it
4643 * previously wasn't, the line was broken. Because of the rule above we
4644 * need to add a space when 'w' is in 'formatoptions' to keep a paragraph
4645 * formatted. */
4646 if (!wasatend && has_format_option(FO_WHITE_PAR))
4647 {
4648 new = ml_get_curline();
4649 len = STRLEN(new);
4650 if (curwin->w_cursor.col == len)
4651 {
4652 pnew = vim_strnsave(new, len + 2);
4653 pnew[len] = ' ';
4654 pnew[len + 1] = NUL;
4655 ml_replace(curwin->w_cursor.lnum, pnew, FALSE);
4656 /* remove the space later */
4657 did_add_space = TRUE;
4658 }
4659 else
4660 /* may remove added space */
4661 check_auto_format(FALSE);
4662 }
4663
4664 check_cursor();
4665}
4666
4667/*
4668 * When an extra space was added to continue a paragraph for auto-formatting,
4669 * delete it now. The space must be under the cursor, just after the insert
4670 * position.
4671 */
4672 static void
4673check_auto_format(end_insert)
4674 int end_insert; /* TRUE when ending Insert mode */
4675{
4676 int c = ' ';
Bram Moolenaar75c50c42005-06-04 22:06:24 +00004677 int cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678
4679 if (did_add_space)
4680 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +00004681 cc = gchar_cursor();
4682 if (!WHITECHAR(cc))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 /* Somehow the space was removed already. */
4684 did_add_space = FALSE;
4685 else
4686 {
4687 if (!end_insert)
4688 {
4689 inc_cursor();
4690 c = gchar_cursor();
4691 dec_cursor();
4692 }
4693 if (c != NUL)
4694 {
4695 /* The space is no longer at the end of the line, delete it. */
4696 del_char(FALSE);
4697 did_add_space = FALSE;
4698 }
4699 }
4700 }
4701}
4702
4703/*
4704 * Find out textwidth to be used for formatting:
4705 * if 'textwidth' option is set, use it
4706 * else if 'wrapmargin' option is set, use W_WIDTH(curwin) - 'wrapmargin'
4707 * if invalid value, use 0.
4708 * Set default to window width (maximum 79) for "gq" operator.
4709 */
4710 int
4711comp_textwidth(ff)
4712 int ff; /* force formatting (for "Q" command) */
4713{
4714 int textwidth;
4715
4716 textwidth = curbuf->b_p_tw;
4717 if (textwidth == 0 && curbuf->b_p_wm)
4718 {
4719 /* The width is the window width minus 'wrapmargin' minus all the
4720 * things that add to the margin. */
4721 textwidth = W_WIDTH(curwin) - curbuf->b_p_wm;
4722#ifdef FEAT_CMDWIN
4723 if (cmdwin_type != 0)
4724 textwidth -= 1;
4725#endif
4726#ifdef FEAT_FOLDING
4727 textwidth -= curwin->w_p_fdc;
4728#endif
4729#ifdef FEAT_SIGNS
4730 if (curwin->w_buffer->b_signlist != NULL
4731# ifdef FEAT_NETBEANS_INTG
4732 || usingNetbeans
4733# endif
4734 )
4735 textwidth -= 1;
4736#endif
4737 if (curwin->w_p_nu)
4738 textwidth -= 8;
4739 }
4740 if (textwidth < 0)
4741 textwidth = 0;
4742 if (ff && textwidth == 0)
4743 {
4744 textwidth = W_WIDTH(curwin) - 1;
4745 if (textwidth > 79)
4746 textwidth = 79;
4747 }
4748 return textwidth;
4749}
4750
4751/*
4752 * Put a character in the redo buffer, for when just after a CTRL-V.
4753 */
4754 static void
4755redo_literal(c)
4756 int c;
4757{
4758 char_u buf[10];
4759
4760 /* Only digits need special treatment. Translate them into a string of
4761 * three digits. */
4762 if (VIM_ISDIGIT(c))
4763 {
4764 sprintf((char *)buf, "%03d", c);
4765 AppendToRedobuff(buf);
4766 }
4767 else
4768 AppendCharToRedobuff(c);
4769}
4770
4771/*
4772 * start_arrow() is called when an arrow key is used in insert mode.
4773 * It resembles hitting the <ESC> key.
4774 */
4775 static void
4776start_arrow(end_insert_pos)
4777 pos_T *end_insert_pos;
4778{
4779 if (!arrow_used) /* something has been inserted */
4780 {
4781 AppendToRedobuff(ESC_STR);
4782 stop_insert(end_insert_pos, FALSE);
4783 arrow_used = TRUE; /* this means we stopped the current insert */
4784 }
Bram Moolenaar217ad922005-03-20 22:37:15 +00004785#ifdef FEAT_SYN_HL
4786 check_spell_redraw();
4787#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788}
4789
Bram Moolenaar217ad922005-03-20 22:37:15 +00004790#ifdef FEAT_SYN_HL
4791/*
4792 * If we skipped highlighting word at cursor, do it now.
4793 * It may be skipped again, thus reset spell_redraw_lnum first.
4794 */
4795 static void
4796check_spell_redraw()
4797{
4798 if (spell_redraw_lnum != 0)
4799 {
4800 linenr_T lnum = spell_redraw_lnum;
4801
4802 spell_redraw_lnum = 0;
4803 redrawWinline(lnum, FALSE);
4804 }
4805}
4806#endif
4807
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808/*
4809 * stop_arrow() is called before a change is made in insert mode.
4810 * If an arrow key has been used, start a new insertion.
4811 * Returns FAIL if undo is impossible, shouldn't insert then.
4812 */
4813 int
4814stop_arrow()
4815{
4816 if (arrow_used)
4817 {
4818 if (u_save_cursor() == OK)
4819 {
4820 arrow_used = FALSE;
4821 ins_need_undo = FALSE;
4822 }
4823 Insstart = curwin->w_cursor; /* new insertion starts here */
4824 Insstart_textlen = linetabsize(ml_get_curline());
4825 ai_col = 0;
4826#ifdef FEAT_VREPLACE
4827 if (State & VREPLACE_FLAG)
4828 {
4829 orig_line_count = curbuf->b_ml.ml_line_count;
4830 vr_lines_changed = 1;
4831 }
4832#endif
4833 ResetRedobuff();
4834 AppendToRedobuff((char_u *)"1i"); /* pretend we start an insertion */
4835 }
4836 else if (ins_need_undo)
4837 {
4838 if (u_save_cursor() == OK)
4839 ins_need_undo = FALSE;
4840 }
4841
4842#ifdef FEAT_FOLDING
4843 /* Always open fold at the cursor line when inserting something. */
4844 foldOpenCursor();
4845#endif
4846
4847 return (arrow_used || ins_need_undo ? FAIL : OK);
4848}
4849
4850/*
4851 * do a few things to stop inserting
4852 */
4853 static void
4854stop_insert(end_insert_pos, esc)
4855 pos_T *end_insert_pos; /* where insert ended */
4856 int esc; /* called by ins_esc() */
4857{
4858 int cc;
4859
4860 stop_redo_ins();
4861 replace_flush(); /* abandon replace stack */
4862
4863 /*
4864 * save the inserted text for later redo with ^@
4865 */
4866 vim_free(last_insert);
4867 last_insert = get_inserted();
4868 last_insert_skip = new_insert_skip;
4869
4870 if (!arrow_used)
4871 {
4872 /* Auto-format now. It may seem strange to do this when stopping an
4873 * insertion (or moving the cursor), but it's required when appending
4874 * a line and having it end in a space. But only do it when something
4875 * was actually inserted, otherwise undo won't work. */
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004876 if (!ins_need_undo && has_format_option(FO_AUTO))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 {
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004878 pos_T tpos = curwin->w_cursor;
4879
Bram Moolenaar071d4272004-06-13 20:20:40 +00004880 /* When the cursor is at the end of the line after a space the
4881 * formatting will move it to the following word. Avoid that by
4882 * moving the cursor onto the space. */
4883 cc = 'x';
4884 if (curwin->w_cursor.col > 0 && gchar_cursor() == NUL)
4885 {
4886 dec_cursor();
4887 cc = gchar_cursor();
4888 if (!vim_iswhite(cc))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004889 curwin->w_cursor = tpos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 }
4891
4892 auto_format(TRUE, FALSE);
4893
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004894 if (vim_iswhite(cc))
4895 {
4896 if (gchar_cursor() != NUL)
4897 inc_cursor();
4898#ifdef FEAT_VIRTUALEDIT
4899 /* If the cursor is still at the same character, also keep
4900 * the "coladd". */
4901 if (gchar_cursor() == NUL
4902 && curwin->w_cursor.lnum == tpos.lnum
4903 && curwin->w_cursor.col == tpos.col)
4904 curwin->w_cursor.coladd = tpos.coladd;
4905#endif
4906 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907 }
4908
4909 /* If a space was inserted for auto-formatting, remove it now. */
4910 check_auto_format(TRUE);
4911
4912 /* If we just did an auto-indent, remove the white space from the end
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004913 * of the line, and put the cursor back.
4914 * Do this when ESC was used or moving the cursor up/down. */
4915 if (did_ai && (esc || (vim_strchr(p_cpo, CPO_INDENT) == NULL
4916 && curwin->w_cursor.lnum != end_insert_pos->lnum)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917 {
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004918 pos_T tpos = curwin->w_cursor;
4919
4920 curwin->w_cursor = *end_insert_pos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921 if (gchar_cursor() == NUL && curwin->w_cursor.col > 0)
4922 --curwin->w_cursor.col;
4923 while (cc = gchar_cursor(), vim_iswhite(cc))
4924 (void)del_char(TRUE);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004925 if (curwin->w_cursor.lnum != tpos.lnum)
4926 curwin->w_cursor = tpos;
4927 else if (cc != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 ++curwin->w_cursor.col; /* put cursor back on the NUL */
4929
4930#ifdef FEAT_VISUAL
4931 /* <C-S-Right> may have started Visual mode, adjust the position for
4932 * deleted characters. */
4933 if (VIsual_active && VIsual.lnum == curwin->w_cursor.lnum)
4934 {
4935 cc = STRLEN(ml_get_curline());
4936 if (VIsual.col > (colnr_T)cc)
4937 {
4938 VIsual.col = cc;
4939# ifdef FEAT_VIRTUALEDIT
4940 VIsual.coladd = 0;
4941# endif
4942 }
4943 }
4944#endif
4945 }
4946 }
4947 did_ai = FALSE;
4948#ifdef FEAT_SMARTINDENT
4949 did_si = FALSE;
4950 can_si = FALSE;
4951 can_si_back = FALSE;
4952#endif
4953
4954 /* set '[ and '] to the inserted text */
4955 curbuf->b_op_start = Insstart;
4956 curbuf->b_op_end = *end_insert_pos;
4957}
4958
4959/*
4960 * Set the last inserted text to a single character.
4961 * Used for the replace command.
4962 */
4963 void
4964set_last_insert(c)
4965 int c;
4966{
4967 char_u *s;
4968
4969 vim_free(last_insert);
4970#ifdef FEAT_MBYTE
4971 last_insert = alloc(MB_MAXBYTES * 3 + 5);
4972#else
4973 last_insert = alloc(6);
4974#endif
4975 if (last_insert != NULL)
4976 {
4977 s = last_insert;
4978 /* Use the CTRL-V only when entering a special char */
4979 if (c < ' ' || c == DEL)
4980 *s++ = Ctrl_V;
4981 s = add_char2buf(c, s);
4982 *s++ = ESC;
4983 *s++ = NUL;
4984 last_insert_skip = 0;
4985 }
4986}
4987
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00004988#if defined(EXITFREE) || defined(PROTO)
4989 void
4990free_last_insert()
4991{
4992 vim_free(last_insert);
4993 last_insert = NULL;
4994}
4995#endif
4996
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997/*
4998 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
4999 * and CSI. Handle multi-byte characters.
5000 * Returns a pointer to after the added bytes.
5001 */
5002 char_u *
5003add_char2buf(c, s)
5004 int c;
5005 char_u *s;
5006{
5007#ifdef FEAT_MBYTE
5008 char_u temp[MB_MAXBYTES];
5009 int i;
5010 int len;
5011
5012 len = (*mb_char2bytes)(c, temp);
5013 for (i = 0; i < len; ++i)
5014 {
5015 c = temp[i];
5016#endif
5017 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
5018 if (c == K_SPECIAL)
5019 {
5020 *s++ = K_SPECIAL;
5021 *s++ = KS_SPECIAL;
5022 *s++ = KE_FILLER;
5023 }
5024#ifdef FEAT_GUI
5025 else if (c == CSI)
5026 {
5027 *s++ = CSI;
5028 *s++ = KS_EXTRA;
5029 *s++ = (int)KE_CSI;
5030 }
5031#endif
5032 else
5033 *s++ = c;
5034#ifdef FEAT_MBYTE
5035 }
5036#endif
5037 return s;
5038}
5039
5040/*
5041 * move cursor to start of line
5042 * if flags & BL_WHITE move to first non-white
5043 * if flags & BL_SOL move to first non-white if startofline is set,
5044 * otherwise keep "curswant" column
5045 * if flags & BL_FIX don't leave the cursor on a NUL.
5046 */
5047 void
5048beginline(flags)
5049 int flags;
5050{
5051 if ((flags & BL_SOL) && !p_sol)
5052 coladvance(curwin->w_curswant);
5053 else
5054 {
5055 curwin->w_cursor.col = 0;
5056#ifdef FEAT_VIRTUALEDIT
5057 curwin->w_cursor.coladd = 0;
5058#endif
5059
5060 if (flags & (BL_WHITE | BL_SOL))
5061 {
5062 char_u *ptr;
5063
5064 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
5065 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
5066 ++curwin->w_cursor.col;
5067 }
5068 curwin->w_set_curswant = TRUE;
5069 }
5070}
5071
5072/*
5073 * oneright oneleft cursor_down cursor_up
5074 *
5075 * Move one char {right,left,down,up}.
5076 * Doesn't move onto the NUL past the end of the line.
5077 * Return OK when successful, FAIL when we hit a line of file boundary.
5078 */
5079
5080 int
5081oneright()
5082{
5083 char_u *ptr;
5084#ifdef FEAT_MBYTE
5085 int l;
5086#endif
5087
5088#ifdef FEAT_VIRTUALEDIT
5089 if (virtual_active())
5090 {
5091 pos_T prevpos = curwin->w_cursor;
5092
5093 /* Adjust for multi-wide char (excluding TAB) */
5094 ptr = ml_get_cursor();
5095 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
5096#ifdef FEAT_MBYTE
5097 (*mb_ptr2char)(ptr)
5098#else
5099 *ptr
5100#endif
5101 ))
5102 ? ptr2cells(ptr) : 1));
5103 curwin->w_set_curswant = TRUE;
5104 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
5105 return (prevpos.col != curwin->w_cursor.col
5106 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
5107 }
5108#endif
5109
5110 ptr = ml_get_cursor();
5111#ifdef FEAT_MBYTE
5112 if (has_mbyte && (l = (*mb_ptr2len_check)(ptr)) > 1)
5113 {
5114 /* The character under the cursor is a multi-byte character, move
5115 * several bytes right, but don't end up on the NUL. */
5116 if (ptr[l] == NUL)
5117 return FAIL;
5118 curwin->w_cursor.col += l;
5119 }
5120 else
5121#endif
5122 {
5123 if (*ptr++ == NUL || *ptr == NUL)
5124 return FAIL;
5125 ++curwin->w_cursor.col;
5126 }
5127
5128 curwin->w_set_curswant = TRUE;
5129 return OK;
5130}
5131
5132 int
5133oneleft()
5134{
5135#ifdef FEAT_VIRTUALEDIT
5136 if (virtual_active())
5137 {
5138 int width;
5139 int v = getviscol();
5140
5141 if (v == 0)
5142 return FAIL;
5143
5144# ifdef FEAT_LINEBREAK
5145 /* We might get stuck on 'showbreak', skip over it. */
5146 width = 1;
5147 for (;;)
5148 {
5149 coladvance(v - width);
5150 /* getviscol() is slow, skip it when 'showbreak' is empty and
5151 * there are no multi-byte characters */
5152 if ((*p_sbr == NUL
5153# ifdef FEAT_MBYTE
5154 && !has_mbyte
5155# endif
5156 ) || getviscol() < v)
5157 break;
5158 ++width;
5159 }
5160# else
5161 coladvance(v - 1);
5162# endif
5163
5164 if (curwin->w_cursor.coladd == 1)
5165 {
5166 char_u *ptr;
5167
5168 /* Adjust for multi-wide char (not a TAB) */
5169 ptr = ml_get_cursor();
5170 if (*ptr != TAB && vim_isprintc(
5171# ifdef FEAT_MBYTE
5172 (*mb_ptr2char)(ptr)
5173# else
5174 *ptr
5175# endif
5176 ) && ptr2cells(ptr) > 1)
5177 curwin->w_cursor.coladd = 0;
5178 }
5179
5180 curwin->w_set_curswant = TRUE;
5181 return OK;
5182 }
5183#endif
5184
5185 if (curwin->w_cursor.col == 0)
5186 return FAIL;
5187
5188 curwin->w_set_curswant = TRUE;
5189 --curwin->w_cursor.col;
5190
5191#ifdef FEAT_MBYTE
5192 /* if the character on the left of the current cursor is a multi-byte
5193 * character, move to its first byte */
5194 if (has_mbyte)
5195 mb_adjust_cursor();
5196#endif
5197 return OK;
5198}
5199
5200 int
5201cursor_up(n, upd_topline)
5202 long n;
5203 int upd_topline; /* When TRUE: update topline */
5204{
5205 linenr_T lnum;
5206
5207 if (n > 0)
5208 {
5209 lnum = curwin->w_cursor.lnum;
Bram Moolenaar7c626922005-02-07 22:01:03 +00005210 /* This fails if the cursor is already in the first line or the count
5211 * is larger than the line number and '-' is in 'cpoptions' */
5212 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 return FAIL;
5214 if (n >= lnum)
5215 lnum = 1;
5216 else
5217#ifdef FEAT_FOLDING
5218 if (hasAnyFolding(curwin))
5219 {
5220 /*
5221 * Count each sequence of folded lines as one logical line.
5222 */
5223 /* go to the the start of the current fold */
5224 (void)hasFolding(lnum, &lnum, NULL);
5225
5226 while (n--)
5227 {
5228 /* move up one line */
5229 --lnum;
5230 if (lnum <= 1)
5231 break;
5232 /* If we entered a fold, move to the beginning, unless in
5233 * Insert mode or when 'foldopen' contains "all": it will open
5234 * in a moment. */
5235 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
5236 (void)hasFolding(lnum, &lnum, NULL);
5237 }
5238 if (lnum < 1)
5239 lnum = 1;
5240 }
5241 else
5242#endif
5243 lnum -= n;
5244 curwin->w_cursor.lnum = lnum;
5245 }
5246
5247 /* try to advance to the column we want to be at */
5248 coladvance(curwin->w_curswant);
5249
5250 if (upd_topline)
5251 update_topline(); /* make sure curwin->w_topline is valid */
5252
5253 return OK;
5254}
5255
5256/*
5257 * Cursor down a number of logical lines.
5258 */
5259 int
5260cursor_down(n, upd_topline)
5261 long n;
5262 int upd_topline; /* When TRUE: update topline */
5263{
5264 linenr_T lnum;
5265
5266 if (n > 0)
5267 {
5268 lnum = curwin->w_cursor.lnum;
5269#ifdef FEAT_FOLDING
5270 /* Move to last line of fold, will fail if it's the end-of-file. */
5271 (void)hasFolding(lnum, NULL, &lnum);
5272#endif
Bram Moolenaar7c626922005-02-07 22:01:03 +00005273 /* This fails if the cursor is already in the last line or would move
5274 * beyound the last line and '-' is in 'cpoptions' */
5275 if (lnum >= curbuf->b_ml.ml_line_count
5276 || (lnum + n > curbuf->b_ml.ml_line_count
5277 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005278 return FAIL;
5279 if (lnum + n >= curbuf->b_ml.ml_line_count)
5280 lnum = curbuf->b_ml.ml_line_count;
5281 else
5282#ifdef FEAT_FOLDING
5283 if (hasAnyFolding(curwin))
5284 {
5285 linenr_T last;
5286
5287 /* count each sequence of folded lines as one logical line */
5288 while (n--)
5289 {
5290 if (hasFolding(lnum, NULL, &last))
5291 lnum = last + 1;
5292 else
5293 ++lnum;
5294 if (lnum >= curbuf->b_ml.ml_line_count)
5295 break;
5296 }
5297 if (lnum > curbuf->b_ml.ml_line_count)
5298 lnum = curbuf->b_ml.ml_line_count;
5299 }
5300 else
5301#endif
5302 lnum += n;
5303 curwin->w_cursor.lnum = lnum;
5304 }
5305
5306 /* try to advance to the column we want to be at */
5307 coladvance(curwin->w_curswant);
5308
5309 if (upd_topline)
5310 update_topline(); /* make sure curwin->w_topline is valid */
5311
5312 return OK;
5313}
5314
5315/*
5316 * Stuff the last inserted text in the read buffer.
5317 * Last_insert actually is a copy of the redo buffer, so we
5318 * first have to remove the command.
5319 */
5320 int
5321stuff_inserted(c, count, no_esc)
5322 int c; /* Command character to be inserted */
5323 long count; /* Repeat this many times */
5324 int no_esc; /* Don't add an ESC at the end */
5325{
5326 char_u *esc_ptr;
5327 char_u *ptr;
5328 char_u *last_ptr;
5329 char_u last = NUL;
5330
5331 ptr = get_last_insert();
5332 if (ptr == NULL)
5333 {
5334 EMSG(_(e_noinstext));
5335 return FAIL;
5336 }
5337
5338 /* may want to stuff the command character, to start Insert mode */
5339 if (c != NUL)
5340 stuffcharReadbuff(c);
5341 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
5342 *esc_ptr = NUL; /* remove the ESC */
5343
5344 /* when the last char is either "0" or "^" it will be quoted if no ESC
5345 * comes after it OR if it will inserted more than once and "ptr"
5346 * starts with ^D. -- Acevedo
5347 */
5348 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
5349 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
5350 && (no_esc || (*ptr == Ctrl_D && count > 1)))
5351 {
5352 last = *last_ptr;
5353 *last_ptr = NUL;
5354 }
5355
5356 do
5357 {
5358 stuffReadbuff(ptr);
5359 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
5360 if (last)
5361 stuffReadbuff((char_u *)(last == '0'
5362 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
5363 : IF_EB("\026^", CTRL_V_STR "^")));
5364 }
5365 while (--count > 0);
5366
5367 if (last)
5368 *last_ptr = last;
5369
5370 if (esc_ptr != NULL)
5371 *esc_ptr = ESC; /* put the ESC back */
5372
5373 /* may want to stuff a trailing ESC, to get out of Insert mode */
5374 if (!no_esc)
5375 stuffcharReadbuff(ESC);
5376
5377 return OK;
5378}
5379
5380 char_u *
5381get_last_insert()
5382{
5383 if (last_insert == NULL)
5384 return NULL;
5385 return last_insert + last_insert_skip;
5386}
5387
5388/*
5389 * Get last inserted string, and remove trailing <Esc>.
5390 * Returns pointer to allocated memory (must be freed) or NULL.
5391 */
5392 char_u *
5393get_last_insert_save()
5394{
5395 char_u *s;
5396 int len;
5397
5398 if (last_insert == NULL)
5399 return NULL;
5400 s = vim_strsave(last_insert + last_insert_skip);
5401 if (s != NULL)
5402 {
5403 len = (int)STRLEN(s);
5404 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
5405 s[len - 1] = NUL;
5406 }
5407 return s;
5408}
5409
5410/*
5411 * Check the word in front of the cursor for an abbreviation.
5412 * Called when the non-id character "c" has been entered.
5413 * When an abbreviation is recognized it is removed from the text and
5414 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
5415 */
5416 static int
5417echeck_abbr(c)
5418 int c;
5419{
5420 /* Don't check for abbreviation in paste mode, when disabled and just
5421 * after moving around with cursor keys. */
5422 if (p_paste || no_abbr || arrow_used)
5423 return FALSE;
5424
5425 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
5426 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
5427}
5428
5429/*
5430 * replace-stack functions
5431 *
5432 * When replacing characters, the replaced characters are remembered for each
5433 * new character. This is used to re-insert the old text when backspacing.
5434 *
5435 * There is a NUL headed list of characters for each character that is
5436 * currently in the file after the insertion point. When BS is used, one NUL
5437 * headed list is put back for the deleted character.
5438 *
5439 * For a newline, there are two NUL headed lists. One contains the characters
5440 * that the NL replaced. The extra one stores the characters after the cursor
5441 * that were deleted (always white space).
5442 *
5443 * Replace_offset is normally 0, in which case replace_push will add a new
5444 * character at the end of the stack. If replace_offset is not 0, that many
5445 * characters will be left on the stack above the newly inserted character.
5446 */
5447
Bram Moolenaar6c0b44b2005-06-01 21:56:33 +00005448static char_u *replace_stack = NULL;
5449static long replace_stack_nr = 0; /* next entry in replace stack */
5450static long replace_stack_len = 0; /* max. number of entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451
5452 void
5453replace_push(c)
5454 int c; /* character that is replaced (NUL is none) */
5455{
5456 char_u *p;
5457
5458 if (replace_stack_nr < replace_offset) /* nothing to do */
5459 return;
5460 if (replace_stack_len <= replace_stack_nr)
5461 {
5462 replace_stack_len += 50;
5463 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
5464 if (p == NULL) /* out of memory */
5465 {
5466 replace_stack_len -= 50;
5467 return;
5468 }
5469 if (replace_stack != NULL)
5470 {
5471 mch_memmove(p, replace_stack,
5472 (size_t)(replace_stack_nr * sizeof(char_u)));
5473 vim_free(replace_stack);
5474 }
5475 replace_stack = p;
5476 }
5477 p = replace_stack + replace_stack_nr - replace_offset;
5478 if (replace_offset)
5479 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
5480 *p = c;
5481 ++replace_stack_nr;
5482}
5483
5484/*
5485 * call replace_push(c) with replace_offset set to the first NUL.
5486 */
5487 static void
5488replace_push_off(c)
5489 int c;
5490{
5491 char_u *p;
5492
5493 p = replace_stack + replace_stack_nr;
5494 for (replace_offset = 1; replace_offset < replace_stack_nr;
5495 ++replace_offset)
5496 if (*--p == NUL)
5497 break;
5498 replace_push(c);
5499 replace_offset = 0;
5500}
5501
5502/*
5503 * Pop one item from the replace stack.
5504 * return -1 if stack empty
5505 * return replaced character or NUL otherwise
5506 */
5507 static int
5508replace_pop()
5509{
5510 if (replace_stack_nr == 0)
5511 return -1;
5512 return (int)replace_stack[--replace_stack_nr];
5513}
5514
5515/*
5516 * Join the top two items on the replace stack. This removes to "off"'th NUL
5517 * encountered.
5518 */
5519 static void
5520replace_join(off)
5521 int off; /* offset for which NUL to remove */
5522{
5523 int i;
5524
5525 for (i = replace_stack_nr; --i >= 0; )
5526 if (replace_stack[i] == NUL && off-- <= 0)
5527 {
5528 --replace_stack_nr;
5529 mch_memmove(replace_stack + i, replace_stack + i + 1,
5530 (size_t)(replace_stack_nr - i));
5531 return;
5532 }
5533}
5534
5535/*
5536 * Pop bytes from the replace stack until a NUL is found, and insert them
5537 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
5538 */
5539 static void
5540replace_pop_ins()
5541{
5542 int cc;
5543 int oldState = State;
5544
5545 State = NORMAL; /* don't want REPLACE here */
5546 while ((cc = replace_pop()) > 0)
5547 {
5548#ifdef FEAT_MBYTE
5549 mb_replace_pop_ins(cc);
5550#else
5551 ins_char(cc);
5552#endif
5553 dec_cursor();
5554 }
5555 State = oldState;
5556}
5557
5558#ifdef FEAT_MBYTE
5559/*
5560 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
5561 * indicates a multi-byte char, pop the other bytes too.
5562 */
5563 static void
5564mb_replace_pop_ins(cc)
5565 int cc;
5566{
5567 int n;
5568 char_u buf[MB_MAXBYTES];
5569 int i;
5570 int c;
5571
5572 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
5573 {
5574 buf[0] = cc;
5575 for (i = 1; i < n; ++i)
5576 buf[i] = replace_pop();
5577 ins_bytes_len(buf, n);
5578 }
5579 else
5580 ins_char(cc);
5581
5582 if (enc_utf8)
5583 /* Handle composing chars. */
5584 for (;;)
5585 {
5586 c = replace_pop();
5587 if (c == -1) /* stack empty */
5588 break;
5589 if ((n = MB_BYTE2LEN(c)) == 1)
5590 {
5591 /* Not a multi-byte char, put it back. */
5592 replace_push(c);
5593 break;
5594 }
5595 else
5596 {
5597 buf[0] = c;
5598 for (i = 1; i < n; ++i)
5599 buf[i] = replace_pop();
5600 if (utf_iscomposing(utf_ptr2char(buf)))
5601 ins_bytes_len(buf, n);
5602 else
5603 {
5604 /* Not a composing char, put it back. */
5605 for (i = n - 1; i >= 0; --i)
5606 replace_push(buf[i]);
5607 break;
5608 }
5609 }
5610 }
5611}
5612#endif
5613
5614/*
5615 * make the replace stack empty
5616 * (called when exiting replace mode)
5617 */
5618 static void
5619replace_flush()
5620{
5621 vim_free(replace_stack);
5622 replace_stack = NULL;
5623 replace_stack_len = 0;
5624 replace_stack_nr = 0;
5625}
5626
5627/*
5628 * Handle doing a BS for one character.
5629 * cc < 0: replace stack empty, just move cursor
5630 * cc == 0: character was inserted, delete it
5631 * cc > 0: character was replaced, put cc (first byte of original char) back
5632 * and check for more characters to be put back
5633 */
5634 static void
5635replace_do_bs()
5636{
5637 int cc;
5638#ifdef FEAT_VREPLACE
5639 int orig_len = 0;
5640 int ins_len;
5641 int orig_vcols = 0;
5642 colnr_T start_vcol;
5643 char_u *p;
5644 int i;
5645 int vcol;
5646#endif
5647
5648 cc = replace_pop();
5649 if (cc > 0)
5650 {
5651#ifdef FEAT_VREPLACE
5652 if (State & VREPLACE_FLAG)
5653 {
5654 /* Get the number of screen cells used by the character we are
5655 * going to delete. */
5656 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
5657 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
5658 }
5659#endif
5660#ifdef FEAT_MBYTE
5661 if (has_mbyte)
5662 {
5663 del_char(FALSE);
5664# ifdef FEAT_VREPLACE
5665 if (State & VREPLACE_FLAG)
5666 orig_len = STRLEN(ml_get_cursor());
5667# endif
5668 replace_push(cc);
5669 }
5670 else
5671#endif
5672 {
5673 pchar_cursor(cc);
5674#ifdef FEAT_VREPLACE
5675 if (State & VREPLACE_FLAG)
5676 orig_len = STRLEN(ml_get_cursor()) - 1;
5677#endif
5678 }
5679 replace_pop_ins();
5680
5681#ifdef FEAT_VREPLACE
5682 if (State & VREPLACE_FLAG)
5683 {
5684 /* Get the number of screen cells used by the inserted characters */
5685 p = ml_get_cursor();
5686 ins_len = STRLEN(p) - orig_len;
5687 vcol = start_vcol;
5688 for (i = 0; i < ins_len; ++i)
5689 {
5690 vcol += chartabsize(p + i, vcol);
5691#ifdef FEAT_MBYTE
5692 i += (*mb_ptr2len_check)(p) - 1;
5693#endif
5694 }
5695 vcol -= start_vcol;
5696
5697 /* Delete spaces that were inserted after the cursor to keep the
5698 * text aligned. */
5699 curwin->w_cursor.col += ins_len;
5700 while (vcol > orig_vcols && gchar_cursor() == ' ')
5701 {
5702 del_char(FALSE);
5703 ++orig_vcols;
5704 }
5705 curwin->w_cursor.col -= ins_len;
5706 }
5707#endif
5708
5709 /* mark the buffer as changed and prepare for displaying */
5710 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
5711 }
5712 else if (cc == 0)
5713 (void)del_char(FALSE);
5714}
5715
5716#ifdef FEAT_CINDENT
5717/*
5718 * Return TRUE if C-indenting is on.
5719 */
5720 static int
5721cindent_on()
5722{
5723 return (!p_paste && (curbuf->b_p_cin
5724# ifdef FEAT_EVAL
5725 || *curbuf->b_p_inde != NUL
5726# endif
5727 ));
5728}
5729#endif
5730
5731#if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
5732/*
5733 * Re-indent the current line, based on the current contents of it and the
5734 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
5735 * confused what all the part that handles Control-T is doing that I'm not.
5736 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
5737 */
5738
5739 void
5740fixthisline(get_the_indent)
5741 int (*get_the_indent) __ARGS((void));
5742{
5743 change_indent(INDENT_SET, get_the_indent(), FALSE, 0);
5744 if (linewhite(curwin->w_cursor.lnum))
5745 did_ai = TRUE; /* delete the indent if the line stays empty */
5746}
5747
5748 void
5749fix_indent()
5750{
5751 if (p_paste)
5752 return;
5753# ifdef FEAT_LISP
5754 if (curbuf->b_p_lisp && curbuf->b_p_ai)
5755 fixthisline(get_lisp_indent);
5756# endif
5757# if defined(FEAT_LISP) && defined(FEAT_CINDENT)
5758 else
5759# endif
5760# ifdef FEAT_CINDENT
5761 if (cindent_on())
5762 do_c_expr_indent();
5763# endif
5764}
5765
5766#endif
5767
5768#ifdef FEAT_CINDENT
5769/*
5770 * return TRUE if 'cinkeys' contains the key "keytyped",
5771 * when == '*': Only if key is preceded with '*' (indent before insert)
5772 * when == '!': Only if key is prededed with '!' (don't insert)
5773 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
5774 *
5775 * "keytyped" can have a few special values:
5776 * KEY_OPEN_FORW
5777 * KEY_OPEN_BACK
5778 * KEY_COMPLETE just finished completion.
5779 *
5780 * If line_is_empty is TRUE accept keys with '0' before them.
5781 */
5782 int
5783in_cinkeys(keytyped, when, line_is_empty)
5784 int keytyped;
5785 int when;
5786 int line_is_empty;
5787{
5788 char_u *look;
5789 int try_match;
5790 int try_match_word;
5791 char_u *p;
5792 char_u *line;
5793 int icase;
5794 int i;
5795
5796#ifdef FEAT_EVAL
5797 if (*curbuf->b_p_inde != NUL)
5798 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
5799 else
5800#endif
5801 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
5802 while (*look)
5803 {
5804 /*
5805 * Find out if we want to try a match with this key, depending on
5806 * 'when' and a '*' or '!' before the key.
5807 */
5808 switch (when)
5809 {
5810 case '*': try_match = (*look == '*'); break;
5811 case '!': try_match = (*look == '!'); break;
5812 default: try_match = (*look != '*'); break;
5813 }
5814 if (*look == '*' || *look == '!')
5815 ++look;
5816
5817 /*
5818 * If there is a '0', only accept a match if the line is empty.
5819 * But may still match when typing last char of a word.
5820 */
5821 if (*look == '0')
5822 {
5823 try_match_word = try_match;
5824 if (!line_is_empty)
5825 try_match = FALSE;
5826 ++look;
5827 }
5828 else
5829 try_match_word = FALSE;
5830
5831 /*
5832 * does it look like a control character?
5833 */
5834 if (*look == '^'
5835#ifdef EBCDIC
5836 && (Ctrl_chr(look[1]) != 0)
5837#else
5838 && look[1] >= '?' && look[1] <= '_'
5839#endif
5840 )
5841 {
5842 if (try_match && keytyped == Ctrl_chr(look[1]))
5843 return TRUE;
5844 look += 2;
5845 }
5846 /*
5847 * 'o' means "o" command, open forward.
5848 * 'O' means "O" command, open backward.
5849 */
5850 else if (*look == 'o')
5851 {
5852 if (try_match && keytyped == KEY_OPEN_FORW)
5853 return TRUE;
5854 ++look;
5855 }
5856 else if (*look == 'O')
5857 {
5858 if (try_match && keytyped == KEY_OPEN_BACK)
5859 return TRUE;
5860 ++look;
5861 }
5862
5863 /*
5864 * 'e' means to check for "else" at start of line and just before the
5865 * cursor.
5866 */
5867 else if (*look == 'e')
5868 {
5869 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
5870 {
5871 p = ml_get_curline();
5872 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
5873 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
5874 return TRUE;
5875 }
5876 ++look;
5877 }
5878
5879 /*
5880 * ':' only causes an indent if it is at the end of a label or case
5881 * statement, or when it was before typing the ':' (to fix
5882 * class::method for C++).
5883 */
5884 else if (*look == ':')
5885 {
5886 if (try_match && keytyped == ':')
5887 {
5888 p = ml_get_curline();
5889 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
5890 return TRUE;
5891 if (curwin->w_cursor.col > 2
5892 && p[curwin->w_cursor.col - 1] == ':'
5893 && p[curwin->w_cursor.col - 2] == ':')
5894 {
5895 p[curwin->w_cursor.col - 1] = ' ';
5896 i = (cin_iscase(p) || cin_isscopedecl(p)
5897 || cin_islabel(30));
5898 p = ml_get_curline();
5899 p[curwin->w_cursor.col - 1] = ':';
5900 if (i)
5901 return TRUE;
5902 }
5903 }
5904 ++look;
5905 }
5906
5907
5908 /*
5909 * Is it a key in <>, maybe?
5910 */
5911 else if (*look == '<')
5912 {
5913 if (try_match)
5914 {
5915 /*
5916 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
5917 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
5918 * >, *, : and ! keys if they really really want to.
5919 */
5920 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
5921 && keytyped == look[1])
5922 return TRUE;
5923
5924 if (keytyped == get_special_key_code(look + 1))
5925 return TRUE;
5926 }
5927 while (*look && *look != '>')
5928 look++;
5929 while (*look == '>')
5930 look++;
5931 }
5932
5933 /*
5934 * Is it a word: "=word"?
5935 */
5936 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
5937 {
5938 ++look;
5939 if (*look == '~')
5940 {
5941 icase = TRUE;
5942 ++look;
5943 }
5944 else
5945 icase = FALSE;
5946 p = vim_strchr(look, ',');
5947 if (p == NULL)
5948 p = look + STRLEN(look);
5949 if ((try_match || try_match_word)
5950 && curwin->w_cursor.col >= (colnr_T)(p - look))
5951 {
5952 int match = FALSE;
5953
5954#ifdef FEAT_INS_EXPAND
5955 if (keytyped == KEY_COMPLETE)
5956 {
5957 char_u *s;
5958
5959 /* Just completed a word, check if it starts with "look".
5960 * search back for the start of a word. */
5961 line = ml_get_curline();
5962# ifdef FEAT_MBYTE
5963 if (has_mbyte)
5964 {
5965 char_u *n;
5966
5967 for (s = line + curwin->w_cursor.col; s > line; s = n)
5968 {
5969 n = mb_prevptr(line, s);
5970 if (!vim_iswordp(n))
5971 break;
5972 }
5973 }
5974 else
5975# endif
5976 for (s = line + curwin->w_cursor.col; s > line; --s)
5977 if (!vim_iswordc(s[-1]))
5978 break;
5979 if (s + (p - look) <= line + curwin->w_cursor.col
5980 && (icase
5981 ? MB_STRNICMP(s, look, p - look)
5982 : STRNCMP(s, look, p - look)) == 0)
5983 match = TRUE;
5984 }
5985 else
5986#endif
5987 /* TODO: multi-byte */
5988 if (keytyped == (int)p[-1] || (icase && keytyped < 256
5989 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
5990 {
5991 line = ml_get_cursor();
5992 if ((curwin->w_cursor.col == (colnr_T)(p - look)
5993 || !vim_iswordc(line[-(p - look) - 1]))
5994 && (icase
5995 ? MB_STRNICMP(line - (p - look), look, p - look)
5996 : STRNCMP(line - (p - look), look, p - look))
5997 == 0)
5998 match = TRUE;
5999 }
6000 if (match && try_match_word && !try_match)
6001 {
6002 /* "0=word": Check if there are only blanks before the
6003 * word. */
6004 line = ml_get_curline();
6005 if ((int)(skipwhite(line) - line) !=
6006 (int)(curwin->w_cursor.col - (p - look)))
6007 match = FALSE;
6008 }
6009 if (match)
6010 return TRUE;
6011 }
6012 look = p;
6013 }
6014
6015 /*
6016 * ok, it's a boring generic character.
6017 */
6018 else
6019 {
6020 if (try_match && *look == keytyped)
6021 return TRUE;
6022 ++look;
6023 }
6024
6025 /*
6026 * Skip over ", ".
6027 */
6028 look = skip_to_option_part(look);
6029 }
6030 return FALSE;
6031}
6032#endif /* FEAT_CINDENT */
6033
6034#if defined(FEAT_RIGHTLEFT) || defined(PROTO)
6035/*
6036 * Map Hebrew keyboard when in hkmap mode.
6037 */
6038 int
6039hkmap(c)
6040 int c;
6041{
6042 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
6043 {
6044 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
6045 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
6046 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
6047 static char_u map[26] =
6048 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
6049 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
6050 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
6051 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
6052 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
6053 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
6054 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
6055 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
6056 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
6057
6058 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
6059 return (int)(map[CharOrd(c)] - 1 + p_aleph);
6060 /* '-1'='sofit' */
6061 else if (c == 'x')
6062 return 'X';
6063 else if (c == 'q')
6064 return '\''; /* {geresh}={'} */
6065 else if (c == 246)
6066 return ' '; /* \"o --> ' ' for a german keyboard */
6067 else if (c == 228)
6068 return ' '; /* \"a --> ' ' -- / -- */
6069 else if (c == 252)
6070 return ' '; /* \"u --> ' ' -- / -- */
6071#ifdef EBCDIC
6072 else if (islower(c))
6073#else
6074 /* NOTE: islower() does not do the right thing for us on Linux so we
6075 * do this the same was as 5.7 and previous, so it works correctly on
6076 * all systems. Specifically, the e.g. Delete and Arrow keys are
6077 * munged and won't work if e.g. searching for Hebrew text.
6078 */
6079 else if (c >= 'a' && c <= 'z')
6080#endif
6081 return (int)(map[CharOrdLow(c)] + p_aleph);
6082 else
6083 return c;
6084 }
6085 else
6086 {
6087 switch (c)
6088 {
6089 case '`': return ';';
6090 case '/': return '.';
6091 case '\'': return ',';
6092 case 'q': return '/';
6093 case 'w': return '\'';
6094
6095 /* Hebrew letters - set offset from 'a' */
6096 case ',': c = '{'; break;
6097 case '.': c = 'v'; break;
6098 case ';': c = 't'; break;
6099 default: {
6100 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
6101
6102#ifdef EBCDIC
6103 /* see note about islower() above */
6104 if (!islower(c))
6105#else
6106 if (c < 'a' || c > 'z')
6107#endif
6108 return c;
6109 c = str[CharOrdLow(c)];
6110 break;
6111 }
6112 }
6113
6114 return (int)(CharOrdLow(c) + p_aleph);
6115 }
6116}
6117#endif
6118
6119 static void
6120ins_reg()
6121{
6122 int need_redraw = FALSE;
6123 int regname;
6124 int literally = 0;
6125
6126 /*
6127 * If we are going to wait for a character, show a '"'.
6128 */
6129 pc_status = PC_STATUS_UNSET;
6130 if (redrawing() && !char_avail())
6131 {
6132 /* may need to redraw when no more chars available now */
6133 ins_redraw();
6134
6135 edit_putchar('"', TRUE);
6136#ifdef FEAT_CMDL_INFO
6137 add_to_showcmd_c(Ctrl_R);
6138#endif
6139 }
6140
6141#ifdef USE_ON_FLY_SCROLL
6142 dont_scroll = TRUE; /* disallow scrolling here */
6143#endif
6144
6145 /*
6146 * Don't map the register name. This also prevents the mode message to be
6147 * deleted when ESC is hit.
6148 */
6149 ++no_mapping;
6150 regname = safe_vgetc();
6151#ifdef FEAT_LANGMAP
6152 LANGMAP_ADJUST(regname, TRUE);
6153#endif
6154 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
6155 {
6156 /* Get a third key for literal register insertion */
6157 literally = regname;
6158#ifdef FEAT_CMDL_INFO
6159 add_to_showcmd_c(literally);
6160#endif
6161 regname = safe_vgetc();
6162#ifdef FEAT_LANGMAP
6163 LANGMAP_ADJUST(regname, TRUE);
6164#endif
6165 }
6166 --no_mapping;
6167
6168#ifdef FEAT_EVAL
6169 /*
6170 * Don't call u_sync() while getting the expression,
6171 * evaluating it or giving an error message for it!
6172 */
6173 ++no_u_sync;
6174 if (regname == '=')
6175 {
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006176# ifdef USE_IM_CONTROL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 int im_on = im_get_status();
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006178# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 regname = get_expr_register();
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006180# ifdef USE_IM_CONTROL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181 /* Restore the Input Method. */
6182 if (im_on)
6183 im_set_active(TRUE);
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006184# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 }
Bram Moolenaar677ee682005-01-27 14:41:15 +00006186 if (regname == NUL || !valid_yank_reg(regname, FALSE))
6187 {
6188 vim_beep();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 need_redraw = TRUE; /* remove the '"' */
Bram Moolenaar677ee682005-01-27 14:41:15 +00006190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 else
6192 {
6193#endif
6194 if (literally == Ctrl_O || literally == Ctrl_P)
6195 {
6196 /* Append the command to the redo buffer. */
6197 AppendCharToRedobuff(Ctrl_R);
6198 AppendCharToRedobuff(literally);
6199 AppendCharToRedobuff(regname);
6200
6201 do_put(regname, BACKWARD, 1L,
6202 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
6203 }
6204 else if (insert_reg(regname, literally) == FAIL)
6205 {
6206 vim_beep();
6207 need_redraw = TRUE; /* remove the '"' */
6208 }
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006209 else if (stop_insert_mode)
6210 /* When the '=' register was used and a function was invoked that
6211 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
6212 * insert anything, need to remove the '"' */
6213 need_redraw = TRUE;
6214
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215#ifdef FEAT_EVAL
6216 }
6217 --no_u_sync;
6218#endif
6219#ifdef FEAT_CMDL_INFO
6220 clear_showcmd();
6221#endif
6222
6223 /* If the inserted register is empty, we need to remove the '"' */
6224 if (need_redraw || stuff_empty())
6225 edit_unputchar();
6226}
6227
6228/*
6229 * CTRL-G commands in Insert mode.
6230 */
6231 static void
6232ins_ctrl_g()
6233{
6234 int c;
6235
6236#ifdef FEAT_INS_EXPAND
6237 /* Right after CTRL-X the cursor will be after the ruler. */
6238 setcursor();
6239#endif
6240
6241 /*
6242 * Don't map the second key. This also prevents the mode message to be
6243 * deleted when ESC is hit.
6244 */
6245 ++no_mapping;
6246 c = safe_vgetc();
6247 --no_mapping;
6248 switch (c)
6249 {
6250 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
6251 case K_UP:
6252 case Ctrl_K:
6253 case 'k': ins_up(TRUE);
6254 break;
6255
6256 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
6257 case K_DOWN:
6258 case Ctrl_J:
6259 case 'j': ins_down(TRUE);
6260 break;
6261
6262 /* CTRL-G u: start new undoable edit */
6263 case 'u': u_sync();
6264 ins_need_undo = TRUE;
6265 break;
6266
6267 /* Unknown CTRL-G command, reserved for future expansion. */
6268 default: vim_beep();
6269 }
6270}
6271
6272/*
6273 * Handle ESC in insert mode.
6274 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
6275 * insert.
6276 */
6277 static int
6278ins_esc(count, cmdchar)
6279 long *count;
6280 int cmdchar;
6281{
6282 int temp;
6283 static int disabled_redraw = FALSE;
6284
6285#if defined(FEAT_HANGULIN)
6286# if defined(ESC_CHG_TO_ENG_MODE)
6287 hangul_input_state_set(0);
6288# endif
6289 if (composing_hangul)
6290 {
6291 push_raw_key(composing_hangul_buffer, 2);
6292 composing_hangul = 0;
6293 }
6294#endif
6295#if defined(FEAT_MBYTE) && defined(MACOS_CLASSIC)
6296 previous_script = GetScriptManagerVariable(smKeyScript);
6297 KeyScript(smKeyRoman); /* or smKeySysScript */
6298#endif
6299
6300 temp = curwin->w_cursor.col;
6301 if (disabled_redraw)
6302 {
6303 --RedrawingDisabled;
6304 disabled_redraw = FALSE;
6305 }
6306 if (!arrow_used)
6307 {
6308 /*
6309 * Don't append the ESC for "r<CR>" and "grx".
Bram Moolenaar12805862005-01-05 22:16:17 +00006310 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
6311 * when "count" is non-zero.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 */
6313 if (cmdchar != 'r' && cmdchar != 'v')
Bram Moolenaar12805862005-01-05 22:16:17 +00006314 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315
6316 /*
6317 * Repeating insert may take a long time. Check for
6318 * interrupt now and then.
6319 */
6320 if (*count > 0)
6321 {
6322 line_breakcheck();
6323 if (got_int)
6324 *count = 0;
6325 }
6326
6327 if (--*count > 0) /* repeat what was typed */
6328 {
Bram Moolenaar4399ef42005-02-12 14:29:27 +00006329 /* Vi repeats the insert without replacing characters. */
6330 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
6331 State &= ~REPLACE_FLAG;
6332
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 (void)start_redo_ins();
6334 if (cmdchar == 'r' || cmdchar == 'v')
6335 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
6336 ++RedrawingDisabled;
6337 disabled_redraw = TRUE;
6338 return FALSE; /* repeat the insert */
6339 }
6340 stop_insert(&curwin->w_cursor, TRUE);
6341 undisplay_dollar();
6342 }
6343
6344 /* When an autoindent was removed, curswant stays after the
6345 * indent */
6346 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
6347 curwin->w_set_curswant = TRUE;
6348
6349 /* Remember the last Insert position in the '^ mark. */
6350 if (!cmdmod.keepjumps)
6351 curbuf->b_last_insert = curwin->w_cursor;
6352
6353 /*
6354 * The cursor should end up on the last inserted character.
6355 */
6356 if ((curwin->w_cursor.col != 0
6357#ifdef FEAT_VIRTUALEDIT
6358 || curwin->w_cursor.coladd > 0
6359#endif
6360 ) && (restart_edit == NUL
6361 || (gchar_cursor() == NUL
6362#ifdef FEAT_VISUAL
6363 && !VIsual_active
6364#endif
6365 ))
6366#ifdef FEAT_RIGHTLEFT
6367 && !revins_on
6368#endif
6369 )
6370 {
6371#ifdef FEAT_VIRTUALEDIT
6372 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
6373 {
6374 oneleft();
6375 if (restart_edit != NUL)
6376 ++curwin->w_cursor.coladd;
6377 }
6378 else
6379#endif
6380 {
6381 --curwin->w_cursor.col;
6382#ifdef FEAT_MBYTE
6383 /* Correct cursor for multi-byte character. */
6384 if (has_mbyte)
6385 mb_adjust_cursor();
6386#endif
6387 }
6388 }
6389
6390#ifdef USE_IM_CONTROL
6391 /* Disable IM to allow typing English directly for Normal mode commands.
6392 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
6393 * well). */
6394 if (!(State & LANGMAP))
6395 im_save_status(&curbuf->b_p_iminsert);
6396 im_set_active(FALSE);
6397#endif
6398
6399 State = NORMAL;
6400 /* need to position cursor again (e.g. when on a TAB ) */
6401 changed_cline_bef_curs();
6402
6403#ifdef FEAT_MOUSE
6404 setmouse();
6405#endif
6406#ifdef CURSOR_SHAPE
6407 ui_cursor_shape(); /* may show different cursor shape */
6408#endif
6409
6410 /*
6411 * When recording or for CTRL-O, need to display the new mode.
6412 * Otherwise remove the mode message.
6413 */
6414 if (Recording || restart_edit != NUL)
6415 showmode();
6416 else if (p_smd)
6417 MSG("");
6418
6419 return TRUE; /* exit Insert mode */
6420}
6421
6422#ifdef FEAT_RIGHTLEFT
6423/*
6424 * Toggle language: hkmap and revins_on.
6425 * Move to end of reverse inserted text.
6426 */
6427 static void
6428ins_ctrl_()
6429{
6430 if (revins_on && revins_chars && revins_scol >= 0)
6431 {
6432 while (gchar_cursor() != NUL && revins_chars--)
6433 ++curwin->w_cursor.col;
6434 }
6435 p_ri = !p_ri;
6436 revins_on = (State == INSERT && p_ri);
6437 if (revins_on)
6438 {
6439 revins_scol = curwin->w_cursor.col;
6440 revins_legal++;
6441 revins_chars = 0;
6442 undisplay_dollar();
6443 }
6444 else
6445 revins_scol = -1;
6446#ifdef FEAT_FKMAP
6447 if (p_altkeymap)
6448 {
6449 /*
6450 * to be consistent also for redo command, using '.'
6451 * set arrow_used to true and stop it - causing to redo
6452 * characters entered in one mode (normal/reverse insert).
6453 */
6454 arrow_used = TRUE;
6455 (void)stop_arrow();
6456 p_fkmap = curwin->w_p_rl ^ p_ri;
6457 if (p_fkmap && p_ri)
6458 State = INSERT;
6459 }
6460 else
6461#endif
6462 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
6463 showmode();
6464}
6465#endif
6466
6467#ifdef FEAT_VISUAL
6468/*
6469 * If 'keymodel' contains "startsel", may start selection.
6470 * Returns TRUE when a CTRL-O and other keys stuffed.
6471 */
6472 static int
6473ins_start_select(c)
6474 int c;
6475{
6476 if (km_startsel)
6477 switch (c)
6478 {
6479 case K_KHOME:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 case K_KEND:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 case K_PAGEUP:
6482 case K_KPAGEUP:
6483 case K_PAGEDOWN:
6484 case K_KPAGEDOWN:
6485# ifdef MACOS
6486 case K_LEFT:
6487 case K_RIGHT:
6488 case K_UP:
6489 case K_DOWN:
6490 case K_END:
6491 case K_HOME:
6492# endif
6493 if (!(mod_mask & MOD_MASK_SHIFT))
6494 break;
6495 /* FALLTHROUGH */
6496 case K_S_LEFT:
6497 case K_S_RIGHT:
6498 case K_S_UP:
6499 case K_S_DOWN:
6500 case K_S_END:
6501 case K_S_HOME:
6502 /* Start selection right away, the cursor can move with
6503 * CTRL-O when beyond the end of the line. */
6504 start_selection();
6505
6506 /* Execute the key in (insert) Select mode. */
6507 stuffcharReadbuff(Ctrl_O);
6508 if (mod_mask)
6509 {
6510 char_u buf[4];
6511
6512 buf[0] = K_SPECIAL;
6513 buf[1] = KS_MODIFIER;
6514 buf[2] = mod_mask;
6515 buf[3] = NUL;
6516 stuffReadbuff(buf);
6517 }
6518 stuffcharReadbuff(c);
6519 return TRUE;
6520 }
6521 return FALSE;
6522}
6523#endif
6524
6525/*
6526 * If the cursor is on an indent, ^T/^D insert/delete one
6527 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
6528 * Always round the indent to 'shiftwith', this is compatible
6529 * with vi. But vi only supports ^T and ^D after an
6530 * autoindent, we support it everywhere.
6531 */
6532 static void
6533ins_shift(c, lastc)
6534 int c;
6535 int lastc;
6536{
6537 if (stop_arrow() == FAIL)
6538 return;
6539 AppendCharToRedobuff(c);
6540
6541 /*
6542 * 0^D and ^^D: remove all indent.
6543 */
6544 if ((lastc == '0' || lastc == '^') && curwin->w_cursor.col)
6545 {
6546 --curwin->w_cursor.col;
6547 (void)del_char(FALSE); /* delete the '^' or '0' */
6548 /* In Replace mode, restore the characters that '^' or '0' replaced. */
6549 if (State & REPLACE_FLAG)
6550 replace_pop_ins();
6551 if (lastc == '^')
6552 old_indent = get_indent(); /* remember curr. indent */
6553 change_indent(INDENT_SET, 0, TRUE, 0);
6554 }
6555 else
6556 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0);
6557
6558 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
6559 did_ai = FALSE;
6560#ifdef FEAT_SMARTINDENT
6561 did_si = FALSE;
6562 can_si = FALSE;
6563 can_si_back = FALSE;
6564#endif
6565#ifdef FEAT_CINDENT
6566 can_cindent = FALSE; /* no cindenting after ^D or ^T */
6567#endif
6568}
6569
6570 static void
6571ins_del()
6572{
6573 int temp;
6574
6575 if (stop_arrow() == FAIL)
6576 return;
6577 if (gchar_cursor() == NUL) /* delete newline */
6578 {
6579 temp = curwin->w_cursor.col;
6580 if (!can_bs(BS_EOL) /* only if "eol" included */
6581 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
6582 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
6583 || do_join(FALSE) == FAIL)
6584 vim_beep();
6585 else
6586 curwin->w_cursor.col = temp;
6587 }
6588 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
6589 vim_beep();
6590 did_ai = FALSE;
6591#ifdef FEAT_SMARTINDENT
6592 did_si = FALSE;
6593 can_si = FALSE;
6594 can_si_back = FALSE;
6595#endif
6596 AppendCharToRedobuff(K_DEL);
6597}
6598
6599/*
6600 * Handle Backspace, delete-word and delete-line in Insert mode.
6601 * Return TRUE when backspace was actually used.
6602 */
6603 static int
6604ins_bs(c, mode, inserted_space_p)
6605 int c;
6606 int mode;
6607 int *inserted_space_p;
6608{
6609 linenr_T lnum;
6610 int cc;
6611 int temp = 0; /* init for GCC */
6612 colnr_T mincol;
6613 int did_backspace = FALSE;
6614 int in_indent;
6615 int oldState;
6616#ifdef FEAT_MBYTE
6617 int p1, p2;
6618#endif
6619
6620 /*
6621 * can't delete anything in an empty file
6622 * can't backup past first character in buffer
6623 * can't backup past starting point unless 'backspace' > 1
6624 * can backup to a previous line if 'backspace' == 0
6625 */
6626 if ( bufempty()
6627 || (
6628#ifdef FEAT_RIGHTLEFT
6629 !revins_on &&
6630#endif
6631 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
6632 || (!can_bs(BS_START)
6633 && (arrow_used
6634 || (curwin->w_cursor.lnum == Insstart.lnum
6635 && curwin->w_cursor.col <= Insstart.col)))
6636 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
6637 && curwin->w_cursor.col <= ai_col)
6638 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
6639 {
6640 vim_beep();
6641 return FALSE;
6642 }
6643
6644 if (stop_arrow() == FAIL)
6645 return FALSE;
6646 in_indent = inindent(0);
6647#ifdef FEAT_CINDENT
6648 if (in_indent)
6649 can_cindent = FALSE;
6650#endif
6651#ifdef FEAT_COMMENTS
6652 end_comment_pending = NUL; /* After BS, don't auto-end comment */
6653#endif
6654#ifdef FEAT_RIGHTLEFT
6655 if (revins_on) /* put cursor after last inserted char */
6656 inc_cursor();
6657#endif
6658
6659#ifdef FEAT_VIRTUALEDIT
6660 /* Virtualedit:
6661 * BACKSPACE_CHAR eats a virtual space
6662 * BACKSPACE_WORD eats all coladd
6663 * BACKSPACE_LINE eats all coladd and keeps going
6664 */
6665 if (curwin->w_cursor.coladd > 0)
6666 {
6667 if (mode == BACKSPACE_CHAR)
6668 {
6669 --curwin->w_cursor.coladd;
6670 return TRUE;
6671 }
6672 if (mode == BACKSPACE_WORD)
6673 {
6674 curwin->w_cursor.coladd = 0;
6675 return TRUE;
6676 }
6677 curwin->w_cursor.coladd = 0;
6678 }
6679#endif
6680
6681 /*
6682 * delete newline!
6683 */
6684 if (curwin->w_cursor.col == 0)
6685 {
6686 lnum = Insstart.lnum;
6687 if (curwin->w_cursor.lnum == Insstart.lnum
6688#ifdef FEAT_RIGHTLEFT
6689 || revins_on
6690#endif
6691 )
6692 {
6693 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
6694 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
6695 return FALSE;
6696 --Insstart.lnum;
6697 Insstart.col = MAXCOL;
6698 }
6699 /*
6700 * In replace mode:
6701 * cc < 0: NL was inserted, delete it
6702 * cc >= 0: NL was replaced, put original characters back
6703 */
6704 cc = -1;
6705 if (State & REPLACE_FLAG)
6706 cc = replace_pop(); /* returns -1 if NL was inserted */
6707 /*
6708 * In replace mode, in the line we started replacing, we only move the
6709 * cursor.
6710 */
6711 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
6712 {
6713 dec_cursor();
6714 }
6715 else
6716 {
6717#ifdef FEAT_VREPLACE
6718 if (!(State & VREPLACE_FLAG)
6719 || curwin->w_cursor.lnum > orig_line_count)
6720#endif
6721 {
6722 temp = gchar_cursor(); /* remember current char */
6723 --curwin->w_cursor.lnum;
Bram Moolenaarc930a3c2005-05-20 21:27:20 +00006724
6725 /* When "aw" is in 'formatoptions' we must delete the space at
6726 * the end of the line, otherwise the line will be broken
6727 * again when auto-formatting. */
6728 if (has_format_option(FO_AUTO)
6729 && has_format_option(FO_WHITE_PAR))
6730 {
6731 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
6732 TRUE);
6733 int len;
6734
6735 len = STRLEN(ptr);
6736 if (len > 0 && ptr[len - 1] == ' ')
6737 ptr[len - 1] = NUL;
6738 }
6739
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 (void)do_join(FALSE);
6741 if (temp == NUL && gchar_cursor() != NUL)
6742 inc_cursor();
6743 }
6744#ifdef FEAT_VREPLACE
6745 else
6746 dec_cursor();
6747#endif
6748
6749 /*
6750 * In REPLACE mode we have to put back the text that was replaced
6751 * by the NL. On the replace stack is first a NUL-terminated
6752 * sequence of characters that were deleted and then the
6753 * characters that NL replaced.
6754 */
6755 if (State & REPLACE_FLAG)
6756 {
6757 /*
6758 * Do the next ins_char() in NORMAL state, to
6759 * prevent ins_char() from replacing characters and
6760 * avoiding showmatch().
6761 */
6762 oldState = State;
6763 State = NORMAL;
6764 /*
6765 * restore characters (blanks) deleted after cursor
6766 */
6767 while (cc > 0)
6768 {
6769 temp = curwin->w_cursor.col;
6770#ifdef FEAT_MBYTE
6771 mb_replace_pop_ins(cc);
6772#else
6773 ins_char(cc);
6774#endif
6775 curwin->w_cursor.col = temp;
6776 cc = replace_pop();
6777 }
6778 /* restore the characters that NL replaced */
6779 replace_pop_ins();
6780 State = oldState;
6781 }
6782 }
6783 did_ai = FALSE;
6784 }
6785 else
6786 {
6787 /*
6788 * Delete character(s) before the cursor.
6789 */
6790#ifdef FEAT_RIGHTLEFT
6791 if (revins_on) /* put cursor on last inserted char */
6792 dec_cursor();
6793#endif
6794 mincol = 0;
6795 /* keep indent */
6796 if (mode == BACKSPACE_LINE && curbuf->b_p_ai
6797#ifdef FEAT_RIGHTLEFT
6798 && !revins_on
6799#endif
6800 )
6801 {
6802 temp = curwin->w_cursor.col;
6803 beginline(BL_WHITE);
6804 if (curwin->w_cursor.col < (colnr_T)temp)
6805 mincol = curwin->w_cursor.col;
6806 curwin->w_cursor.col = temp;
6807 }
6808
6809 /*
6810 * Handle deleting one 'shiftwidth' or 'softtabstop'.
6811 */
6812 if ( mode == BACKSPACE_CHAR
6813 && ((p_sta && in_indent)
6814 || (curbuf->b_p_sts
6815 && (*(ml_get_cursor() - 1) == TAB
6816 || (*(ml_get_cursor() - 1) == ' '
6817 && (!*inserted_space_p
6818 || arrow_used))))))
6819 {
6820 int ts;
6821 colnr_T vcol;
6822 colnr_T want_vcol;
6823 int extra = 0;
6824
6825 *inserted_space_p = FALSE;
6826 if (p_sta)
6827 ts = curbuf->b_p_sw;
6828 else
6829 ts = curbuf->b_p_sts;
6830 /* Compute the virtual column where we want to be. Since
6831 * 'showbreak' may get in the way, need to get the last column of
6832 * the previous character. */
6833 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6834 dec_cursor();
6835 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
6836 inc_cursor();
6837 want_vcol = (want_vcol / ts) * ts;
6838
6839 /* delete characters until we are at or before want_vcol */
6840 while (vcol > want_vcol
6841 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
6842 {
6843 dec_cursor();
6844 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6845 if (State & REPLACE_FLAG)
6846 {
6847 /* Don't delete characters before the insert point when in
6848 * Replace mode */
6849 if (curwin->w_cursor.lnum != Insstart.lnum
6850 || curwin->w_cursor.col >= Insstart.col)
6851 {
6852#if 0 /* what was this for? It causes problems when sw != ts. */
6853 if (State == REPLACE && (int)vcol < want_vcol)
6854 {
6855 (void)del_char(FALSE);
6856 extra = 2; /* don't pop too much */
6857 }
6858 else
6859#endif
6860 replace_do_bs();
6861 }
6862 }
6863 else
6864 (void)del_char(FALSE);
6865 }
6866
6867 /* insert extra spaces until we are at want_vcol */
6868 while (vcol < want_vcol)
6869 {
6870 /* Remember the first char we inserted */
6871 if (curwin->w_cursor.lnum == Insstart.lnum
6872 && curwin->w_cursor.col < Insstart.col)
6873 Insstart.col = curwin->w_cursor.col;
6874
6875#ifdef FEAT_VREPLACE
6876 if (State & VREPLACE_FLAG)
6877 ins_char(' ');
6878 else
6879#endif
6880 {
6881 ins_str((char_u *)" ");
6882 if ((State & REPLACE_FLAG) && extra <= 1)
6883 {
6884 if (extra)
6885 replace_push_off(NUL);
6886 else
6887 replace_push(NUL);
6888 }
6889 if (extra == 2)
6890 extra = 1;
6891 }
6892 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6893 }
6894 }
6895
6896 /*
6897 * Delete upto starting point, start of line or previous word.
6898 */
6899 else do
6900 {
6901#ifdef FEAT_RIGHTLEFT
6902 if (!revins_on) /* put cursor on char to be deleted */
6903#endif
6904 dec_cursor();
6905
6906 /* start of word? */
6907 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
6908 {
6909 mode = BACKSPACE_WORD_NOT_SPACE;
6910 temp = vim_iswordc(gchar_cursor());
6911 }
6912 /* end of word? */
6913 else if (mode == BACKSPACE_WORD_NOT_SPACE
6914 && (vim_isspace(cc = gchar_cursor())
6915 || vim_iswordc(cc) != temp))
6916 {
6917#ifdef FEAT_RIGHTLEFT
6918 if (!revins_on)
6919#endif
6920 inc_cursor();
6921#ifdef FEAT_RIGHTLEFT
6922 else if (State & REPLACE_FLAG)
6923 dec_cursor();
6924#endif
6925 break;
6926 }
6927 if (State & REPLACE_FLAG)
6928 replace_do_bs();
6929 else
6930 {
6931#ifdef FEAT_MBYTE
6932 if (enc_utf8 && p_deco)
6933 (void)utfc_ptr2char(ml_get_cursor(), &p1, &p2);
6934#endif
6935 (void)del_char(FALSE);
6936#ifdef FEAT_MBYTE
6937 /*
6938 * If p1 or p2 is non-zero, there are combining characters we
6939 * need to take account of. Don't back up before the base
6940 * character.
6941 */
6942 if (enc_utf8 && p_deco && (p1 != NUL || p2 != NUL))
6943 inc_cursor();
6944#endif
6945#ifdef FEAT_RIGHTLEFT
6946 if (revins_chars)
6947 {
6948 revins_chars--;
6949 revins_legal++;
6950 }
6951 if (revins_on && gchar_cursor() == NUL)
6952 break;
6953#endif
6954 }
6955 /* Just a single backspace?: */
6956 if (mode == BACKSPACE_CHAR)
6957 break;
6958 } while (
6959#ifdef FEAT_RIGHTLEFT
6960 revins_on ||
6961#endif
6962 (curwin->w_cursor.col > mincol
6963 && (curwin->w_cursor.lnum != Insstart.lnum
6964 || curwin->w_cursor.col != Insstart.col)));
6965 did_backspace = TRUE;
6966 }
6967#ifdef FEAT_SMARTINDENT
6968 did_si = FALSE;
6969 can_si = FALSE;
6970 can_si_back = FALSE;
6971#endif
6972 if (curwin->w_cursor.col <= 1)
6973 did_ai = FALSE;
6974 /*
6975 * It's a little strange to put backspaces into the redo
6976 * buffer, but it makes auto-indent a lot easier to deal
6977 * with.
6978 */
6979 AppendCharToRedobuff(c);
6980
6981 /* If deleted before the insertion point, adjust it */
6982 if (curwin->w_cursor.lnum == Insstart.lnum
6983 && curwin->w_cursor.col < Insstart.col)
6984 Insstart.col = curwin->w_cursor.col;
6985
6986 /* vi behaviour: the cursor moves backward but the character that
6987 * was there remains visible
6988 * Vim behaviour: the cursor moves backward and the character that
6989 * was there is erased from the screen.
6990 * We can emulate the vi behaviour by pretending there is a dollar
6991 * displayed even when there isn't.
6992 * --pkv Sun Jan 19 01:56:40 EST 2003 */
6993 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
6994 dollar_vcol = curwin->w_virtcol;
6995
6996 return did_backspace;
6997}
6998
6999#ifdef FEAT_MOUSE
7000 static void
7001ins_mouse(c)
7002 int c;
7003{
7004 pos_T tpos;
7005
7006# ifdef FEAT_GUI
7007 /* When GUI is active, also move/paste when 'mouse' is empty */
7008 if (!gui.in_use)
7009# endif
7010 if (!mouse_has(MOUSE_INSERT))
7011 return;
7012
7013 undisplay_dollar();
7014 tpos = curwin->w_cursor;
7015 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
7016 {
7017 start_arrow(&tpos);
7018# ifdef FEAT_CINDENT
7019 can_cindent = TRUE;
7020# endif
7021 }
7022
7023#ifdef FEAT_WINDOWS
7024 /* redraw status lines (in case another window became active) */
7025 redraw_statuslines();
7026#endif
7027}
7028
7029 static void
7030ins_mousescroll(up)
7031 int up;
7032{
7033 pos_T tpos;
7034# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7035 win_T *old_curwin;
7036# endif
7037
7038 tpos = curwin->w_cursor;
7039
7040# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7041 old_curwin = curwin;
7042
7043 /* Currently the mouse coordinates are only known in the GUI. */
7044 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
7045 {
7046 int row, col;
7047
7048 row = mouse_row;
7049 col = mouse_col;
7050
7051 /* find the window at the pointer coordinates */
7052 curwin = mouse_find_win(&row, &col);
7053 curbuf = curwin->w_buffer;
7054 }
7055 if (curwin == old_curwin)
7056# endif
7057 undisplay_dollar();
7058
7059 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
7060 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
7061 else
7062 scroll_redraw(up, 3L);
7063
7064# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7065 curwin->w_redr_status = TRUE;
7066
7067 curwin = old_curwin;
7068 curbuf = curwin->w_buffer;
7069# endif
7070
7071 if (!equalpos(curwin->w_cursor, tpos))
7072 {
7073 start_arrow(&tpos);
7074# ifdef FEAT_CINDENT
7075 can_cindent = TRUE;
7076# endif
7077 }
7078}
7079#endif
7080
7081#ifdef FEAT_GUI
7082 void
7083ins_scroll()
7084{
7085 pos_T tpos;
7086
7087 undisplay_dollar();
7088 tpos = curwin->w_cursor;
7089 if (gui_do_scroll())
7090 {
7091 start_arrow(&tpos);
7092# ifdef FEAT_CINDENT
7093 can_cindent = TRUE;
7094# endif
7095 }
7096}
7097
7098 void
7099ins_horscroll()
7100{
7101 pos_T tpos;
7102
7103 undisplay_dollar();
7104 tpos = curwin->w_cursor;
7105 if (gui_do_horiz_scroll())
7106 {
7107 start_arrow(&tpos);
7108# ifdef FEAT_CINDENT
7109 can_cindent = TRUE;
7110# endif
7111 }
7112}
7113#endif
7114
7115 static void
7116ins_left()
7117{
7118 pos_T tpos;
7119
7120#ifdef FEAT_FOLDING
7121 if ((fdo_flags & FDO_HOR) && KeyTyped)
7122 foldOpenCursor();
7123#endif
7124 undisplay_dollar();
7125 tpos = curwin->w_cursor;
7126 if (oneleft() == OK)
7127 {
7128 start_arrow(&tpos);
7129#ifdef FEAT_RIGHTLEFT
7130 /* If exit reversed string, position is fixed */
7131 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
7132 revins_legal++;
7133 revins_chars++;
7134#endif
7135 }
7136
7137 /*
7138 * if 'whichwrap' set for cursor in insert mode may go to
7139 * previous line
7140 */
7141 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
7142 {
7143 start_arrow(&tpos);
7144 --(curwin->w_cursor.lnum);
7145 coladvance((colnr_T)MAXCOL);
7146 curwin->w_set_curswant = TRUE; /* so we stay at the end */
7147 }
7148 else
7149 vim_beep();
7150}
7151
7152 static void
7153ins_home(c)
7154 int c;
7155{
7156 pos_T tpos;
7157
7158#ifdef FEAT_FOLDING
7159 if ((fdo_flags & FDO_HOR) && KeyTyped)
7160 foldOpenCursor();
7161#endif
7162 undisplay_dollar();
7163 tpos = curwin->w_cursor;
7164 if (c == K_C_HOME)
7165 curwin->w_cursor.lnum = 1;
7166 curwin->w_cursor.col = 0;
7167#ifdef FEAT_VIRTUALEDIT
7168 curwin->w_cursor.coladd = 0;
7169#endif
7170 curwin->w_curswant = 0;
7171 start_arrow(&tpos);
7172}
7173
7174 static void
7175ins_end(c)
7176 int c;
7177{
7178 pos_T tpos;
7179
7180#ifdef FEAT_FOLDING
7181 if ((fdo_flags & FDO_HOR) && KeyTyped)
7182 foldOpenCursor();
7183#endif
7184 undisplay_dollar();
7185 tpos = curwin->w_cursor;
7186 if (c == K_C_END)
7187 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7188 coladvance((colnr_T)MAXCOL);
7189 curwin->w_curswant = MAXCOL;
7190
7191 start_arrow(&tpos);
7192}
7193
7194 static void
7195ins_s_left()
7196{
7197#ifdef FEAT_FOLDING
7198 if ((fdo_flags & FDO_HOR) && KeyTyped)
7199 foldOpenCursor();
7200#endif
7201 undisplay_dollar();
7202 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
7203 {
7204 start_arrow(&curwin->w_cursor);
7205 (void)bck_word(1L, FALSE, FALSE);
7206 curwin->w_set_curswant = TRUE;
7207 }
7208 else
7209 vim_beep();
7210}
7211
7212 static void
7213ins_right()
7214{
7215#ifdef FEAT_FOLDING
7216 if ((fdo_flags & FDO_HOR) && KeyTyped)
7217 foldOpenCursor();
7218#endif
7219 undisplay_dollar();
7220 if (gchar_cursor() != NUL || virtual_active()
7221 )
7222 {
7223 start_arrow(&curwin->w_cursor);
7224 curwin->w_set_curswant = TRUE;
7225#ifdef FEAT_VIRTUALEDIT
7226 if (virtual_active())
7227 oneright();
7228 else
7229#endif
7230 {
7231#ifdef FEAT_MBYTE
7232 if (has_mbyte)
7233 curwin->w_cursor.col += (*mb_ptr2len_check)(ml_get_cursor());
7234 else
7235#endif
7236 ++curwin->w_cursor.col;
7237 }
7238
7239#ifdef FEAT_RIGHTLEFT
7240 revins_legal++;
7241 if (revins_chars)
7242 revins_chars--;
7243#endif
7244 }
7245 /* if 'whichwrap' set for cursor in insert mode, may move the
7246 * cursor to the next line */
7247 else if (vim_strchr(p_ww, ']') != NULL
7248 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
7249 {
7250 start_arrow(&curwin->w_cursor);
7251 curwin->w_set_curswant = TRUE;
7252 ++curwin->w_cursor.lnum;
7253 curwin->w_cursor.col = 0;
7254 }
7255 else
7256 vim_beep();
7257}
7258
7259 static void
7260ins_s_right()
7261{
7262#ifdef FEAT_FOLDING
7263 if ((fdo_flags & FDO_HOR) && KeyTyped)
7264 foldOpenCursor();
7265#endif
7266 undisplay_dollar();
7267 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
7268 || gchar_cursor() != NUL)
7269 {
7270 start_arrow(&curwin->w_cursor);
7271 (void)fwd_word(1L, FALSE, 0);
7272 curwin->w_set_curswant = TRUE;
7273 }
7274 else
7275 vim_beep();
7276}
7277
7278 static void
7279ins_up(startcol)
7280 int startcol; /* when TRUE move to Insstart.col */
7281{
7282 pos_T tpos;
7283 linenr_T old_topline = curwin->w_topline;
7284#ifdef FEAT_DIFF
7285 int old_topfill = curwin->w_topfill;
7286#endif
7287
7288 undisplay_dollar();
7289 tpos = curwin->w_cursor;
7290 if (cursor_up(1L, TRUE) == OK)
7291 {
7292 if (startcol)
7293 coladvance(getvcol_nolist(&Insstart));
7294 if (old_topline != curwin->w_topline
7295#ifdef FEAT_DIFF
7296 || old_topfill != curwin->w_topfill
7297#endif
7298 )
7299 redraw_later(VALID);
7300 start_arrow(&tpos);
7301#ifdef FEAT_CINDENT
7302 can_cindent = TRUE;
7303#endif
7304 }
7305 else
7306 vim_beep();
7307}
7308
7309 static void
7310ins_pageup()
7311{
7312 pos_T tpos;
7313
7314 undisplay_dollar();
7315 tpos = curwin->w_cursor;
7316 if (onepage(BACKWARD, 1L) == OK)
7317 {
7318 start_arrow(&tpos);
7319#ifdef FEAT_CINDENT
7320 can_cindent = TRUE;
7321#endif
7322 }
7323 else
7324 vim_beep();
7325}
7326
7327 static void
7328ins_down(startcol)
7329 int startcol; /* when TRUE move to Insstart.col */
7330{
7331 pos_T tpos;
7332 linenr_T old_topline = curwin->w_topline;
7333#ifdef FEAT_DIFF
7334 int old_topfill = curwin->w_topfill;
7335#endif
7336
7337 undisplay_dollar();
7338 tpos = curwin->w_cursor;
7339 if (cursor_down(1L, TRUE) == OK)
7340 {
7341 if (startcol)
7342 coladvance(getvcol_nolist(&Insstart));
7343 if (old_topline != curwin->w_topline
7344#ifdef FEAT_DIFF
7345 || old_topfill != curwin->w_topfill
7346#endif
7347 )
7348 redraw_later(VALID);
7349 start_arrow(&tpos);
7350#ifdef FEAT_CINDENT
7351 can_cindent = TRUE;
7352#endif
7353 }
7354 else
7355 vim_beep();
7356}
7357
7358 static void
7359ins_pagedown()
7360{
7361 pos_T tpos;
7362
7363 undisplay_dollar();
7364 tpos = curwin->w_cursor;
7365 if (onepage(FORWARD, 1L) == OK)
7366 {
7367 start_arrow(&tpos);
7368#ifdef FEAT_CINDENT
7369 can_cindent = TRUE;
7370#endif
7371 }
7372 else
7373 vim_beep();
7374}
7375
7376#ifdef FEAT_DND
7377 static void
7378ins_drop()
7379{
7380 do_put('~', BACKWARD, 1L, PUT_CURSEND);
7381}
7382#endif
7383
7384/*
7385 * Handle TAB in Insert or Replace mode.
7386 * Return TRUE when the TAB needs to be inserted like a normal character.
7387 */
7388 static int
7389ins_tab()
7390{
7391 int ind;
7392 int i;
7393 int temp;
7394
7395 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
7396 Insstart_blank_vcol = get_nolist_virtcol();
7397 if (echeck_abbr(TAB + ABBR_OFF))
7398 return FALSE;
7399
7400 ind = inindent(0);
7401#ifdef FEAT_CINDENT
7402 if (ind)
7403 can_cindent = FALSE;
7404#endif
7405
7406 /*
7407 * When nothing special, insert TAB like a normal character
7408 */
7409 if (!curbuf->b_p_et
7410 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
7411 && curbuf->b_p_sts == 0)
7412 return TRUE;
7413
7414 if (stop_arrow() == FAIL)
7415 return TRUE;
7416
7417 did_ai = FALSE;
7418#ifdef FEAT_SMARTINDENT
7419 did_si = FALSE;
7420 can_si = FALSE;
7421 can_si_back = FALSE;
7422#endif
7423 AppendToRedobuff((char_u *)"\t");
7424
7425 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
7426 temp = (int)curbuf->b_p_sw;
7427 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
7428 temp = (int)curbuf->b_p_sts;
7429 else /* otherwise use 'tabstop' */
7430 temp = (int)curbuf->b_p_ts;
7431 temp -= get_nolist_virtcol() % temp;
7432
7433 /*
7434 * Insert the first space with ins_char(). It will delete one char in
7435 * replace mode. Insert the rest with ins_str(); it will not delete any
7436 * chars. For VREPLACE mode, we use ins_char() for all characters.
7437 */
7438 ins_char(' ');
7439 while (--temp > 0)
7440 {
7441#ifdef FEAT_VREPLACE
7442 if (State & VREPLACE_FLAG)
7443 ins_char(' ');
7444 else
7445#endif
7446 {
7447 ins_str((char_u *)" ");
7448 if (State & REPLACE_FLAG) /* no char replaced */
7449 replace_push(NUL);
7450 }
7451 }
7452
7453 /*
7454 * When 'expandtab' not set: Replace spaces by TABs where possible.
7455 */
7456 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
7457 {
7458 char_u *ptr;
7459#ifdef FEAT_VREPLACE
7460 char_u *saved_line = NULL; /* init for GCC */
7461 pos_T pos;
7462#endif
7463 pos_T fpos;
7464 pos_T *cursor;
7465 colnr_T want_vcol, vcol;
7466 int change_col = -1;
7467 int save_list = curwin->w_p_list;
7468
7469 /*
7470 * Get the current line. For VREPLACE mode, don't make real changes
7471 * yet, just work on a copy of the line.
7472 */
7473#ifdef FEAT_VREPLACE
7474 if (State & VREPLACE_FLAG)
7475 {
7476 pos = curwin->w_cursor;
7477 cursor = &pos;
7478 saved_line = vim_strsave(ml_get_curline());
7479 if (saved_line == NULL)
7480 return FALSE;
7481 ptr = saved_line + pos.col;
7482 }
7483 else
7484#endif
7485 {
7486 ptr = ml_get_cursor();
7487 cursor = &curwin->w_cursor;
7488 }
7489
7490 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
7491 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
7492 curwin->w_p_list = FALSE;
7493
7494 /* Find first white before the cursor */
7495 fpos = curwin->w_cursor;
7496 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
7497 {
7498 --fpos.col;
7499 --ptr;
7500 }
7501
7502 /* In Replace mode, don't change characters before the insert point. */
7503 if ((State & REPLACE_FLAG)
7504 && fpos.lnum == Insstart.lnum
7505 && fpos.col < Insstart.col)
7506 {
7507 ptr += Insstart.col - fpos.col;
7508 fpos.col = Insstart.col;
7509 }
7510
7511 /* compute virtual column numbers of first white and cursor */
7512 getvcol(curwin, &fpos, &vcol, NULL, NULL);
7513 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
7514
7515 /* Use as many TABs as possible. Beware of 'showbreak' and
7516 * 'linebreak' adding extra virtual columns. */
7517 while (vim_iswhite(*ptr))
7518 {
7519 i = lbr_chartabsize((char_u *)"\t", vcol);
7520 if (vcol + i > want_vcol)
7521 break;
7522 if (*ptr != TAB)
7523 {
7524 *ptr = TAB;
7525 if (change_col < 0)
7526 {
7527 change_col = fpos.col; /* Column of first change */
7528 /* May have to adjust Insstart */
7529 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
7530 Insstart.col = fpos.col;
7531 }
7532 }
7533 ++fpos.col;
7534 ++ptr;
7535 vcol += i;
7536 }
7537
7538 if (change_col >= 0)
7539 {
7540 int repl_off = 0;
7541
7542 /* Skip over the spaces we need. */
7543 while (vcol < want_vcol && *ptr == ' ')
7544 {
7545 vcol += lbr_chartabsize(ptr, vcol);
7546 ++ptr;
7547 ++repl_off;
7548 }
7549 if (vcol > want_vcol)
7550 {
7551 /* Must have a char with 'showbreak' just before it. */
7552 --ptr;
7553 --repl_off;
7554 }
7555 fpos.col += repl_off;
7556
7557 /* Delete following spaces. */
7558 i = cursor->col - fpos.col;
7559 if (i > 0)
7560 {
7561 mch_memmove(ptr, ptr + i, STRLEN(ptr + i) + 1);
7562 /* correct replace stack. */
7563 if ((State & REPLACE_FLAG)
7564#ifdef FEAT_VREPLACE
7565 && !(State & VREPLACE_FLAG)
7566#endif
7567 )
7568 for (temp = i; --temp >= 0; )
7569 replace_join(repl_off);
7570 }
Bram Moolenaar009b2592004-10-24 19:18:58 +00007571#ifdef FEAT_NETBEANS_INTG
7572 if (usingNetbeans)
7573 {
7574 netbeans_removed(curbuf, fpos.lnum, cursor->col,
7575 (long)(i + 1));
7576 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
7577 (char_u *)"\t", 1);
7578 }
7579#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007580 cursor->col -= i;
7581
7582#ifdef FEAT_VREPLACE
7583 /*
7584 * In VREPLACE mode, we haven't changed anything yet. Do it now by
7585 * backspacing over the changed spacing and then inserting the new
7586 * spacing.
7587 */
7588 if (State & VREPLACE_FLAG)
7589 {
7590 /* Backspace from real cursor to change_col */
7591 backspace_until_column(change_col);
7592
7593 /* Insert each char in saved_line from changed_col to
7594 * ptr-cursor */
7595 ins_bytes_len(saved_line + change_col,
7596 cursor->col - change_col);
7597 }
7598#endif
7599 }
7600
7601#ifdef FEAT_VREPLACE
7602 if (State & VREPLACE_FLAG)
7603 vim_free(saved_line);
7604#endif
7605 curwin->w_p_list = save_list;
7606 }
7607
7608 return FALSE;
7609}
7610
7611/*
7612 * Handle CR or NL in insert mode.
7613 * Return TRUE when out of memory or can't undo.
7614 */
7615 static int
7616ins_eol(c)
7617 int c;
7618{
7619 int i;
7620
7621 if (echeck_abbr(c + ABBR_OFF))
7622 return FALSE;
7623 if (stop_arrow() == FAIL)
7624 return TRUE;
7625 undisplay_dollar();
7626
7627 /*
7628 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
7629 * character under the cursor. Only push a NUL on the replace stack,
7630 * nothing to put back when the NL is deleted.
7631 */
7632 if ((State & REPLACE_FLAG)
7633#ifdef FEAT_VREPLACE
7634 && !(State & VREPLACE_FLAG)
7635#endif
7636 )
7637 replace_push(NUL);
7638
7639 /*
7640 * In VREPLACE mode, a NL replaces the rest of the line, and starts
7641 * replacing the next line, so we push all of the characters left on the
7642 * line onto the replace stack. This is not done here though, it is done
7643 * in open_line().
7644 */
7645
7646#ifdef FEAT_RIGHTLEFT
7647# ifdef FEAT_FKMAP
7648 if (p_altkeymap && p_fkmap)
7649 fkmap(NL);
7650# endif
7651 /* NL in reverse insert will always start in the end of
7652 * current line. */
7653 if (revins_on)
7654 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
7655#endif
7656
7657 AppendToRedobuff(NL_STR);
7658 i = open_line(FORWARD,
7659#ifdef FEAT_COMMENTS
7660 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
7661#endif
7662 0, old_indent);
7663 old_indent = 0;
7664#ifdef FEAT_CINDENT
7665 can_cindent = TRUE;
7666#endif
7667
7668 return (!i);
7669}
7670
7671#ifdef FEAT_DIGRAPHS
7672/*
7673 * Handle digraph in insert mode.
7674 * Returns character still to be inserted, or NUL when nothing remaining to be
7675 * done.
7676 */
7677 static int
7678ins_digraph()
7679{
7680 int c;
7681 int cc;
7682
7683 pc_status = PC_STATUS_UNSET;
7684 if (redrawing() && !char_avail())
7685 {
7686 /* may need to redraw when no more chars available now */
7687 ins_redraw();
7688
7689 edit_putchar('?', TRUE);
7690#ifdef FEAT_CMDL_INFO
7691 add_to_showcmd_c(Ctrl_K);
7692#endif
7693 }
7694
7695#ifdef USE_ON_FLY_SCROLL
7696 dont_scroll = TRUE; /* disallow scrolling here */
7697#endif
7698
7699 /* don't map the digraph chars. This also prevents the
7700 * mode message to be deleted when ESC is hit */
7701 ++no_mapping;
7702 ++allow_keys;
7703 c = safe_vgetc();
7704 --no_mapping;
7705 --allow_keys;
7706 if (IS_SPECIAL(c) || mod_mask) /* special key */
7707 {
7708#ifdef FEAT_CMDL_INFO
7709 clear_showcmd();
7710#endif
7711 insert_special(c, TRUE, FALSE);
7712 return NUL;
7713 }
7714 if (c != ESC)
7715 {
7716 if (redrawing() && !char_avail())
7717 {
7718 /* may need to redraw when no more chars available now */
7719 ins_redraw();
7720
7721 if (char2cells(c) == 1)
7722 {
7723 /* first remove the '?', otherwise it's restored when typing
7724 * an ESC next */
7725 edit_unputchar();
7726 ins_redraw();
7727 edit_putchar(c, TRUE);
7728 }
7729#ifdef FEAT_CMDL_INFO
7730 add_to_showcmd_c(c);
7731#endif
7732 }
7733 ++no_mapping;
7734 ++allow_keys;
7735 cc = safe_vgetc();
7736 --no_mapping;
7737 --allow_keys;
7738 if (cc != ESC)
7739 {
7740 AppendToRedobuff((char_u *)CTRL_V_STR);
7741 c = getdigraph(c, cc, TRUE);
7742#ifdef FEAT_CMDL_INFO
7743 clear_showcmd();
7744#endif
7745 return c;
7746 }
7747 }
7748 edit_unputchar();
7749#ifdef FEAT_CMDL_INFO
7750 clear_showcmd();
7751#endif
7752 return NUL;
7753}
7754#endif
7755
7756/*
7757 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
7758 * Returns the char to be inserted, or NUL if none found.
7759 */
7760 static int
7761ins_copychar(lnum)
7762 linenr_T lnum;
7763{
7764 int c;
7765 int temp;
7766 char_u *ptr, *prev_ptr;
7767
7768 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
7769 {
7770 vim_beep();
7771 return NUL;
7772 }
7773
7774 /* try to advance to the cursor column */
7775 temp = 0;
7776 ptr = ml_get(lnum);
7777 prev_ptr = ptr;
7778 validate_virtcol();
7779 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
7780 {
7781 prev_ptr = ptr;
7782 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
7783 }
7784 if ((colnr_T)temp > curwin->w_virtcol)
7785 ptr = prev_ptr;
7786
7787#ifdef FEAT_MBYTE
7788 c = (*mb_ptr2char)(ptr);
7789#else
7790 c = *ptr;
7791#endif
7792 if (c == NUL)
7793 vim_beep();
7794 return c;
7795}
7796
7797#ifdef FEAT_SMARTINDENT
7798/*
7799 * Try to do some very smart auto-indenting.
7800 * Used when inserting a "normal" character.
7801 */
7802 static void
7803ins_try_si(c)
7804 int c;
7805{
7806 pos_T *pos, old_pos;
7807 char_u *ptr;
7808 int i;
7809 int temp;
7810
7811 /*
7812 * do some very smart indenting when entering '{' or '}'
7813 */
7814 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
7815 {
7816 /*
7817 * for '}' set indent equal to indent of line containing matching '{'
7818 */
7819 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
7820 {
7821 old_pos = curwin->w_cursor;
7822 /*
7823 * If the matching '{' has a ')' immediately before it (ignoring
7824 * white-space), then line up with the start of the line
7825 * containing the matching '(' if there is one. This handles the
7826 * case where an "if (..\n..) {" statement continues over multiple
7827 * lines -- webb
7828 */
7829 ptr = ml_get(pos->lnum);
7830 i = pos->col;
7831 if (i > 0) /* skip blanks before '{' */
7832 while (--i > 0 && vim_iswhite(ptr[i]))
7833 ;
7834 curwin->w_cursor.lnum = pos->lnum;
7835 curwin->w_cursor.col = i;
7836 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
7837 curwin->w_cursor = *pos;
7838 i = get_indent();
7839 curwin->w_cursor = old_pos;
7840#ifdef FEAT_VREPLACE
7841 if (State & VREPLACE_FLAG)
7842 change_indent(INDENT_SET, i, FALSE, NUL);
7843 else
7844#endif
7845 (void)set_indent(i, SIN_CHANGED);
7846 }
7847 else if (curwin->w_cursor.col > 0)
7848 {
7849 /*
7850 * when inserting '{' after "O" reduce indent, but not
7851 * more than indent of previous line
7852 */
7853 temp = TRUE;
7854 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
7855 {
7856 old_pos = curwin->w_cursor;
7857 i = get_indent();
7858 while (curwin->w_cursor.lnum > 1)
7859 {
7860 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
7861
7862 /* ignore empty lines and lines starting with '#'. */
7863 if (*ptr != '#' && *ptr != NUL)
7864 break;
7865 }
7866 if (get_indent() >= i)
7867 temp = FALSE;
7868 curwin->w_cursor = old_pos;
7869 }
7870 if (temp)
7871 shift_line(TRUE, FALSE, 1);
7872 }
7873 }
7874
7875 /*
7876 * set indent of '#' always to 0
7877 */
7878 if (curwin->w_cursor.col > 0 && can_si && c == '#')
7879 {
7880 /* remember current indent for next line */
7881 old_indent = get_indent();
7882 (void)set_indent(0, SIN_CHANGED);
7883 }
7884
7885 /* Adjust ai_col, the char at this position can be deleted. */
7886 if (ai_col > curwin->w_cursor.col)
7887 ai_col = curwin->w_cursor.col;
7888}
7889#endif
7890
7891/*
7892 * Get the value that w_virtcol would have when 'list' is off.
7893 * Unless 'cpo' contains the 'L' flag.
7894 */
7895 static colnr_T
7896get_nolist_virtcol()
7897{
7898 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
7899 return getvcol_nolist(&curwin->w_cursor);
7900 validate_virtcol();
7901 return curwin->w_virtcol;
7902}