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