blob: ebfe7fd6996a6a65189a0bf0a505371e39c1edc6 [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
4988/*
4989 * Add character "c" to buffer "s". Escape the special meaning of K_SPECIAL
4990 * and CSI. Handle multi-byte characters.
4991 * Returns a pointer to after the added bytes.
4992 */
4993 char_u *
4994add_char2buf(c, s)
4995 int c;
4996 char_u *s;
4997{
4998#ifdef FEAT_MBYTE
4999 char_u temp[MB_MAXBYTES];
5000 int i;
5001 int len;
5002
5003 len = (*mb_char2bytes)(c, temp);
5004 for (i = 0; i < len; ++i)
5005 {
5006 c = temp[i];
5007#endif
5008 /* Need to escape K_SPECIAL and CSI like in the typeahead buffer. */
5009 if (c == K_SPECIAL)
5010 {
5011 *s++ = K_SPECIAL;
5012 *s++ = KS_SPECIAL;
5013 *s++ = KE_FILLER;
5014 }
5015#ifdef FEAT_GUI
5016 else if (c == CSI)
5017 {
5018 *s++ = CSI;
5019 *s++ = KS_EXTRA;
5020 *s++ = (int)KE_CSI;
5021 }
5022#endif
5023 else
5024 *s++ = c;
5025#ifdef FEAT_MBYTE
5026 }
5027#endif
5028 return s;
5029}
5030
5031/*
5032 * move cursor to start of line
5033 * if flags & BL_WHITE move to first non-white
5034 * if flags & BL_SOL move to first non-white if startofline is set,
5035 * otherwise keep "curswant" column
5036 * if flags & BL_FIX don't leave the cursor on a NUL.
5037 */
5038 void
5039beginline(flags)
5040 int flags;
5041{
5042 if ((flags & BL_SOL) && !p_sol)
5043 coladvance(curwin->w_curswant);
5044 else
5045 {
5046 curwin->w_cursor.col = 0;
5047#ifdef FEAT_VIRTUALEDIT
5048 curwin->w_cursor.coladd = 0;
5049#endif
5050
5051 if (flags & (BL_WHITE | BL_SOL))
5052 {
5053 char_u *ptr;
5054
5055 for (ptr = ml_get_curline(); vim_iswhite(*ptr)
5056 && !((flags & BL_FIX) && ptr[1] == NUL); ++ptr)
5057 ++curwin->w_cursor.col;
5058 }
5059 curwin->w_set_curswant = TRUE;
5060 }
5061}
5062
5063/*
5064 * oneright oneleft cursor_down cursor_up
5065 *
5066 * Move one char {right,left,down,up}.
5067 * Doesn't move onto the NUL past the end of the line.
5068 * Return OK when successful, FAIL when we hit a line of file boundary.
5069 */
5070
5071 int
5072oneright()
5073{
5074 char_u *ptr;
5075#ifdef FEAT_MBYTE
5076 int l;
5077#endif
5078
5079#ifdef FEAT_VIRTUALEDIT
5080 if (virtual_active())
5081 {
5082 pos_T prevpos = curwin->w_cursor;
5083
5084 /* Adjust for multi-wide char (excluding TAB) */
5085 ptr = ml_get_cursor();
5086 coladvance(getviscol() + ((*ptr != TAB && vim_isprintc(
5087#ifdef FEAT_MBYTE
5088 (*mb_ptr2char)(ptr)
5089#else
5090 *ptr
5091#endif
5092 ))
5093 ? ptr2cells(ptr) : 1));
5094 curwin->w_set_curswant = TRUE;
5095 /* Return OK if the cursor moved, FAIL otherwise (at window edge). */
5096 return (prevpos.col != curwin->w_cursor.col
5097 || prevpos.coladd != curwin->w_cursor.coladd) ? OK : FAIL;
5098 }
5099#endif
5100
5101 ptr = ml_get_cursor();
5102#ifdef FEAT_MBYTE
5103 if (has_mbyte && (l = (*mb_ptr2len_check)(ptr)) > 1)
5104 {
5105 /* The character under the cursor is a multi-byte character, move
5106 * several bytes right, but don't end up on the NUL. */
5107 if (ptr[l] == NUL)
5108 return FAIL;
5109 curwin->w_cursor.col += l;
5110 }
5111 else
5112#endif
5113 {
5114 if (*ptr++ == NUL || *ptr == NUL)
5115 return FAIL;
5116 ++curwin->w_cursor.col;
5117 }
5118
5119 curwin->w_set_curswant = TRUE;
5120 return OK;
5121}
5122
5123 int
5124oneleft()
5125{
5126#ifdef FEAT_VIRTUALEDIT
5127 if (virtual_active())
5128 {
5129 int width;
5130 int v = getviscol();
5131
5132 if (v == 0)
5133 return FAIL;
5134
5135# ifdef FEAT_LINEBREAK
5136 /* We might get stuck on 'showbreak', skip over it. */
5137 width = 1;
5138 for (;;)
5139 {
5140 coladvance(v - width);
5141 /* getviscol() is slow, skip it when 'showbreak' is empty and
5142 * there are no multi-byte characters */
5143 if ((*p_sbr == NUL
5144# ifdef FEAT_MBYTE
5145 && !has_mbyte
5146# endif
5147 ) || getviscol() < v)
5148 break;
5149 ++width;
5150 }
5151# else
5152 coladvance(v - 1);
5153# endif
5154
5155 if (curwin->w_cursor.coladd == 1)
5156 {
5157 char_u *ptr;
5158
5159 /* Adjust for multi-wide char (not a TAB) */
5160 ptr = ml_get_cursor();
5161 if (*ptr != TAB && vim_isprintc(
5162# ifdef FEAT_MBYTE
5163 (*mb_ptr2char)(ptr)
5164# else
5165 *ptr
5166# endif
5167 ) && ptr2cells(ptr) > 1)
5168 curwin->w_cursor.coladd = 0;
5169 }
5170
5171 curwin->w_set_curswant = TRUE;
5172 return OK;
5173 }
5174#endif
5175
5176 if (curwin->w_cursor.col == 0)
5177 return FAIL;
5178
5179 curwin->w_set_curswant = TRUE;
5180 --curwin->w_cursor.col;
5181
5182#ifdef FEAT_MBYTE
5183 /* if the character on the left of the current cursor is a multi-byte
5184 * character, move to its first byte */
5185 if (has_mbyte)
5186 mb_adjust_cursor();
5187#endif
5188 return OK;
5189}
5190
5191 int
5192cursor_up(n, upd_topline)
5193 long n;
5194 int upd_topline; /* When TRUE: update topline */
5195{
5196 linenr_T lnum;
5197
5198 if (n > 0)
5199 {
5200 lnum = curwin->w_cursor.lnum;
Bram Moolenaar7c626922005-02-07 22:01:03 +00005201 /* This fails if the cursor is already in the first line or the count
5202 * is larger than the line number and '-' is in 'cpoptions' */
5203 if (lnum <= 1 || (n >= lnum && vim_strchr(p_cpo, CPO_MINUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 return FAIL;
5205 if (n >= lnum)
5206 lnum = 1;
5207 else
5208#ifdef FEAT_FOLDING
5209 if (hasAnyFolding(curwin))
5210 {
5211 /*
5212 * Count each sequence of folded lines as one logical line.
5213 */
5214 /* go to the the start of the current fold */
5215 (void)hasFolding(lnum, &lnum, NULL);
5216
5217 while (n--)
5218 {
5219 /* move up one line */
5220 --lnum;
5221 if (lnum <= 1)
5222 break;
5223 /* If we entered a fold, move to the beginning, unless in
5224 * Insert mode or when 'foldopen' contains "all": it will open
5225 * in a moment. */
5226 if (n > 0 || !((State & INSERT) || (fdo_flags & FDO_ALL)))
5227 (void)hasFolding(lnum, &lnum, NULL);
5228 }
5229 if (lnum < 1)
5230 lnum = 1;
5231 }
5232 else
5233#endif
5234 lnum -= n;
5235 curwin->w_cursor.lnum = lnum;
5236 }
5237
5238 /* try to advance to the column we want to be at */
5239 coladvance(curwin->w_curswant);
5240
5241 if (upd_topline)
5242 update_topline(); /* make sure curwin->w_topline is valid */
5243
5244 return OK;
5245}
5246
5247/*
5248 * Cursor down a number of logical lines.
5249 */
5250 int
5251cursor_down(n, upd_topline)
5252 long n;
5253 int upd_topline; /* When TRUE: update topline */
5254{
5255 linenr_T lnum;
5256
5257 if (n > 0)
5258 {
5259 lnum = curwin->w_cursor.lnum;
5260#ifdef FEAT_FOLDING
5261 /* Move to last line of fold, will fail if it's the end-of-file. */
5262 (void)hasFolding(lnum, NULL, &lnum);
5263#endif
Bram Moolenaar7c626922005-02-07 22:01:03 +00005264 /* This fails if the cursor is already in the last line or would move
5265 * beyound the last line and '-' is in 'cpoptions' */
5266 if (lnum >= curbuf->b_ml.ml_line_count
5267 || (lnum + n > curbuf->b_ml.ml_line_count
5268 && vim_strchr(p_cpo, CPO_MINUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005269 return FAIL;
5270 if (lnum + n >= curbuf->b_ml.ml_line_count)
5271 lnum = curbuf->b_ml.ml_line_count;
5272 else
5273#ifdef FEAT_FOLDING
5274 if (hasAnyFolding(curwin))
5275 {
5276 linenr_T last;
5277
5278 /* count each sequence of folded lines as one logical line */
5279 while (n--)
5280 {
5281 if (hasFolding(lnum, NULL, &last))
5282 lnum = last + 1;
5283 else
5284 ++lnum;
5285 if (lnum >= curbuf->b_ml.ml_line_count)
5286 break;
5287 }
5288 if (lnum > curbuf->b_ml.ml_line_count)
5289 lnum = curbuf->b_ml.ml_line_count;
5290 }
5291 else
5292#endif
5293 lnum += n;
5294 curwin->w_cursor.lnum = lnum;
5295 }
5296
5297 /* try to advance to the column we want to be at */
5298 coladvance(curwin->w_curswant);
5299
5300 if (upd_topline)
5301 update_topline(); /* make sure curwin->w_topline is valid */
5302
5303 return OK;
5304}
5305
5306/*
5307 * Stuff the last inserted text in the read buffer.
5308 * Last_insert actually is a copy of the redo buffer, so we
5309 * first have to remove the command.
5310 */
5311 int
5312stuff_inserted(c, count, no_esc)
5313 int c; /* Command character to be inserted */
5314 long count; /* Repeat this many times */
5315 int no_esc; /* Don't add an ESC at the end */
5316{
5317 char_u *esc_ptr;
5318 char_u *ptr;
5319 char_u *last_ptr;
5320 char_u last = NUL;
5321
5322 ptr = get_last_insert();
5323 if (ptr == NULL)
5324 {
5325 EMSG(_(e_noinstext));
5326 return FAIL;
5327 }
5328
5329 /* may want to stuff the command character, to start Insert mode */
5330 if (c != NUL)
5331 stuffcharReadbuff(c);
5332 if ((esc_ptr = (char_u *)vim_strrchr(ptr, ESC)) != NULL)
5333 *esc_ptr = NUL; /* remove the ESC */
5334
5335 /* when the last char is either "0" or "^" it will be quoted if no ESC
5336 * comes after it OR if it will inserted more than once and "ptr"
5337 * starts with ^D. -- Acevedo
5338 */
5339 last_ptr = (esc_ptr ? esc_ptr : ptr + STRLEN(ptr)) - 1;
5340 if (last_ptr >= ptr && (*last_ptr == '0' || *last_ptr == '^')
5341 && (no_esc || (*ptr == Ctrl_D && count > 1)))
5342 {
5343 last = *last_ptr;
5344 *last_ptr = NUL;
5345 }
5346
5347 do
5348 {
5349 stuffReadbuff(ptr);
5350 /* a trailing "0" is inserted as "<C-V>048", "^" as "<C-V>^" */
5351 if (last)
5352 stuffReadbuff((char_u *)(last == '0'
5353 ? IF_EB("\026\060\064\070", CTRL_V_STR "xf0")
5354 : IF_EB("\026^", CTRL_V_STR "^")));
5355 }
5356 while (--count > 0);
5357
5358 if (last)
5359 *last_ptr = last;
5360
5361 if (esc_ptr != NULL)
5362 *esc_ptr = ESC; /* put the ESC back */
5363
5364 /* may want to stuff a trailing ESC, to get out of Insert mode */
5365 if (!no_esc)
5366 stuffcharReadbuff(ESC);
5367
5368 return OK;
5369}
5370
5371 char_u *
5372get_last_insert()
5373{
5374 if (last_insert == NULL)
5375 return NULL;
5376 return last_insert + last_insert_skip;
5377}
5378
5379/*
5380 * Get last inserted string, and remove trailing <Esc>.
5381 * Returns pointer to allocated memory (must be freed) or NULL.
5382 */
5383 char_u *
5384get_last_insert_save()
5385{
5386 char_u *s;
5387 int len;
5388
5389 if (last_insert == NULL)
5390 return NULL;
5391 s = vim_strsave(last_insert + last_insert_skip);
5392 if (s != NULL)
5393 {
5394 len = (int)STRLEN(s);
5395 if (len > 0 && s[len - 1] == ESC) /* remove trailing ESC */
5396 s[len - 1] = NUL;
5397 }
5398 return s;
5399}
5400
5401/*
5402 * Check the word in front of the cursor for an abbreviation.
5403 * Called when the non-id character "c" has been entered.
5404 * When an abbreviation is recognized it is removed from the text and
5405 * the replacement string is inserted in typebuf.tb_buf[], followed by "c".
5406 */
5407 static int
5408echeck_abbr(c)
5409 int c;
5410{
5411 /* Don't check for abbreviation in paste mode, when disabled and just
5412 * after moving around with cursor keys. */
5413 if (p_paste || no_abbr || arrow_used)
5414 return FALSE;
5415
5416 return check_abbr(c, ml_get_curline(), curwin->w_cursor.col,
5417 curwin->w_cursor.lnum == Insstart.lnum ? Insstart.col : 0);
5418}
5419
5420/*
5421 * replace-stack functions
5422 *
5423 * When replacing characters, the replaced characters are remembered for each
5424 * new character. This is used to re-insert the old text when backspacing.
5425 *
5426 * There is a NUL headed list of characters for each character that is
5427 * currently in the file after the insertion point. When BS is used, one NUL
5428 * headed list is put back for the deleted character.
5429 *
5430 * For a newline, there are two NUL headed lists. One contains the characters
5431 * that the NL replaced. The extra one stores the characters after the cursor
5432 * that were deleted (always white space).
5433 *
5434 * Replace_offset is normally 0, in which case replace_push will add a new
5435 * character at the end of the stack. If replace_offset is not 0, that many
5436 * characters will be left on the stack above the newly inserted character.
5437 */
5438
Bram Moolenaar6c0b44b2005-06-01 21:56:33 +00005439static char_u *replace_stack = NULL;
5440static long replace_stack_nr = 0; /* next entry in replace stack */
5441static long replace_stack_len = 0; /* max. number of entries */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442
5443 void
5444replace_push(c)
5445 int c; /* character that is replaced (NUL is none) */
5446{
5447 char_u *p;
5448
5449 if (replace_stack_nr < replace_offset) /* nothing to do */
5450 return;
5451 if (replace_stack_len <= replace_stack_nr)
5452 {
5453 replace_stack_len += 50;
5454 p = lalloc(sizeof(char_u) * replace_stack_len, TRUE);
5455 if (p == NULL) /* out of memory */
5456 {
5457 replace_stack_len -= 50;
5458 return;
5459 }
5460 if (replace_stack != NULL)
5461 {
5462 mch_memmove(p, replace_stack,
5463 (size_t)(replace_stack_nr * sizeof(char_u)));
5464 vim_free(replace_stack);
5465 }
5466 replace_stack = p;
5467 }
5468 p = replace_stack + replace_stack_nr - replace_offset;
5469 if (replace_offset)
5470 mch_memmove(p + 1, p, (size_t)(replace_offset * sizeof(char_u)));
5471 *p = c;
5472 ++replace_stack_nr;
5473}
5474
5475/*
5476 * call replace_push(c) with replace_offset set to the first NUL.
5477 */
5478 static void
5479replace_push_off(c)
5480 int c;
5481{
5482 char_u *p;
5483
5484 p = replace_stack + replace_stack_nr;
5485 for (replace_offset = 1; replace_offset < replace_stack_nr;
5486 ++replace_offset)
5487 if (*--p == NUL)
5488 break;
5489 replace_push(c);
5490 replace_offset = 0;
5491}
5492
5493/*
5494 * Pop one item from the replace stack.
5495 * return -1 if stack empty
5496 * return replaced character or NUL otherwise
5497 */
5498 static int
5499replace_pop()
5500{
5501 if (replace_stack_nr == 0)
5502 return -1;
5503 return (int)replace_stack[--replace_stack_nr];
5504}
5505
5506/*
5507 * Join the top two items on the replace stack. This removes to "off"'th NUL
5508 * encountered.
5509 */
5510 static void
5511replace_join(off)
5512 int off; /* offset for which NUL to remove */
5513{
5514 int i;
5515
5516 for (i = replace_stack_nr; --i >= 0; )
5517 if (replace_stack[i] == NUL && off-- <= 0)
5518 {
5519 --replace_stack_nr;
5520 mch_memmove(replace_stack + i, replace_stack + i + 1,
5521 (size_t)(replace_stack_nr - i));
5522 return;
5523 }
5524}
5525
5526/*
5527 * Pop bytes from the replace stack until a NUL is found, and insert them
5528 * before the cursor. Can only be used in REPLACE or VREPLACE mode.
5529 */
5530 static void
5531replace_pop_ins()
5532{
5533 int cc;
5534 int oldState = State;
5535
5536 State = NORMAL; /* don't want REPLACE here */
5537 while ((cc = replace_pop()) > 0)
5538 {
5539#ifdef FEAT_MBYTE
5540 mb_replace_pop_ins(cc);
5541#else
5542 ins_char(cc);
5543#endif
5544 dec_cursor();
5545 }
5546 State = oldState;
5547}
5548
5549#ifdef FEAT_MBYTE
5550/*
5551 * Insert bytes popped from the replace stack. "cc" is the first byte. If it
5552 * indicates a multi-byte char, pop the other bytes too.
5553 */
5554 static void
5555mb_replace_pop_ins(cc)
5556 int cc;
5557{
5558 int n;
5559 char_u buf[MB_MAXBYTES];
5560 int i;
5561 int c;
5562
5563 if (has_mbyte && (n = MB_BYTE2LEN(cc)) > 1)
5564 {
5565 buf[0] = cc;
5566 for (i = 1; i < n; ++i)
5567 buf[i] = replace_pop();
5568 ins_bytes_len(buf, n);
5569 }
5570 else
5571 ins_char(cc);
5572
5573 if (enc_utf8)
5574 /* Handle composing chars. */
5575 for (;;)
5576 {
5577 c = replace_pop();
5578 if (c == -1) /* stack empty */
5579 break;
5580 if ((n = MB_BYTE2LEN(c)) == 1)
5581 {
5582 /* Not a multi-byte char, put it back. */
5583 replace_push(c);
5584 break;
5585 }
5586 else
5587 {
5588 buf[0] = c;
5589 for (i = 1; i < n; ++i)
5590 buf[i] = replace_pop();
5591 if (utf_iscomposing(utf_ptr2char(buf)))
5592 ins_bytes_len(buf, n);
5593 else
5594 {
5595 /* Not a composing char, put it back. */
5596 for (i = n - 1; i >= 0; --i)
5597 replace_push(buf[i]);
5598 break;
5599 }
5600 }
5601 }
5602}
5603#endif
5604
5605/*
5606 * make the replace stack empty
5607 * (called when exiting replace mode)
5608 */
5609 static void
5610replace_flush()
5611{
5612 vim_free(replace_stack);
5613 replace_stack = NULL;
5614 replace_stack_len = 0;
5615 replace_stack_nr = 0;
5616}
5617
5618/*
5619 * Handle doing a BS for one character.
5620 * cc < 0: replace stack empty, just move cursor
5621 * cc == 0: character was inserted, delete it
5622 * cc > 0: character was replaced, put cc (first byte of original char) back
5623 * and check for more characters to be put back
5624 */
5625 static void
5626replace_do_bs()
5627{
5628 int cc;
5629#ifdef FEAT_VREPLACE
5630 int orig_len = 0;
5631 int ins_len;
5632 int orig_vcols = 0;
5633 colnr_T start_vcol;
5634 char_u *p;
5635 int i;
5636 int vcol;
5637#endif
5638
5639 cc = replace_pop();
5640 if (cc > 0)
5641 {
5642#ifdef FEAT_VREPLACE
5643 if (State & VREPLACE_FLAG)
5644 {
5645 /* Get the number of screen cells used by the character we are
5646 * going to delete. */
5647 getvcol(curwin, &curwin->w_cursor, NULL, &start_vcol, NULL);
5648 orig_vcols = chartabsize(ml_get_cursor(), start_vcol);
5649 }
5650#endif
5651#ifdef FEAT_MBYTE
5652 if (has_mbyte)
5653 {
5654 del_char(FALSE);
5655# ifdef FEAT_VREPLACE
5656 if (State & VREPLACE_FLAG)
5657 orig_len = STRLEN(ml_get_cursor());
5658# endif
5659 replace_push(cc);
5660 }
5661 else
5662#endif
5663 {
5664 pchar_cursor(cc);
5665#ifdef FEAT_VREPLACE
5666 if (State & VREPLACE_FLAG)
5667 orig_len = STRLEN(ml_get_cursor()) - 1;
5668#endif
5669 }
5670 replace_pop_ins();
5671
5672#ifdef FEAT_VREPLACE
5673 if (State & VREPLACE_FLAG)
5674 {
5675 /* Get the number of screen cells used by the inserted characters */
5676 p = ml_get_cursor();
5677 ins_len = STRLEN(p) - orig_len;
5678 vcol = start_vcol;
5679 for (i = 0; i < ins_len; ++i)
5680 {
5681 vcol += chartabsize(p + i, vcol);
5682#ifdef FEAT_MBYTE
5683 i += (*mb_ptr2len_check)(p) - 1;
5684#endif
5685 }
5686 vcol -= start_vcol;
5687
5688 /* Delete spaces that were inserted after the cursor to keep the
5689 * text aligned. */
5690 curwin->w_cursor.col += ins_len;
5691 while (vcol > orig_vcols && gchar_cursor() == ' ')
5692 {
5693 del_char(FALSE);
5694 ++orig_vcols;
5695 }
5696 curwin->w_cursor.col -= ins_len;
5697 }
5698#endif
5699
5700 /* mark the buffer as changed and prepare for displaying */
5701 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
5702 }
5703 else if (cc == 0)
5704 (void)del_char(FALSE);
5705}
5706
5707#ifdef FEAT_CINDENT
5708/*
5709 * Return TRUE if C-indenting is on.
5710 */
5711 static int
5712cindent_on()
5713{
5714 return (!p_paste && (curbuf->b_p_cin
5715# ifdef FEAT_EVAL
5716 || *curbuf->b_p_inde != NUL
5717# endif
5718 ));
5719}
5720#endif
5721
5722#if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
5723/*
5724 * Re-indent the current line, based on the current contents of it and the
5725 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
5726 * confused what all the part that handles Control-T is doing that I'm not.
5727 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
5728 */
5729
5730 void
5731fixthisline(get_the_indent)
5732 int (*get_the_indent) __ARGS((void));
5733{
5734 change_indent(INDENT_SET, get_the_indent(), FALSE, 0);
5735 if (linewhite(curwin->w_cursor.lnum))
5736 did_ai = TRUE; /* delete the indent if the line stays empty */
5737}
5738
5739 void
5740fix_indent()
5741{
5742 if (p_paste)
5743 return;
5744# ifdef FEAT_LISP
5745 if (curbuf->b_p_lisp && curbuf->b_p_ai)
5746 fixthisline(get_lisp_indent);
5747# endif
5748# if defined(FEAT_LISP) && defined(FEAT_CINDENT)
5749 else
5750# endif
5751# ifdef FEAT_CINDENT
5752 if (cindent_on())
5753 do_c_expr_indent();
5754# endif
5755}
5756
5757#endif
5758
5759#ifdef FEAT_CINDENT
5760/*
5761 * return TRUE if 'cinkeys' contains the key "keytyped",
5762 * when == '*': Only if key is preceded with '*' (indent before insert)
5763 * when == '!': Only if key is prededed with '!' (don't insert)
5764 * when == ' ': Only if key is not preceded with '*'(indent afterwards)
5765 *
5766 * "keytyped" can have a few special values:
5767 * KEY_OPEN_FORW
5768 * KEY_OPEN_BACK
5769 * KEY_COMPLETE just finished completion.
5770 *
5771 * If line_is_empty is TRUE accept keys with '0' before them.
5772 */
5773 int
5774in_cinkeys(keytyped, when, line_is_empty)
5775 int keytyped;
5776 int when;
5777 int line_is_empty;
5778{
5779 char_u *look;
5780 int try_match;
5781 int try_match_word;
5782 char_u *p;
5783 char_u *line;
5784 int icase;
5785 int i;
5786
5787#ifdef FEAT_EVAL
5788 if (*curbuf->b_p_inde != NUL)
5789 look = curbuf->b_p_indk; /* 'indentexpr' set: use 'indentkeys' */
5790 else
5791#endif
5792 look = curbuf->b_p_cink; /* 'indentexpr' empty: use 'cinkeys' */
5793 while (*look)
5794 {
5795 /*
5796 * Find out if we want to try a match with this key, depending on
5797 * 'when' and a '*' or '!' before the key.
5798 */
5799 switch (when)
5800 {
5801 case '*': try_match = (*look == '*'); break;
5802 case '!': try_match = (*look == '!'); break;
5803 default: try_match = (*look != '*'); break;
5804 }
5805 if (*look == '*' || *look == '!')
5806 ++look;
5807
5808 /*
5809 * If there is a '0', only accept a match if the line is empty.
5810 * But may still match when typing last char of a word.
5811 */
5812 if (*look == '0')
5813 {
5814 try_match_word = try_match;
5815 if (!line_is_empty)
5816 try_match = FALSE;
5817 ++look;
5818 }
5819 else
5820 try_match_word = FALSE;
5821
5822 /*
5823 * does it look like a control character?
5824 */
5825 if (*look == '^'
5826#ifdef EBCDIC
5827 && (Ctrl_chr(look[1]) != 0)
5828#else
5829 && look[1] >= '?' && look[1] <= '_'
5830#endif
5831 )
5832 {
5833 if (try_match && keytyped == Ctrl_chr(look[1]))
5834 return TRUE;
5835 look += 2;
5836 }
5837 /*
5838 * 'o' means "o" command, open forward.
5839 * 'O' means "O" command, open backward.
5840 */
5841 else if (*look == 'o')
5842 {
5843 if (try_match && keytyped == KEY_OPEN_FORW)
5844 return TRUE;
5845 ++look;
5846 }
5847 else if (*look == 'O')
5848 {
5849 if (try_match && keytyped == KEY_OPEN_BACK)
5850 return TRUE;
5851 ++look;
5852 }
5853
5854 /*
5855 * 'e' means to check for "else" at start of line and just before the
5856 * cursor.
5857 */
5858 else if (*look == 'e')
5859 {
5860 if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4)
5861 {
5862 p = ml_get_curline();
5863 if (skipwhite(p) == p + curwin->w_cursor.col - 4 &&
5864 STRNCMP(p + curwin->w_cursor.col - 4, "else", 4) == 0)
5865 return TRUE;
5866 }
5867 ++look;
5868 }
5869
5870 /*
5871 * ':' only causes an indent if it is at the end of a label or case
5872 * statement, or when it was before typing the ':' (to fix
5873 * class::method for C++).
5874 */
5875 else if (*look == ':')
5876 {
5877 if (try_match && keytyped == ':')
5878 {
5879 p = ml_get_curline();
5880 if (cin_iscase(p) || cin_isscopedecl(p) || cin_islabel(30))
5881 return TRUE;
5882 if (curwin->w_cursor.col > 2
5883 && p[curwin->w_cursor.col - 1] == ':'
5884 && p[curwin->w_cursor.col - 2] == ':')
5885 {
5886 p[curwin->w_cursor.col - 1] = ' ';
5887 i = (cin_iscase(p) || cin_isscopedecl(p)
5888 || cin_islabel(30));
5889 p = ml_get_curline();
5890 p[curwin->w_cursor.col - 1] = ':';
5891 if (i)
5892 return TRUE;
5893 }
5894 }
5895 ++look;
5896 }
5897
5898
5899 /*
5900 * Is it a key in <>, maybe?
5901 */
5902 else if (*look == '<')
5903 {
5904 if (try_match)
5905 {
5906 /*
5907 * make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
5908 * <:> and <!> so that people can re-indent on o, O, e, 0, <,
5909 * >, *, : and ! keys if they really really want to.
5910 */
5911 if (vim_strchr((char_u *)"<>!*oOe0:", look[1]) != NULL
5912 && keytyped == look[1])
5913 return TRUE;
5914
5915 if (keytyped == get_special_key_code(look + 1))
5916 return TRUE;
5917 }
5918 while (*look && *look != '>')
5919 look++;
5920 while (*look == '>')
5921 look++;
5922 }
5923
5924 /*
5925 * Is it a word: "=word"?
5926 */
5927 else if (*look == '=' && look[1] != ',' && look[1] != NUL)
5928 {
5929 ++look;
5930 if (*look == '~')
5931 {
5932 icase = TRUE;
5933 ++look;
5934 }
5935 else
5936 icase = FALSE;
5937 p = vim_strchr(look, ',');
5938 if (p == NULL)
5939 p = look + STRLEN(look);
5940 if ((try_match || try_match_word)
5941 && curwin->w_cursor.col >= (colnr_T)(p - look))
5942 {
5943 int match = FALSE;
5944
5945#ifdef FEAT_INS_EXPAND
5946 if (keytyped == KEY_COMPLETE)
5947 {
5948 char_u *s;
5949
5950 /* Just completed a word, check if it starts with "look".
5951 * search back for the start of a word. */
5952 line = ml_get_curline();
5953# ifdef FEAT_MBYTE
5954 if (has_mbyte)
5955 {
5956 char_u *n;
5957
5958 for (s = line + curwin->w_cursor.col; s > line; s = n)
5959 {
5960 n = mb_prevptr(line, s);
5961 if (!vim_iswordp(n))
5962 break;
5963 }
5964 }
5965 else
5966# endif
5967 for (s = line + curwin->w_cursor.col; s > line; --s)
5968 if (!vim_iswordc(s[-1]))
5969 break;
5970 if (s + (p - look) <= line + curwin->w_cursor.col
5971 && (icase
5972 ? MB_STRNICMP(s, look, p - look)
5973 : STRNCMP(s, look, p - look)) == 0)
5974 match = TRUE;
5975 }
5976 else
5977#endif
5978 /* TODO: multi-byte */
5979 if (keytyped == (int)p[-1] || (icase && keytyped < 256
5980 && TOLOWER_LOC(keytyped) == TOLOWER_LOC((int)p[-1])))
5981 {
5982 line = ml_get_cursor();
5983 if ((curwin->w_cursor.col == (colnr_T)(p - look)
5984 || !vim_iswordc(line[-(p - look) - 1]))
5985 && (icase
5986 ? MB_STRNICMP(line - (p - look), look, p - look)
5987 : STRNCMP(line - (p - look), look, p - look))
5988 == 0)
5989 match = TRUE;
5990 }
5991 if (match && try_match_word && !try_match)
5992 {
5993 /* "0=word": Check if there are only blanks before the
5994 * word. */
5995 line = ml_get_curline();
5996 if ((int)(skipwhite(line) - line) !=
5997 (int)(curwin->w_cursor.col - (p - look)))
5998 match = FALSE;
5999 }
6000 if (match)
6001 return TRUE;
6002 }
6003 look = p;
6004 }
6005
6006 /*
6007 * ok, it's a boring generic character.
6008 */
6009 else
6010 {
6011 if (try_match && *look == keytyped)
6012 return TRUE;
6013 ++look;
6014 }
6015
6016 /*
6017 * Skip over ", ".
6018 */
6019 look = skip_to_option_part(look);
6020 }
6021 return FALSE;
6022}
6023#endif /* FEAT_CINDENT */
6024
6025#if defined(FEAT_RIGHTLEFT) || defined(PROTO)
6026/*
6027 * Map Hebrew keyboard when in hkmap mode.
6028 */
6029 int
6030hkmap(c)
6031 int c;
6032{
6033 if (p_hkmapp) /* phonetic mapping, by Ilya Dogolazky */
6034 {
6035 enum {hALEF=0, BET, GIMEL, DALET, HEI, VAV, ZAIN, HET, TET, IUD,
6036 KAFsofit, hKAF, LAMED, MEMsofit, MEM, NUNsofit, NUN, SAMEH, AIN,
6037 PEIsofit, PEI, ZADIsofit, ZADI, KOF, RESH, hSHIN, TAV};
6038 static char_u map[26] =
6039 {(char_u)hALEF/*a*/, (char_u)BET /*b*/, (char_u)hKAF /*c*/,
6040 (char_u)DALET/*d*/, (char_u)-1 /*e*/, (char_u)PEIsofit/*f*/,
6041 (char_u)GIMEL/*g*/, (char_u)HEI /*h*/, (char_u)IUD /*i*/,
6042 (char_u)HET /*j*/, (char_u)KOF /*k*/, (char_u)LAMED /*l*/,
6043 (char_u)MEM /*m*/, (char_u)NUN /*n*/, (char_u)SAMEH /*o*/,
6044 (char_u)PEI /*p*/, (char_u)-1 /*q*/, (char_u)RESH /*r*/,
6045 (char_u)ZAIN /*s*/, (char_u)TAV /*t*/, (char_u)TET /*u*/,
6046 (char_u)VAV /*v*/, (char_u)hSHIN/*w*/, (char_u)-1 /*x*/,
6047 (char_u)AIN /*y*/, (char_u)ZADI /*z*/};
6048
6049 if (c == 'N' || c == 'M' || c == 'P' || c == 'C' || c == 'Z')
6050 return (int)(map[CharOrd(c)] - 1 + p_aleph);
6051 /* '-1'='sofit' */
6052 else if (c == 'x')
6053 return 'X';
6054 else if (c == 'q')
6055 return '\''; /* {geresh}={'} */
6056 else if (c == 246)
6057 return ' '; /* \"o --> ' ' for a german keyboard */
6058 else if (c == 228)
6059 return ' '; /* \"a --> ' ' -- / -- */
6060 else if (c == 252)
6061 return ' '; /* \"u --> ' ' -- / -- */
6062#ifdef EBCDIC
6063 else if (islower(c))
6064#else
6065 /* NOTE: islower() does not do the right thing for us on Linux so we
6066 * do this the same was as 5.7 and previous, so it works correctly on
6067 * all systems. Specifically, the e.g. Delete and Arrow keys are
6068 * munged and won't work if e.g. searching for Hebrew text.
6069 */
6070 else if (c >= 'a' && c <= 'z')
6071#endif
6072 return (int)(map[CharOrdLow(c)] + p_aleph);
6073 else
6074 return c;
6075 }
6076 else
6077 {
6078 switch (c)
6079 {
6080 case '`': return ';';
6081 case '/': return '.';
6082 case '\'': return ',';
6083 case 'q': return '/';
6084 case 'w': return '\'';
6085
6086 /* Hebrew letters - set offset from 'a' */
6087 case ',': c = '{'; break;
6088 case '.': c = 'v'; break;
6089 case ';': c = 't'; break;
6090 default: {
6091 static char str[] = "zqbcxlsjphmkwonu ydafe rig";
6092
6093#ifdef EBCDIC
6094 /* see note about islower() above */
6095 if (!islower(c))
6096#else
6097 if (c < 'a' || c > 'z')
6098#endif
6099 return c;
6100 c = str[CharOrdLow(c)];
6101 break;
6102 }
6103 }
6104
6105 return (int)(CharOrdLow(c) + p_aleph);
6106 }
6107}
6108#endif
6109
6110 static void
6111ins_reg()
6112{
6113 int need_redraw = FALSE;
6114 int regname;
6115 int literally = 0;
6116
6117 /*
6118 * If we are going to wait for a character, show a '"'.
6119 */
6120 pc_status = PC_STATUS_UNSET;
6121 if (redrawing() && !char_avail())
6122 {
6123 /* may need to redraw when no more chars available now */
6124 ins_redraw();
6125
6126 edit_putchar('"', TRUE);
6127#ifdef FEAT_CMDL_INFO
6128 add_to_showcmd_c(Ctrl_R);
6129#endif
6130 }
6131
6132#ifdef USE_ON_FLY_SCROLL
6133 dont_scroll = TRUE; /* disallow scrolling here */
6134#endif
6135
6136 /*
6137 * Don't map the register name. This also prevents the mode message to be
6138 * deleted when ESC is hit.
6139 */
6140 ++no_mapping;
6141 regname = safe_vgetc();
6142#ifdef FEAT_LANGMAP
6143 LANGMAP_ADJUST(regname, TRUE);
6144#endif
6145 if (regname == Ctrl_R || regname == Ctrl_O || regname == Ctrl_P)
6146 {
6147 /* Get a third key for literal register insertion */
6148 literally = regname;
6149#ifdef FEAT_CMDL_INFO
6150 add_to_showcmd_c(literally);
6151#endif
6152 regname = safe_vgetc();
6153#ifdef FEAT_LANGMAP
6154 LANGMAP_ADJUST(regname, TRUE);
6155#endif
6156 }
6157 --no_mapping;
6158
6159#ifdef FEAT_EVAL
6160 /*
6161 * Don't call u_sync() while getting the expression,
6162 * evaluating it or giving an error message for it!
6163 */
6164 ++no_u_sync;
6165 if (regname == '=')
6166 {
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006167# ifdef USE_IM_CONTROL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 int im_on = im_get_status();
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006169# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 regname = get_expr_register();
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006171# ifdef USE_IM_CONTROL
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 /* Restore the Input Method. */
6173 if (im_on)
6174 im_set_active(TRUE);
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006175# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 }
Bram Moolenaar677ee682005-01-27 14:41:15 +00006177 if (regname == NUL || !valid_yank_reg(regname, FALSE))
6178 {
6179 vim_beep();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006180 need_redraw = TRUE; /* remove the '"' */
Bram Moolenaar677ee682005-01-27 14:41:15 +00006181 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182 else
6183 {
6184#endif
6185 if (literally == Ctrl_O || literally == Ctrl_P)
6186 {
6187 /* Append the command to the redo buffer. */
6188 AppendCharToRedobuff(Ctrl_R);
6189 AppendCharToRedobuff(literally);
6190 AppendCharToRedobuff(regname);
6191
6192 do_put(regname, BACKWARD, 1L,
6193 (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND);
6194 }
6195 else if (insert_reg(regname, literally) == FAIL)
6196 {
6197 vim_beep();
6198 need_redraw = TRUE; /* remove the '"' */
6199 }
Bram Moolenaar8f999f12005-01-25 22:12:55 +00006200 else if (stop_insert_mode)
6201 /* When the '=' register was used and a function was invoked that
6202 * did ":stopinsert" then stuff_empty() returns FALSE but we won't
6203 * insert anything, need to remove the '"' */
6204 need_redraw = TRUE;
6205
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206#ifdef FEAT_EVAL
6207 }
6208 --no_u_sync;
6209#endif
6210#ifdef FEAT_CMDL_INFO
6211 clear_showcmd();
6212#endif
6213
6214 /* If the inserted register is empty, we need to remove the '"' */
6215 if (need_redraw || stuff_empty())
6216 edit_unputchar();
6217}
6218
6219/*
6220 * CTRL-G commands in Insert mode.
6221 */
6222 static void
6223ins_ctrl_g()
6224{
6225 int c;
6226
6227#ifdef FEAT_INS_EXPAND
6228 /* Right after CTRL-X the cursor will be after the ruler. */
6229 setcursor();
6230#endif
6231
6232 /*
6233 * Don't map the second key. This also prevents the mode message to be
6234 * deleted when ESC is hit.
6235 */
6236 ++no_mapping;
6237 c = safe_vgetc();
6238 --no_mapping;
6239 switch (c)
6240 {
6241 /* CTRL-G k and CTRL-G <Up>: cursor up to Insstart.col */
6242 case K_UP:
6243 case Ctrl_K:
6244 case 'k': ins_up(TRUE);
6245 break;
6246
6247 /* CTRL-G j and CTRL-G <Down>: cursor down to Insstart.col */
6248 case K_DOWN:
6249 case Ctrl_J:
6250 case 'j': ins_down(TRUE);
6251 break;
6252
6253 /* CTRL-G u: start new undoable edit */
6254 case 'u': u_sync();
6255 ins_need_undo = TRUE;
6256 break;
6257
6258 /* Unknown CTRL-G command, reserved for future expansion. */
6259 default: vim_beep();
6260 }
6261}
6262
6263/*
6264 * Handle ESC in insert mode.
6265 * Returns TRUE when leaving insert mode, FALSE when going to repeat the
6266 * insert.
6267 */
6268 static int
6269ins_esc(count, cmdchar)
6270 long *count;
6271 int cmdchar;
6272{
6273 int temp;
6274 static int disabled_redraw = FALSE;
6275
6276#if defined(FEAT_HANGULIN)
6277# if defined(ESC_CHG_TO_ENG_MODE)
6278 hangul_input_state_set(0);
6279# endif
6280 if (composing_hangul)
6281 {
6282 push_raw_key(composing_hangul_buffer, 2);
6283 composing_hangul = 0;
6284 }
6285#endif
6286#if defined(FEAT_MBYTE) && defined(MACOS_CLASSIC)
6287 previous_script = GetScriptManagerVariable(smKeyScript);
6288 KeyScript(smKeyRoman); /* or smKeySysScript */
6289#endif
6290
6291 temp = curwin->w_cursor.col;
6292 if (disabled_redraw)
6293 {
6294 --RedrawingDisabled;
6295 disabled_redraw = FALSE;
6296 }
6297 if (!arrow_used)
6298 {
6299 /*
6300 * Don't append the ESC for "r<CR>" and "grx".
Bram Moolenaar12805862005-01-05 22:16:17 +00006301 * When 'insertmode' is set only CTRL-L stops Insert mode. Needed for
6302 * when "count" is non-zero.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303 */
6304 if (cmdchar != 'r' && cmdchar != 'v')
Bram Moolenaar12805862005-01-05 22:16:17 +00006305 AppendToRedobuff(p_im ? (char_u *)"\014" : ESC_STR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006306
6307 /*
6308 * Repeating insert may take a long time. Check for
6309 * interrupt now and then.
6310 */
6311 if (*count > 0)
6312 {
6313 line_breakcheck();
6314 if (got_int)
6315 *count = 0;
6316 }
6317
6318 if (--*count > 0) /* repeat what was typed */
6319 {
Bram Moolenaar4399ef42005-02-12 14:29:27 +00006320 /* Vi repeats the insert without replacing characters. */
6321 if (vim_strchr(p_cpo, CPO_REPLCNT) != NULL)
6322 State &= ~REPLACE_FLAG;
6323
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 (void)start_redo_ins();
6325 if (cmdchar == 'r' || cmdchar == 'v')
6326 stuffReadbuff(ESC_STR); /* no ESC in redo buffer */
6327 ++RedrawingDisabled;
6328 disabled_redraw = TRUE;
6329 return FALSE; /* repeat the insert */
6330 }
6331 stop_insert(&curwin->w_cursor, TRUE);
6332 undisplay_dollar();
6333 }
6334
6335 /* When an autoindent was removed, curswant stays after the
6336 * indent */
6337 if (restart_edit == NUL && (colnr_T)temp == curwin->w_cursor.col)
6338 curwin->w_set_curswant = TRUE;
6339
6340 /* Remember the last Insert position in the '^ mark. */
6341 if (!cmdmod.keepjumps)
6342 curbuf->b_last_insert = curwin->w_cursor;
6343
6344 /*
6345 * The cursor should end up on the last inserted character.
6346 */
6347 if ((curwin->w_cursor.col != 0
6348#ifdef FEAT_VIRTUALEDIT
6349 || curwin->w_cursor.coladd > 0
6350#endif
6351 ) && (restart_edit == NUL
6352 || (gchar_cursor() == NUL
6353#ifdef FEAT_VISUAL
6354 && !VIsual_active
6355#endif
6356 ))
6357#ifdef FEAT_RIGHTLEFT
6358 && !revins_on
6359#endif
6360 )
6361 {
6362#ifdef FEAT_VIRTUALEDIT
6363 if (curwin->w_cursor.coladd > 0 || ve_flags == VE_ALL)
6364 {
6365 oneleft();
6366 if (restart_edit != NUL)
6367 ++curwin->w_cursor.coladd;
6368 }
6369 else
6370#endif
6371 {
6372 --curwin->w_cursor.col;
6373#ifdef FEAT_MBYTE
6374 /* Correct cursor for multi-byte character. */
6375 if (has_mbyte)
6376 mb_adjust_cursor();
6377#endif
6378 }
6379 }
6380
6381#ifdef USE_IM_CONTROL
6382 /* Disable IM to allow typing English directly for Normal mode commands.
6383 * When ":lmap" is enabled don't change 'iminsert' (IM can be enabled as
6384 * well). */
6385 if (!(State & LANGMAP))
6386 im_save_status(&curbuf->b_p_iminsert);
6387 im_set_active(FALSE);
6388#endif
6389
6390 State = NORMAL;
6391 /* need to position cursor again (e.g. when on a TAB ) */
6392 changed_cline_bef_curs();
6393
6394#ifdef FEAT_MOUSE
6395 setmouse();
6396#endif
6397#ifdef CURSOR_SHAPE
6398 ui_cursor_shape(); /* may show different cursor shape */
6399#endif
6400
6401 /*
6402 * When recording or for CTRL-O, need to display the new mode.
6403 * Otherwise remove the mode message.
6404 */
6405 if (Recording || restart_edit != NUL)
6406 showmode();
6407 else if (p_smd)
6408 MSG("");
6409
6410 return TRUE; /* exit Insert mode */
6411}
6412
6413#ifdef FEAT_RIGHTLEFT
6414/*
6415 * Toggle language: hkmap and revins_on.
6416 * Move to end of reverse inserted text.
6417 */
6418 static void
6419ins_ctrl_()
6420{
6421 if (revins_on && revins_chars && revins_scol >= 0)
6422 {
6423 while (gchar_cursor() != NUL && revins_chars--)
6424 ++curwin->w_cursor.col;
6425 }
6426 p_ri = !p_ri;
6427 revins_on = (State == INSERT && p_ri);
6428 if (revins_on)
6429 {
6430 revins_scol = curwin->w_cursor.col;
6431 revins_legal++;
6432 revins_chars = 0;
6433 undisplay_dollar();
6434 }
6435 else
6436 revins_scol = -1;
6437#ifdef FEAT_FKMAP
6438 if (p_altkeymap)
6439 {
6440 /*
6441 * to be consistent also for redo command, using '.'
6442 * set arrow_used to true and stop it - causing to redo
6443 * characters entered in one mode (normal/reverse insert).
6444 */
6445 arrow_used = TRUE;
6446 (void)stop_arrow();
6447 p_fkmap = curwin->w_p_rl ^ p_ri;
6448 if (p_fkmap && p_ri)
6449 State = INSERT;
6450 }
6451 else
6452#endif
6453 p_hkmap = curwin->w_p_rl ^ p_ri; /* be consistent! */
6454 showmode();
6455}
6456#endif
6457
6458#ifdef FEAT_VISUAL
6459/*
6460 * If 'keymodel' contains "startsel", may start selection.
6461 * Returns TRUE when a CTRL-O and other keys stuffed.
6462 */
6463 static int
6464ins_start_select(c)
6465 int c;
6466{
6467 if (km_startsel)
6468 switch (c)
6469 {
6470 case K_KHOME:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 case K_KEND:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472 case K_PAGEUP:
6473 case K_KPAGEUP:
6474 case K_PAGEDOWN:
6475 case K_KPAGEDOWN:
6476# ifdef MACOS
6477 case K_LEFT:
6478 case K_RIGHT:
6479 case K_UP:
6480 case K_DOWN:
6481 case K_END:
6482 case K_HOME:
6483# endif
6484 if (!(mod_mask & MOD_MASK_SHIFT))
6485 break;
6486 /* FALLTHROUGH */
6487 case K_S_LEFT:
6488 case K_S_RIGHT:
6489 case K_S_UP:
6490 case K_S_DOWN:
6491 case K_S_END:
6492 case K_S_HOME:
6493 /* Start selection right away, the cursor can move with
6494 * CTRL-O when beyond the end of the line. */
6495 start_selection();
6496
6497 /* Execute the key in (insert) Select mode. */
6498 stuffcharReadbuff(Ctrl_O);
6499 if (mod_mask)
6500 {
6501 char_u buf[4];
6502
6503 buf[0] = K_SPECIAL;
6504 buf[1] = KS_MODIFIER;
6505 buf[2] = mod_mask;
6506 buf[3] = NUL;
6507 stuffReadbuff(buf);
6508 }
6509 stuffcharReadbuff(c);
6510 return TRUE;
6511 }
6512 return FALSE;
6513}
6514#endif
6515
6516/*
6517 * If the cursor is on an indent, ^T/^D insert/delete one
6518 * shiftwidth. Otherwise ^T/^D behave like a "<<" or ">>".
6519 * Always round the indent to 'shiftwith', this is compatible
6520 * with vi. But vi only supports ^T and ^D after an
6521 * autoindent, we support it everywhere.
6522 */
6523 static void
6524ins_shift(c, lastc)
6525 int c;
6526 int lastc;
6527{
6528 if (stop_arrow() == FAIL)
6529 return;
6530 AppendCharToRedobuff(c);
6531
6532 /*
6533 * 0^D and ^^D: remove all indent.
6534 */
6535 if ((lastc == '0' || lastc == '^') && curwin->w_cursor.col)
6536 {
6537 --curwin->w_cursor.col;
6538 (void)del_char(FALSE); /* delete the '^' or '0' */
6539 /* In Replace mode, restore the characters that '^' or '0' replaced. */
6540 if (State & REPLACE_FLAG)
6541 replace_pop_ins();
6542 if (lastc == '^')
6543 old_indent = get_indent(); /* remember curr. indent */
6544 change_indent(INDENT_SET, 0, TRUE, 0);
6545 }
6546 else
6547 change_indent(c == Ctrl_D ? INDENT_DEC : INDENT_INC, 0, TRUE, 0);
6548
6549 if (did_ai && *skipwhite(ml_get_curline()) != NUL)
6550 did_ai = FALSE;
6551#ifdef FEAT_SMARTINDENT
6552 did_si = FALSE;
6553 can_si = FALSE;
6554 can_si_back = FALSE;
6555#endif
6556#ifdef FEAT_CINDENT
6557 can_cindent = FALSE; /* no cindenting after ^D or ^T */
6558#endif
6559}
6560
6561 static void
6562ins_del()
6563{
6564 int temp;
6565
6566 if (stop_arrow() == FAIL)
6567 return;
6568 if (gchar_cursor() == NUL) /* delete newline */
6569 {
6570 temp = curwin->w_cursor.col;
6571 if (!can_bs(BS_EOL) /* only if "eol" included */
6572 || u_save((linenr_T)(curwin->w_cursor.lnum - 1),
6573 (linenr_T)(curwin->w_cursor.lnum + 2)) == FAIL
6574 || do_join(FALSE) == FAIL)
6575 vim_beep();
6576 else
6577 curwin->w_cursor.col = temp;
6578 }
6579 else if (del_char(FALSE) == FAIL) /* delete char under cursor */
6580 vim_beep();
6581 did_ai = FALSE;
6582#ifdef FEAT_SMARTINDENT
6583 did_si = FALSE;
6584 can_si = FALSE;
6585 can_si_back = FALSE;
6586#endif
6587 AppendCharToRedobuff(K_DEL);
6588}
6589
6590/*
6591 * Handle Backspace, delete-word and delete-line in Insert mode.
6592 * Return TRUE when backspace was actually used.
6593 */
6594 static int
6595ins_bs(c, mode, inserted_space_p)
6596 int c;
6597 int mode;
6598 int *inserted_space_p;
6599{
6600 linenr_T lnum;
6601 int cc;
6602 int temp = 0; /* init for GCC */
6603 colnr_T mincol;
6604 int did_backspace = FALSE;
6605 int in_indent;
6606 int oldState;
6607#ifdef FEAT_MBYTE
6608 int p1, p2;
6609#endif
6610
6611 /*
6612 * can't delete anything in an empty file
6613 * can't backup past first character in buffer
6614 * can't backup past starting point unless 'backspace' > 1
6615 * can backup to a previous line if 'backspace' == 0
6616 */
6617 if ( bufempty()
6618 || (
6619#ifdef FEAT_RIGHTLEFT
6620 !revins_on &&
6621#endif
6622 ((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
6623 || (!can_bs(BS_START)
6624 && (arrow_used
6625 || (curwin->w_cursor.lnum == Insstart.lnum
6626 && curwin->w_cursor.col <= Insstart.col)))
6627 || (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
6628 && curwin->w_cursor.col <= ai_col)
6629 || (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
6630 {
6631 vim_beep();
6632 return FALSE;
6633 }
6634
6635 if (stop_arrow() == FAIL)
6636 return FALSE;
6637 in_indent = inindent(0);
6638#ifdef FEAT_CINDENT
6639 if (in_indent)
6640 can_cindent = FALSE;
6641#endif
6642#ifdef FEAT_COMMENTS
6643 end_comment_pending = NUL; /* After BS, don't auto-end comment */
6644#endif
6645#ifdef FEAT_RIGHTLEFT
6646 if (revins_on) /* put cursor after last inserted char */
6647 inc_cursor();
6648#endif
6649
6650#ifdef FEAT_VIRTUALEDIT
6651 /* Virtualedit:
6652 * BACKSPACE_CHAR eats a virtual space
6653 * BACKSPACE_WORD eats all coladd
6654 * BACKSPACE_LINE eats all coladd and keeps going
6655 */
6656 if (curwin->w_cursor.coladd > 0)
6657 {
6658 if (mode == BACKSPACE_CHAR)
6659 {
6660 --curwin->w_cursor.coladd;
6661 return TRUE;
6662 }
6663 if (mode == BACKSPACE_WORD)
6664 {
6665 curwin->w_cursor.coladd = 0;
6666 return TRUE;
6667 }
6668 curwin->w_cursor.coladd = 0;
6669 }
6670#endif
6671
6672 /*
6673 * delete newline!
6674 */
6675 if (curwin->w_cursor.col == 0)
6676 {
6677 lnum = Insstart.lnum;
6678 if (curwin->w_cursor.lnum == Insstart.lnum
6679#ifdef FEAT_RIGHTLEFT
6680 || revins_on
6681#endif
6682 )
6683 {
6684 if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
6685 (linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
6686 return FALSE;
6687 --Insstart.lnum;
6688 Insstart.col = MAXCOL;
6689 }
6690 /*
6691 * In replace mode:
6692 * cc < 0: NL was inserted, delete it
6693 * cc >= 0: NL was replaced, put original characters back
6694 */
6695 cc = -1;
6696 if (State & REPLACE_FLAG)
6697 cc = replace_pop(); /* returns -1 if NL was inserted */
6698 /*
6699 * In replace mode, in the line we started replacing, we only move the
6700 * cursor.
6701 */
6702 if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
6703 {
6704 dec_cursor();
6705 }
6706 else
6707 {
6708#ifdef FEAT_VREPLACE
6709 if (!(State & VREPLACE_FLAG)
6710 || curwin->w_cursor.lnum > orig_line_count)
6711#endif
6712 {
6713 temp = gchar_cursor(); /* remember current char */
6714 --curwin->w_cursor.lnum;
Bram Moolenaarc930a3c2005-05-20 21:27:20 +00006715
6716 /* When "aw" is in 'formatoptions' we must delete the space at
6717 * the end of the line, otherwise the line will be broken
6718 * again when auto-formatting. */
6719 if (has_format_option(FO_AUTO)
6720 && has_format_option(FO_WHITE_PAR))
6721 {
6722 char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
6723 TRUE);
6724 int len;
6725
6726 len = STRLEN(ptr);
6727 if (len > 0 && ptr[len - 1] == ' ')
6728 ptr[len - 1] = NUL;
6729 }
6730
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 (void)do_join(FALSE);
6732 if (temp == NUL && gchar_cursor() != NUL)
6733 inc_cursor();
6734 }
6735#ifdef FEAT_VREPLACE
6736 else
6737 dec_cursor();
6738#endif
6739
6740 /*
6741 * In REPLACE mode we have to put back the text that was replaced
6742 * by the NL. On the replace stack is first a NUL-terminated
6743 * sequence of characters that were deleted and then the
6744 * characters that NL replaced.
6745 */
6746 if (State & REPLACE_FLAG)
6747 {
6748 /*
6749 * Do the next ins_char() in NORMAL state, to
6750 * prevent ins_char() from replacing characters and
6751 * avoiding showmatch().
6752 */
6753 oldState = State;
6754 State = NORMAL;
6755 /*
6756 * restore characters (blanks) deleted after cursor
6757 */
6758 while (cc > 0)
6759 {
6760 temp = curwin->w_cursor.col;
6761#ifdef FEAT_MBYTE
6762 mb_replace_pop_ins(cc);
6763#else
6764 ins_char(cc);
6765#endif
6766 curwin->w_cursor.col = temp;
6767 cc = replace_pop();
6768 }
6769 /* restore the characters that NL replaced */
6770 replace_pop_ins();
6771 State = oldState;
6772 }
6773 }
6774 did_ai = FALSE;
6775 }
6776 else
6777 {
6778 /*
6779 * Delete character(s) before the cursor.
6780 */
6781#ifdef FEAT_RIGHTLEFT
6782 if (revins_on) /* put cursor on last inserted char */
6783 dec_cursor();
6784#endif
6785 mincol = 0;
6786 /* keep indent */
6787 if (mode == BACKSPACE_LINE && curbuf->b_p_ai
6788#ifdef FEAT_RIGHTLEFT
6789 && !revins_on
6790#endif
6791 )
6792 {
6793 temp = curwin->w_cursor.col;
6794 beginline(BL_WHITE);
6795 if (curwin->w_cursor.col < (colnr_T)temp)
6796 mincol = curwin->w_cursor.col;
6797 curwin->w_cursor.col = temp;
6798 }
6799
6800 /*
6801 * Handle deleting one 'shiftwidth' or 'softtabstop'.
6802 */
6803 if ( mode == BACKSPACE_CHAR
6804 && ((p_sta && in_indent)
6805 || (curbuf->b_p_sts
6806 && (*(ml_get_cursor() - 1) == TAB
6807 || (*(ml_get_cursor() - 1) == ' '
6808 && (!*inserted_space_p
6809 || arrow_used))))))
6810 {
6811 int ts;
6812 colnr_T vcol;
6813 colnr_T want_vcol;
6814 int extra = 0;
6815
6816 *inserted_space_p = FALSE;
6817 if (p_sta)
6818 ts = curbuf->b_p_sw;
6819 else
6820 ts = curbuf->b_p_sts;
6821 /* Compute the virtual column where we want to be. Since
6822 * 'showbreak' may get in the way, need to get the last column of
6823 * the previous character. */
6824 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6825 dec_cursor();
6826 getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
6827 inc_cursor();
6828 want_vcol = (want_vcol / ts) * ts;
6829
6830 /* delete characters until we are at or before want_vcol */
6831 while (vcol > want_vcol
6832 && (cc = *(ml_get_cursor() - 1), vim_iswhite(cc)))
6833 {
6834 dec_cursor();
6835 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6836 if (State & REPLACE_FLAG)
6837 {
6838 /* Don't delete characters before the insert point when in
6839 * Replace mode */
6840 if (curwin->w_cursor.lnum != Insstart.lnum
6841 || curwin->w_cursor.col >= Insstart.col)
6842 {
6843#if 0 /* what was this for? It causes problems when sw != ts. */
6844 if (State == REPLACE && (int)vcol < want_vcol)
6845 {
6846 (void)del_char(FALSE);
6847 extra = 2; /* don't pop too much */
6848 }
6849 else
6850#endif
6851 replace_do_bs();
6852 }
6853 }
6854 else
6855 (void)del_char(FALSE);
6856 }
6857
6858 /* insert extra spaces until we are at want_vcol */
6859 while (vcol < want_vcol)
6860 {
6861 /* Remember the first char we inserted */
6862 if (curwin->w_cursor.lnum == Insstart.lnum
6863 && curwin->w_cursor.col < Insstart.col)
6864 Insstart.col = curwin->w_cursor.col;
6865
6866#ifdef FEAT_VREPLACE
6867 if (State & VREPLACE_FLAG)
6868 ins_char(' ');
6869 else
6870#endif
6871 {
6872 ins_str((char_u *)" ");
6873 if ((State & REPLACE_FLAG) && extra <= 1)
6874 {
6875 if (extra)
6876 replace_push_off(NUL);
6877 else
6878 replace_push(NUL);
6879 }
6880 if (extra == 2)
6881 extra = 1;
6882 }
6883 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6884 }
6885 }
6886
6887 /*
6888 * Delete upto starting point, start of line or previous word.
6889 */
6890 else do
6891 {
6892#ifdef FEAT_RIGHTLEFT
6893 if (!revins_on) /* put cursor on char to be deleted */
6894#endif
6895 dec_cursor();
6896
6897 /* start of word? */
6898 if (mode == BACKSPACE_WORD && !vim_isspace(gchar_cursor()))
6899 {
6900 mode = BACKSPACE_WORD_NOT_SPACE;
6901 temp = vim_iswordc(gchar_cursor());
6902 }
6903 /* end of word? */
6904 else if (mode == BACKSPACE_WORD_NOT_SPACE
6905 && (vim_isspace(cc = gchar_cursor())
6906 || vim_iswordc(cc) != temp))
6907 {
6908#ifdef FEAT_RIGHTLEFT
6909 if (!revins_on)
6910#endif
6911 inc_cursor();
6912#ifdef FEAT_RIGHTLEFT
6913 else if (State & REPLACE_FLAG)
6914 dec_cursor();
6915#endif
6916 break;
6917 }
6918 if (State & REPLACE_FLAG)
6919 replace_do_bs();
6920 else
6921 {
6922#ifdef FEAT_MBYTE
6923 if (enc_utf8 && p_deco)
6924 (void)utfc_ptr2char(ml_get_cursor(), &p1, &p2);
6925#endif
6926 (void)del_char(FALSE);
6927#ifdef FEAT_MBYTE
6928 /*
6929 * If p1 or p2 is non-zero, there are combining characters we
6930 * need to take account of. Don't back up before the base
6931 * character.
6932 */
6933 if (enc_utf8 && p_deco && (p1 != NUL || p2 != NUL))
6934 inc_cursor();
6935#endif
6936#ifdef FEAT_RIGHTLEFT
6937 if (revins_chars)
6938 {
6939 revins_chars--;
6940 revins_legal++;
6941 }
6942 if (revins_on && gchar_cursor() == NUL)
6943 break;
6944#endif
6945 }
6946 /* Just a single backspace?: */
6947 if (mode == BACKSPACE_CHAR)
6948 break;
6949 } while (
6950#ifdef FEAT_RIGHTLEFT
6951 revins_on ||
6952#endif
6953 (curwin->w_cursor.col > mincol
6954 && (curwin->w_cursor.lnum != Insstart.lnum
6955 || curwin->w_cursor.col != Insstart.col)));
6956 did_backspace = TRUE;
6957 }
6958#ifdef FEAT_SMARTINDENT
6959 did_si = FALSE;
6960 can_si = FALSE;
6961 can_si_back = FALSE;
6962#endif
6963 if (curwin->w_cursor.col <= 1)
6964 did_ai = FALSE;
6965 /*
6966 * It's a little strange to put backspaces into the redo
6967 * buffer, but it makes auto-indent a lot easier to deal
6968 * with.
6969 */
6970 AppendCharToRedobuff(c);
6971
6972 /* If deleted before the insertion point, adjust it */
6973 if (curwin->w_cursor.lnum == Insstart.lnum
6974 && curwin->w_cursor.col < Insstart.col)
6975 Insstart.col = curwin->w_cursor.col;
6976
6977 /* vi behaviour: the cursor moves backward but the character that
6978 * was there remains visible
6979 * Vim behaviour: the cursor moves backward and the character that
6980 * was there is erased from the screen.
6981 * We can emulate the vi behaviour by pretending there is a dollar
6982 * displayed even when there isn't.
6983 * --pkv Sun Jan 19 01:56:40 EST 2003 */
6984 if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == 0)
6985 dollar_vcol = curwin->w_virtcol;
6986
6987 return did_backspace;
6988}
6989
6990#ifdef FEAT_MOUSE
6991 static void
6992ins_mouse(c)
6993 int c;
6994{
6995 pos_T tpos;
6996
6997# ifdef FEAT_GUI
6998 /* When GUI is active, also move/paste when 'mouse' is empty */
6999 if (!gui.in_use)
7000# endif
7001 if (!mouse_has(MOUSE_INSERT))
7002 return;
7003
7004 undisplay_dollar();
7005 tpos = curwin->w_cursor;
7006 if (do_mouse(NULL, c, BACKWARD, 1L, 0))
7007 {
7008 start_arrow(&tpos);
7009# ifdef FEAT_CINDENT
7010 can_cindent = TRUE;
7011# endif
7012 }
7013
7014#ifdef FEAT_WINDOWS
7015 /* redraw status lines (in case another window became active) */
7016 redraw_statuslines();
7017#endif
7018}
7019
7020 static void
7021ins_mousescroll(up)
7022 int up;
7023{
7024 pos_T tpos;
7025# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7026 win_T *old_curwin;
7027# endif
7028
7029 tpos = curwin->w_cursor;
7030
7031# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7032 old_curwin = curwin;
7033
7034 /* Currently the mouse coordinates are only known in the GUI. */
7035 if (gui.in_use && mouse_row >= 0 && mouse_col >= 0)
7036 {
7037 int row, col;
7038
7039 row = mouse_row;
7040 col = mouse_col;
7041
7042 /* find the window at the pointer coordinates */
7043 curwin = mouse_find_win(&row, &col);
7044 curbuf = curwin->w_buffer;
7045 }
7046 if (curwin == old_curwin)
7047# endif
7048 undisplay_dollar();
7049
7050 if (mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))
7051 scroll_redraw(up, (long)(curwin->w_botline - curwin->w_topline));
7052 else
7053 scroll_redraw(up, 3L);
7054
7055# if defined(FEAT_GUI) && defined(FEAT_WINDOWS)
7056 curwin->w_redr_status = TRUE;
7057
7058 curwin = old_curwin;
7059 curbuf = curwin->w_buffer;
7060# endif
7061
7062 if (!equalpos(curwin->w_cursor, tpos))
7063 {
7064 start_arrow(&tpos);
7065# ifdef FEAT_CINDENT
7066 can_cindent = TRUE;
7067# endif
7068 }
7069}
7070#endif
7071
7072#ifdef FEAT_GUI
7073 void
7074ins_scroll()
7075{
7076 pos_T tpos;
7077
7078 undisplay_dollar();
7079 tpos = curwin->w_cursor;
7080 if (gui_do_scroll())
7081 {
7082 start_arrow(&tpos);
7083# ifdef FEAT_CINDENT
7084 can_cindent = TRUE;
7085# endif
7086 }
7087}
7088
7089 void
7090ins_horscroll()
7091{
7092 pos_T tpos;
7093
7094 undisplay_dollar();
7095 tpos = curwin->w_cursor;
7096 if (gui_do_horiz_scroll())
7097 {
7098 start_arrow(&tpos);
7099# ifdef FEAT_CINDENT
7100 can_cindent = TRUE;
7101# endif
7102 }
7103}
7104#endif
7105
7106 static void
7107ins_left()
7108{
7109 pos_T tpos;
7110
7111#ifdef FEAT_FOLDING
7112 if ((fdo_flags & FDO_HOR) && KeyTyped)
7113 foldOpenCursor();
7114#endif
7115 undisplay_dollar();
7116 tpos = curwin->w_cursor;
7117 if (oneleft() == OK)
7118 {
7119 start_arrow(&tpos);
7120#ifdef FEAT_RIGHTLEFT
7121 /* If exit reversed string, position is fixed */
7122 if (revins_scol != -1 && (int)curwin->w_cursor.col >= revins_scol)
7123 revins_legal++;
7124 revins_chars++;
7125#endif
7126 }
7127
7128 /*
7129 * if 'whichwrap' set for cursor in insert mode may go to
7130 * previous line
7131 */
7132 else if (vim_strchr(p_ww, '[') != NULL && curwin->w_cursor.lnum > 1)
7133 {
7134 start_arrow(&tpos);
7135 --(curwin->w_cursor.lnum);
7136 coladvance((colnr_T)MAXCOL);
7137 curwin->w_set_curswant = TRUE; /* so we stay at the end */
7138 }
7139 else
7140 vim_beep();
7141}
7142
7143 static void
7144ins_home(c)
7145 int c;
7146{
7147 pos_T tpos;
7148
7149#ifdef FEAT_FOLDING
7150 if ((fdo_flags & FDO_HOR) && KeyTyped)
7151 foldOpenCursor();
7152#endif
7153 undisplay_dollar();
7154 tpos = curwin->w_cursor;
7155 if (c == K_C_HOME)
7156 curwin->w_cursor.lnum = 1;
7157 curwin->w_cursor.col = 0;
7158#ifdef FEAT_VIRTUALEDIT
7159 curwin->w_cursor.coladd = 0;
7160#endif
7161 curwin->w_curswant = 0;
7162 start_arrow(&tpos);
7163}
7164
7165 static void
7166ins_end(c)
7167 int c;
7168{
7169 pos_T tpos;
7170
7171#ifdef FEAT_FOLDING
7172 if ((fdo_flags & FDO_HOR) && KeyTyped)
7173 foldOpenCursor();
7174#endif
7175 undisplay_dollar();
7176 tpos = curwin->w_cursor;
7177 if (c == K_C_END)
7178 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
7179 coladvance((colnr_T)MAXCOL);
7180 curwin->w_curswant = MAXCOL;
7181
7182 start_arrow(&tpos);
7183}
7184
7185 static void
7186ins_s_left()
7187{
7188#ifdef FEAT_FOLDING
7189 if ((fdo_flags & FDO_HOR) && KeyTyped)
7190 foldOpenCursor();
7191#endif
7192 undisplay_dollar();
7193 if (curwin->w_cursor.lnum > 1 || curwin->w_cursor.col > 0)
7194 {
7195 start_arrow(&curwin->w_cursor);
7196 (void)bck_word(1L, FALSE, FALSE);
7197 curwin->w_set_curswant = TRUE;
7198 }
7199 else
7200 vim_beep();
7201}
7202
7203 static void
7204ins_right()
7205{
7206#ifdef FEAT_FOLDING
7207 if ((fdo_flags & FDO_HOR) && KeyTyped)
7208 foldOpenCursor();
7209#endif
7210 undisplay_dollar();
7211 if (gchar_cursor() != NUL || virtual_active()
7212 )
7213 {
7214 start_arrow(&curwin->w_cursor);
7215 curwin->w_set_curswant = TRUE;
7216#ifdef FEAT_VIRTUALEDIT
7217 if (virtual_active())
7218 oneright();
7219 else
7220#endif
7221 {
7222#ifdef FEAT_MBYTE
7223 if (has_mbyte)
7224 curwin->w_cursor.col += (*mb_ptr2len_check)(ml_get_cursor());
7225 else
7226#endif
7227 ++curwin->w_cursor.col;
7228 }
7229
7230#ifdef FEAT_RIGHTLEFT
7231 revins_legal++;
7232 if (revins_chars)
7233 revins_chars--;
7234#endif
7235 }
7236 /* if 'whichwrap' set for cursor in insert mode, may move the
7237 * cursor to the next line */
7238 else if (vim_strchr(p_ww, ']') != NULL
7239 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
7240 {
7241 start_arrow(&curwin->w_cursor);
7242 curwin->w_set_curswant = TRUE;
7243 ++curwin->w_cursor.lnum;
7244 curwin->w_cursor.col = 0;
7245 }
7246 else
7247 vim_beep();
7248}
7249
7250 static void
7251ins_s_right()
7252{
7253#ifdef FEAT_FOLDING
7254 if ((fdo_flags & FDO_HOR) && KeyTyped)
7255 foldOpenCursor();
7256#endif
7257 undisplay_dollar();
7258 if (curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count
7259 || gchar_cursor() != NUL)
7260 {
7261 start_arrow(&curwin->w_cursor);
7262 (void)fwd_word(1L, FALSE, 0);
7263 curwin->w_set_curswant = TRUE;
7264 }
7265 else
7266 vim_beep();
7267}
7268
7269 static void
7270ins_up(startcol)
7271 int startcol; /* when TRUE move to Insstart.col */
7272{
7273 pos_T tpos;
7274 linenr_T old_topline = curwin->w_topline;
7275#ifdef FEAT_DIFF
7276 int old_topfill = curwin->w_topfill;
7277#endif
7278
7279 undisplay_dollar();
7280 tpos = curwin->w_cursor;
7281 if (cursor_up(1L, TRUE) == OK)
7282 {
7283 if (startcol)
7284 coladvance(getvcol_nolist(&Insstart));
7285 if (old_topline != curwin->w_topline
7286#ifdef FEAT_DIFF
7287 || old_topfill != curwin->w_topfill
7288#endif
7289 )
7290 redraw_later(VALID);
7291 start_arrow(&tpos);
7292#ifdef FEAT_CINDENT
7293 can_cindent = TRUE;
7294#endif
7295 }
7296 else
7297 vim_beep();
7298}
7299
7300 static void
7301ins_pageup()
7302{
7303 pos_T tpos;
7304
7305 undisplay_dollar();
7306 tpos = curwin->w_cursor;
7307 if (onepage(BACKWARD, 1L) == OK)
7308 {
7309 start_arrow(&tpos);
7310#ifdef FEAT_CINDENT
7311 can_cindent = TRUE;
7312#endif
7313 }
7314 else
7315 vim_beep();
7316}
7317
7318 static void
7319ins_down(startcol)
7320 int startcol; /* when TRUE move to Insstart.col */
7321{
7322 pos_T tpos;
7323 linenr_T old_topline = curwin->w_topline;
7324#ifdef FEAT_DIFF
7325 int old_topfill = curwin->w_topfill;
7326#endif
7327
7328 undisplay_dollar();
7329 tpos = curwin->w_cursor;
7330 if (cursor_down(1L, TRUE) == OK)
7331 {
7332 if (startcol)
7333 coladvance(getvcol_nolist(&Insstart));
7334 if (old_topline != curwin->w_topline
7335#ifdef FEAT_DIFF
7336 || old_topfill != curwin->w_topfill
7337#endif
7338 )
7339 redraw_later(VALID);
7340 start_arrow(&tpos);
7341#ifdef FEAT_CINDENT
7342 can_cindent = TRUE;
7343#endif
7344 }
7345 else
7346 vim_beep();
7347}
7348
7349 static void
7350ins_pagedown()
7351{
7352 pos_T tpos;
7353
7354 undisplay_dollar();
7355 tpos = curwin->w_cursor;
7356 if (onepage(FORWARD, 1L) == OK)
7357 {
7358 start_arrow(&tpos);
7359#ifdef FEAT_CINDENT
7360 can_cindent = TRUE;
7361#endif
7362 }
7363 else
7364 vim_beep();
7365}
7366
7367#ifdef FEAT_DND
7368 static void
7369ins_drop()
7370{
7371 do_put('~', BACKWARD, 1L, PUT_CURSEND);
7372}
7373#endif
7374
7375/*
7376 * Handle TAB in Insert or Replace mode.
7377 * Return TRUE when the TAB needs to be inserted like a normal character.
7378 */
7379 static int
7380ins_tab()
7381{
7382 int ind;
7383 int i;
7384 int temp;
7385
7386 if (Insstart_blank_vcol == MAXCOL && curwin->w_cursor.lnum == Insstart.lnum)
7387 Insstart_blank_vcol = get_nolist_virtcol();
7388 if (echeck_abbr(TAB + ABBR_OFF))
7389 return FALSE;
7390
7391 ind = inindent(0);
7392#ifdef FEAT_CINDENT
7393 if (ind)
7394 can_cindent = FALSE;
7395#endif
7396
7397 /*
7398 * When nothing special, insert TAB like a normal character
7399 */
7400 if (!curbuf->b_p_et
7401 && !(p_sta && ind && curbuf->b_p_ts != curbuf->b_p_sw)
7402 && curbuf->b_p_sts == 0)
7403 return TRUE;
7404
7405 if (stop_arrow() == FAIL)
7406 return TRUE;
7407
7408 did_ai = FALSE;
7409#ifdef FEAT_SMARTINDENT
7410 did_si = FALSE;
7411 can_si = FALSE;
7412 can_si_back = FALSE;
7413#endif
7414 AppendToRedobuff((char_u *)"\t");
7415
7416 if (p_sta && ind) /* insert tab in indent, use 'shiftwidth' */
7417 temp = (int)curbuf->b_p_sw;
7418 else if (curbuf->b_p_sts > 0) /* use 'softtabstop' when set */
7419 temp = (int)curbuf->b_p_sts;
7420 else /* otherwise use 'tabstop' */
7421 temp = (int)curbuf->b_p_ts;
7422 temp -= get_nolist_virtcol() % temp;
7423
7424 /*
7425 * Insert the first space with ins_char(). It will delete one char in
7426 * replace mode. Insert the rest with ins_str(); it will not delete any
7427 * chars. For VREPLACE mode, we use ins_char() for all characters.
7428 */
7429 ins_char(' ');
7430 while (--temp > 0)
7431 {
7432#ifdef FEAT_VREPLACE
7433 if (State & VREPLACE_FLAG)
7434 ins_char(' ');
7435 else
7436#endif
7437 {
7438 ins_str((char_u *)" ");
7439 if (State & REPLACE_FLAG) /* no char replaced */
7440 replace_push(NUL);
7441 }
7442 }
7443
7444 /*
7445 * When 'expandtab' not set: Replace spaces by TABs where possible.
7446 */
7447 if (!curbuf->b_p_et && (curbuf->b_p_sts || (p_sta && ind)))
7448 {
7449 char_u *ptr;
7450#ifdef FEAT_VREPLACE
7451 char_u *saved_line = NULL; /* init for GCC */
7452 pos_T pos;
7453#endif
7454 pos_T fpos;
7455 pos_T *cursor;
7456 colnr_T want_vcol, vcol;
7457 int change_col = -1;
7458 int save_list = curwin->w_p_list;
7459
7460 /*
7461 * Get the current line. For VREPLACE mode, don't make real changes
7462 * yet, just work on a copy of the line.
7463 */
7464#ifdef FEAT_VREPLACE
7465 if (State & VREPLACE_FLAG)
7466 {
7467 pos = curwin->w_cursor;
7468 cursor = &pos;
7469 saved_line = vim_strsave(ml_get_curline());
7470 if (saved_line == NULL)
7471 return FALSE;
7472 ptr = saved_line + pos.col;
7473 }
7474 else
7475#endif
7476 {
7477 ptr = ml_get_cursor();
7478 cursor = &curwin->w_cursor;
7479 }
7480
7481 /* When 'L' is not in 'cpoptions' a tab always takes up 'ts' spaces. */
7482 if (vim_strchr(p_cpo, CPO_LISTWM) == NULL)
7483 curwin->w_p_list = FALSE;
7484
7485 /* Find first white before the cursor */
7486 fpos = curwin->w_cursor;
7487 while (fpos.col > 0 && vim_iswhite(ptr[-1]))
7488 {
7489 --fpos.col;
7490 --ptr;
7491 }
7492
7493 /* In Replace mode, don't change characters before the insert point. */
7494 if ((State & REPLACE_FLAG)
7495 && fpos.lnum == Insstart.lnum
7496 && fpos.col < Insstart.col)
7497 {
7498 ptr += Insstart.col - fpos.col;
7499 fpos.col = Insstart.col;
7500 }
7501
7502 /* compute virtual column numbers of first white and cursor */
7503 getvcol(curwin, &fpos, &vcol, NULL, NULL);
7504 getvcol(curwin, cursor, &want_vcol, NULL, NULL);
7505
7506 /* Use as many TABs as possible. Beware of 'showbreak' and
7507 * 'linebreak' adding extra virtual columns. */
7508 while (vim_iswhite(*ptr))
7509 {
7510 i = lbr_chartabsize((char_u *)"\t", vcol);
7511 if (vcol + i > want_vcol)
7512 break;
7513 if (*ptr != TAB)
7514 {
7515 *ptr = TAB;
7516 if (change_col < 0)
7517 {
7518 change_col = fpos.col; /* Column of first change */
7519 /* May have to adjust Insstart */
7520 if (fpos.lnum == Insstart.lnum && fpos.col < Insstart.col)
7521 Insstart.col = fpos.col;
7522 }
7523 }
7524 ++fpos.col;
7525 ++ptr;
7526 vcol += i;
7527 }
7528
7529 if (change_col >= 0)
7530 {
7531 int repl_off = 0;
7532
7533 /* Skip over the spaces we need. */
7534 while (vcol < want_vcol && *ptr == ' ')
7535 {
7536 vcol += lbr_chartabsize(ptr, vcol);
7537 ++ptr;
7538 ++repl_off;
7539 }
7540 if (vcol > want_vcol)
7541 {
7542 /* Must have a char with 'showbreak' just before it. */
7543 --ptr;
7544 --repl_off;
7545 }
7546 fpos.col += repl_off;
7547
7548 /* Delete following spaces. */
7549 i = cursor->col - fpos.col;
7550 if (i > 0)
7551 {
7552 mch_memmove(ptr, ptr + i, STRLEN(ptr + i) + 1);
7553 /* correct replace stack. */
7554 if ((State & REPLACE_FLAG)
7555#ifdef FEAT_VREPLACE
7556 && !(State & VREPLACE_FLAG)
7557#endif
7558 )
7559 for (temp = i; --temp >= 0; )
7560 replace_join(repl_off);
7561 }
Bram Moolenaar009b2592004-10-24 19:18:58 +00007562#ifdef FEAT_NETBEANS_INTG
7563 if (usingNetbeans)
7564 {
7565 netbeans_removed(curbuf, fpos.lnum, cursor->col,
7566 (long)(i + 1));
7567 netbeans_inserted(curbuf, fpos.lnum, cursor->col,
7568 (char_u *)"\t", 1);
7569 }
7570#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007571 cursor->col -= i;
7572
7573#ifdef FEAT_VREPLACE
7574 /*
7575 * In VREPLACE mode, we haven't changed anything yet. Do it now by
7576 * backspacing over the changed spacing and then inserting the new
7577 * spacing.
7578 */
7579 if (State & VREPLACE_FLAG)
7580 {
7581 /* Backspace from real cursor to change_col */
7582 backspace_until_column(change_col);
7583
7584 /* Insert each char in saved_line from changed_col to
7585 * ptr-cursor */
7586 ins_bytes_len(saved_line + change_col,
7587 cursor->col - change_col);
7588 }
7589#endif
7590 }
7591
7592#ifdef FEAT_VREPLACE
7593 if (State & VREPLACE_FLAG)
7594 vim_free(saved_line);
7595#endif
7596 curwin->w_p_list = save_list;
7597 }
7598
7599 return FALSE;
7600}
7601
7602/*
7603 * Handle CR or NL in insert mode.
7604 * Return TRUE when out of memory or can't undo.
7605 */
7606 static int
7607ins_eol(c)
7608 int c;
7609{
7610 int i;
7611
7612 if (echeck_abbr(c + ABBR_OFF))
7613 return FALSE;
7614 if (stop_arrow() == FAIL)
7615 return TRUE;
7616 undisplay_dollar();
7617
7618 /*
7619 * Strange Vi behaviour: In Replace mode, typing a NL will not delete the
7620 * character under the cursor. Only push a NUL on the replace stack,
7621 * nothing to put back when the NL is deleted.
7622 */
7623 if ((State & REPLACE_FLAG)
7624#ifdef FEAT_VREPLACE
7625 && !(State & VREPLACE_FLAG)
7626#endif
7627 )
7628 replace_push(NUL);
7629
7630 /*
7631 * In VREPLACE mode, a NL replaces the rest of the line, and starts
7632 * replacing the next line, so we push all of the characters left on the
7633 * line onto the replace stack. This is not done here though, it is done
7634 * in open_line().
7635 */
7636
7637#ifdef FEAT_RIGHTLEFT
7638# ifdef FEAT_FKMAP
7639 if (p_altkeymap && p_fkmap)
7640 fkmap(NL);
7641# endif
7642 /* NL in reverse insert will always start in the end of
7643 * current line. */
7644 if (revins_on)
7645 curwin->w_cursor.col += (colnr_T)STRLEN(ml_get_cursor());
7646#endif
7647
7648 AppendToRedobuff(NL_STR);
7649 i = open_line(FORWARD,
7650#ifdef FEAT_COMMENTS
7651 has_format_option(FO_RET_COMS) ? OPENLINE_DO_COM :
7652#endif
7653 0, old_indent);
7654 old_indent = 0;
7655#ifdef FEAT_CINDENT
7656 can_cindent = TRUE;
7657#endif
7658
7659 return (!i);
7660}
7661
7662#ifdef FEAT_DIGRAPHS
7663/*
7664 * Handle digraph in insert mode.
7665 * Returns character still to be inserted, or NUL when nothing remaining to be
7666 * done.
7667 */
7668 static int
7669ins_digraph()
7670{
7671 int c;
7672 int cc;
7673
7674 pc_status = PC_STATUS_UNSET;
7675 if (redrawing() && !char_avail())
7676 {
7677 /* may need to redraw when no more chars available now */
7678 ins_redraw();
7679
7680 edit_putchar('?', TRUE);
7681#ifdef FEAT_CMDL_INFO
7682 add_to_showcmd_c(Ctrl_K);
7683#endif
7684 }
7685
7686#ifdef USE_ON_FLY_SCROLL
7687 dont_scroll = TRUE; /* disallow scrolling here */
7688#endif
7689
7690 /* don't map the digraph chars. This also prevents the
7691 * mode message to be deleted when ESC is hit */
7692 ++no_mapping;
7693 ++allow_keys;
7694 c = safe_vgetc();
7695 --no_mapping;
7696 --allow_keys;
7697 if (IS_SPECIAL(c) || mod_mask) /* special key */
7698 {
7699#ifdef FEAT_CMDL_INFO
7700 clear_showcmd();
7701#endif
7702 insert_special(c, TRUE, FALSE);
7703 return NUL;
7704 }
7705 if (c != ESC)
7706 {
7707 if (redrawing() && !char_avail())
7708 {
7709 /* may need to redraw when no more chars available now */
7710 ins_redraw();
7711
7712 if (char2cells(c) == 1)
7713 {
7714 /* first remove the '?', otherwise it's restored when typing
7715 * an ESC next */
7716 edit_unputchar();
7717 ins_redraw();
7718 edit_putchar(c, TRUE);
7719 }
7720#ifdef FEAT_CMDL_INFO
7721 add_to_showcmd_c(c);
7722#endif
7723 }
7724 ++no_mapping;
7725 ++allow_keys;
7726 cc = safe_vgetc();
7727 --no_mapping;
7728 --allow_keys;
7729 if (cc != ESC)
7730 {
7731 AppendToRedobuff((char_u *)CTRL_V_STR);
7732 c = getdigraph(c, cc, TRUE);
7733#ifdef FEAT_CMDL_INFO
7734 clear_showcmd();
7735#endif
7736 return c;
7737 }
7738 }
7739 edit_unputchar();
7740#ifdef FEAT_CMDL_INFO
7741 clear_showcmd();
7742#endif
7743 return NUL;
7744}
7745#endif
7746
7747/*
7748 * Handle CTRL-E and CTRL-Y in Insert mode: copy char from other line.
7749 * Returns the char to be inserted, or NUL if none found.
7750 */
7751 static int
7752ins_copychar(lnum)
7753 linenr_T lnum;
7754{
7755 int c;
7756 int temp;
7757 char_u *ptr, *prev_ptr;
7758
7759 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
7760 {
7761 vim_beep();
7762 return NUL;
7763 }
7764
7765 /* try to advance to the cursor column */
7766 temp = 0;
7767 ptr = ml_get(lnum);
7768 prev_ptr = ptr;
7769 validate_virtcol();
7770 while ((colnr_T)temp < curwin->w_virtcol && *ptr != NUL)
7771 {
7772 prev_ptr = ptr;
7773 temp += lbr_chartabsize_adv(&ptr, (colnr_T)temp);
7774 }
7775 if ((colnr_T)temp > curwin->w_virtcol)
7776 ptr = prev_ptr;
7777
7778#ifdef FEAT_MBYTE
7779 c = (*mb_ptr2char)(ptr);
7780#else
7781 c = *ptr;
7782#endif
7783 if (c == NUL)
7784 vim_beep();
7785 return c;
7786}
7787
7788#ifdef FEAT_SMARTINDENT
7789/*
7790 * Try to do some very smart auto-indenting.
7791 * Used when inserting a "normal" character.
7792 */
7793 static void
7794ins_try_si(c)
7795 int c;
7796{
7797 pos_T *pos, old_pos;
7798 char_u *ptr;
7799 int i;
7800 int temp;
7801
7802 /*
7803 * do some very smart indenting when entering '{' or '}'
7804 */
7805 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
7806 {
7807 /*
7808 * for '}' set indent equal to indent of line containing matching '{'
7809 */
7810 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
7811 {
7812 old_pos = curwin->w_cursor;
7813 /*
7814 * If the matching '{' has a ')' immediately before it (ignoring
7815 * white-space), then line up with the start of the line
7816 * containing the matching '(' if there is one. This handles the
7817 * case where an "if (..\n..) {" statement continues over multiple
7818 * lines -- webb
7819 */
7820 ptr = ml_get(pos->lnum);
7821 i = pos->col;
7822 if (i > 0) /* skip blanks before '{' */
7823 while (--i > 0 && vim_iswhite(ptr[i]))
7824 ;
7825 curwin->w_cursor.lnum = pos->lnum;
7826 curwin->w_cursor.col = i;
7827 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
7828 curwin->w_cursor = *pos;
7829 i = get_indent();
7830 curwin->w_cursor = old_pos;
7831#ifdef FEAT_VREPLACE
7832 if (State & VREPLACE_FLAG)
7833 change_indent(INDENT_SET, i, FALSE, NUL);
7834 else
7835#endif
7836 (void)set_indent(i, SIN_CHANGED);
7837 }
7838 else if (curwin->w_cursor.col > 0)
7839 {
7840 /*
7841 * when inserting '{' after "O" reduce indent, but not
7842 * more than indent of previous line
7843 */
7844 temp = TRUE;
7845 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
7846 {
7847 old_pos = curwin->w_cursor;
7848 i = get_indent();
7849 while (curwin->w_cursor.lnum > 1)
7850 {
7851 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
7852
7853 /* ignore empty lines and lines starting with '#'. */
7854 if (*ptr != '#' && *ptr != NUL)
7855 break;
7856 }
7857 if (get_indent() >= i)
7858 temp = FALSE;
7859 curwin->w_cursor = old_pos;
7860 }
7861 if (temp)
7862 shift_line(TRUE, FALSE, 1);
7863 }
7864 }
7865
7866 /*
7867 * set indent of '#' always to 0
7868 */
7869 if (curwin->w_cursor.col > 0 && can_si && c == '#')
7870 {
7871 /* remember current indent for next line */
7872 old_indent = get_indent();
7873 (void)set_indent(0, SIN_CHANGED);
7874 }
7875
7876 /* Adjust ai_col, the char at this position can be deleted. */
7877 if (ai_col > curwin->w_cursor.col)
7878 ai_col = curwin->w_cursor.col;
7879}
7880#endif
7881
7882/*
7883 * Get the value that w_virtcol would have when 'list' is off.
7884 * Unless 'cpo' contains the 'L' flag.
7885 */
7886 static colnr_T
7887get_nolist_virtcol()
7888{
7889 if (curwin->w_p_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
7890 return getvcol_nolist(&curwin->w_cursor);
7891 validate_virtcol();
7892 return curwin->w_virtcol;
7893}