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