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