Use 7.2a "spell" folder (and remove all extra spell files)
[MacVim.git] / src / ex_getln.c
blob4979b2ff9d893732f7bf479008df89ea6567539f
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * ex_getln.c: Functions for entering and editing an Ex command line.
14 #include "vim.h"
17 * Variables shared between getcmdline(), redrawcmdline() and others.
18 * These need to be saved when using CTRL-R |, that's why they are in a
19 * structure.
21 struct cmdline_info
23 char_u *cmdbuff; /* pointer to command line buffer */
24 int cmdbufflen; /* length of cmdbuff */
25 int cmdlen; /* number of chars in command line */
26 int cmdpos; /* current cursor position */
27 int cmdspos; /* cursor column on screen */
28 int cmdfirstc; /* ':', '/', '?', '=' or NUL */
29 int cmdindent; /* number of spaces before cmdline */
30 char_u *cmdprompt; /* message in front of cmdline */
31 int cmdattr; /* attributes for prompt */
32 int overstrike; /* Typing mode on the command line. Shared by
33 getcmdline() and put_on_cmdline(). */
34 int xp_context; /* type of expansion */
35 # ifdef FEAT_EVAL
36 char_u *xp_arg; /* user-defined expansion arg */
37 int input_fn; /* when TRUE Invoked for input() function */
38 # endif
41 static struct cmdline_info ccline; /* current cmdline_info */
43 static int cmd_showtail; /* Only show path tail in lists ? */
45 #ifdef FEAT_EVAL
46 static int new_cmdpos; /* position set by set_cmdline_pos() */
47 #endif
49 #ifdef FEAT_CMDHIST
50 typedef struct hist_entry
52 int hisnum; /* identifying number */
53 char_u *hisstr; /* actual entry, separator char after the NUL */
54 } histentry_T;
56 static histentry_T *(history[HIST_COUNT]) = {NULL, NULL, NULL, NULL, NULL};
57 static int hisidx[HIST_COUNT] = {-1, -1, -1, -1, -1}; /* lastused entry */
58 static int hisnum[HIST_COUNT] = {0, 0, 0, 0, 0};
59 /* identifying (unique) number of newest history entry */
60 static int hislen = 0; /* actual length of history tables */
62 static int hist_char2type __ARGS((int c));
64 static int in_history __ARGS((int, char_u *, int));
65 # ifdef FEAT_EVAL
66 static int calc_hist_idx __ARGS((int histype, int num));
67 # endif
68 #endif
70 #ifdef FEAT_RIGHTLEFT
71 static int cmd_hkmap = 0; /* Hebrew mapping during command line */
72 #endif
74 #ifdef FEAT_FKMAP
75 static int cmd_fkmap = 0; /* Farsi mapping during command line */
76 #endif
78 static int cmdline_charsize __ARGS((int idx));
79 static void set_cmdspos __ARGS((void));
80 static void set_cmdspos_cursor __ARGS((void));
81 #ifdef FEAT_MBYTE
82 static void correct_cmdspos __ARGS((int idx, int cells));
83 #endif
84 static void alloc_cmdbuff __ARGS((int len));
85 static int realloc_cmdbuff __ARGS((int len));
86 static void draw_cmdline __ARGS((int start, int len));
87 static void save_cmdline __ARGS((struct cmdline_info *ccp));
88 static void restore_cmdline __ARGS((struct cmdline_info *ccp));
89 static int cmdline_paste __ARGS((int regname, int literally, int remcr));
90 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
91 static void redrawcmd_preedit __ARGS((void));
92 #endif
93 #ifdef FEAT_WILDMENU
94 static void cmdline_del __ARGS((int from));
95 #endif
96 static void redrawcmdprompt __ARGS((void));
97 static void cursorcmd __ARGS((void));
98 static int ccheck_abbr __ARGS((int));
99 static int nextwild __ARGS((expand_T *xp, int type, int options));
100 static void escape_fname __ARGS((char_u **pp));
101 static int showmatches __ARGS((expand_T *xp, int wildmenu));
102 static void set_expand_context __ARGS((expand_T *xp));
103 static int ExpandFromContext __ARGS((expand_T *xp, char_u *, int *, char_u ***, int));
104 static int expand_showtail __ARGS((expand_T *xp));
105 #ifdef FEAT_CMDL_COMPL
106 static int expand_shellcmd __ARGS((char_u *filepat, int *num_file, char_u ***file, int flagsarg));
107 static int ExpandRTDir __ARGS((char_u *pat, int *num_file, char_u ***file, char *dirname));
108 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
109 static int ExpandUserDefined __ARGS((expand_T *xp, regmatch_T *regmatch, int *num_file, char_u ***file));
110 static int ExpandUserList __ARGS((expand_T *xp, int *num_file, char_u ***file));
111 # endif
112 #endif
114 #ifdef FEAT_CMDWIN
115 static int ex_window __ARGS((void));
116 #endif
119 * getcmdline() - accept a command line starting with firstc.
121 * firstc == ':' get ":" command line.
122 * firstc == '/' or '?' get search pattern
123 * firstc == '=' get expression
124 * firstc == '@' get text for input() function
125 * firstc == '>' get text for debug mode
126 * firstc == NUL get text for :insert command
127 * firstc == -1 like NUL, and break on CTRL-C
129 * The line is collected in ccline.cmdbuff, which is reallocated to fit the
130 * command line.
132 * Careful: getcmdline() can be called recursively!
134 * Return pointer to allocated string if there is a commandline, NULL
135 * otherwise.
137 /*ARGSUSED*/
138 char_u *
139 getcmdline(firstc, count, indent)
140 int firstc;
141 long count; /* only used for incremental search */
142 int indent; /* indent for inside conditionals */
144 int c;
145 int i;
146 int j;
147 int gotesc = FALSE; /* TRUE when <ESC> just typed */
148 int do_abbr; /* when TRUE check for abbr. */
149 #ifdef FEAT_CMDHIST
150 char_u *lookfor = NULL; /* string to match */
151 int hiscnt; /* current history line in use */
152 int histype; /* history type to be used */
153 #endif
154 #ifdef FEAT_SEARCH_EXTRA
155 pos_T old_cursor;
156 colnr_T old_curswant;
157 colnr_T old_leftcol;
158 linenr_T old_topline;
159 # ifdef FEAT_DIFF
160 int old_topfill;
161 # endif
162 linenr_T old_botline;
163 int did_incsearch = FALSE;
164 int incsearch_postponed = FALSE;
165 #endif
166 int did_wild_list = FALSE; /* did wild_list() recently */
167 int wim_index = 0; /* index in wim_flags[] */
168 int res;
169 int save_msg_scroll = msg_scroll;
170 int save_State = State; /* remember State when called */
171 int some_key_typed = FALSE; /* one of the keys was typed */
172 #ifdef FEAT_MOUSE
173 /* mouse drag and release events are ignored, unless they are
174 * preceded with a mouse down event */
175 int ignore_drag_release = TRUE;
176 #endif
177 #ifdef FEAT_EVAL
178 int break_ctrl_c = FALSE;
179 #endif
180 expand_T xpc;
181 long *b_im_ptr = NULL;
182 #if defined(FEAT_WILDMENU) || defined(FEAT_EVAL) || defined(FEAT_SEARCH_EXTRA)
183 /* Everything that may work recursively should save and restore the
184 * current command line in save_ccline. That includes update_screen(), a
185 * custom status line may invoke ":normal". */
186 struct cmdline_info save_ccline;
187 #endif
189 #ifdef FEAT_SNIFF
190 want_sniff_request = 0;
191 #endif
192 #ifdef FEAT_EVAL
193 if (firstc == -1)
195 firstc = NUL;
196 break_ctrl_c = TRUE;
198 #endif
199 #ifdef FEAT_RIGHTLEFT
200 /* start without Hebrew mapping for a command line */
201 if (firstc == ':' || firstc == '=' || firstc == '>')
202 cmd_hkmap = 0;
203 #endif
205 ccline.overstrike = FALSE; /* always start in insert mode */
206 #ifdef FEAT_SEARCH_EXTRA
207 old_cursor = curwin->w_cursor; /* needs to be restored later */
208 old_curswant = curwin->w_curswant;
209 old_leftcol = curwin->w_leftcol;
210 old_topline = curwin->w_topline;
211 # ifdef FEAT_DIFF
212 old_topfill = curwin->w_topfill;
213 # endif
214 old_botline = curwin->w_botline;
215 #endif
218 * set some variables for redrawcmd()
220 ccline.cmdfirstc = (firstc == '@' ? 0 : firstc);
221 ccline.cmdindent = (firstc > 0 ? indent : 0);
223 /* alloc initial ccline.cmdbuff */
224 alloc_cmdbuff(exmode_active ? 250 : indent + 1);
225 if (ccline.cmdbuff == NULL)
226 return NULL; /* out of memory */
227 ccline.cmdlen = ccline.cmdpos = 0;
228 ccline.cmdbuff[0] = NUL;
230 /* autoindent for :insert and :append */
231 if (firstc <= 0)
233 copy_spaces(ccline.cmdbuff, indent);
234 ccline.cmdbuff[indent] = NUL;
235 ccline.cmdpos = indent;
236 ccline.cmdspos = indent;
237 ccline.cmdlen = indent;
240 ExpandInit(&xpc);
242 #ifdef FEAT_RIGHTLEFT
243 if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
244 && (firstc == '/' || firstc == '?'))
245 cmdmsg_rl = TRUE;
246 else
247 cmdmsg_rl = FALSE;
248 #endif
250 redir_off = TRUE; /* don't redirect the typed command */
251 if (!cmd_silent)
253 i = msg_scrolled;
254 msg_scrolled = 0; /* avoid wait_return message */
255 gotocmdline(TRUE);
256 msg_scrolled += i;
257 redrawcmdprompt(); /* draw prompt or indent */
258 set_cmdspos();
260 xpc.xp_context = EXPAND_NOTHING;
261 xpc.xp_backslash = XP_BS_NONE;
262 #ifndef BACKSLASH_IN_FILENAME
263 xpc.xp_shell = FALSE;
264 #endif
266 #if defined(FEAT_EVAL)
267 if (ccline.input_fn)
269 xpc.xp_context = ccline.xp_context;
270 xpc.xp_pattern = ccline.cmdbuff;
271 # if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
272 xpc.xp_arg = ccline.xp_arg;
273 # endif
275 #endif
278 * Avoid scrolling when called by a recursive do_cmdline(), e.g. when
279 * doing ":@0" when register 0 doesn't contain a CR.
281 msg_scroll = FALSE;
283 State = CMDLINE;
285 if (firstc == '/' || firstc == '?' || firstc == '@')
287 /* Use ":lmap" mappings for search pattern and input(). */
288 if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
289 b_im_ptr = &curbuf->b_p_iminsert;
290 else
291 b_im_ptr = &curbuf->b_p_imsearch;
292 if (*b_im_ptr == B_IMODE_LMAP)
293 State |= LANGMAP;
294 #ifdef USE_IM_CONTROL
295 im_set_active(*b_im_ptr == B_IMODE_IM);
296 #endif
298 #ifdef USE_IM_CONTROL
299 else if (p_imcmdline)
300 im_set_active(TRUE);
301 #endif
303 #ifdef FEAT_MOUSE
304 setmouse();
305 #endif
306 #ifdef CURSOR_SHAPE
307 ui_cursor_shape(); /* may show different cursor shape */
308 #endif
310 /* When inside an autocommand for writing "exiting" may be set and
311 * terminal mode set to cooked. Need to set raw mode here then. */
312 settmode(TMODE_RAW);
314 #ifdef FEAT_CMDHIST
315 init_history();
316 hiscnt = hislen; /* set hiscnt to impossible history value */
317 histype = hist_char2type(firstc);
318 #endif
320 #ifdef FEAT_DIGRAPHS
321 do_digraph(-1); /* init digraph typahead */
322 #endif
325 * Collect the command string, handling editing keys.
327 for (;;)
329 redir_off = TRUE; /* Don't redirect the typed command.
330 Repeated, because a ":redir" inside
331 completion may switch it on. */
332 #ifdef USE_ON_FLY_SCROLL
333 dont_scroll = FALSE; /* allow scrolling here */
334 #endif
335 quit_more = FALSE; /* reset after CTRL-D which had a more-prompt */
337 cursorcmd(); /* set the cursor on the right spot */
339 /* Get a character. Ignore K_IGNORE, it should not do anything, such
340 * as stop completion. */
343 c = safe_vgetc();
344 } while (c == K_IGNORE);
346 if (KeyTyped)
348 some_key_typed = TRUE;
349 #ifdef FEAT_RIGHTLEFT
350 if (cmd_hkmap)
351 c = hkmap(c);
352 # ifdef FEAT_FKMAP
353 if (cmd_fkmap)
354 c = cmdl_fkmap(c);
355 # endif
356 if (cmdmsg_rl && !KeyStuffed)
358 /* Invert horizontal movements and operations. Only when
359 * typed by the user directly, not when the result of a
360 * mapping. */
361 switch (c)
363 case K_RIGHT: c = K_LEFT; break;
364 case K_S_RIGHT: c = K_S_LEFT; break;
365 case K_C_RIGHT: c = K_C_LEFT; break;
366 case K_LEFT: c = K_RIGHT; break;
367 case K_S_LEFT: c = K_S_RIGHT; break;
368 case K_C_LEFT: c = K_C_RIGHT; break;
371 #endif
375 * Ignore got_int when CTRL-C was typed here.
376 * Don't ignore it in :global, we really need to break then, e.g., for
377 * ":g/pat/normal /pat" (without the <CR>).
378 * Don't ignore it for the input() function.
380 if ((c == Ctrl_C
381 #ifdef UNIX
382 || c == intr_char
383 #endif
385 #if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
386 && firstc != '@'
387 #endif
388 #ifdef FEAT_EVAL
389 && !break_ctrl_c
390 #endif
391 && !global_busy)
392 got_int = FALSE;
394 #ifdef FEAT_CMDHIST
395 /* free old command line when finished moving around in the history
396 * list */
397 if (lookfor != NULL
398 && c != K_S_DOWN && c != K_S_UP
399 && c != K_DOWN && c != K_UP
400 && c != K_PAGEDOWN && c != K_PAGEUP
401 && c != K_KPAGEDOWN && c != K_KPAGEUP
402 && c != K_LEFT && c != K_RIGHT
403 && (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
405 vim_free(lookfor);
406 lookfor = NULL;
408 #endif
411 * <S-Tab> works like CTRL-P (unless 'wc' is <S-Tab>).
413 if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles != -1)
414 c = Ctrl_P;
416 #ifdef FEAT_WILDMENU
417 /* Special translations for 'wildmenu' */
418 if (did_wild_list && p_wmnu)
420 if (c == K_LEFT)
421 c = Ctrl_P;
422 else if (c == K_RIGHT)
423 c = Ctrl_N;
425 /* Hitting CR after "emenu Name.": complete submenu */
426 if (xpc.xp_context == EXPAND_MENUNAMES && p_wmnu
427 && ccline.cmdpos > 1
428 && ccline.cmdbuff[ccline.cmdpos - 1] == '.'
429 && ccline.cmdbuff[ccline.cmdpos - 2] != '\\'
430 && (c == '\n' || c == '\r' || c == K_KENTER))
431 c = K_DOWN;
432 #endif
434 /* free expanded names when finished walking through matches */
435 if (xpc.xp_numfiles != -1
436 && !(c == p_wc && KeyTyped) && c != p_wcm
437 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_A
438 && c != Ctrl_L)
440 (void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
441 did_wild_list = FALSE;
442 #ifdef FEAT_WILDMENU
443 if (!p_wmnu || (c != K_UP && c != K_DOWN))
444 #endif
445 xpc.xp_context = EXPAND_NOTHING;
446 wim_index = 0;
447 #ifdef FEAT_WILDMENU
448 if (p_wmnu && wild_menu_showing != 0)
450 int skt = KeyTyped;
451 int old_RedrawingDisabled = RedrawingDisabled;
453 if (ccline.input_fn)
454 RedrawingDisabled = 0;
456 if (wild_menu_showing == WM_SCROLLED)
458 /* Entered command line, move it up */
459 cmdline_row--;
460 redrawcmd();
462 else if (save_p_ls != -1)
464 /* restore 'laststatus' and 'winminheight' */
465 p_ls = save_p_ls;
466 p_wmh = save_p_wmh;
467 last_status(FALSE);
468 save_cmdline(&save_ccline);
469 update_screen(VALID); /* redraw the screen NOW */
470 restore_cmdline(&save_ccline);
471 redrawcmd();
472 save_p_ls = -1;
474 else
476 # ifdef FEAT_VERTSPLIT
477 win_redraw_last_status(topframe);
478 # else
479 lastwin->w_redr_status = TRUE;
480 # endif
481 redraw_statuslines();
483 KeyTyped = skt;
484 wild_menu_showing = 0;
485 if (ccline.input_fn)
486 RedrawingDisabled = old_RedrawingDisabled;
488 #endif
491 #ifdef FEAT_WILDMENU
492 /* Special translations for 'wildmenu' */
493 if (xpc.xp_context == EXPAND_MENUNAMES && p_wmnu)
495 /* Hitting <Down> after "emenu Name.": complete submenu */
496 if (c == K_DOWN && ccline.cmdpos > 0
497 && ccline.cmdbuff[ccline.cmdpos - 1] == '.')
498 c = p_wc;
499 else if (c == K_UP)
501 /* Hitting <Up>: Remove one submenu name in front of the
502 * cursor */
503 int found = FALSE;
505 j = (int)(xpc.xp_pattern - ccline.cmdbuff);
506 i = 0;
507 while (--j > 0)
509 /* check for start of menu name */
510 if (ccline.cmdbuff[j] == ' '
511 && ccline.cmdbuff[j - 1] != '\\')
513 i = j + 1;
514 break;
516 /* check for start of submenu name */
517 if (ccline.cmdbuff[j] == '.'
518 && ccline.cmdbuff[j - 1] != '\\')
520 if (found)
522 i = j + 1;
523 break;
525 else
526 found = TRUE;
529 if (i > 0)
530 cmdline_del(i);
531 c = p_wc;
532 xpc.xp_context = EXPAND_NOTHING;
535 if ((xpc.xp_context == EXPAND_FILES
536 || xpc.xp_context == EXPAND_DIRECTORIES
537 || xpc.xp_context == EXPAND_SHELLCMD) && p_wmnu)
539 char_u upseg[5];
541 upseg[0] = PATHSEP;
542 upseg[1] = '.';
543 upseg[2] = '.';
544 upseg[3] = PATHSEP;
545 upseg[4] = NUL;
547 if (c == K_DOWN
548 && ccline.cmdpos > 0
549 && ccline.cmdbuff[ccline.cmdpos - 1] == PATHSEP
550 && (ccline.cmdpos < 3
551 || ccline.cmdbuff[ccline.cmdpos - 2] != '.'
552 || ccline.cmdbuff[ccline.cmdpos - 3] != '.'))
554 /* go down a directory */
555 c = p_wc;
557 else if (STRNCMP(xpc.xp_pattern, upseg + 1, 3) == 0 && c == K_DOWN)
559 /* If in a direct ancestor, strip off one ../ to go down */
560 int found = FALSE;
562 j = ccline.cmdpos;
563 i = (int)(xpc.xp_pattern - ccline.cmdbuff);
564 while (--j > i)
566 #ifdef FEAT_MBYTE
567 if (has_mbyte)
568 j -= (*mb_head_off)(ccline.cmdbuff, ccline.cmdbuff + j);
569 #endif
570 if (vim_ispathsep(ccline.cmdbuff[j]))
572 found = TRUE;
573 break;
576 if (found
577 && ccline.cmdbuff[j - 1] == '.'
578 && ccline.cmdbuff[j - 2] == '.'
579 && (vim_ispathsep(ccline.cmdbuff[j - 3]) || j == i + 2))
581 cmdline_del(j - 2);
582 c = p_wc;
585 else if (c == K_UP)
587 /* go up a directory */
588 int found = FALSE;
590 j = ccline.cmdpos - 1;
591 i = (int)(xpc.xp_pattern - ccline.cmdbuff);
592 while (--j > i)
594 #ifdef FEAT_MBYTE
595 if (has_mbyte)
596 j -= (*mb_head_off)(ccline.cmdbuff, ccline.cmdbuff + j);
597 #endif
598 if (vim_ispathsep(ccline.cmdbuff[j])
599 #ifdef BACKSLASH_IN_FILENAME
600 && vim_strchr(" *?[{`$%#", ccline.cmdbuff[j + 1])
601 == NULL
602 #endif
605 if (found)
607 i = j + 1;
608 break;
610 else
611 found = TRUE;
615 if (!found)
616 j = i;
617 else if (STRNCMP(ccline.cmdbuff + j, upseg, 4) == 0)
618 j += 4;
619 else if (STRNCMP(ccline.cmdbuff + j, upseg + 1, 3) == 0
620 && j == i)
621 j += 3;
622 else
623 j = 0;
624 if (j > 0)
626 /* TODO this is only for DOS/UNIX systems - need to put in
627 * machine-specific stuff here and in upseg init */
628 cmdline_del(j);
629 put_on_cmdline(upseg + 1, 3, FALSE);
631 else if (ccline.cmdpos > i)
632 cmdline_del(i);
633 c = p_wc;
636 #if 0 /* If enabled <Down> on a file takes you _completely_ out of wildmenu */
637 if (p_wmnu
638 && (xpc.xp_context == EXPAND_FILES
639 || xpc.xp_context == EXPAND_MENUNAMES)
640 && (c == K_UP || c == K_DOWN))
641 xpc.xp_context = EXPAND_NOTHING;
642 #endif
644 #endif /* FEAT_WILDMENU */
646 /* CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
647 * mode when 'insertmode' is set, CTRL-\ e prompts for an expression. */
648 if (c == Ctrl_BSL)
650 ++no_mapping;
651 ++allow_keys;
652 c = plain_vgetc();
653 --no_mapping;
654 --allow_keys;
655 /* CTRL-\ e doesn't work when obtaining an expression. */
656 if (c != Ctrl_N && c != Ctrl_G
657 && (c != 'e' || ccline.cmdfirstc == '='))
659 vungetc(c);
660 c = Ctrl_BSL;
662 #ifdef FEAT_EVAL
663 else if (c == 'e')
665 char_u *p = NULL;
668 * Replace the command line with the result of an expression.
669 * Need to save and restore the current command line, to be
670 * able to enter a new one...
672 if (ccline.cmdpos == ccline.cmdlen)
673 new_cmdpos = 99999; /* keep it at the end */
674 else
675 new_cmdpos = ccline.cmdpos;
677 save_cmdline(&save_ccline);
678 c = get_expr_register();
679 restore_cmdline(&save_ccline);
680 if (c == '=')
682 /* Need to save and restore ccline. And set "textlock"
683 * to avoid nasty things like going to another buffer when
684 * evaluating an expression. */
685 save_cmdline(&save_ccline);
686 ++textlock;
687 p = get_expr_line();
688 --textlock;
689 restore_cmdline(&save_ccline);
691 if (p != NULL && realloc_cmdbuff((int)STRLEN(p) + 1) == OK)
693 ccline.cmdlen = (int)STRLEN(p);
694 STRCPY(ccline.cmdbuff, p);
695 vim_free(p);
697 /* Restore the cursor or use the position set with
698 * set_cmdline_pos(). */
699 if (new_cmdpos > ccline.cmdlen)
700 ccline.cmdpos = ccline.cmdlen;
701 else
702 ccline.cmdpos = new_cmdpos;
704 KeyTyped = FALSE; /* Don't do p_wc completion. */
705 redrawcmd();
706 goto cmdline_changed;
709 beep_flush();
710 c = ESC;
712 #endif
713 else
715 if (c == Ctrl_G && p_im && restart_edit == 0)
716 restart_edit = 'a';
717 gotesc = TRUE; /* will free ccline.cmdbuff after putting it
718 in history */
719 goto returncmd; /* back to Normal mode */
723 #ifdef FEAT_CMDWIN
724 if (c == cedit_key || c == K_CMDWIN)
727 * Open a window to edit the command line (and history).
729 c = ex_window();
730 some_key_typed = TRUE;
732 # ifdef FEAT_DIGRAPHS
733 else
734 # endif
735 #endif
736 #ifdef FEAT_DIGRAPHS
737 c = do_digraph(c);
738 #endif
740 if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
741 && (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
743 /* In Ex mode a backslash escapes a newline. */
744 if (exmode_active
745 && c != ESC
746 && ccline.cmdpos == ccline.cmdlen
747 && ccline.cmdpos > 0
748 && ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
750 if (c == K_KENTER)
751 c = '\n';
753 else
755 gotesc = FALSE; /* Might have typed ESC previously, don't
756 truncate the cmdline now. */
757 if (ccheck_abbr(c + ABBR_OFF))
758 goto cmdline_changed;
759 if (!cmd_silent)
761 windgoto(msg_row, 0);
762 out_flush();
764 break;
769 * Completion for 'wildchar' or 'wildcharm' key.
770 * - hitting <ESC> twice means: abandon command line.
771 * - wildcard expansion is only done when the 'wildchar' key is really
772 * typed, not when it comes from a macro
774 if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
776 if (xpc.xp_numfiles > 0) /* typed p_wc at least twice */
778 /* if 'wildmode' contains "list" may still need to list */
779 if (xpc.xp_numfiles > 1
780 && !did_wild_list
781 && (wim_flags[wim_index] & WIM_LIST))
783 (void)showmatches(&xpc, FALSE);
784 redrawcmd();
785 did_wild_list = TRUE;
787 if (wim_flags[wim_index] & WIM_LONGEST)
788 res = nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
789 else if (wim_flags[wim_index] & WIM_FULL)
790 res = nextwild(&xpc, WILD_NEXT, WILD_NO_BEEP);
791 else
792 res = OK; /* don't insert 'wildchar' now */
794 else /* typed p_wc first time */
796 wim_index = 0;
797 j = ccline.cmdpos;
798 /* if 'wildmode' first contains "longest", get longest
799 * common part */
800 if (wim_flags[0] & WIM_LONGEST)
801 res = nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
802 else
803 res = nextwild(&xpc, WILD_EXPAND_KEEP, WILD_NO_BEEP);
805 /* if interrupted while completing, behave like it failed */
806 if (got_int)
808 (void)vpeekc(); /* remove <C-C> from input stream */
809 got_int = FALSE; /* don't abandon the command line */
810 (void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
811 #ifdef FEAT_WILDMENU
812 xpc.xp_context = EXPAND_NOTHING;
813 #endif
814 goto cmdline_changed;
817 /* when more than one match, and 'wildmode' first contains
818 * "list", or no change and 'wildmode' contains "longest,list",
819 * list all matches */
820 if (res == OK && xpc.xp_numfiles > 1)
822 /* a "longest" that didn't do anything is skipped (but not
823 * "list:longest") */
824 if (wim_flags[0] == WIM_LONGEST && ccline.cmdpos == j)
825 wim_index = 1;
826 if ((wim_flags[wim_index] & WIM_LIST)
827 #ifdef FEAT_WILDMENU
828 || (p_wmnu && (wim_flags[wim_index] & WIM_FULL) != 0)
829 #endif
832 if (!(wim_flags[0] & WIM_LONGEST))
834 #ifdef FEAT_WILDMENU
835 int p_wmnu_save = p_wmnu;
836 p_wmnu = 0;
837 #endif
838 nextwild(&xpc, WILD_PREV, 0); /* remove match */
839 #ifdef FEAT_WILDMENU
840 p_wmnu = p_wmnu_save;
841 #endif
843 #ifdef FEAT_WILDMENU
844 (void)showmatches(&xpc, p_wmnu
845 && ((wim_flags[wim_index] & WIM_LIST) == 0));
846 #else
847 (void)showmatches(&xpc, FALSE);
848 #endif
849 redrawcmd();
850 did_wild_list = TRUE;
851 if (wim_flags[wim_index] & WIM_LONGEST)
852 nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
853 else if (wim_flags[wim_index] & WIM_FULL)
854 nextwild(&xpc, WILD_NEXT, WILD_NO_BEEP);
856 else
857 vim_beep();
859 #ifdef FEAT_WILDMENU
860 else if (xpc.xp_numfiles == -1)
861 xpc.xp_context = EXPAND_NOTHING;
862 #endif
864 if (wim_index < 3)
865 ++wim_index;
866 if (c == ESC)
867 gotesc = TRUE;
868 if (res == OK)
869 goto cmdline_changed;
872 gotesc = FALSE;
874 /* <S-Tab> goes to last match, in a clumsy way */
875 if (c == K_S_TAB && KeyTyped)
877 if (nextwild(&xpc, WILD_EXPAND_KEEP, 0) == OK
878 && nextwild(&xpc, WILD_PREV, 0) == OK
879 && nextwild(&xpc, WILD_PREV, 0) == OK)
880 goto cmdline_changed;
883 if (c == NUL || c == K_ZERO) /* NUL is stored as NL */
884 c = NL;
886 do_abbr = TRUE; /* default: check for abbreviation */
889 * Big switch for a typed command line character.
891 switch (c)
893 case K_BS:
894 case Ctrl_H:
895 case K_DEL:
896 case K_KDEL:
897 case Ctrl_W:
898 #ifdef FEAT_FKMAP
899 if (cmd_fkmap && c == K_BS)
900 c = K_DEL;
901 #endif
902 if (c == K_KDEL)
903 c = K_DEL;
906 * delete current character is the same as backspace on next
907 * character, except at end of line
909 if (c == K_DEL && ccline.cmdpos != ccline.cmdlen)
910 ++ccline.cmdpos;
911 #ifdef FEAT_MBYTE
912 if (has_mbyte && c == K_DEL)
913 ccline.cmdpos += mb_off_next(ccline.cmdbuff,
914 ccline.cmdbuff + ccline.cmdpos);
915 #endif
916 if (ccline.cmdpos > 0)
918 char_u *p;
920 j = ccline.cmdpos;
921 p = ccline.cmdbuff + j;
922 #ifdef FEAT_MBYTE
923 if (has_mbyte)
925 p = mb_prevptr(ccline.cmdbuff, p);
926 if (c == Ctrl_W)
928 while (p > ccline.cmdbuff && vim_isspace(*p))
929 p = mb_prevptr(ccline.cmdbuff, p);
930 i = mb_get_class(p);
931 while (p > ccline.cmdbuff && mb_get_class(p) == i)
932 p = mb_prevptr(ccline.cmdbuff, p);
933 if (mb_get_class(p) != i)
934 p += (*mb_ptr2len)(p);
937 else
938 #endif
939 if (c == Ctrl_W)
941 while (p > ccline.cmdbuff && vim_isspace(p[-1]))
942 --p;
943 i = vim_iswordc(p[-1]);
944 while (p > ccline.cmdbuff && !vim_isspace(p[-1])
945 && vim_iswordc(p[-1]) == i)
946 --p;
948 else
949 --p;
950 ccline.cmdpos = (int)(p - ccline.cmdbuff);
951 ccline.cmdlen -= j - ccline.cmdpos;
952 i = ccline.cmdpos;
953 while (i < ccline.cmdlen)
954 ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
956 /* Truncate at the end, required for multi-byte chars. */
957 ccline.cmdbuff[ccline.cmdlen] = NUL;
958 redrawcmd();
960 else if (ccline.cmdlen == 0 && c != Ctrl_W
961 && ccline.cmdprompt == NULL && indent == 0)
963 /* In ex and debug mode it doesn't make sense to return. */
964 if (exmode_active
965 #ifdef FEAT_EVAL
966 || ccline.cmdfirstc == '>'
967 #endif
969 goto cmdline_not_changed;
971 vim_free(ccline.cmdbuff); /* no commandline to return */
972 ccline.cmdbuff = NULL;
973 if (!cmd_silent)
975 #ifdef FEAT_RIGHTLEFT
976 if (cmdmsg_rl)
977 msg_col = Columns;
978 else
979 #endif
980 msg_col = 0;
981 msg_putchar(' '); /* delete ':' */
983 redraw_cmdline = TRUE;
984 goto returncmd; /* back to cmd mode */
986 goto cmdline_changed;
988 case K_INS:
989 case K_KINS:
990 #ifdef FEAT_FKMAP
991 /* if Farsi mode set, we are in reverse insert mode -
992 Do not change the mode */
993 if (cmd_fkmap)
994 beep_flush();
995 else
996 #endif
997 ccline.overstrike = !ccline.overstrike;
998 #ifdef CURSOR_SHAPE
999 ui_cursor_shape(); /* may show different cursor shape */
1000 #endif
1001 goto cmdline_not_changed;
1003 case Ctrl_HAT:
1004 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
1006 /* ":lmap" mappings exists, toggle use of mappings. */
1007 State ^= LANGMAP;
1008 #ifdef USE_IM_CONTROL
1009 im_set_active(FALSE); /* Disable input method */
1010 #endif
1011 if (b_im_ptr != NULL)
1013 if (State & LANGMAP)
1014 *b_im_ptr = B_IMODE_LMAP;
1015 else
1016 *b_im_ptr = B_IMODE_NONE;
1019 #ifdef USE_IM_CONTROL
1020 else
1022 /* There are no ":lmap" mappings, toggle IM. When
1023 * 'imdisable' is set don't try getting the status, it's
1024 * always off. */
1025 if ((p_imdisable && b_im_ptr != NULL)
1026 ? *b_im_ptr == B_IMODE_IM : im_get_status())
1028 im_set_active(FALSE); /* Disable input method */
1029 if (b_im_ptr != NULL)
1030 *b_im_ptr = B_IMODE_NONE;
1032 else
1034 im_set_active(TRUE); /* Enable input method */
1035 if (b_im_ptr != NULL)
1036 *b_im_ptr = B_IMODE_IM;
1039 #endif
1040 if (b_im_ptr != NULL)
1042 if (b_im_ptr == &curbuf->b_p_iminsert)
1043 set_iminsert_global();
1044 else
1045 set_imsearch_global();
1047 #ifdef CURSOR_SHAPE
1048 ui_cursor_shape(); /* may show different cursor shape */
1049 #endif
1050 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
1051 /* Show/unshow value of 'keymap' in status lines later. */
1052 status_redraw_curbuf();
1053 #endif
1054 goto cmdline_not_changed;
1056 /* case '@': only in very old vi */
1057 case Ctrl_U:
1058 /* delete all characters left of the cursor */
1059 j = ccline.cmdpos;
1060 ccline.cmdlen -= j;
1061 i = ccline.cmdpos = 0;
1062 while (i < ccline.cmdlen)
1063 ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
1064 /* Truncate at the end, required for multi-byte chars. */
1065 ccline.cmdbuff[ccline.cmdlen] = NUL;
1066 redrawcmd();
1067 goto cmdline_changed;
1069 #ifdef FEAT_CLIPBOARD
1070 case Ctrl_Y:
1071 /* Copy the modeless selection, if there is one. */
1072 if (clip_star.state != SELECT_CLEARED)
1074 if (clip_star.state == SELECT_DONE)
1075 clip_copy_modeless_selection(TRUE);
1076 goto cmdline_not_changed;
1078 break;
1079 #endif
1081 case ESC: /* get here if p_wc != ESC or when ESC typed twice */
1082 case Ctrl_C:
1083 /* In exmode it doesn't make sense to return. Except when
1084 * ":normal" runs out of characters. */
1085 if (exmode_active
1086 #ifdef FEAT_EX_EXTRA
1087 && (ex_normal_busy == 0 || typebuf.tb_len > 0)
1088 #endif
1090 goto cmdline_not_changed;
1092 gotesc = TRUE; /* will free ccline.cmdbuff after
1093 putting it in history */
1094 goto returncmd; /* back to cmd mode */
1096 case Ctrl_R: /* insert register */
1097 #ifdef USE_ON_FLY_SCROLL
1098 dont_scroll = TRUE; /* disallow scrolling here */
1099 #endif
1100 putcmdline('"', TRUE);
1101 ++no_mapping;
1102 i = c = plain_vgetc(); /* CTRL-R <char> */
1103 if (i == Ctrl_O)
1104 i = Ctrl_R; /* CTRL-R CTRL-O == CTRL-R CTRL-R */
1105 if (i == Ctrl_R)
1106 c = plain_vgetc(); /* CTRL-R CTRL-R <char> */
1107 --no_mapping;
1108 #ifdef FEAT_EVAL
1110 * Insert the result of an expression.
1111 * Need to save the current command line, to be able to enter
1112 * a new one...
1114 new_cmdpos = -1;
1115 if (c == '=')
1117 if (ccline.cmdfirstc == '=')/* can't do this recursively */
1119 beep_flush();
1120 c = ESC;
1122 else
1124 save_cmdline(&save_ccline);
1125 c = get_expr_register();
1126 restore_cmdline(&save_ccline);
1129 #endif
1130 if (c != ESC) /* use ESC to cancel inserting register */
1132 cmdline_paste(c, i == Ctrl_R, FALSE);
1134 #ifdef FEAT_EVAL
1135 /* When there was a serious error abort getting the
1136 * command line. */
1137 if (aborting())
1139 gotesc = TRUE; /* will free ccline.cmdbuff after
1140 putting it in history */
1141 goto returncmd; /* back to cmd mode */
1143 #endif
1144 KeyTyped = FALSE; /* Don't do p_wc completion. */
1145 #ifdef FEAT_EVAL
1146 if (new_cmdpos >= 0)
1148 /* set_cmdline_pos() was used */
1149 if (new_cmdpos > ccline.cmdlen)
1150 ccline.cmdpos = ccline.cmdlen;
1151 else
1152 ccline.cmdpos = new_cmdpos;
1154 #endif
1156 redrawcmd();
1157 goto cmdline_changed;
1159 case Ctrl_D:
1160 if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
1161 break; /* Use ^D as normal char instead */
1163 redrawcmd();
1164 continue; /* don't do incremental search now */
1166 case K_RIGHT:
1167 case K_S_RIGHT:
1168 case K_C_RIGHT:
1171 if (ccline.cmdpos >= ccline.cmdlen)
1172 break;
1173 i = cmdline_charsize(ccline.cmdpos);
1174 if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
1175 break;
1176 ccline.cmdspos += i;
1177 #ifdef FEAT_MBYTE
1178 if (has_mbyte)
1179 ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
1180 + ccline.cmdpos);
1181 else
1182 #endif
1183 ++ccline.cmdpos;
1185 while ((c == K_S_RIGHT || c == K_C_RIGHT
1186 || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
1187 && ccline.cmdbuff[ccline.cmdpos] != ' ');
1188 #ifdef FEAT_MBYTE
1189 if (has_mbyte)
1190 set_cmdspos_cursor();
1191 #endif
1192 goto cmdline_not_changed;
1194 case K_LEFT:
1195 case K_S_LEFT:
1196 case K_C_LEFT:
1197 if (ccline.cmdpos == 0)
1198 goto cmdline_not_changed;
1201 --ccline.cmdpos;
1202 #ifdef FEAT_MBYTE
1203 if (has_mbyte) /* move to first byte of char */
1204 ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
1205 ccline.cmdbuff + ccline.cmdpos);
1206 #endif
1207 ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
1209 while (ccline.cmdpos > 0
1210 && (c == K_S_LEFT || c == K_C_LEFT
1211 || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
1212 && ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
1213 #ifdef FEAT_MBYTE
1214 if (has_mbyte)
1215 set_cmdspos_cursor();
1216 #endif
1217 goto cmdline_not_changed;
1219 case K_IGNORE:
1220 /* Ignore mouse event or ex_window() result. */
1221 goto cmdline_not_changed;
1223 #ifdef FEAT_GUI_W32
1224 /* On Win32 ignore <M-F4>, we get it when closing the window was
1225 * cancelled. */
1226 case K_F4:
1227 if (mod_mask == MOD_MASK_ALT)
1229 redrawcmd(); /* somehow the cmdline is cleared */
1230 goto cmdline_not_changed;
1232 break;
1233 #endif
1235 #ifdef FEAT_MOUSE
1236 case K_MIDDLEDRAG:
1237 case K_MIDDLERELEASE:
1238 goto cmdline_not_changed; /* Ignore mouse */
1240 case K_MIDDLEMOUSE:
1241 # ifdef FEAT_GUI
1242 /* When GUI is active, also paste when 'mouse' is empty */
1243 if (!gui.in_use)
1244 # endif
1245 if (!mouse_has(MOUSE_COMMAND))
1246 goto cmdline_not_changed; /* Ignore mouse */
1247 # ifdef FEAT_CLIPBOARD
1248 if (clip_star.available)
1249 cmdline_paste('*', TRUE, TRUE);
1250 else
1251 # endif
1252 cmdline_paste(0, TRUE, TRUE);
1253 redrawcmd();
1254 goto cmdline_changed;
1256 # ifdef FEAT_DND
1257 case K_DROP:
1258 cmdline_paste('~', TRUE, FALSE);
1259 redrawcmd();
1260 goto cmdline_changed;
1261 # endif
1263 case K_LEFTDRAG:
1264 case K_LEFTRELEASE:
1265 case K_RIGHTDRAG:
1266 case K_RIGHTRELEASE:
1267 /* Ignore drag and release events when the button-down wasn't
1268 * seen before. */
1269 if (ignore_drag_release)
1270 goto cmdline_not_changed;
1271 /* FALLTHROUGH */
1272 case K_LEFTMOUSE:
1273 case K_RIGHTMOUSE:
1274 if (c == K_LEFTRELEASE || c == K_RIGHTRELEASE)
1275 ignore_drag_release = TRUE;
1276 else
1277 ignore_drag_release = FALSE;
1278 # ifdef FEAT_GUI
1279 /* When GUI is active, also move when 'mouse' is empty */
1280 if (!gui.in_use)
1281 # endif
1282 if (!mouse_has(MOUSE_COMMAND))
1283 goto cmdline_not_changed; /* Ignore mouse */
1284 # ifdef FEAT_CLIPBOARD
1285 if (mouse_row < cmdline_row && clip_star.available)
1287 int button, is_click, is_drag;
1290 * Handle modeless selection.
1292 button = get_mouse_button(KEY2TERMCAP1(c),
1293 &is_click, &is_drag);
1294 if (mouse_model_popup() && button == MOUSE_LEFT
1295 && (mod_mask & MOD_MASK_SHIFT))
1297 /* Translate shift-left to right button. */
1298 button = MOUSE_RIGHT;
1299 mod_mask &= ~MOD_MASK_SHIFT;
1301 clip_modeless(button, is_click, is_drag);
1302 goto cmdline_not_changed;
1304 # endif
1306 set_cmdspos();
1307 for (ccline.cmdpos = 0; ccline.cmdpos < ccline.cmdlen;
1308 ++ccline.cmdpos)
1310 i = cmdline_charsize(ccline.cmdpos);
1311 if (mouse_row <= cmdline_row + ccline.cmdspos / Columns
1312 && mouse_col < ccline.cmdspos % Columns + i)
1313 break;
1314 # ifdef FEAT_MBYTE
1315 if (has_mbyte)
1317 /* Count ">" for double-wide char that doesn't fit. */
1318 correct_cmdspos(ccline.cmdpos, i);
1319 ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
1320 + ccline.cmdpos) - 1;
1322 # endif
1323 ccline.cmdspos += i;
1325 goto cmdline_not_changed;
1327 /* Mouse scroll wheel: ignored here */
1328 case K_MOUSEDOWN:
1329 case K_MOUSEUP:
1330 /* Alternate buttons ignored here */
1331 case K_X1MOUSE:
1332 case K_X1DRAG:
1333 case K_X1RELEASE:
1334 case K_X2MOUSE:
1335 case K_X2DRAG:
1336 case K_X2RELEASE:
1337 goto cmdline_not_changed;
1339 #endif /* FEAT_MOUSE */
1341 #ifdef FEAT_GUI
1342 case K_LEFTMOUSE_NM: /* mousefocus click, ignored */
1343 case K_LEFTRELEASE_NM:
1344 goto cmdline_not_changed;
1346 case K_VER_SCROLLBAR:
1347 if (msg_scrolled == 0)
1349 gui_do_scroll();
1350 redrawcmd();
1352 goto cmdline_not_changed;
1354 case K_HOR_SCROLLBAR:
1355 if (msg_scrolled == 0)
1357 gui_do_horiz_scroll();
1358 redrawcmd();
1360 goto cmdline_not_changed;
1361 #endif
1362 #ifdef FEAT_GUI_TABLINE
1363 case K_TABLINE:
1364 case K_TABMENU:
1365 /* Don't want to change any tabs here. Make sure the same tab
1366 * is still selected. */
1367 if (gui_use_tabline())
1368 gui_mch_set_curtab(tabpage_index(curtab));
1369 goto cmdline_not_changed;
1370 #endif
1372 case K_SELECT: /* end of Select mode mapping - ignore */
1373 goto cmdline_not_changed;
1375 case Ctrl_B: /* begin of command line */
1376 case K_HOME:
1377 case K_KHOME:
1378 case K_S_HOME:
1379 case K_C_HOME:
1380 ccline.cmdpos = 0;
1381 set_cmdspos();
1382 goto cmdline_not_changed;
1384 case Ctrl_E: /* end of command line */
1385 case K_END:
1386 case K_KEND:
1387 case K_S_END:
1388 case K_C_END:
1389 ccline.cmdpos = ccline.cmdlen;
1390 set_cmdspos_cursor();
1391 goto cmdline_not_changed;
1393 case Ctrl_A: /* all matches */
1394 if (nextwild(&xpc, WILD_ALL, 0) == FAIL)
1395 break;
1396 goto cmdline_changed;
1398 case Ctrl_L:
1399 #ifdef FEAT_SEARCH_EXTRA
1400 if (p_is && !cmd_silent && (firstc == '/' || firstc == '?'))
1402 /* Add a character from under the cursor for 'incsearch' */
1403 if (did_incsearch
1404 && !equalpos(curwin->w_cursor, old_cursor))
1406 c = gchar_cursor();
1407 if (c != NUL)
1409 if (c == firstc || vim_strchr((char_u *)(
1410 p_magic ? "\\^$.*[" : "\\^$"), c)
1411 != NULL)
1413 /* put a backslash before special characters */
1414 stuffcharReadbuff(c);
1415 c = '\\';
1417 break;
1420 goto cmdline_not_changed;
1422 #endif
1424 /* completion: longest common part */
1425 if (nextwild(&xpc, WILD_LONGEST, 0) == FAIL)
1426 break;
1427 goto cmdline_changed;
1429 case Ctrl_N: /* next match */
1430 case Ctrl_P: /* previous match */
1431 if (xpc.xp_numfiles > 0)
1433 if (nextwild(&xpc, (c == Ctrl_P) ? WILD_PREV : WILD_NEXT, 0)
1434 == FAIL)
1435 break;
1436 goto cmdline_changed;
1439 #ifdef FEAT_CMDHIST
1440 case K_UP:
1441 case K_DOWN:
1442 case K_S_UP:
1443 case K_S_DOWN:
1444 case K_PAGEUP:
1445 case K_KPAGEUP:
1446 case K_PAGEDOWN:
1447 case K_KPAGEDOWN:
1448 if (hislen == 0 || firstc == NUL) /* no history */
1449 goto cmdline_not_changed;
1451 i = hiscnt;
1453 /* save current command string so it can be restored later */
1454 if (lookfor == NULL)
1456 if ((lookfor = vim_strsave(ccline.cmdbuff)) == NULL)
1457 goto cmdline_not_changed;
1458 lookfor[ccline.cmdpos] = NUL;
1461 j = (int)STRLEN(lookfor);
1462 for (;;)
1464 /* one step backwards */
1465 if (c == K_UP|| c == K_S_UP || c == Ctrl_P
1466 || c == K_PAGEUP || c == K_KPAGEUP)
1468 if (hiscnt == hislen) /* first time */
1469 hiscnt = hisidx[histype];
1470 else if (hiscnt == 0 && hisidx[histype] != hislen - 1)
1471 hiscnt = hislen - 1;
1472 else if (hiscnt != hisidx[histype] + 1)
1473 --hiscnt;
1474 else /* at top of list */
1476 hiscnt = i;
1477 break;
1480 else /* one step forwards */
1482 /* on last entry, clear the line */
1483 if (hiscnt == hisidx[histype])
1485 hiscnt = hislen;
1486 break;
1489 /* not on a history line, nothing to do */
1490 if (hiscnt == hislen)
1491 break;
1492 if (hiscnt == hislen - 1) /* wrap around */
1493 hiscnt = 0;
1494 else
1495 ++hiscnt;
1497 if (hiscnt < 0 || history[histype][hiscnt].hisstr == NULL)
1499 hiscnt = i;
1500 break;
1502 if ((c != K_UP && c != K_DOWN)
1503 || hiscnt == i
1504 || STRNCMP(history[histype][hiscnt].hisstr,
1505 lookfor, (size_t)j) == 0)
1506 break;
1509 if (hiscnt != i) /* jumped to other entry */
1511 char_u *p;
1512 int len;
1513 int old_firstc;
1515 vim_free(ccline.cmdbuff);
1516 if (hiscnt == hislen)
1517 p = lookfor; /* back to the old one */
1518 else
1519 p = history[histype][hiscnt].hisstr;
1521 if (histype == HIST_SEARCH
1522 && p != lookfor
1523 && (old_firstc = p[STRLEN(p) + 1]) != firstc)
1525 /* Correct for the separator character used when
1526 * adding the history entry vs the one used now.
1527 * First loop: count length.
1528 * Second loop: copy the characters. */
1529 for (i = 0; i <= 1; ++i)
1531 len = 0;
1532 for (j = 0; p[j] != NUL; ++j)
1534 /* Replace old sep with new sep, unless it is
1535 * escaped. */
1536 if (p[j] == old_firstc
1537 && (j == 0 || p[j - 1] != '\\'))
1539 if (i > 0)
1540 ccline.cmdbuff[len] = firstc;
1542 else
1544 /* Escape new sep, unless it is already
1545 * escaped. */
1546 if (p[j] == firstc
1547 && (j == 0 || p[j - 1] != '\\'))
1549 if (i > 0)
1550 ccline.cmdbuff[len] = '\\';
1551 ++len;
1553 if (i > 0)
1554 ccline.cmdbuff[len] = p[j];
1556 ++len;
1558 if (i == 0)
1560 alloc_cmdbuff(len);
1561 if (ccline.cmdbuff == NULL)
1562 goto returncmd;
1565 ccline.cmdbuff[len] = NUL;
1567 else
1569 alloc_cmdbuff((int)STRLEN(p));
1570 if (ccline.cmdbuff == NULL)
1571 goto returncmd;
1572 STRCPY(ccline.cmdbuff, p);
1575 ccline.cmdpos = ccline.cmdlen = (int)STRLEN(ccline.cmdbuff);
1576 redrawcmd();
1577 goto cmdline_changed;
1579 beep_flush();
1580 goto cmdline_not_changed;
1581 #endif
1583 case Ctrl_V:
1584 case Ctrl_Q:
1585 #ifdef FEAT_MOUSE
1586 ignore_drag_release = TRUE;
1587 #endif
1588 putcmdline('^', TRUE);
1589 c = get_literal(); /* get next (two) character(s) */
1590 do_abbr = FALSE; /* don't do abbreviation now */
1591 #ifdef FEAT_MBYTE
1592 /* may need to remove ^ when composing char was typed */
1593 if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
1595 draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
1596 msg_putchar(' ');
1597 cursorcmd();
1599 #endif
1600 break;
1602 #ifdef FEAT_DIGRAPHS
1603 case Ctrl_K:
1604 #ifdef FEAT_MOUSE
1605 ignore_drag_release = TRUE;
1606 #endif
1607 putcmdline('?', TRUE);
1608 #ifdef USE_ON_FLY_SCROLL
1609 dont_scroll = TRUE; /* disallow scrolling here */
1610 #endif
1611 c = get_digraph(TRUE);
1612 if (c != NUL)
1613 break;
1615 redrawcmd();
1616 goto cmdline_not_changed;
1617 #endif /* FEAT_DIGRAPHS */
1619 #ifdef FEAT_RIGHTLEFT
1620 case Ctrl__: /* CTRL-_: switch language mode */
1621 if (!p_ari)
1622 break;
1623 #ifdef FEAT_FKMAP
1624 if (p_altkeymap)
1626 cmd_fkmap = !cmd_fkmap;
1627 if (cmd_fkmap) /* in Farsi always in Insert mode */
1628 ccline.overstrike = FALSE;
1630 else /* Hebrew is default */
1631 #endif
1632 cmd_hkmap = !cmd_hkmap;
1633 goto cmdline_not_changed;
1634 #endif
1636 default:
1637 #ifdef UNIX
1638 if (c == intr_char)
1640 gotesc = TRUE; /* will free ccline.cmdbuff after
1641 putting it in history */
1642 goto returncmd; /* back to Normal mode */
1644 #endif
1646 * Normal character with no special meaning. Just set mod_mask
1647 * to 0x0 so that typing Shift-Space in the GUI doesn't enter
1648 * the string <S-Space>. This should only happen after ^V.
1650 if (!IS_SPECIAL(c))
1651 mod_mask = 0x0;
1652 break;
1655 * End of switch on command line character.
1656 * We come here if we have a normal character.
1659 if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c)) && ccheck_abbr(
1660 #ifdef FEAT_MBYTE
1661 /* Add ABBR_OFF for characters above 0x100, this is
1662 * what check_abbr() expects. */
1663 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1664 #endif
1666 goto cmdline_changed;
1669 * put the character in the command line
1671 if (IS_SPECIAL(c) || mod_mask != 0)
1672 put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
1673 else
1675 #ifdef FEAT_MBYTE
1676 if (has_mbyte)
1678 j = (*mb_char2bytes)(c, IObuff);
1679 IObuff[j] = NUL; /* exclude composing chars */
1680 put_on_cmdline(IObuff, j, TRUE);
1682 else
1683 #endif
1685 IObuff[0] = c;
1686 put_on_cmdline(IObuff, 1, TRUE);
1689 goto cmdline_changed;
1692 * This part implements incremental searches for "/" and "?"
1693 * Jump to cmdline_not_changed when a character has been read but the command
1694 * line did not change. Then we only search and redraw if something changed in
1695 * the past.
1696 * Jump to cmdline_changed when the command line did change.
1697 * (Sorry for the goto's, I know it is ugly).
1699 cmdline_not_changed:
1700 #ifdef FEAT_SEARCH_EXTRA
1701 if (!incsearch_postponed)
1702 continue;
1703 #endif
1705 cmdline_changed:
1706 #ifdef FEAT_SEARCH_EXTRA
1708 * 'incsearch' highlighting.
1710 if (p_is && !cmd_silent && (firstc == '/' || firstc == '?'))
1712 pos_T end_pos;
1713 #ifdef FEAT_RELTIME
1714 proftime_T tm;
1715 #endif
1717 /* if there is a character waiting, search and redraw later */
1718 if (char_avail())
1720 incsearch_postponed = TRUE;
1721 continue;
1723 incsearch_postponed = FALSE;
1724 curwin->w_cursor = old_cursor; /* start at old position */
1726 /* If there is no command line, don't do anything */
1727 if (ccline.cmdlen == 0)
1728 i = 0;
1729 else
1731 cursor_off(); /* so the user knows we're busy */
1732 out_flush();
1733 ++emsg_off; /* So it doesn't beep if bad expr */
1734 #ifdef FEAT_RELTIME
1735 /* Set the time limit to half a second. */
1736 profile_setlimit(500L, &tm);
1737 #endif
1738 i = do_search(NULL, firstc, ccline.cmdbuff, count,
1739 SEARCH_KEEP + SEARCH_OPT + SEARCH_NOOF + SEARCH_PEEK,
1740 #ifdef FEAT_RELTIME
1742 #else
1743 NULL
1744 #endif
1746 --emsg_off;
1747 /* if interrupted while searching, behave like it failed */
1748 if (got_int)
1750 (void)vpeekc(); /* remove <C-C> from input stream */
1751 got_int = FALSE; /* don't abandon the command line */
1752 i = 0;
1754 else if (char_avail())
1755 /* cancelled searching because a char was typed */
1756 incsearch_postponed = TRUE;
1758 if (i != 0)
1759 highlight_match = TRUE; /* highlight position */
1760 else
1761 highlight_match = FALSE; /* remove highlight */
1763 /* first restore the old curwin values, so the screen is
1764 * positioned in the same way as the actual search command */
1765 curwin->w_leftcol = old_leftcol;
1766 curwin->w_topline = old_topline;
1767 # ifdef FEAT_DIFF
1768 curwin->w_topfill = old_topfill;
1769 # endif
1770 curwin->w_botline = old_botline;
1771 changed_cline_bef_curs();
1772 update_topline();
1774 if (i != 0)
1776 pos_T save_pos = curwin->w_cursor;
1779 * First move cursor to end of match, then to the start. This
1780 * moves the whole match onto the screen when 'nowrap' is set.
1782 curwin->w_cursor.lnum += search_match_lines;
1783 curwin->w_cursor.col = search_match_endcol;
1784 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
1786 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
1787 coladvance((colnr_T)MAXCOL);
1789 validate_cursor();
1790 end_pos = curwin->w_cursor;
1791 curwin->w_cursor = save_pos;
1793 else
1794 end_pos = curwin->w_cursor; /* shutup gcc 4 */
1796 validate_cursor();
1797 # ifdef FEAT_WINDOWS
1798 /* May redraw the status line to show the cursor position. */
1799 if (p_ru && curwin->w_status_height > 0)
1800 curwin->w_redr_status = TRUE;
1801 # endif
1803 save_cmdline(&save_ccline);
1804 update_screen(SOME_VALID);
1805 restore_cmdline(&save_ccline);
1807 /* Leave it at the end to make CTRL-R CTRL-W work. */
1808 if (i != 0)
1809 curwin->w_cursor = end_pos;
1811 msg_starthere();
1812 redrawcmdline();
1813 did_incsearch = TRUE;
1815 #else /* FEAT_SEARCH_EXTRA */
1817 #endif
1819 #ifdef FEAT_RIGHTLEFT
1820 if (cmdmsg_rl
1821 # ifdef FEAT_ARABIC
1822 || (p_arshape && !p_tbidi && enc_utf8)
1823 # endif
1825 /* Always redraw the whole command line to fix shaping and
1826 * right-left typing. Not efficient, but it works. */
1827 redrawcmd();
1828 #endif
1831 returncmd:
1833 #ifdef FEAT_RIGHTLEFT
1834 cmdmsg_rl = FALSE;
1835 #endif
1837 #ifdef FEAT_FKMAP
1838 cmd_fkmap = 0;
1839 #endif
1841 ExpandCleanup(&xpc);
1843 #ifdef FEAT_SEARCH_EXTRA
1844 if (did_incsearch)
1846 curwin->w_cursor = old_cursor;
1847 curwin->w_curswant = old_curswant;
1848 curwin->w_leftcol = old_leftcol;
1849 curwin->w_topline = old_topline;
1850 # ifdef FEAT_DIFF
1851 curwin->w_topfill = old_topfill;
1852 # endif
1853 curwin->w_botline = old_botline;
1854 highlight_match = FALSE;
1855 validate_cursor(); /* needed for TAB */
1856 redraw_later(SOME_VALID);
1858 #endif
1860 if (ccline.cmdbuff != NULL)
1863 * Put line in history buffer (":" and "=" only when it was typed).
1865 #ifdef FEAT_CMDHIST
1866 if (ccline.cmdlen && firstc != NUL
1867 && (some_key_typed || histype == HIST_SEARCH))
1869 add_to_history(histype, ccline.cmdbuff, TRUE,
1870 histype == HIST_SEARCH ? firstc : NUL);
1871 if (firstc == ':')
1873 vim_free(new_last_cmdline);
1874 new_last_cmdline = vim_strsave(ccline.cmdbuff);
1877 #endif
1879 if (gotesc) /* abandon command line */
1881 vim_free(ccline.cmdbuff);
1882 ccline.cmdbuff = NULL;
1883 if (msg_scrolled == 0)
1884 compute_cmdrow();
1885 MSG("");
1886 redraw_cmdline = TRUE;
1891 * If the screen was shifted up, redraw the whole screen (later).
1892 * If the line is too long, clear it, so ruler and shown command do
1893 * not get printed in the middle of it.
1895 msg_check();
1896 msg_scroll = save_msg_scroll;
1897 redir_off = FALSE;
1899 /* When the command line was typed, no need for a wait-return prompt. */
1900 if (some_key_typed)
1901 need_wait_return = FALSE;
1903 State = save_State;
1904 #ifdef USE_IM_CONTROL
1905 if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)
1906 im_save_status(b_im_ptr);
1907 im_set_active(FALSE);
1908 #endif
1909 #ifdef FEAT_MOUSE
1910 setmouse();
1911 #endif
1912 #ifdef CURSOR_SHAPE
1913 ui_cursor_shape(); /* may show different cursor shape */
1914 #endif
1917 char_u *p = ccline.cmdbuff;
1919 /* Make ccline empty, getcmdline() may try to use it. */
1920 ccline.cmdbuff = NULL;
1921 return p;
1925 #if (defined(FEAT_CRYPT) || defined(FEAT_EVAL)) || defined(PROTO)
1927 * Get a command line with a prompt.
1928 * This is prepared to be called recursively from getcmdline() (e.g. by
1929 * f_input() when evaluating an expression from CTRL-R =).
1930 * Returns the command line in allocated memory, or NULL.
1932 char_u *
1933 getcmdline_prompt(firstc, prompt, attr, xp_context, xp_arg)
1934 int firstc;
1935 char_u *prompt; /* command line prompt */
1936 int attr; /* attributes for prompt */
1937 int xp_context; /* type of expansion */
1938 char_u *xp_arg; /* user-defined expansion argument */
1940 char_u *s;
1941 struct cmdline_info save_ccline;
1942 int msg_col_save = msg_col;
1944 save_cmdline(&save_ccline);
1945 ccline.cmdprompt = prompt;
1946 ccline.cmdattr = attr;
1947 # ifdef FEAT_EVAL
1948 ccline.xp_context = xp_context;
1949 ccline.xp_arg = xp_arg;
1950 ccline.input_fn = (firstc == '@');
1951 # endif
1952 s = getcmdline(firstc, 1L, 0);
1953 restore_cmdline(&save_ccline);
1954 /* Restore msg_col, the prompt from input() may have changed it. */
1955 msg_col = msg_col_save;
1957 return s;
1959 #endif
1962 * Return TRUE when the text must not be changed and we can't switch to
1963 * another window or buffer. Used when editing the command line, evaluating
1964 * 'balloonexpr', etc.
1967 text_locked()
1969 #ifdef FEAT_CMDWIN
1970 if (cmdwin_type != 0)
1971 return TRUE;
1972 #endif
1973 return textlock != 0;
1977 * Give an error message for a command that isn't allowed while the cmdline
1978 * window is open or editing the cmdline in another way.
1980 void
1981 text_locked_msg()
1983 #ifdef FEAT_CMDWIN
1984 if (cmdwin_type != 0)
1985 EMSG(_(e_cmdwin));
1986 else
1987 #endif
1988 EMSG(_(e_secure));
1991 #if defined(FEAT_AUTOCMD) || defined(PROTO)
1993 * Check if "curbuf_lock" is set and return TRUE when it is and give an error
1994 * message.
1997 curbuf_locked()
1999 if (curbuf_lock > 0)
2001 EMSG(_("E788: Not allowed to edit another buffer now"));
2002 return TRUE;
2004 return FALSE;
2006 #endif
2008 static int
2009 cmdline_charsize(idx)
2010 int idx;
2012 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
2013 if (cmdline_star > 0) /* showing '*', always 1 position */
2014 return 1;
2015 #endif
2016 return ptr2cells(ccline.cmdbuff + idx);
2020 * Compute the offset of the cursor on the command line for the prompt and
2021 * indent.
2023 static void
2024 set_cmdspos()
2026 if (ccline.cmdfirstc != NUL)
2027 ccline.cmdspos = 1 + ccline.cmdindent;
2028 else
2029 ccline.cmdspos = 0 + ccline.cmdindent;
2033 * Compute the screen position for the cursor on the command line.
2035 static void
2036 set_cmdspos_cursor()
2038 int i, m, c;
2040 set_cmdspos();
2041 if (KeyTyped)
2043 m = Columns * Rows;
2044 if (m < 0) /* overflow, Columns or Rows at weird value */
2045 m = MAXCOL;
2047 else
2048 m = MAXCOL;
2049 for (i = 0; i < ccline.cmdlen && i < ccline.cmdpos; ++i)
2051 c = cmdline_charsize(i);
2052 #ifdef FEAT_MBYTE
2053 /* Count ">" for double-wide multi-byte char that doesn't fit. */
2054 if (has_mbyte)
2055 correct_cmdspos(i, c);
2056 #endif
2057 /* If the cmdline doesn't fit, show cursor on last visible char.
2058 * Don't move the cursor itself, so we can still append. */
2059 if ((ccline.cmdspos += c) >= m)
2061 ccline.cmdspos -= c;
2062 break;
2064 #ifdef FEAT_MBYTE
2065 if (has_mbyte)
2066 i += (*mb_ptr2len)(ccline.cmdbuff + i) - 1;
2067 #endif
2071 #ifdef FEAT_MBYTE
2073 * Check if the character at "idx", which is "cells" wide, is a multi-byte
2074 * character that doesn't fit, so that a ">" must be displayed.
2076 static void
2077 correct_cmdspos(idx, cells)
2078 int idx;
2079 int cells;
2081 if ((*mb_ptr2len)(ccline.cmdbuff + idx) > 1
2082 && (*mb_ptr2cells)(ccline.cmdbuff + idx) > 1
2083 && ccline.cmdspos % Columns + cells > Columns)
2084 ccline.cmdspos++;
2086 #endif
2089 * Get an Ex command line for the ":" command.
2091 /* ARGSUSED */
2092 char_u *
2093 getexline(c, dummy, indent)
2094 int c; /* normally ':', NUL for ":append" */
2095 void *dummy; /* cookie not used */
2096 int indent; /* indent for inside conditionals */
2098 /* When executing a register, remove ':' that's in front of each line. */
2099 if (exec_from_reg && vpeekc() == ':')
2100 (void)vgetc();
2101 return getcmdline(c, 1L, indent);
2105 * Get an Ex command line for Ex mode.
2106 * In Ex mode we only use the OS supplied line editing features and no
2107 * mappings or abbreviations.
2108 * Returns a string in allocated memory or NULL.
2110 /* ARGSUSED */
2111 char_u *
2112 getexmodeline(promptc, dummy, indent)
2113 int promptc; /* normally ':', NUL for ":append" and '?' for
2114 :s prompt */
2115 void *dummy; /* cookie not used */
2116 int indent; /* indent for inside conditionals */
2118 garray_T line_ga;
2119 char_u *pend;
2120 int startcol = 0;
2121 int c1 = 0;
2122 int escaped = FALSE; /* CTRL-V typed */
2123 int vcol = 0;
2124 char_u *p;
2125 int prev_char;
2127 /* Switch cursor on now. This avoids that it happens after the "\n", which
2128 * confuses the system function that computes tabstops. */
2129 cursor_on();
2131 /* always start in column 0; write a newline if necessary */
2132 compute_cmdrow();
2133 if ((msg_col || msg_didout) && promptc != '?')
2134 msg_putchar('\n');
2135 if (promptc == ':')
2137 /* indent that is only displayed, not in the line itself */
2138 if (p_prompt)
2139 msg_putchar(':');
2140 while (indent-- > 0)
2141 msg_putchar(' ');
2142 startcol = msg_col;
2145 ga_init2(&line_ga, 1, 30);
2147 /* autoindent for :insert and :append is in the line itself */
2148 if (promptc <= 0)
2150 vcol = indent;
2151 while (indent >= 8)
2153 ga_append(&line_ga, TAB);
2154 msg_puts((char_u *)" ");
2155 indent -= 8;
2157 while (indent-- > 0)
2159 ga_append(&line_ga, ' ');
2160 msg_putchar(' ');
2163 ++no_mapping;
2164 ++allow_keys;
2167 * Get the line, one character at a time.
2169 got_int = FALSE;
2170 while (!got_int)
2172 if (ga_grow(&line_ga, 40) == FAIL)
2173 break;
2174 pend = (char_u *)line_ga.ga_data + line_ga.ga_len;
2176 /* Get one character at a time. Don't use inchar(), it can't handle
2177 * special characters. */
2178 prev_char = c1;
2179 c1 = vgetc();
2182 * Handle line editing.
2183 * Previously this was left to the system, putting the terminal in
2184 * cooked mode, but then CTRL-D and CTRL-T can't be used properly.
2186 if (got_int)
2188 msg_putchar('\n');
2189 break;
2192 if (!escaped)
2194 /* CR typed means "enter", which is NL */
2195 if (c1 == '\r')
2196 c1 = '\n';
2198 if (c1 == BS || c1 == K_BS
2199 || c1 == DEL || c1 == K_DEL || c1 == K_KDEL)
2201 if (line_ga.ga_len > 0)
2203 --line_ga.ga_len;
2204 goto redraw;
2206 continue;
2209 if (c1 == Ctrl_U)
2211 msg_col = startcol;
2212 msg_clr_eos();
2213 line_ga.ga_len = 0;
2214 continue;
2217 if (c1 == Ctrl_T)
2219 p = (char_u *)line_ga.ga_data;
2220 p[line_ga.ga_len] = NUL;
2221 indent = get_indent_str(p, 8);
2222 indent += curbuf->b_p_sw - indent % curbuf->b_p_sw;
2223 add_indent:
2224 while (get_indent_str(p, 8) < indent)
2226 char_u *s = skipwhite(p);
2228 ga_grow(&line_ga, 1);
2229 mch_memmove(s + 1, s, line_ga.ga_len - (s - p) + 1);
2230 *s = ' ';
2231 ++line_ga.ga_len;
2233 redraw:
2234 /* redraw the line */
2235 msg_col = startcol;
2236 vcol = 0;
2237 for (p = (char_u *)line_ga.ga_data;
2238 p < (char_u *)line_ga.ga_data + line_ga.ga_len; ++p)
2240 if (*p == TAB)
2244 msg_putchar(' ');
2245 } while (++vcol % 8);
2247 else
2249 msg_outtrans_len(p, 1);
2250 vcol += char2cells(*p);
2253 msg_clr_eos();
2254 windgoto(msg_row, msg_col);
2255 continue;
2258 if (c1 == Ctrl_D)
2260 /* Delete one shiftwidth. */
2261 p = (char_u *)line_ga.ga_data;
2262 if (prev_char == '0' || prev_char == '^')
2264 if (prev_char == '^')
2265 ex_keep_indent = TRUE;
2266 indent = 0;
2267 p[--line_ga.ga_len] = NUL;
2269 else
2271 p[line_ga.ga_len] = NUL;
2272 indent = get_indent_str(p, 8);
2273 --indent;
2274 indent -= indent % curbuf->b_p_sw;
2276 while (get_indent_str(p, 8) > indent)
2278 char_u *s = skipwhite(p);
2280 mch_memmove(s - 1, s, line_ga.ga_len - (s - p) + 1);
2281 --line_ga.ga_len;
2283 goto add_indent;
2286 if (c1 == Ctrl_V || c1 == Ctrl_Q)
2288 escaped = TRUE;
2289 continue;
2292 /* Ignore special key codes: mouse movement, K_IGNORE, etc. */
2293 if (IS_SPECIAL(c1))
2294 continue;
2297 if (IS_SPECIAL(c1))
2298 c1 = '?';
2299 ((char_u *)line_ga.ga_data)[line_ga.ga_len] = c1;
2300 if (c1 == '\n')
2301 msg_putchar('\n');
2302 else if (c1 == TAB)
2304 /* Don't use chartabsize(), 'ts' can be different */
2307 msg_putchar(' ');
2308 } while (++vcol % 8);
2310 else
2312 msg_outtrans_len(
2313 ((char_u *)line_ga.ga_data) + line_ga.ga_len, 1);
2314 vcol += char2cells(c1);
2316 ++line_ga.ga_len;
2317 escaped = FALSE;
2319 windgoto(msg_row, msg_col);
2320 pend = (char_u *)(line_ga.ga_data) + line_ga.ga_len;
2322 /* we are done when a NL is entered, but not when it comes after a
2323 * backslash */
2324 if (line_ga.ga_len > 0 && pend[-1] == '\n'
2325 && (line_ga.ga_len <= 1 || pend[-2] != '\\'))
2327 --line_ga.ga_len;
2328 --pend;
2329 *pend = NUL;
2330 break;
2334 --no_mapping;
2335 --allow_keys;
2337 /* make following messages go to the next line */
2338 msg_didout = FALSE;
2339 msg_col = 0;
2340 if (msg_row < Rows - 1)
2341 ++msg_row;
2342 emsg_on_display = FALSE; /* don't want ui_delay() */
2344 if (got_int)
2345 ga_clear(&line_ga);
2347 return (char_u *)line_ga.ga_data;
2350 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
2351 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
2353 * Return TRUE if ccline.overstrike is on.
2356 cmdline_overstrike()
2358 return ccline.overstrike;
2362 * Return TRUE if the cursor is at the end of the cmdline.
2365 cmdline_at_end()
2367 return (ccline.cmdpos >= ccline.cmdlen);
2369 #endif
2371 #if (defined(FEAT_XIM) && (defined(FEAT_GUI_GTK))) || defined(PROTO)
2373 * Return the virtual column number at the current cursor position.
2374 * This is used by the IM code to obtain the start of the preedit string.
2376 colnr_T
2377 cmdline_getvcol_cursor()
2379 if (ccline.cmdbuff == NULL || ccline.cmdpos > ccline.cmdlen)
2380 return MAXCOL;
2382 # ifdef FEAT_MBYTE
2383 if (has_mbyte)
2385 colnr_T col;
2386 int i = 0;
2388 for (col = 0; i < ccline.cmdpos; ++col)
2389 i += (*mb_ptr2len)(ccline.cmdbuff + i);
2391 return col;
2393 else
2394 # endif
2395 return ccline.cmdpos;
2397 #endif
2399 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2401 * If part of the command line is an IM preedit string, redraw it with
2402 * IM feedback attributes. The cursor position is restored after drawing.
2404 static void
2405 redrawcmd_preedit()
2407 if ((State & CMDLINE)
2408 && xic != NULL
2409 /* && im_get_status() doesn't work when using SCIM */
2410 && !p_imdisable
2411 && im_is_preediting())
2413 int cmdpos = 0;
2414 int cmdspos;
2415 int old_row;
2416 int old_col;
2417 colnr_T col;
2419 old_row = msg_row;
2420 old_col = msg_col;
2421 cmdspos = ((ccline.cmdfirstc != NUL) ? 1 : 0) + ccline.cmdindent;
2423 # ifdef FEAT_MBYTE
2424 if (has_mbyte)
2426 for (col = 0; col < preedit_start_col
2427 && cmdpos < ccline.cmdlen; ++col)
2429 cmdspos += (*mb_ptr2cells)(ccline.cmdbuff + cmdpos);
2430 cmdpos += (*mb_ptr2len)(ccline.cmdbuff + cmdpos);
2433 else
2434 # endif
2436 cmdspos += preedit_start_col;
2437 cmdpos += preedit_start_col;
2440 msg_row = cmdline_row + (cmdspos / (int)Columns);
2441 msg_col = cmdspos % (int)Columns;
2442 if (msg_row >= Rows)
2443 msg_row = Rows - 1;
2445 for (col = 0; cmdpos < ccline.cmdlen; ++col)
2447 int char_len;
2448 int char_attr;
2450 char_attr = im_get_feedback_attr(col);
2451 if (char_attr < 0)
2452 break; /* end of preedit string */
2454 # ifdef FEAT_MBYTE
2455 if (has_mbyte)
2456 char_len = (*mb_ptr2len)(ccline.cmdbuff + cmdpos);
2457 else
2458 # endif
2459 char_len = 1;
2461 msg_outtrans_len_attr(ccline.cmdbuff + cmdpos, char_len, char_attr);
2462 cmdpos += char_len;
2465 msg_row = old_row;
2466 msg_col = old_col;
2469 #endif /* FEAT_XIM && FEAT_GUI_GTK */
2472 * Allocate a new command line buffer.
2473 * Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen.
2474 * Returns the new value of ccline.cmdbuff and ccline.cmdbufflen.
2476 static void
2477 alloc_cmdbuff(len)
2478 int len;
2481 * give some extra space to avoid having to allocate all the time
2483 if (len < 80)
2484 len = 100;
2485 else
2486 len += 20;
2488 ccline.cmdbuff = alloc(len); /* caller should check for out-of-memory */
2489 ccline.cmdbufflen = len;
2493 * Re-allocate the command line to length len + something extra.
2494 * return FAIL for failure, OK otherwise
2496 static int
2497 realloc_cmdbuff(len)
2498 int len;
2500 char_u *p;
2502 p = ccline.cmdbuff;
2503 alloc_cmdbuff(len); /* will get some more */
2504 if (ccline.cmdbuff == NULL) /* out of memory */
2506 ccline.cmdbuff = p; /* keep the old one */
2507 return FAIL;
2509 mch_memmove(ccline.cmdbuff, p, (size_t)ccline.cmdlen + 1);
2510 vim_free(p);
2511 return OK;
2514 #if defined(FEAT_ARABIC) || defined(PROTO)
2515 static char_u *arshape_buf = NULL;
2517 # if defined(EXITFREE) || defined(PROTO)
2518 void
2519 free_cmdline_buf()
2521 vim_free(arshape_buf);
2523 # endif
2524 #endif
2527 * Draw part of the cmdline at the current cursor position. But draw stars
2528 * when cmdline_star is TRUE.
2530 static void
2531 draw_cmdline(start, len)
2532 int start;
2533 int len;
2535 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
2536 int i;
2538 if (cmdline_star > 0)
2539 for (i = 0; i < len; ++i)
2541 msg_putchar('*');
2542 # ifdef FEAT_MBYTE
2543 if (has_mbyte)
2544 i += (*mb_ptr2len)(ccline.cmdbuff + start + i) - 1;
2545 # endif
2547 else
2548 #endif
2549 #ifdef FEAT_ARABIC
2550 if (p_arshape && !p_tbidi && enc_utf8 && len > 0)
2552 static int buflen = 0;
2553 char_u *p;
2554 int j;
2555 int newlen = 0;
2556 int mb_l;
2557 int pc, pc1 = 0;
2558 int prev_c = 0;
2559 int prev_c1 = 0;
2560 int u8c;
2561 int u8cc[MAX_MCO];
2562 int nc = 0;
2565 * Do arabic shaping into a temporary buffer. This is very
2566 * inefficient!
2568 if (len * 2 + 2 > buflen)
2570 /* Re-allocate the buffer. We keep it around to avoid a lot of
2571 * alloc()/free() calls. */
2572 vim_free(arshape_buf);
2573 buflen = len * 2 + 2;
2574 arshape_buf = alloc(buflen);
2575 if (arshape_buf == NULL)
2576 return; /* out of memory */
2579 if (utf_iscomposing(utf_ptr2char(ccline.cmdbuff + start)))
2581 /* Prepend a space to draw the leading composing char on. */
2582 arshape_buf[0] = ' ';
2583 newlen = 1;
2586 for (j = start; j < start + len; j += mb_l)
2588 p = ccline.cmdbuff + j;
2589 u8c = utfc_ptr2char_len(p, u8cc, start + len - j);
2590 mb_l = utfc_ptr2len_len(p, start + len - j);
2591 if (ARABIC_CHAR(u8c))
2593 /* Do Arabic shaping. */
2594 if (cmdmsg_rl)
2596 /* displaying from right to left */
2597 pc = prev_c;
2598 pc1 = prev_c1;
2599 prev_c1 = u8cc[0];
2600 if (j + mb_l >= start + len)
2601 nc = NUL;
2602 else
2603 nc = utf_ptr2char(p + mb_l);
2605 else
2607 /* displaying from left to right */
2608 if (j + mb_l >= start + len)
2609 pc = NUL;
2610 else
2612 int pcc[MAX_MCO];
2614 pc = utfc_ptr2char_len(p + mb_l, pcc,
2615 start + len - j - mb_l);
2616 pc1 = pcc[0];
2618 nc = prev_c;
2620 prev_c = u8c;
2622 u8c = arabic_shape(u8c, NULL, &u8cc[0], pc, pc1, nc);
2624 newlen += (*mb_char2bytes)(u8c, arshape_buf + newlen);
2625 if (u8cc[0] != 0)
2627 newlen += (*mb_char2bytes)(u8cc[0], arshape_buf + newlen);
2628 if (u8cc[1] != 0)
2629 newlen += (*mb_char2bytes)(u8cc[1],
2630 arshape_buf + newlen);
2633 else
2635 prev_c = u8c;
2636 mch_memmove(arshape_buf + newlen, p, mb_l);
2637 newlen += mb_l;
2641 msg_outtrans_len(arshape_buf, newlen);
2643 else
2644 #endif
2645 msg_outtrans_len(ccline.cmdbuff + start, len);
2649 * Put a character on the command line. Shifts the following text to the
2650 * right when "shift" is TRUE. Used for CTRL-V, CTRL-K, etc.
2651 * "c" must be printable (fit in one display cell)!
2653 void
2654 putcmdline(c, shift)
2655 int c;
2656 int shift;
2658 if (cmd_silent)
2659 return;
2660 msg_no_more = TRUE;
2661 msg_putchar(c);
2662 if (shift)
2663 draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
2664 msg_no_more = FALSE;
2665 cursorcmd();
2669 * Undo a putcmdline(c, FALSE).
2671 void
2672 unputcmdline()
2674 if (cmd_silent)
2675 return;
2676 msg_no_more = TRUE;
2677 if (ccline.cmdlen == ccline.cmdpos)
2678 msg_putchar(' ');
2679 else
2680 draw_cmdline(ccline.cmdpos, 1);
2681 msg_no_more = FALSE;
2682 cursorcmd();
2686 * Put the given string, of the given length, onto the command line.
2687 * If len is -1, then STRLEN() is used to calculate the length.
2688 * If 'redraw' is TRUE then the new part of the command line, and the remaining
2689 * part will be redrawn, otherwise it will not. If this function is called
2690 * twice in a row, then 'redraw' should be FALSE and redrawcmd() should be
2691 * called afterwards.
2694 put_on_cmdline(str, len, redraw)
2695 char_u *str;
2696 int len;
2697 int redraw;
2699 int retval;
2700 int i;
2701 int m;
2702 int c;
2704 if (len < 0)
2705 len = (int)STRLEN(str);
2707 /* Check if ccline.cmdbuff needs to be longer */
2708 if (ccline.cmdlen + len + 1 >= ccline.cmdbufflen)
2709 retval = realloc_cmdbuff(ccline.cmdlen + len);
2710 else
2711 retval = OK;
2712 if (retval == OK)
2714 if (!ccline.overstrike)
2716 mch_memmove(ccline.cmdbuff + ccline.cmdpos + len,
2717 ccline.cmdbuff + ccline.cmdpos,
2718 (size_t)(ccline.cmdlen - ccline.cmdpos));
2719 ccline.cmdlen += len;
2721 else
2723 #ifdef FEAT_MBYTE
2724 if (has_mbyte)
2726 /* Count nr of characters in the new string. */
2727 m = 0;
2728 for (i = 0; i < len; i += (*mb_ptr2len)(str + i))
2729 ++m;
2730 /* Count nr of bytes in cmdline that are overwritten by these
2731 * characters. */
2732 for (i = ccline.cmdpos; i < ccline.cmdlen && m > 0;
2733 i += (*mb_ptr2len)(ccline.cmdbuff + i))
2734 --m;
2735 if (i < ccline.cmdlen)
2737 mch_memmove(ccline.cmdbuff + ccline.cmdpos + len,
2738 ccline.cmdbuff + i, (size_t)(ccline.cmdlen - i));
2739 ccline.cmdlen += ccline.cmdpos + len - i;
2741 else
2742 ccline.cmdlen = ccline.cmdpos + len;
2744 else
2745 #endif
2746 if (ccline.cmdpos + len > ccline.cmdlen)
2747 ccline.cmdlen = ccline.cmdpos + len;
2749 mch_memmove(ccline.cmdbuff + ccline.cmdpos, str, (size_t)len);
2750 ccline.cmdbuff[ccline.cmdlen] = NUL;
2752 #ifdef FEAT_MBYTE
2753 if (enc_utf8)
2755 /* When the inserted text starts with a composing character,
2756 * backup to the character before it. There could be two of them.
2758 i = 0;
2759 c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
2760 while (ccline.cmdpos > 0 && utf_iscomposing(c))
2762 i = (*mb_head_off)(ccline.cmdbuff,
2763 ccline.cmdbuff + ccline.cmdpos - 1) + 1;
2764 ccline.cmdpos -= i;
2765 len += i;
2766 c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
2768 # ifdef FEAT_ARABIC
2769 if (i == 0 && ccline.cmdpos > 0 && arabic_maycombine(c))
2771 /* Check the previous character for Arabic combining pair. */
2772 i = (*mb_head_off)(ccline.cmdbuff,
2773 ccline.cmdbuff + ccline.cmdpos - 1) + 1;
2774 if (arabic_combine(utf_ptr2char(ccline.cmdbuff
2775 + ccline.cmdpos - i), c))
2777 ccline.cmdpos -= i;
2778 len += i;
2780 else
2781 i = 0;
2783 # endif
2784 if (i != 0)
2786 /* Also backup the cursor position. */
2787 i = ptr2cells(ccline.cmdbuff + ccline.cmdpos);
2788 ccline.cmdspos -= i;
2789 msg_col -= i;
2790 if (msg_col < 0)
2792 msg_col += Columns;
2793 --msg_row;
2797 #endif
2799 if (redraw && !cmd_silent)
2801 msg_no_more = TRUE;
2802 i = cmdline_row;
2803 draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
2804 /* Avoid clearing the rest of the line too often. */
2805 if (cmdline_row != i || ccline.overstrike)
2806 msg_clr_eos();
2807 msg_no_more = FALSE;
2809 #ifdef FEAT_FKMAP
2811 * If we are in Farsi command mode, the character input must be in
2812 * Insert mode. So do not advance the cmdpos.
2814 if (!cmd_fkmap)
2815 #endif
2817 if (KeyTyped)
2819 m = Columns * Rows;
2820 if (m < 0) /* overflow, Columns or Rows at weird value */
2821 m = MAXCOL;
2823 else
2824 m = MAXCOL;
2825 for (i = 0; i < len; ++i)
2827 c = cmdline_charsize(ccline.cmdpos);
2828 #ifdef FEAT_MBYTE
2829 /* count ">" for a double-wide char that doesn't fit. */
2830 if (has_mbyte)
2831 correct_cmdspos(ccline.cmdpos, c);
2832 #endif
2833 /* Stop cursor at the end of the screen, but do increment the
2834 * insert position, so that entering a very long command
2835 * works, even though you can't see it. */
2836 if (ccline.cmdspos + c < m)
2837 ccline.cmdspos += c;
2838 #ifdef FEAT_MBYTE
2839 if (has_mbyte)
2841 c = (*mb_ptr2len)(ccline.cmdbuff + ccline.cmdpos) - 1;
2842 if (c > len - i - 1)
2843 c = len - i - 1;
2844 ccline.cmdpos += c;
2845 i += c;
2847 #endif
2848 ++ccline.cmdpos;
2852 if (redraw)
2853 msg_check();
2854 return retval;
2857 static struct cmdline_info prev_ccline;
2858 static int prev_ccline_used = FALSE;
2861 * Save ccline, because obtaining the "=" register may execute "normal :cmd"
2862 * and overwrite it. But get_cmdline_str() may need it, thus make it
2863 * available globally in prev_ccline.
2865 static void
2866 save_cmdline(ccp)
2867 struct cmdline_info *ccp;
2869 if (!prev_ccline_used)
2871 vim_memset(&prev_ccline, 0, sizeof(struct cmdline_info));
2872 prev_ccline_used = TRUE;
2874 *ccp = prev_ccline;
2875 prev_ccline = ccline;
2876 ccline.cmdbuff = NULL;
2877 ccline.cmdprompt = NULL;
2881 * Restore ccline after it has been saved with save_cmdline().
2883 static void
2884 restore_cmdline(ccp)
2885 struct cmdline_info *ccp;
2887 ccline = prev_ccline;
2888 prev_ccline = *ccp;
2891 #if defined(FEAT_EVAL) || defined(PROTO)
2893 * Save the command line into allocated memory. Returns a pointer to be
2894 * passed to restore_cmdline_alloc() later.
2895 * Returns NULL when failed.
2897 char_u *
2898 save_cmdline_alloc()
2900 struct cmdline_info *p;
2902 p = (struct cmdline_info *)alloc((unsigned)sizeof(struct cmdline_info));
2903 if (p != NULL)
2904 save_cmdline(p);
2905 return (char_u *)p;
2909 * Restore the command line from the return value of save_cmdline_alloc().
2911 void
2912 restore_cmdline_alloc(p)
2913 char_u *p;
2915 if (p != NULL)
2917 restore_cmdline((struct cmdline_info *)p);
2918 vim_free(p);
2921 #endif
2924 * paste a yank register into the command line.
2925 * used by CTRL-R command in command-line mode
2926 * insert_reg() can't be used here, because special characters from the
2927 * register contents will be interpreted as commands.
2929 * return FAIL for failure, OK otherwise
2931 static int
2932 cmdline_paste(regname, literally, remcr)
2933 int regname;
2934 int literally; /* Insert text literally instead of "as typed" */
2935 int remcr; /* remove trailing CR */
2937 long i;
2938 char_u *arg;
2939 char_u *p;
2940 int allocated;
2941 struct cmdline_info save_ccline;
2943 /* check for valid regname; also accept special characters for CTRL-R in
2944 * the command line */
2945 if (regname != Ctrl_F && regname != Ctrl_P && regname != Ctrl_W
2946 && regname != Ctrl_A && !valid_yank_reg(regname, FALSE))
2947 return FAIL;
2949 /* A register containing CTRL-R can cause an endless loop. Allow using
2950 * CTRL-C to break the loop. */
2951 line_breakcheck();
2952 if (got_int)
2953 return FAIL;
2955 #ifdef FEAT_CLIPBOARD
2956 regname = may_get_selection(regname);
2957 #endif
2959 /* Need to save and restore ccline. And set "textlock" to avoid nasty
2960 * things like going to another buffer when evaluating an expression. */
2961 save_cmdline(&save_ccline);
2962 ++textlock;
2963 i = get_spec_reg(regname, &arg, &allocated, TRUE);
2964 --textlock;
2965 restore_cmdline(&save_ccline);
2967 if (i)
2969 /* Got the value of a special register in "arg". */
2970 if (arg == NULL)
2971 return FAIL;
2973 /* When 'incsearch' is set and CTRL-R CTRL-W used: skip the duplicate
2974 * part of the word. */
2975 p = arg;
2976 if (p_is && regname == Ctrl_W)
2978 char_u *w;
2979 int len;
2981 /* Locate start of last word in the cmd buffer. */
2982 for (w = ccline.cmdbuff + ccline.cmdlen; w > ccline.cmdbuff; )
2984 #ifdef FEAT_MBYTE
2985 if (has_mbyte)
2987 len = (*mb_head_off)(ccline.cmdbuff, w - 1) + 1;
2988 if (!vim_iswordc(mb_ptr2char(w - len)))
2989 break;
2990 w -= len;
2992 else
2993 #endif
2995 if (!vim_iswordc(w[-1]))
2996 break;
2997 --w;
3000 len = (int)((ccline.cmdbuff + ccline.cmdlen) - w);
3001 if (p_ic ? STRNICMP(w, arg, len) == 0 : STRNCMP(w, arg, len) == 0)
3002 p += len;
3005 cmdline_paste_str(p, literally);
3006 if (allocated)
3007 vim_free(arg);
3008 return OK;
3011 return cmdline_paste_reg(regname, literally, remcr);
3015 * Put a string on the command line.
3016 * When "literally" is TRUE, insert literally.
3017 * When "literally" is FALSE, insert as typed, but don't leave the command
3018 * line.
3020 void
3021 cmdline_paste_str(s, literally)
3022 char_u *s;
3023 int literally;
3025 int c, cv;
3027 if (literally)
3028 put_on_cmdline(s, -1, TRUE);
3029 else
3030 while (*s != NUL)
3032 cv = *s;
3033 if (cv == Ctrl_V && s[1])
3034 ++s;
3035 #ifdef FEAT_MBYTE
3036 if (has_mbyte)
3037 c = mb_cptr2char_adv(&s);
3038 else
3039 #endif
3040 c = *s++;
3041 if (cv == Ctrl_V || c == ESC || c == Ctrl_C || c == CAR || c == NL
3042 #ifdef UNIX
3043 || c == intr_char
3044 #endif
3045 || (c == Ctrl_BSL && *s == Ctrl_N))
3046 stuffcharReadbuff(Ctrl_V);
3047 stuffcharReadbuff(c);
3051 #ifdef FEAT_WILDMENU
3053 * Delete characters on the command line, from "from" to the current
3054 * position.
3056 static void
3057 cmdline_del(from)
3058 int from;
3060 mch_memmove(ccline.cmdbuff + from, ccline.cmdbuff + ccline.cmdpos,
3061 (size_t)(ccline.cmdlen - ccline.cmdpos + 1));
3062 ccline.cmdlen -= ccline.cmdpos - from;
3063 ccline.cmdpos = from;
3065 #endif
3068 * this function is called when the screen size changes and with incremental
3069 * search
3071 void
3072 redrawcmdline()
3074 if (cmd_silent)
3075 return;
3076 need_wait_return = FALSE;
3077 compute_cmdrow();
3078 redrawcmd();
3079 cursorcmd();
3082 static void
3083 redrawcmdprompt()
3085 int i;
3087 if (cmd_silent)
3088 return;
3089 if (ccline.cmdfirstc != NUL)
3090 msg_putchar(ccline.cmdfirstc);
3091 if (ccline.cmdprompt != NULL)
3093 msg_puts_attr(ccline.cmdprompt, ccline.cmdattr);
3094 ccline.cmdindent = msg_col + (msg_row - cmdline_row) * Columns;
3095 /* do the reverse of set_cmdspos() */
3096 if (ccline.cmdfirstc != NUL)
3097 --ccline.cmdindent;
3099 else
3100 for (i = ccline.cmdindent; i > 0; --i)
3101 msg_putchar(' ');
3105 * Redraw what is currently on the command line.
3107 void
3108 redrawcmd()
3110 if (cmd_silent)
3111 return;
3113 /* when 'incsearch' is set there may be no command line while redrawing */
3114 if (ccline.cmdbuff == NULL)
3116 windgoto(cmdline_row, 0);
3117 msg_clr_eos();
3118 return;
3121 msg_start();
3122 redrawcmdprompt();
3124 /* Don't use more prompt, truncate the cmdline if it doesn't fit. */
3125 msg_no_more = TRUE;
3126 draw_cmdline(0, ccline.cmdlen);
3127 msg_clr_eos();
3128 msg_no_more = FALSE;
3130 set_cmdspos_cursor();
3133 * An emsg() before may have set msg_scroll. This is used in normal mode,
3134 * in cmdline mode we can reset them now.
3136 msg_scroll = FALSE; /* next message overwrites cmdline */
3138 /* Typing ':' at the more prompt may set skip_redraw. We don't want this
3139 * in cmdline mode */
3140 skip_redraw = FALSE;
3143 void
3144 compute_cmdrow()
3146 if (exmode_active || msg_scrolled != 0)
3147 cmdline_row = Rows - 1;
3148 else
3149 cmdline_row = W_WINROW(lastwin) + lastwin->w_height
3150 + W_STATUS_HEIGHT(lastwin);
3153 static void
3154 cursorcmd()
3156 if (cmd_silent)
3157 return;
3159 #ifdef FEAT_RIGHTLEFT
3160 if (cmdmsg_rl)
3162 msg_row = cmdline_row + (ccline.cmdspos / (int)(Columns - 1));
3163 msg_col = (int)Columns - (ccline.cmdspos % (int)(Columns - 1)) - 1;
3164 if (msg_row <= 0)
3165 msg_row = Rows - 1;
3167 else
3168 #endif
3170 msg_row = cmdline_row + (ccline.cmdspos / (int)Columns);
3171 msg_col = ccline.cmdspos % (int)Columns;
3172 if (msg_row >= Rows)
3173 msg_row = Rows - 1;
3176 windgoto(msg_row, msg_col);
3177 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
3178 redrawcmd_preedit();
3179 #endif
3180 #ifdef MCH_CURSOR_SHAPE
3181 mch_update_cursor();
3182 #endif
3185 void
3186 gotocmdline(clr)
3187 int clr;
3189 msg_start();
3190 #ifdef FEAT_RIGHTLEFT
3191 if (cmdmsg_rl)
3192 msg_col = Columns - 1;
3193 else
3194 #endif
3195 msg_col = 0; /* always start in column 0 */
3196 if (clr) /* clear the bottom line(s) */
3197 msg_clr_eos(); /* will reset clear_cmdline */
3198 windgoto(cmdline_row, 0);
3202 * Check the word in front of the cursor for an abbreviation.
3203 * Called when the non-id character "c" has been entered.
3204 * When an abbreviation is recognized it is removed from the text with
3205 * backspaces and the replacement string is inserted, followed by "c".
3207 static int
3208 ccheck_abbr(c)
3209 int c;
3211 if (p_paste || no_abbr) /* no abbreviations or in paste mode */
3212 return FALSE;
3214 return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, 0);
3218 * Return FAIL if this is not an appropriate context in which to do
3219 * completion of anything, return OK if it is (even if there are no matches).
3220 * For the caller, this means that the character is just passed through like a
3221 * normal character (instead of being expanded). This allows :s/^I^D etc.
3223 static int
3224 nextwild(xp, type, options)
3225 expand_T *xp;
3226 int type;
3227 int options; /* extra options for ExpandOne() */
3229 int i, j;
3230 char_u *p1;
3231 char_u *p2;
3232 int oldlen;
3233 int difflen;
3234 int v;
3236 if (xp->xp_numfiles == -1)
3238 set_expand_context(xp);
3239 cmd_showtail = expand_showtail(xp);
3242 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
3244 beep_flush();
3245 return OK; /* Something illegal on command line */
3247 if (xp->xp_context == EXPAND_NOTHING)
3249 /* Caller can use the character as a normal char instead */
3250 return FAIL;
3253 MSG_PUTS("..."); /* show that we are busy */
3254 out_flush();
3256 i = (int)(xp->xp_pattern - ccline.cmdbuff);
3257 oldlen = ccline.cmdpos - i;
3259 if (type == WILD_NEXT || type == WILD_PREV)
3262 * Get next/previous match for a previous expanded pattern.
3264 p2 = ExpandOne(xp, NULL, NULL, 0, type);
3266 else
3269 * Translate string into pattern and expand it.
3271 if ((p1 = addstar(&ccline.cmdbuff[i], oldlen, xp->xp_context)) == NULL)
3272 p2 = NULL;
3273 else
3275 p2 = ExpandOne(xp, p1, vim_strnsave(&ccline.cmdbuff[i], oldlen),
3276 WILD_HOME_REPLACE|WILD_ADD_SLASH|WILD_SILENT|WILD_ESCAPE
3277 |options, type);
3278 vim_free(p1);
3279 /* longest match: make sure it is not shorter (happens with :help */
3280 if (p2 != NULL && type == WILD_LONGEST)
3282 for (j = 0; j < oldlen; ++j)
3283 if (ccline.cmdbuff[i + j] == '*'
3284 || ccline.cmdbuff[i + j] == '?')
3285 break;
3286 if ((int)STRLEN(p2) < j)
3288 vim_free(p2);
3289 p2 = NULL;
3295 if (p2 != NULL && !got_int)
3297 difflen = (int)STRLEN(p2) - oldlen;
3298 if (ccline.cmdlen + difflen > ccline.cmdbufflen - 4)
3300 v = realloc_cmdbuff(ccline.cmdlen + difflen);
3301 xp->xp_pattern = ccline.cmdbuff + i;
3303 else
3304 v = OK;
3305 if (v == OK)
3307 mch_memmove(&ccline.cmdbuff[ccline.cmdpos + difflen],
3308 &ccline.cmdbuff[ccline.cmdpos],
3309 (size_t)(ccline.cmdlen - ccline.cmdpos + 1));
3310 mch_memmove(&ccline.cmdbuff[i], p2, STRLEN(p2));
3311 ccline.cmdlen += difflen;
3312 ccline.cmdpos += difflen;
3315 vim_free(p2);
3317 redrawcmd();
3318 cursorcmd();
3320 /* When expanding a ":map" command and no matches are found, assume that
3321 * the key is supposed to be inserted literally */
3322 if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL)
3323 return FAIL;
3325 if (xp->xp_numfiles <= 0 && p2 == NULL)
3326 beep_flush();
3327 else if (xp->xp_numfiles == 1)
3328 /* free expanded pattern */
3329 (void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE);
3331 return OK;
3335 * Do wildcard expansion on the string 'str'.
3336 * Chars that should not be expanded must be preceded with a backslash.
3337 * Return a pointer to allocated memory containing the new string.
3338 * Return NULL for failure.
3340 * "orig" is the originally expanded string, copied to allocated memory. It
3341 * should either be kept in orig_save or freed. When "mode" is WILD_NEXT or
3342 * WILD_PREV "orig" should be NULL.
3344 * Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode"
3345 * is WILD_EXPAND_FREE or WILD_ALL.
3347 * mode = WILD_FREE: just free previously expanded matches
3348 * mode = WILD_EXPAND_FREE: normal expansion, do not keep matches
3349 * mode = WILD_EXPAND_KEEP: normal expansion, keep matches
3350 * mode = WILD_NEXT: use next match in multiple match, wrap to first
3351 * mode = WILD_PREV: use previous match in multiple match, wrap to first
3352 * mode = WILD_ALL: return all matches concatenated
3353 * mode = WILD_LONGEST: return longest matched part
3355 * options = WILD_LIST_NOTFOUND: list entries without a match
3356 * options = WILD_HOME_REPLACE: do home_replace() for buffer names
3357 * options = WILD_USE_NL: Use '\n' for WILD_ALL
3358 * options = WILD_NO_BEEP: Don't beep for multiple matches
3359 * options = WILD_ADD_SLASH: add a slash after directory names
3360 * options = WILD_KEEP_ALL: don't remove 'wildignore' entries
3361 * options = WILD_SILENT: don't print warning messages
3362 * options = WILD_ESCAPE: put backslash before special chars
3364 * The variables xp->xp_context and xp->xp_backslash must have been set!
3366 char_u *
3367 ExpandOne(xp, str, orig, options, mode)
3368 expand_T *xp;
3369 char_u *str;
3370 char_u *orig; /* allocated copy of original of expanded string */
3371 int options;
3372 int mode;
3374 char_u *ss = NULL;
3375 static int findex;
3376 static char_u *orig_save = NULL; /* kept value of orig */
3377 int orig_saved = FALSE;
3378 int i;
3379 long_u len;
3380 int non_suf_match; /* number without matching suffix */
3383 * first handle the case of using an old match
3385 if (mode == WILD_NEXT || mode == WILD_PREV)
3387 if (xp->xp_numfiles > 0)
3389 if (mode == WILD_PREV)
3391 if (findex == -1)
3392 findex = xp->xp_numfiles;
3393 --findex;
3395 else /* mode == WILD_NEXT */
3396 ++findex;
3399 * When wrapping around, return the original string, set findex to
3400 * -1.
3402 if (findex < 0)
3404 if (orig_save == NULL)
3405 findex = xp->xp_numfiles - 1;
3406 else
3407 findex = -1;
3409 if (findex >= xp->xp_numfiles)
3411 if (orig_save == NULL)
3412 findex = 0;
3413 else
3414 findex = -1;
3416 #ifdef FEAT_WILDMENU
3417 if (p_wmnu)
3418 win_redr_status_matches(xp, xp->xp_numfiles, xp->xp_files,
3419 findex, cmd_showtail);
3420 #endif
3421 if (findex == -1)
3422 return vim_strsave(orig_save);
3423 return vim_strsave(xp->xp_files[findex]);
3425 else
3426 return NULL;
3429 /* free old names */
3430 if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST)
3432 FreeWild(xp->xp_numfiles, xp->xp_files);
3433 xp->xp_numfiles = -1;
3434 vim_free(orig_save);
3435 orig_save = NULL;
3437 findex = 0;
3439 if (mode == WILD_FREE) /* only release file name */
3440 return NULL;
3442 if (xp->xp_numfiles == -1)
3444 vim_free(orig_save);
3445 orig_save = orig;
3446 orig_saved = TRUE;
3449 * Do the expansion.
3451 if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files,
3452 options) == FAIL)
3454 #ifdef FNAME_ILLEGAL
3455 /* Illegal file name has been silently skipped. But when there
3456 * are wildcards, the real problem is that there was no match,
3457 * causing the pattern to be added, which has illegal characters.
3459 if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND))
3460 EMSG2(_(e_nomatch2), str);
3461 #endif
3463 else if (xp->xp_numfiles == 0)
3465 if (!(options & WILD_SILENT))
3466 EMSG2(_(e_nomatch2), str);
3468 else
3470 /* Escape the matches for use on the command line. */
3471 ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
3474 * Check for matching suffixes in file names.
3476 if (mode != WILD_ALL && mode != WILD_LONGEST)
3478 if (xp->xp_numfiles)
3479 non_suf_match = xp->xp_numfiles;
3480 else
3481 non_suf_match = 1;
3482 if ((xp->xp_context == EXPAND_FILES
3483 || xp->xp_context == EXPAND_DIRECTORIES)
3484 && xp->xp_numfiles > 1)
3487 * More than one match; check suffix.
3488 * The files will have been sorted on matching suffix in
3489 * expand_wildcards, only need to check the first two.
3491 non_suf_match = 0;
3492 for (i = 0; i < 2; ++i)
3493 if (match_suffix(xp->xp_files[i]))
3494 ++non_suf_match;
3496 if (non_suf_match != 1)
3498 /* Can we ever get here unless it's while expanding
3499 * interactively? If not, we can get rid of this all
3500 * together. Don't really want to wait for this message
3501 * (and possibly have to hit return to continue!).
3503 if (!(options & WILD_SILENT))
3504 EMSG(_(e_toomany));
3505 else if (!(options & WILD_NO_BEEP))
3506 beep_flush();
3508 if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE))
3509 ss = vim_strsave(xp->xp_files[0]);
3514 /* Find longest common part */
3515 if (mode == WILD_LONGEST && xp->xp_numfiles > 0)
3517 for (len = 0; xp->xp_files[0][len]; ++len)
3519 for (i = 0; i < xp->xp_numfiles; ++i)
3521 #ifdef CASE_INSENSITIVE_FILENAME
3522 if (xp->xp_context == EXPAND_DIRECTORIES
3523 || xp->xp_context == EXPAND_FILES
3524 || xp->xp_context == EXPAND_SHELLCMD
3525 || xp->xp_context == EXPAND_BUFFERS)
3527 if (TOLOWER_LOC(xp->xp_files[i][len]) !=
3528 TOLOWER_LOC(xp->xp_files[0][len]))
3529 break;
3531 else
3532 #endif
3533 if (xp->xp_files[i][len] != xp->xp_files[0][len])
3534 break;
3536 if (i < xp->xp_numfiles)
3538 if (!(options & WILD_NO_BEEP))
3539 vim_beep();
3540 break;
3543 ss = alloc((unsigned)len + 1);
3544 if (ss)
3545 vim_strncpy(ss, xp->xp_files[0], (size_t)len);
3546 findex = -1; /* next p_wc gets first one */
3549 /* Concatenate all matching names */
3550 if (mode == WILD_ALL && xp->xp_numfiles > 0)
3552 len = 0;
3553 for (i = 0; i < xp->xp_numfiles; ++i)
3554 len += (long_u)STRLEN(xp->xp_files[i]) + 1;
3555 ss = lalloc(len, TRUE);
3556 if (ss != NULL)
3558 *ss = NUL;
3559 for (i = 0; i < xp->xp_numfiles; ++i)
3561 STRCAT(ss, xp->xp_files[i]);
3562 if (i != xp->xp_numfiles - 1)
3563 STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " ");
3568 if (mode == WILD_EXPAND_FREE || mode == WILD_ALL)
3569 ExpandCleanup(xp);
3571 /* Free "orig" if it wasn't stored in "orig_save". */
3572 if (!orig_saved)
3573 vim_free(orig);
3575 return ss;
3579 * Prepare an expand structure for use.
3581 void
3582 ExpandInit(xp)
3583 expand_T *xp;
3585 xp->xp_backslash = XP_BS_NONE;
3586 #ifndef BACKSLASH_IN_FILENAME
3587 xp->xp_shell = FALSE;
3588 #endif
3589 xp->xp_numfiles = -1;
3590 xp->xp_files = NULL;
3591 #if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
3592 xp->xp_arg = NULL;
3593 #endif
3597 * Cleanup an expand structure after use.
3599 void
3600 ExpandCleanup(xp)
3601 expand_T *xp;
3603 if (xp->xp_numfiles >= 0)
3605 FreeWild(xp->xp_numfiles, xp->xp_files);
3606 xp->xp_numfiles = -1;
3610 void
3611 ExpandEscape(xp, str, numfiles, files, options)
3612 expand_T *xp;
3613 char_u *str;
3614 int numfiles;
3615 char_u **files;
3616 int options;
3618 int i;
3619 char_u *p;
3622 * May change home directory back to "~"
3624 if (options & WILD_HOME_REPLACE)
3625 tilde_replace(str, numfiles, files);
3627 if (options & WILD_ESCAPE)
3629 if (xp->xp_context == EXPAND_FILES
3630 || xp->xp_context == EXPAND_SHELLCMD
3631 || xp->xp_context == EXPAND_BUFFERS
3632 || xp->xp_context == EXPAND_DIRECTORIES)
3635 * Insert a backslash into a file name before a space, \, %, #
3636 * and wildmatch characters, except '~'.
3638 for (i = 0; i < numfiles; ++i)
3640 /* for ":set path=" we need to escape spaces twice */
3641 if (xp->xp_backslash == XP_BS_THREE)
3643 p = vim_strsave_escaped(files[i], (char_u *)" ");
3644 if (p != NULL)
3646 vim_free(files[i]);
3647 files[i] = p;
3648 #if defined(BACKSLASH_IN_FILENAME)
3649 p = vim_strsave_escaped(files[i], (char_u *)" ");
3650 if (p != NULL)
3652 vim_free(files[i]);
3653 files[i] = p;
3655 #endif
3658 #ifdef BACKSLASH_IN_FILENAME
3659 p = vim_strsave_fnameescape(files[i], FALSE);
3660 #else
3661 p = vim_strsave_fnameescape(files[i], xp->xp_shell);
3662 #endif
3663 if (p != NULL)
3665 vim_free(files[i]);
3666 files[i] = p;
3669 /* If 'str' starts with "\~", replace "~" at start of
3670 * files[i] with "\~". */
3671 if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~')
3672 escape_fname(&files[i]);
3674 xp->xp_backslash = XP_BS_NONE;
3676 /* If the first file starts with a '+' escape it. Otherwise it
3677 * could be seen as "+cmd". */
3678 if (*files[0] == '+')
3679 escape_fname(&files[0]);
3681 else if (xp->xp_context == EXPAND_TAGS)
3684 * Insert a backslash before characters in a tag name that
3685 * would terminate the ":tag" command.
3687 for (i = 0; i < numfiles; ++i)
3689 p = vim_strsave_escaped(files[i], (char_u *)"\\|\"");
3690 if (p != NULL)
3692 vim_free(files[i]);
3693 files[i] = p;
3701 * Escape special characters in "fname" for when used as a file name argument
3702 * after a Vim command, or, when "shell" is non-zero, a shell command.
3703 * Returns the result in allocated memory.
3705 char_u *
3706 vim_strsave_fnameescape(fname, shell)
3707 char_u *fname;
3708 int shell;
3710 #ifdef BACKSLASH_IN_FILENAME
3711 char_u buf[20];
3712 int j = 0;
3713 char_u *p;
3715 /* Don't escape '[' and '{' if they are in 'isfname'. */
3716 for (p = PATH_ESC_CHARS; *p != NUL; ++p)
3717 if ((*p != '[' && *p != '{') || !vim_isfilec(*p))
3718 buf[j++] = *p;
3719 buf[j] = NUL;
3720 return vim_strsave_escaped(fname, buf);
3721 #else
3722 return vim_strsave_escaped(fname, shell ? SHELL_ESC_CHARS : PATH_ESC_CHARS);
3723 #endif
3727 * Put a backslash before the file name in "pp", which is in allocated memory.
3729 static void
3730 escape_fname(pp)
3731 char_u **pp;
3733 char_u *p;
3735 p = alloc((unsigned)(STRLEN(*pp) + 2));
3736 if (p != NULL)
3738 p[0] = '\\';
3739 STRCPY(p + 1, *pp);
3740 vim_free(*pp);
3741 *pp = p;
3746 * For each file name in files[num_files]:
3747 * If 'orig_pat' starts with "~/", replace the home directory with "~".
3749 void
3750 tilde_replace(orig_pat, num_files, files)
3751 char_u *orig_pat;
3752 int num_files;
3753 char_u **files;
3755 int i;
3756 char_u *p;
3758 if (orig_pat[0] == '~' && vim_ispathsep(orig_pat[1]))
3760 for (i = 0; i < num_files; ++i)
3762 p = home_replace_save(NULL, files[i]);
3763 if (p != NULL)
3765 vim_free(files[i]);
3766 files[i] = p;
3773 * Show all matches for completion on the command line.
3774 * Returns EXPAND_NOTHING when the character that triggered expansion should
3775 * be inserted like a normal character.
3777 /*ARGSUSED*/
3778 static int
3779 showmatches(xp, wildmenu)
3780 expand_T *xp;
3781 int wildmenu;
3783 #define L_SHOWFILE(m) (showtail ? sm_gettail(files_found[m]) : files_found[m])
3784 int num_files;
3785 char_u **files_found;
3786 int i, j, k;
3787 int maxlen;
3788 int lines;
3789 int columns;
3790 char_u *p;
3791 int lastlen;
3792 int attr;
3793 int showtail;
3795 if (xp->xp_numfiles == -1)
3797 set_expand_context(xp);
3798 i = expand_cmdline(xp, ccline.cmdbuff, ccline.cmdpos,
3799 &num_files, &files_found);
3800 showtail = expand_showtail(xp);
3801 if (i != EXPAND_OK)
3802 return i;
3805 else
3807 num_files = xp->xp_numfiles;
3808 files_found = xp->xp_files;
3809 showtail = cmd_showtail;
3812 #ifdef FEAT_WILDMENU
3813 if (!wildmenu)
3815 #endif
3816 msg_didany = FALSE; /* lines_left will be set */
3817 msg_start(); /* prepare for paging */
3818 msg_putchar('\n');
3819 out_flush();
3820 cmdline_row = msg_row;
3821 msg_didany = FALSE; /* lines_left will be set again */
3822 msg_start(); /* prepare for paging */
3823 #ifdef FEAT_WILDMENU
3825 #endif
3827 if (got_int)
3828 got_int = FALSE; /* only int. the completion, not the cmd line */
3829 #ifdef FEAT_WILDMENU
3830 else if (wildmenu)
3831 win_redr_status_matches(xp, num_files, files_found, 0, showtail);
3832 #endif
3833 else
3835 /* find the length of the longest file name */
3836 maxlen = 0;
3837 for (i = 0; i < num_files; ++i)
3839 if (!showtail && (xp->xp_context == EXPAND_FILES
3840 || xp->xp_context == EXPAND_SHELLCMD
3841 || xp->xp_context == EXPAND_BUFFERS))
3843 home_replace(NULL, files_found[i], NameBuff, MAXPATHL, TRUE);
3844 j = vim_strsize(NameBuff);
3846 else
3847 j = vim_strsize(L_SHOWFILE(i));
3848 if (j > maxlen)
3849 maxlen = j;
3852 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
3853 lines = num_files;
3854 else
3856 /* compute the number of columns and lines for the listing */
3857 maxlen += 2; /* two spaces between file names */
3858 columns = ((int)Columns + 2) / maxlen;
3859 if (columns < 1)
3860 columns = 1;
3861 lines = (num_files + columns - 1) / columns;
3864 attr = hl_attr(HLF_D); /* find out highlighting for directories */
3866 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
3868 MSG_PUTS_ATTR(_("tagname"), hl_attr(HLF_T));
3869 msg_clr_eos();
3870 msg_advance(maxlen - 3);
3871 MSG_PUTS_ATTR(_(" kind file\n"), hl_attr(HLF_T));
3874 /* list the files line by line */
3875 for (i = 0; i < lines; ++i)
3877 lastlen = 999;
3878 for (k = i; k < num_files; k += lines)
3880 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
3882 msg_outtrans_attr(files_found[k], hl_attr(HLF_D));
3883 p = files_found[k] + STRLEN(files_found[k]) + 1;
3884 msg_advance(maxlen + 1);
3885 msg_puts(p);
3886 msg_advance(maxlen + 3);
3887 msg_puts_long_attr(p + 2, hl_attr(HLF_D));
3888 break;
3890 for (j = maxlen - lastlen; --j >= 0; )
3891 msg_putchar(' ');
3892 if (xp->xp_context == EXPAND_FILES
3893 || xp->xp_context == EXPAND_SHELLCMD
3894 || xp->xp_context == EXPAND_BUFFERS)
3896 /* highlight directories */
3897 j = (mch_isdir(files_found[k]));
3898 if (showtail)
3899 p = L_SHOWFILE(k);
3900 else
3902 home_replace(NULL, files_found[k], NameBuff, MAXPATHL,
3903 TRUE);
3904 p = NameBuff;
3907 else
3909 j = FALSE;
3910 p = L_SHOWFILE(k);
3912 lastlen = msg_outtrans_attr(p, j ? attr : 0);
3914 if (msg_col > 0) /* when not wrapped around */
3916 msg_clr_eos();
3917 msg_putchar('\n');
3919 out_flush(); /* show one line at a time */
3920 if (got_int)
3922 got_int = FALSE;
3923 break;
3928 * we redraw the command below the lines that we have just listed
3929 * This is a bit tricky, but it saves a lot of screen updating.
3931 cmdline_row = msg_row; /* will put it back later */
3934 if (xp->xp_numfiles == -1)
3935 FreeWild(num_files, files_found);
3937 return EXPAND_OK;
3941 * Private gettail for showmatches() (and win_redr_status_matches()):
3942 * Find tail of file name path, but ignore trailing "/".
3944 char_u *
3945 sm_gettail(s)
3946 char_u *s;
3948 char_u *p;
3949 char_u *t = s;
3950 int had_sep = FALSE;
3952 for (p = s; *p != NUL; )
3954 if (vim_ispathsep(*p)
3955 #ifdef BACKSLASH_IN_FILENAME
3956 && !rem_backslash(p)
3957 #endif
3959 had_sep = TRUE;
3960 else if (had_sep)
3962 t = p;
3963 had_sep = FALSE;
3965 mb_ptr_adv(p);
3967 return t;
3971 * Return TRUE if we only need to show the tail of completion matches.
3972 * When not completing file names or there is a wildcard in the path FALSE is
3973 * returned.
3975 static int
3976 expand_showtail(xp)
3977 expand_T *xp;
3979 char_u *s;
3980 char_u *end;
3982 /* When not completing file names a "/" may mean something different. */
3983 if (xp->xp_context != EXPAND_FILES
3984 && xp->xp_context != EXPAND_SHELLCMD
3985 && xp->xp_context != EXPAND_DIRECTORIES)
3986 return FALSE;
3988 end = gettail(xp->xp_pattern);
3989 if (end == xp->xp_pattern) /* there is no path separator */
3990 return FALSE;
3992 for (s = xp->xp_pattern; s < end; s++)
3994 /* Skip escaped wildcards. Only when the backslash is not a path
3995 * separator, on DOS the '*' "path\*\file" must not be skipped. */
3996 if (rem_backslash(s))
3997 ++s;
3998 else if (vim_strchr((char_u *)"*?[", *s) != NULL)
3999 return FALSE;
4001 return TRUE;
4005 * Prepare a string for expansion.
4006 * When expanding file names: The string will be used with expand_wildcards().
4007 * Copy the file name into allocated memory and add a '*' at the end.
4008 * When expanding other names: The string will be used with regcomp(). Copy
4009 * the name into allocated memory and prepend "^".
4011 char_u *
4012 addstar(fname, len, context)
4013 char_u *fname;
4014 int len;
4015 int context; /* EXPAND_FILES etc. */
4017 char_u *retval;
4018 int i, j;
4019 int new_len;
4020 char_u *tail;
4022 if (context != EXPAND_FILES
4023 && context != EXPAND_SHELLCMD
4024 && context != EXPAND_DIRECTORIES)
4027 * Matching will be done internally (on something other than files).
4028 * So we convert the file-matching-type wildcards into our kind for
4029 * use with vim_regcomp(). First work out how long it will be:
4032 /* For help tags the translation is done in find_help_tags().
4033 * For a tag pattern starting with "/" no translation is needed. */
4034 if (context == EXPAND_HELP
4035 || context == EXPAND_COLORS
4036 || context == EXPAND_COMPILER
4037 || (context == EXPAND_TAGS && fname[0] == '/'))
4038 retval = vim_strnsave(fname, len);
4039 else
4041 new_len = len + 2; /* +2 for '^' at start, NUL at end */
4042 for (i = 0; i < len; i++)
4044 if (fname[i] == '*' || fname[i] == '~')
4045 new_len++; /* '*' needs to be replaced by ".*"
4046 '~' needs to be replaced by "\~" */
4048 /* Buffer names are like file names. "." should be literal */
4049 if (context == EXPAND_BUFFERS && fname[i] == '.')
4050 new_len++; /* "." becomes "\." */
4052 /* Custom expansion takes care of special things, match
4053 * backslashes literally (perhaps also for other types?) */
4054 if ((context == EXPAND_USER_DEFINED
4055 || context == EXPAND_USER_LIST) && fname[i] == '\\')
4056 new_len++; /* '\' becomes "\\" */
4058 retval = alloc(new_len);
4059 if (retval != NULL)
4061 retval[0] = '^';
4062 j = 1;
4063 for (i = 0; i < len; i++, j++)
4065 /* Skip backslash. But why? At least keep it for custom
4066 * expansion. */
4067 if (context != EXPAND_USER_DEFINED
4068 && context != EXPAND_USER_LIST
4069 && fname[i] == '\\'
4070 && ++i == len)
4071 break;
4073 switch (fname[i])
4075 case '*': retval[j++] = '.';
4076 break;
4077 case '~': retval[j++] = '\\';
4078 break;
4079 case '?': retval[j] = '.';
4080 continue;
4081 case '.': if (context == EXPAND_BUFFERS)
4082 retval[j++] = '\\';
4083 break;
4084 case '\\': if (context == EXPAND_USER_DEFINED
4085 || context == EXPAND_USER_LIST)
4086 retval[j++] = '\\';
4087 break;
4089 retval[j] = fname[i];
4091 retval[j] = NUL;
4095 else
4097 retval = alloc(len + 4);
4098 if (retval != NULL)
4100 vim_strncpy(retval, fname, len);
4103 * Don't add a star to *, ~, ~user, $var or `cmd`.
4104 * * would become **, which walks the whole tree.
4105 * ~ would be at the start of the file name, but not the tail.
4106 * $ could be anywhere in the tail.
4107 * ` could be anywhere in the file name.
4108 * When the name ends in '$' don't add a star, remove the '$'.
4110 tail = gettail(retval);
4111 if ((*retval != '~' || tail != retval)
4112 && (len == 0 || retval[len - 1] != '*')
4113 && vim_strchr(tail, '$') == NULL
4114 && vim_strchr(retval, '`') == NULL)
4115 retval[len++] = '*';
4116 else if (len > 0 && retval[len - 1] == '$')
4117 --len;
4118 retval[len] = NUL;
4121 return retval;
4125 * Must parse the command line so far to work out what context we are in.
4126 * Completion can then be done based on that context.
4127 * This routine sets the variables:
4128 * xp->xp_pattern The start of the pattern to be expanded within
4129 * the command line (ends at the cursor).
4130 * xp->xp_context The type of thing to expand. Will be one of:
4132 * EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on
4133 * the command line, like an unknown command. Caller
4134 * should beep.
4135 * EXPAND_NOTHING Unrecognised context for completion, use char like
4136 * a normal char, rather than for completion. eg
4137 * :s/^I/
4138 * EXPAND_COMMANDS Cursor is still touching the command, so complete
4139 * it.
4140 * EXPAND_BUFFERS Complete file names for :buf and :sbuf commands.
4141 * EXPAND_FILES After command with XFILE set, or after setting
4142 * with P_EXPAND set. eg :e ^I, :w>>^I
4143 * EXPAND_DIRECTORIES In some cases this is used instead of the latter
4144 * when we know only directories are of interest. eg
4145 * :set dir=^I
4146 * EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd".
4147 * EXPAND_SETTINGS Complete variable names. eg :set d^I
4148 * EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I
4149 * EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I
4150 * EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect
4151 * EXPAND_HELP Complete tags from the file 'helpfile'/tags
4152 * EXPAND_EVENTS Complete event names
4153 * EXPAND_SYNTAX Complete :syntax command arguments
4154 * EXPAND_HIGHLIGHT Complete highlight (syntax) group names
4155 * EXPAND_AUGROUP Complete autocommand group names
4156 * EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I
4157 * EXPAND_MAPPINGS Complete mapping and abbreviation names,
4158 * eg :unmap a^I , :cunab x^I
4159 * EXPAND_FUNCTIONS Complete internal or user defined function names,
4160 * eg :call sub^I
4161 * EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I
4162 * EXPAND_EXPRESSION Complete internal or user defined function/variable
4163 * names in expressions, eg :while s^I
4164 * EXPAND_ENV_VARS Complete environment variable names
4166 static void
4167 set_expand_context(xp)
4168 expand_T *xp;
4170 /* only expansion for ':', '>' and '=' command-lines */
4171 if (ccline.cmdfirstc != ':'
4172 #ifdef FEAT_EVAL
4173 && ccline.cmdfirstc != '>' && ccline.cmdfirstc != '='
4174 && !ccline.input_fn
4175 #endif
4178 xp->xp_context = EXPAND_NOTHING;
4179 return;
4181 set_cmd_context(xp, ccline.cmdbuff, ccline.cmdlen, ccline.cmdpos);
4184 void
4185 set_cmd_context(xp, str, len, col)
4186 expand_T *xp;
4187 char_u *str; /* start of command line */
4188 int len; /* length of command line (excl. NUL) */
4189 int col; /* position of cursor */
4191 int old_char = NUL;
4192 char_u *nextcomm;
4195 * Avoid a UMR warning from Purify, only save the character if it has been
4196 * written before.
4198 if (col < len)
4199 old_char = str[col];
4200 str[col] = NUL;
4201 nextcomm = str;
4203 #ifdef FEAT_EVAL
4204 if (ccline.cmdfirstc == '=')
4206 # ifdef FEAT_CMDL_COMPL
4207 /* pass CMD_SIZE because there is no real command */
4208 set_context_for_expression(xp, str, CMD_SIZE);
4209 # endif
4211 else if (ccline.input_fn)
4213 xp->xp_context = ccline.xp_context;
4214 xp->xp_pattern = ccline.cmdbuff;
4215 # if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
4216 xp->xp_arg = ccline.xp_arg;
4217 # endif
4219 else
4220 #endif
4221 while (nextcomm != NULL)
4222 nextcomm = set_one_cmd_context(xp, nextcomm);
4224 str[col] = old_char;
4228 * Expand the command line "str" from context "xp".
4229 * "xp" must have been set by set_cmd_context().
4230 * xp->xp_pattern points into "str", to where the text that is to be expanded
4231 * starts.
4232 * Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
4233 * cursor.
4234 * Returns EXPAND_NOTHING when there is nothing to expand, might insert the
4235 * key that triggered expansion literally.
4236 * Returns EXPAND_OK otherwise.
4239 expand_cmdline(xp, str, col, matchcount, matches)
4240 expand_T *xp;
4241 char_u *str; /* start of command line */
4242 int col; /* position of cursor */
4243 int *matchcount; /* return: nr of matches */
4244 char_u ***matches; /* return: array of pointers to matches */
4246 char_u *file_str = NULL;
4248 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
4250 beep_flush();
4251 return EXPAND_UNSUCCESSFUL; /* Something illegal on command line */
4253 if (xp->xp_context == EXPAND_NOTHING)
4255 /* Caller can use the character as a normal char instead */
4256 return EXPAND_NOTHING;
4259 /* add star to file name, or convert to regexp if not exp. files. */
4260 file_str = addstar(xp->xp_pattern,
4261 (int)(str + col - xp->xp_pattern), xp->xp_context);
4262 if (file_str == NULL)
4263 return EXPAND_UNSUCCESSFUL;
4265 /* find all files that match the description */
4266 if (ExpandFromContext(xp, file_str, matchcount, matches,
4267 WILD_ADD_SLASH|WILD_SILENT) == FAIL)
4269 *matchcount = 0;
4270 *matches = NULL;
4272 vim_free(file_str);
4274 return EXPAND_OK;
4277 #ifdef FEAT_MULTI_LANG
4279 * Cleanup matches for help tags: remove "@en" if "en" is the only language.
4281 static void cleanup_help_tags __ARGS((int num_file, char_u **file));
4283 static void
4284 cleanup_help_tags(num_file, file)
4285 int num_file;
4286 char_u **file;
4288 int i, j;
4289 int len;
4291 for (i = 0; i < num_file; ++i)
4293 len = (int)STRLEN(file[i]) - 3;
4294 if (len > 0 && STRCMP(file[i] + len, "@en") == 0)
4296 /* Sorting on priority means the same item in another language may
4297 * be anywhere. Search all items for a match up to the "@en". */
4298 for (j = 0; j < num_file; ++j)
4299 if (j != i
4300 && (int)STRLEN(file[j]) == len + 3
4301 && STRNCMP(file[i], file[j], len + 1) == 0)
4302 break;
4303 if (j == num_file)
4304 file[i][len] = NUL;
4308 #endif
4311 * Do the expansion based on xp->xp_context and "pat".
4313 static int
4314 ExpandFromContext(xp, pat, num_file, file, options)
4315 expand_T *xp;
4316 char_u *pat;
4317 int *num_file;
4318 char_u ***file;
4319 int options;
4321 #ifdef FEAT_CMDL_COMPL
4322 regmatch_T regmatch;
4323 #endif
4324 int ret;
4325 int flags;
4327 flags = EW_DIR; /* include directories */
4328 if (options & WILD_LIST_NOTFOUND)
4329 flags |= EW_NOTFOUND;
4330 if (options & WILD_ADD_SLASH)
4331 flags |= EW_ADDSLASH;
4332 if (options & WILD_KEEP_ALL)
4333 flags |= EW_KEEPALL;
4334 if (options & WILD_SILENT)
4335 flags |= EW_SILENT;
4337 if (xp->xp_context == EXPAND_FILES || xp->xp_context == EXPAND_DIRECTORIES)
4340 * Expand file or directory names.
4342 int free_pat = FALSE;
4343 int i;
4345 /* for ":set path=" and ":set tags=" halve backslashes for escaped
4346 * space */
4347 if (xp->xp_backslash != XP_BS_NONE)
4349 free_pat = TRUE;
4350 pat = vim_strsave(pat);
4351 for (i = 0; pat[i]; ++i)
4352 if (pat[i] == '\\')
4354 if (xp->xp_backslash == XP_BS_THREE
4355 && pat[i + 1] == '\\'
4356 && pat[i + 2] == '\\'
4357 && pat[i + 3] == ' ')
4358 STRMOVE(pat + i, pat + i + 3);
4359 if (xp->xp_backslash == XP_BS_ONE
4360 && pat[i + 1] == ' ')
4361 STRMOVE(pat + i, pat + i + 1);
4365 if (xp->xp_context == EXPAND_FILES)
4366 flags |= EW_FILE;
4367 else
4368 flags = (flags | EW_DIR) & ~EW_FILE;
4369 ret = expand_wildcards(1, &pat, num_file, file, flags);
4370 if (free_pat)
4371 vim_free(pat);
4372 return ret;
4375 *file = (char_u **)"";
4376 *num_file = 0;
4377 if (xp->xp_context == EXPAND_HELP)
4379 if (find_help_tags(pat, num_file, file, FALSE) == OK)
4381 #ifdef FEAT_MULTI_LANG
4382 cleanup_help_tags(*num_file, *file);
4383 #endif
4384 return OK;
4386 return FAIL;
4389 #ifndef FEAT_CMDL_COMPL
4390 return FAIL;
4391 #else
4392 if (xp->xp_context == EXPAND_SHELLCMD)
4393 return expand_shellcmd(pat, num_file, file, flags);
4394 if (xp->xp_context == EXPAND_OLD_SETTING)
4395 return ExpandOldSetting(num_file, file);
4396 if (xp->xp_context == EXPAND_BUFFERS)
4397 return ExpandBufnames(pat, num_file, file, options);
4398 if (xp->xp_context == EXPAND_TAGS
4399 || xp->xp_context == EXPAND_TAGS_LISTFILES)
4400 return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
4401 if (xp->xp_context == EXPAND_COLORS)
4402 return ExpandRTDir(pat, num_file, file, "colors");
4403 if (xp->xp_context == EXPAND_COMPILER)
4404 return ExpandRTDir(pat, num_file, file, "compiler");
4405 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
4406 if (xp->xp_context == EXPAND_USER_LIST)
4407 return ExpandUserList(xp, num_file, file);
4408 # endif
4410 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
4411 if (regmatch.regprog == NULL)
4412 return FAIL;
4414 /* set ignore-case according to p_ic, p_scs and pat */
4415 regmatch.rm_ic = ignorecase(pat);
4417 if (xp->xp_context == EXPAND_SETTINGS
4418 || xp->xp_context == EXPAND_BOOL_SETTINGS)
4419 ret = ExpandSettings(xp, &regmatch, num_file, file);
4420 else if (xp->xp_context == EXPAND_MAPPINGS)
4421 ret = ExpandMappings(&regmatch, num_file, file);
4422 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
4423 else if (xp->xp_context == EXPAND_USER_DEFINED)
4424 ret = ExpandUserDefined(xp, &regmatch, num_file, file);
4425 # endif
4426 else
4428 static struct expgen
4430 int context;
4431 char_u *((*func)__ARGS((expand_T *, int)));
4432 int ic;
4433 } tab[] =
4435 {EXPAND_COMMANDS, get_command_name, FALSE},
4436 #ifdef FEAT_USR_CMDS
4437 {EXPAND_USER_COMMANDS, get_user_commands, FALSE},
4438 {EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE},
4439 {EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE},
4440 {EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE},
4441 #endif
4442 #ifdef FEAT_EVAL
4443 {EXPAND_USER_VARS, get_user_var_name, FALSE},
4444 {EXPAND_FUNCTIONS, get_function_name, FALSE},
4445 {EXPAND_USER_FUNC, get_user_func_name, FALSE},
4446 {EXPAND_EXPRESSION, get_expr_name, FALSE},
4447 #endif
4448 #ifdef FEAT_MENU
4449 {EXPAND_MENUS, get_menu_name, FALSE},
4450 {EXPAND_MENUNAMES, get_menu_names, FALSE},
4451 #endif
4452 #ifdef FEAT_SYN_HL
4453 {EXPAND_SYNTAX, get_syntax_name, TRUE},
4454 #endif
4455 {EXPAND_HIGHLIGHT, get_highlight_name, TRUE},
4456 #ifdef FEAT_AUTOCMD
4457 {EXPAND_EVENTS, get_event_name, TRUE},
4458 {EXPAND_AUGROUP, get_augroup_name, TRUE},
4459 #endif
4460 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
4461 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
4462 {EXPAND_LANGUAGE, get_lang_arg, TRUE},
4463 #endif
4464 {EXPAND_ENV_VARS, get_env_name, TRUE},
4466 int i;
4469 * Find a context in the table and call the ExpandGeneric() with the
4470 * right function to do the expansion.
4472 ret = FAIL;
4473 for (i = 0; i < sizeof(tab) / sizeof(struct expgen); ++i)
4474 if (xp->xp_context == tab[i].context)
4476 if (tab[i].ic)
4477 regmatch.rm_ic = TRUE;
4478 ret = ExpandGeneric(xp, &regmatch, num_file, file, tab[i].func);
4479 break;
4483 vim_free(regmatch.regprog);
4485 return ret;
4486 #endif /* FEAT_CMDL_COMPL */
4489 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4491 * Expand a list of names.
4493 * Generic function for command line completion. It calls a function to
4494 * obtain strings, one by one. The strings are matched against a regexp
4495 * program. Matching strings are copied into an array, which is returned.
4497 * Returns OK when no problems encountered, FAIL for error (out of memory).
4500 ExpandGeneric(xp, regmatch, num_file, file, func)
4501 expand_T *xp;
4502 regmatch_T *regmatch;
4503 int *num_file;
4504 char_u ***file;
4505 char_u *((*func)__ARGS((expand_T *, int)));
4506 /* returns a string from the list */
4508 int i;
4509 int count = 0;
4510 int round;
4511 char_u *str;
4513 /* do this loop twice:
4514 * round == 0: count the number of matching names
4515 * round == 1: copy the matching names into allocated memory
4517 for (round = 0; round <= 1; ++round)
4519 for (i = 0; ; ++i)
4521 str = (*func)(xp, i);
4522 if (str == NULL) /* end of list */
4523 break;
4524 if (*str == NUL) /* skip empty strings */
4525 continue;
4527 if (vim_regexec(regmatch, str, (colnr_T)0))
4529 if (round)
4531 str = vim_strsave_escaped(str, (char_u *)" \t\\.");
4532 (*file)[count] = str;
4533 #ifdef FEAT_MENU
4534 if (func == get_menu_names && str != NULL)
4536 /* test for separator added by get_menu_names() */
4537 str += STRLEN(str) - 1;
4538 if (*str == '\001')
4539 *str = '.';
4541 #endif
4543 ++count;
4546 if (round == 0)
4548 if (count == 0)
4549 return OK;
4550 *num_file = count;
4551 *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
4552 if (*file == NULL)
4554 *file = (char_u **)"";
4555 return FAIL;
4557 count = 0;
4561 /* Sort the results. Keep menu's in the specified order. */
4562 if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
4563 sort_strings(*file, *num_file);
4565 #ifdef FEAT_CMDL_COMPL
4566 /* Reset the variables used for special highlight names expansion, so that
4567 * they don't show up when getting normal highlight names by ID. */
4568 reset_expand_highlight();
4569 #endif
4571 return OK;
4575 * Complete a shell command.
4576 * Returns FAIL or OK;
4578 static int
4579 expand_shellcmd(filepat, num_file, file, flagsarg)
4580 char_u *filepat; /* pattern to match with command names */
4581 int *num_file; /* return: number of matches */
4582 char_u ***file; /* return: array with matches */
4583 int flagsarg; /* EW_ flags */
4585 char_u *pat;
4586 int i;
4587 char_u *path;
4588 int mustfree = FALSE;
4589 garray_T ga;
4590 char_u *buf = alloc(MAXPATHL);
4591 size_t l;
4592 char_u *s, *e;
4593 int flags = flagsarg;
4594 int ret;
4596 if (buf == NULL)
4597 return FAIL;
4599 /* for ":set path=" and ":set tags=" halve backslashes for escaped
4600 * space */
4601 pat = vim_strsave(filepat);
4602 for (i = 0; pat[i]; ++i)
4603 if (pat[i] == '\\' && pat[i + 1] == ' ')
4604 STRMOVE(pat + i, pat + i + 1);
4606 flags |= EW_FILE | EW_EXEC;
4608 /* For an absolute name we don't use $PATH. */
4609 if (mch_isFullName(pat))
4610 path = (char_u *)" ";
4611 else if ((pat[0] == '.' && (vim_ispathsep(pat[1])
4612 || (pat[1] == '.' && vim_ispathsep(pat[2])))))
4613 path = (char_u *)".";
4614 else
4615 path = vim_getenv((char_u *)"PATH", &mustfree);
4618 * Go over all directories in $PATH. Expand matches in that directory and
4619 * collect them in "ga".
4621 ga_init2(&ga, (int)sizeof(char *), 10);
4622 for (s = path; *s != NUL; s = e)
4624 if (*s == ' ')
4625 ++s; /* Skip space used for absolute path name. */
4627 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4628 e = vim_strchr(s, ';');
4629 #else
4630 e = vim_strchr(s, ':');
4631 #endif
4632 if (e == NULL)
4633 e = s + STRLEN(s);
4635 l = e - s;
4636 if (l > MAXPATHL - 5)
4637 break;
4638 vim_strncpy(buf, s, l);
4639 add_pathsep(buf);
4640 l = STRLEN(buf);
4641 vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
4643 /* Expand matches in one directory of $PATH. */
4644 ret = expand_wildcards(1, &buf, num_file, file, flags);
4645 if (ret == OK)
4647 if (ga_grow(&ga, *num_file) == FAIL)
4648 FreeWild(*num_file, *file);
4649 else
4651 for (i = 0; i < *num_file; ++i)
4653 s = (*file)[i];
4654 if (STRLEN(s) > l)
4656 /* Remove the path again. */
4657 STRMOVE(s, s + l);
4658 ((char_u **)ga.ga_data)[ga.ga_len++] = s;
4660 else
4661 vim_free(s);
4663 vim_free(*file);
4666 if (*e != NUL)
4667 ++e;
4669 *file = ga.ga_data;
4670 *num_file = ga.ga_len;
4672 vim_free(buf);
4673 vim_free(pat);
4674 if (mustfree)
4675 vim_free(path);
4676 return OK;
4680 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
4681 static void * call_user_expand_func __ARGS((void *(*user_expand_func) __ARGS((char_u *, int, char_u **, int)), expand_T *xp, int *num_file, char_u ***file));
4684 * Call "user_expand_func()" to invoke a user defined VimL function and return
4685 * the result (either a string or a List).
4687 static void *
4688 call_user_expand_func(user_expand_func, xp, num_file, file)
4689 void *(*user_expand_func) __ARGS((char_u *, int, char_u **, int));
4690 expand_T *xp;
4691 int *num_file;
4692 char_u ***file;
4694 char_u keep;
4695 char_u num[50];
4696 char_u *args[3];
4697 int save_current_SID = current_SID;
4698 void *ret;
4699 struct cmdline_info save_ccline;
4701 if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0')
4702 return NULL;
4703 *num_file = 0;
4704 *file = NULL;
4706 if (ccline.cmdbuff == NULL)
4708 /* Completion from Insert mode, pass fake arguments. */
4709 keep = 0;
4710 sprintf((char *)num, "%d", (int)STRLEN(xp->xp_pattern));
4711 args[1] = xp->xp_pattern;
4713 else
4715 /* Completion on the command line, pass real arguments. */
4716 keep = ccline.cmdbuff[ccline.cmdlen];
4717 ccline.cmdbuff[ccline.cmdlen] = 0;
4718 sprintf((char *)num, "%d", ccline.cmdpos);
4719 args[1] = ccline.cmdbuff;
4721 args[0] = xp->xp_pattern;
4722 args[2] = num;
4724 /* Save the cmdline, we don't know what the function may do. */
4725 save_ccline = ccline;
4726 ccline.cmdbuff = NULL;
4727 ccline.cmdprompt = NULL;
4728 current_SID = xp->xp_scriptID;
4730 ret = user_expand_func(xp->xp_arg, 3, args, FALSE);
4732 ccline = save_ccline;
4733 current_SID = save_current_SID;
4734 if (ccline.cmdbuff != NULL)
4735 ccline.cmdbuff[ccline.cmdlen] = keep;
4737 return ret;
4741 * Expand names with a function defined by the user.
4743 static int
4744 ExpandUserDefined(xp, regmatch, num_file, file)
4745 expand_T *xp;
4746 regmatch_T *regmatch;
4747 int *num_file;
4748 char_u ***file;
4750 char_u *retstr;
4751 char_u *s;
4752 char_u *e;
4753 char_u keep;
4754 garray_T ga;
4756 retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
4757 if (retstr == NULL)
4758 return FAIL;
4760 ga_init2(&ga, (int)sizeof(char *), 3);
4761 for (s = retstr; *s != NUL; s = e)
4763 e = vim_strchr(s, '\n');
4764 if (e == NULL)
4765 e = s + STRLEN(s);
4766 keep = *e;
4767 *e = 0;
4769 if (xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0)
4771 *e = keep;
4772 if (*e != NUL)
4773 ++e;
4774 continue;
4777 if (ga_grow(&ga, 1) == FAIL)
4778 break;
4780 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
4781 ++ga.ga_len;
4783 *e = keep;
4784 if (*e != NUL)
4785 ++e;
4787 vim_free(retstr);
4788 *file = ga.ga_data;
4789 *num_file = ga.ga_len;
4790 return OK;
4794 * Expand names with a list returned by a function defined by the user.
4796 static int
4797 ExpandUserList(xp, num_file, file)
4798 expand_T *xp;
4799 int *num_file;
4800 char_u ***file;
4802 list_T *retlist;
4803 listitem_T *li;
4804 garray_T ga;
4806 retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
4807 if (retlist == NULL)
4808 return FAIL;
4810 ga_init2(&ga, (int)sizeof(char *), 3);
4811 /* Loop over the items in the list. */
4812 for (li = retlist->lv_first; li != NULL; li = li->li_next)
4814 if (li->li_tv.v_type != VAR_STRING)
4815 continue; /* Skip non-string items */
4817 if (ga_grow(&ga, 1) == FAIL)
4818 break;
4820 ((char_u **)ga.ga_data)[ga.ga_len] =
4821 vim_strsave(li->li_tv.vval.v_string);
4822 ++ga.ga_len;
4824 list_unref(retlist);
4826 *file = ga.ga_data;
4827 *num_file = ga.ga_len;
4828 return OK;
4830 #endif
4833 * Expand color scheme names: 'runtimepath'/colors/{pat}.vim
4834 * or compiler names.
4836 static int
4837 ExpandRTDir(pat, num_file, file, dirname)
4838 char_u *pat;
4839 int *num_file;
4840 char_u ***file;
4841 char *dirname; /* "colors" or "compiler" */
4843 char_u *all;
4844 char_u *s;
4845 char_u *e;
4846 garray_T ga;
4848 *num_file = 0;
4849 *file = NULL;
4850 s = alloc((unsigned)(STRLEN(pat) + STRLEN(dirname) + 7));
4851 if (s == NULL)
4852 return FAIL;
4853 sprintf((char *)s, "%s/%s*.vim", dirname, pat);
4854 all = globpath(p_rtp, s);
4855 vim_free(s);
4856 if (all == NULL)
4857 return FAIL;
4859 ga_init2(&ga, (int)sizeof(char *), 3);
4860 for (s = all; *s != NUL; s = e)
4862 e = vim_strchr(s, '\n');
4863 if (e == NULL)
4864 e = s + STRLEN(s);
4865 if (ga_grow(&ga, 1) == FAIL)
4866 break;
4867 if (e - 4 > s && STRNICMP(e - 4, ".vim", 4) == 0)
4869 for (s = e - 4; s > all; mb_ptr_back(all, s))
4870 if (*s == '\n' || vim_ispathsep(*s))
4871 break;
4872 ++s;
4873 ((char_u **)ga.ga_data)[ga.ga_len] =
4874 vim_strnsave(s, (int)(e - s - 4));
4875 ++ga.ga_len;
4877 if (*e != NUL)
4878 ++e;
4880 vim_free(all);
4881 *file = ga.ga_data;
4882 *num_file = ga.ga_len;
4883 return OK;
4886 #endif
4888 #if defined(FEAT_CMDL_COMPL) || defined(FEAT_EVAL) || defined(PROTO)
4890 * Expand "file" for all comma-separated directories in "path".
4891 * Returns an allocated string with all matches concatenated, separated by
4892 * newlines. Returns NULL for an error or no matches.
4894 char_u *
4895 globpath(path, file)
4896 char_u *path;
4897 char_u *file;
4899 expand_T xpc;
4900 char_u *buf;
4901 garray_T ga;
4902 int i;
4903 int len;
4904 int num_p;
4905 char_u **p;
4906 char_u *cur = NULL;
4908 buf = alloc(MAXPATHL);
4909 if (buf == NULL)
4910 return NULL;
4912 ExpandInit(&xpc);
4913 xpc.xp_context = EXPAND_FILES;
4915 ga_init2(&ga, 1, 100);
4917 /* Loop over all entries in {path}. */
4918 while (*path != NUL)
4920 /* Copy one item of the path to buf[] and concatenate the file name. */
4921 copy_option_part(&path, buf, MAXPATHL, ",");
4922 if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
4924 add_pathsep(buf);
4925 STRCAT(buf, file);
4926 if (ExpandFromContext(&xpc, buf, &num_p, &p, WILD_SILENT) != FAIL
4927 && num_p > 0)
4929 ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT);
4930 for (len = 0, i = 0; i < num_p; ++i)
4931 len += (int)STRLEN(p[i]) + 1;
4933 /* Concatenate new results to previous ones. */
4934 if (ga_grow(&ga, len) == OK)
4936 cur = (char_u *)ga.ga_data + ga.ga_len;
4937 for (i = 0; i < num_p; ++i)
4939 STRCPY(cur, p[i]);
4940 cur += STRLEN(p[i]);
4941 *cur++ = '\n';
4943 ga.ga_len += len;
4945 FreeWild(num_p, p);
4949 if (cur != NULL)
4950 *--cur = 0; /* Replace trailing newline with NUL */
4952 vim_free(buf);
4953 return (char_u *)ga.ga_data;
4956 #endif
4958 #if defined(FEAT_CMDHIST) || defined(PROTO)
4960 /*********************************
4961 * Command line history stuff *
4962 *********************************/
4965 * Translate a history character to the associated type number.
4967 static int
4968 hist_char2type(c)
4969 int c;
4971 if (c == ':')
4972 return HIST_CMD;
4973 if (c == '=')
4974 return HIST_EXPR;
4975 if (c == '@')
4976 return HIST_INPUT;
4977 if (c == '>')
4978 return HIST_DEBUG;
4979 return HIST_SEARCH; /* must be '?' or '/' */
4983 * Table of history names.
4984 * These names are used in :history and various hist...() functions.
4985 * It is sufficient to give the significant prefix of a history name.
4988 static char *(history_names[]) =
4990 "cmd",
4991 "search",
4992 "expr",
4993 "input",
4994 "debug",
4995 NULL
4999 * init_history() - Initialize the command line history.
5000 * Also used to re-allocate the history when the size changes.
5002 void
5003 init_history()
5005 int newlen; /* new length of history table */
5006 histentry_T *temp;
5007 int i;
5008 int j;
5009 int type;
5012 * If size of history table changed, reallocate it
5014 newlen = (int)p_hi;
5015 if (newlen != hislen) /* history length changed */
5017 for (type = 0; type < HIST_COUNT; ++type) /* adjust the tables */
5019 if (newlen)
5021 temp = (histentry_T *)lalloc(
5022 (long_u)(newlen * sizeof(histentry_T)), TRUE);
5023 if (temp == NULL) /* out of memory! */
5025 if (type == 0) /* first one: just keep the old length */
5027 newlen = hislen;
5028 break;
5030 /* Already changed one table, now we can only have zero
5031 * length for all tables. */
5032 newlen = 0;
5033 type = -1;
5034 continue;
5037 else
5038 temp = NULL;
5039 if (newlen == 0 || temp != NULL)
5041 if (hisidx[type] < 0) /* there are no entries yet */
5043 for (i = 0; i < newlen; ++i)
5045 temp[i].hisnum = 0;
5046 temp[i].hisstr = NULL;
5049 else if (newlen > hislen) /* array becomes bigger */
5051 for (i = 0; i <= hisidx[type]; ++i)
5052 temp[i] = history[type][i];
5053 j = i;
5054 for ( ; i <= newlen - (hislen - hisidx[type]); ++i)
5056 temp[i].hisnum = 0;
5057 temp[i].hisstr = NULL;
5059 for ( ; j < hislen; ++i, ++j)
5060 temp[i] = history[type][j];
5062 else /* array becomes smaller or 0 */
5064 j = hisidx[type];
5065 for (i = newlen - 1; ; --i)
5067 if (i >= 0) /* copy newest entries */
5068 temp[i] = history[type][j];
5069 else /* remove older entries */
5070 vim_free(history[type][j].hisstr);
5071 if (--j < 0)
5072 j = hislen - 1;
5073 if (j == hisidx[type])
5074 break;
5076 hisidx[type] = newlen - 1;
5078 vim_free(history[type]);
5079 history[type] = temp;
5082 hislen = newlen;
5087 * Check if command line 'str' is already in history.
5088 * If 'move_to_front' is TRUE, matching entry is moved to end of history.
5090 static int
5091 in_history(type, str, move_to_front)
5092 int type;
5093 char_u *str;
5094 int move_to_front; /* Move the entry to the front if it exists */
5096 int i;
5097 int last_i = -1;
5099 if (hisidx[type] < 0)
5100 return FALSE;
5101 i = hisidx[type];
5104 if (history[type][i].hisstr == NULL)
5105 return FALSE;
5106 if (STRCMP(str, history[type][i].hisstr) == 0)
5108 if (!move_to_front)
5109 return TRUE;
5110 last_i = i;
5111 break;
5113 if (--i < 0)
5114 i = hislen - 1;
5115 } while (i != hisidx[type]);
5117 if (last_i >= 0)
5119 str = history[type][i].hisstr;
5120 while (i != hisidx[type])
5122 if (++i >= hislen)
5123 i = 0;
5124 history[type][last_i] = history[type][i];
5125 last_i = i;
5127 history[type][i].hisstr = str;
5128 history[type][i].hisnum = ++hisnum[type];
5129 return TRUE;
5131 return FALSE;
5135 * Convert history name (from table above) to its HIST_ equivalent.
5136 * When "name" is empty, return "cmd" history.
5137 * Returns -1 for unknown history name.
5140 get_histtype(name)
5141 char_u *name;
5143 int i;
5144 int len = (int)STRLEN(name);
5146 /* No argument: use current history. */
5147 if (len == 0)
5148 return hist_char2type(ccline.cmdfirstc);
5150 for (i = 0; history_names[i] != NULL; ++i)
5151 if (STRNICMP(name, history_names[i], len) == 0)
5152 return i;
5154 if (vim_strchr((char_u *)":=@>?/", name[0]) != NULL && name[1] == NUL)
5155 return hist_char2type(name[0]);
5157 return -1;
5160 static int last_maptick = -1; /* last seen maptick */
5163 * Add the given string to the given history. If the string is already in the
5164 * history then it is moved to the front. "histype" may be one of he HIST_
5165 * values.
5167 void
5168 add_to_history(histype, new_entry, in_map, sep)
5169 int histype;
5170 char_u *new_entry;
5171 int in_map; /* consider maptick when inside a mapping */
5172 int sep; /* separator character used (search hist) */
5174 histentry_T *hisptr;
5175 int len;
5177 if (hislen == 0) /* no history */
5178 return;
5181 * Searches inside the same mapping overwrite each other, so that only
5182 * the last line is kept. Be careful not to remove a line that was moved
5183 * down, only lines that were added.
5185 if (histype == HIST_SEARCH && in_map)
5187 if (maptick == last_maptick)
5189 /* Current line is from the same mapping, remove it */
5190 hisptr = &history[HIST_SEARCH][hisidx[HIST_SEARCH]];
5191 vim_free(hisptr->hisstr);
5192 hisptr->hisstr = NULL;
5193 hisptr->hisnum = 0;
5194 --hisnum[histype];
5195 if (--hisidx[HIST_SEARCH] < 0)
5196 hisidx[HIST_SEARCH] = hislen - 1;
5198 last_maptick = -1;
5200 if (!in_history(histype, new_entry, TRUE))
5202 if (++hisidx[histype] == hislen)
5203 hisidx[histype] = 0;
5204 hisptr = &history[histype][hisidx[histype]];
5205 vim_free(hisptr->hisstr);
5207 /* Store the separator after the NUL of the string. */
5208 len = (int)STRLEN(new_entry);
5209 hisptr->hisstr = vim_strnsave(new_entry, len + 2);
5210 if (hisptr->hisstr != NULL)
5211 hisptr->hisstr[len + 1] = sep;
5213 hisptr->hisnum = ++hisnum[histype];
5214 if (histype == HIST_SEARCH && in_map)
5215 last_maptick = maptick;
5219 #if defined(FEAT_EVAL) || defined(PROTO)
5222 * Get identifier of newest history entry.
5223 * "histype" may be one of the HIST_ values.
5226 get_history_idx(histype)
5227 int histype;
5229 if (hislen == 0 || histype < 0 || histype >= HIST_COUNT
5230 || hisidx[histype] < 0)
5231 return -1;
5233 return history[histype][hisidx[histype]].hisnum;
5236 static struct cmdline_info *get_ccline_ptr __ARGS((void));
5239 * Get pointer to the command line info to use. cmdline_paste() may clear
5240 * ccline and put the previous value in prev_ccline.
5242 static struct cmdline_info *
5243 get_ccline_ptr()
5245 if ((State & CMDLINE) == 0)
5246 return NULL;
5247 if (ccline.cmdbuff != NULL)
5248 return &ccline;
5249 if (prev_ccline_used && prev_ccline.cmdbuff != NULL)
5250 return &prev_ccline;
5251 return NULL;
5255 * Get the current command line in allocated memory.
5256 * Only works when the command line is being edited.
5257 * Returns NULL when something is wrong.
5259 char_u *
5260 get_cmdline_str()
5262 struct cmdline_info *p = get_ccline_ptr();
5264 if (p == NULL)
5265 return NULL;
5266 return vim_strnsave(p->cmdbuff, p->cmdlen);
5270 * Get the current command line position, counted in bytes.
5271 * Zero is the first position.
5272 * Only works when the command line is being edited.
5273 * Returns -1 when something is wrong.
5276 get_cmdline_pos()
5278 struct cmdline_info *p = get_ccline_ptr();
5280 if (p == NULL)
5281 return -1;
5282 return p->cmdpos;
5286 * Set the command line byte position to "pos". Zero is the first position.
5287 * Only works when the command line is being edited.
5288 * Returns 1 when failed, 0 when OK.
5291 set_cmdline_pos(pos)
5292 int pos;
5294 struct cmdline_info *p = get_ccline_ptr();
5296 if (p == NULL)
5297 return 1;
5299 /* The position is not set directly but after CTRL-\ e or CTRL-R = has
5300 * changed the command line. */
5301 if (pos < 0)
5302 new_cmdpos = 0;
5303 else
5304 new_cmdpos = pos;
5305 return 0;
5309 * Get the current command-line type.
5310 * Returns ':' or '/' or '?' or '@' or '>' or '-'
5311 * Only works when the command line is being edited.
5312 * Returns NUL when something is wrong.
5315 get_cmdline_type()
5317 struct cmdline_info *p = get_ccline_ptr();
5319 if (p == NULL)
5320 return NUL;
5321 if (p->cmdfirstc == NUL)
5322 return (p->input_fn) ? '@' : '-';
5323 return p->cmdfirstc;
5327 * Calculate history index from a number:
5328 * num > 0: seen as identifying number of a history entry
5329 * num < 0: relative position in history wrt newest entry
5330 * "histype" may be one of the HIST_ values.
5332 static int
5333 calc_hist_idx(histype, num)
5334 int histype;
5335 int num;
5337 int i;
5338 histentry_T *hist;
5339 int wrapped = FALSE;
5341 if (hislen == 0 || histype < 0 || histype >= HIST_COUNT
5342 || (i = hisidx[histype]) < 0 || num == 0)
5343 return -1;
5345 hist = history[histype];
5346 if (num > 0)
5348 while (hist[i].hisnum > num)
5349 if (--i < 0)
5351 if (wrapped)
5352 break;
5353 i += hislen;
5354 wrapped = TRUE;
5356 if (hist[i].hisnum == num && hist[i].hisstr != NULL)
5357 return i;
5359 else if (-num <= hislen)
5361 i += num + 1;
5362 if (i < 0)
5363 i += hislen;
5364 if (hist[i].hisstr != NULL)
5365 return i;
5367 return -1;
5371 * Get a history entry by its index.
5372 * "histype" may be one of the HIST_ values.
5374 char_u *
5375 get_history_entry(histype, idx)
5376 int histype;
5377 int idx;
5379 idx = calc_hist_idx(histype, idx);
5380 if (idx >= 0)
5381 return history[histype][idx].hisstr;
5382 else
5383 return (char_u *)"";
5387 * Clear all entries of a history.
5388 * "histype" may be one of the HIST_ values.
5391 clr_history(histype)
5392 int histype;
5394 int i;
5395 histentry_T *hisptr;
5397 if (hislen != 0 && histype >= 0 && histype < HIST_COUNT)
5399 hisptr = history[histype];
5400 for (i = hislen; i--;)
5402 vim_free(hisptr->hisstr);
5403 hisptr->hisnum = 0;
5404 hisptr++->hisstr = NULL;
5406 hisidx[histype] = -1; /* mark history as cleared */
5407 hisnum[histype] = 0; /* reset identifier counter */
5408 return OK;
5410 return FAIL;
5414 * Remove all entries matching {str} from a history.
5415 * "histype" may be one of the HIST_ values.
5418 del_history_entry(histype, str)
5419 int histype;
5420 char_u *str;
5422 regmatch_T regmatch;
5423 histentry_T *hisptr;
5424 int idx;
5425 int i;
5426 int last;
5427 int found = FALSE;
5429 regmatch.regprog = NULL;
5430 regmatch.rm_ic = FALSE; /* always match case */
5431 if (hislen != 0
5432 && histype >= 0
5433 && histype < HIST_COUNT
5434 && *str != NUL
5435 && (idx = hisidx[histype]) >= 0
5436 && (regmatch.regprog = vim_regcomp(str, RE_MAGIC + RE_STRING))
5437 != NULL)
5439 i = last = idx;
5442 hisptr = &history[histype][i];
5443 if (hisptr->hisstr == NULL)
5444 break;
5445 if (vim_regexec(&regmatch, hisptr->hisstr, (colnr_T)0))
5447 found = TRUE;
5448 vim_free(hisptr->hisstr);
5449 hisptr->hisstr = NULL;
5450 hisptr->hisnum = 0;
5452 else
5454 if (i != last)
5456 history[histype][last] = *hisptr;
5457 hisptr->hisstr = NULL;
5458 hisptr->hisnum = 0;
5460 if (--last < 0)
5461 last += hislen;
5463 if (--i < 0)
5464 i += hislen;
5465 } while (i != idx);
5466 if (history[histype][idx].hisstr == NULL)
5467 hisidx[histype] = -1;
5469 vim_free(regmatch.regprog);
5470 return found;
5474 * Remove an indexed entry from a history.
5475 * "histype" may be one of the HIST_ values.
5478 del_history_idx(histype, idx)
5479 int histype;
5480 int idx;
5482 int i, j;
5484 i = calc_hist_idx(histype, idx);
5485 if (i < 0)
5486 return FALSE;
5487 idx = hisidx[histype];
5488 vim_free(history[histype][i].hisstr);
5490 /* When deleting the last added search string in a mapping, reset
5491 * last_maptick, so that the last added search string isn't deleted again.
5493 if (histype == HIST_SEARCH && maptick == last_maptick && i == idx)
5494 last_maptick = -1;
5496 while (i != idx)
5498 j = (i + 1) % hislen;
5499 history[histype][i] = history[histype][j];
5500 i = j;
5502 history[histype][i].hisstr = NULL;
5503 history[histype][i].hisnum = 0;
5504 if (--i < 0)
5505 i += hislen;
5506 hisidx[histype] = i;
5507 return TRUE;
5510 #endif /* FEAT_EVAL */
5512 #if defined(FEAT_CRYPT) || defined(PROTO)
5514 * Very specific function to remove the value in ":set key=val" from the
5515 * history.
5517 void
5518 remove_key_from_history()
5520 char_u *p;
5521 int i;
5523 i = hisidx[HIST_CMD];
5524 if (i < 0)
5525 return;
5526 p = history[HIST_CMD][i].hisstr;
5527 if (p != NULL)
5528 for ( ; *p; ++p)
5529 if (STRNCMP(p, "key", 3) == 0 && !isalpha(p[3]))
5531 p = vim_strchr(p + 3, '=');
5532 if (p == NULL)
5533 break;
5534 ++p;
5535 for (i = 0; p[i] && !vim_iswhite(p[i]); ++i)
5536 if (p[i] == '\\' && p[i + 1])
5537 ++i;
5538 STRMOVE(p, p + i);
5539 --p;
5542 #endif
5544 #endif /* FEAT_CMDHIST */
5546 #if defined(FEAT_QUICKFIX) || defined(FEAT_CMDHIST) || defined(PROTO)
5548 * Get indices "num1,num2" that specify a range within a list (not a range of
5549 * text lines in a buffer!) from a string. Used for ":history" and ":clist".
5550 * Returns OK if parsed successfully, otherwise FAIL.
5553 get_list_range(str, num1, num2)
5554 char_u **str;
5555 int *num1;
5556 int *num2;
5558 int len;
5559 int first = FALSE;
5560 long num;
5562 *str = skipwhite(*str);
5563 if (**str == '-' || vim_isdigit(**str)) /* parse "from" part of range */
5565 vim_str2nr(*str, NULL, &len, FALSE, FALSE, &num, NULL);
5566 *str += len;
5567 *num1 = (int)num;
5568 first = TRUE;
5570 *str = skipwhite(*str);
5571 if (**str == ',') /* parse "to" part of range */
5573 *str = skipwhite(*str + 1);
5574 vim_str2nr(*str, NULL, &len, FALSE, FALSE, &num, NULL);
5575 if (len > 0)
5577 *num2 = (int)num;
5578 *str = skipwhite(*str + len);
5580 else if (!first) /* no number given at all */
5581 return FAIL;
5583 else if (first) /* only one number given */
5584 *num2 = *num1;
5585 return OK;
5587 #endif
5589 #if defined(FEAT_CMDHIST) || defined(PROTO)
5591 * :history command - print a history
5593 void
5594 ex_history(eap)
5595 exarg_T *eap;
5597 histentry_T *hist;
5598 int histype1 = HIST_CMD;
5599 int histype2 = HIST_CMD;
5600 int hisidx1 = 1;
5601 int hisidx2 = -1;
5602 int idx;
5603 int i, j, k;
5604 char_u *end;
5605 char_u *arg = eap->arg;
5607 if (hislen == 0)
5609 MSG(_("'history' option is zero"));
5610 return;
5613 if (!(VIM_ISDIGIT(*arg) || *arg == '-' || *arg == ','))
5615 end = arg;
5616 while (ASCII_ISALPHA(*end)
5617 || vim_strchr((char_u *)":=@>/?", *end) != NULL)
5618 end++;
5619 i = *end;
5620 *end = NUL;
5621 histype1 = get_histtype(arg);
5622 if (histype1 == -1)
5624 if (STRICMP(arg, "all") == 0)
5626 histype1 = 0;
5627 histype2 = HIST_COUNT-1;
5629 else
5631 *end = i;
5632 EMSG(_(e_trailing));
5633 return;
5636 else
5637 histype2 = histype1;
5638 *end = i;
5640 else
5641 end = arg;
5642 if (!get_list_range(&end, &hisidx1, &hisidx2) || *end != NUL)
5644 EMSG(_(e_trailing));
5645 return;
5648 for (; !got_int && histype1 <= histype2; ++histype1)
5650 STRCPY(IObuff, "\n # ");
5651 STRCAT(STRCAT(IObuff, history_names[histype1]), " history");
5652 MSG_PUTS_TITLE(IObuff);
5653 idx = hisidx[histype1];
5654 hist = history[histype1];
5655 j = hisidx1;
5656 k = hisidx2;
5657 if (j < 0)
5658 j = (-j > hislen) ? 0 : hist[(hislen+j+idx+1) % hislen].hisnum;
5659 if (k < 0)
5660 k = (-k > hislen) ? 0 : hist[(hislen+k+idx+1) % hislen].hisnum;
5661 if (idx >= 0 && j <= k)
5662 for (i = idx + 1; !got_int; ++i)
5664 if (i == hislen)
5665 i = 0;
5666 if (hist[i].hisstr != NULL
5667 && hist[i].hisnum >= j && hist[i].hisnum <= k)
5669 msg_putchar('\n');
5670 sprintf((char *)IObuff, "%c%6d ", i == idx ? '>' : ' ',
5671 hist[i].hisnum);
5672 if (vim_strsize(hist[i].hisstr) > (int)Columns - 10)
5673 trunc_string(hist[i].hisstr, IObuff + STRLEN(IObuff),
5674 (int)Columns - 10);
5675 else
5676 STRCAT(IObuff, hist[i].hisstr);
5677 msg_outtrans(IObuff);
5678 out_flush();
5680 if (i == idx)
5681 break;
5685 #endif
5687 #if (defined(FEAT_VIMINFO) && defined(FEAT_CMDHIST)) || defined(PROTO)
5688 static char_u **viminfo_history[HIST_COUNT] = {NULL, NULL, NULL, NULL};
5689 static int viminfo_hisidx[HIST_COUNT] = {0, 0, 0, 0};
5690 static int viminfo_hislen[HIST_COUNT] = {0, 0, 0, 0};
5691 static int viminfo_add_at_front = FALSE;
5693 static int hist_type2char __ARGS((int type, int use_question));
5696 * Translate a history type number to the associated character.
5698 static int
5699 hist_type2char(type, use_question)
5700 int type;
5701 int use_question; /* use '?' instead of '/' */
5703 if (type == HIST_CMD)
5704 return ':';
5705 if (type == HIST_SEARCH)
5707 if (use_question)
5708 return '?';
5709 else
5710 return '/';
5712 if (type == HIST_EXPR)
5713 return '=';
5714 return '@';
5718 * Prepare for reading the history from the viminfo file.
5719 * This allocates history arrays to store the read history lines.
5721 void
5722 prepare_viminfo_history(asklen)
5723 int asklen;
5725 int i;
5726 int num;
5727 int type;
5728 int len;
5730 init_history();
5731 viminfo_add_at_front = (asklen != 0);
5732 if (asklen > hislen)
5733 asklen = hislen;
5735 for (type = 0; type < HIST_COUNT; ++type)
5738 * Count the number of empty spaces in the history list. If there are
5739 * more spaces available than we request, then fill them up.
5741 for (i = 0, num = 0; i < hislen; i++)
5742 if (history[type][i].hisstr == NULL)
5743 num++;
5744 len = asklen;
5745 if (num > len)
5746 len = num;
5747 if (len <= 0)
5748 viminfo_history[type] = NULL;
5749 else
5750 viminfo_history[type] =
5751 (char_u **)lalloc((long_u)(len * sizeof(char_u *)), FALSE);
5752 if (viminfo_history[type] == NULL)
5753 len = 0;
5754 viminfo_hislen[type] = len;
5755 viminfo_hisidx[type] = 0;
5760 * Accept a line from the viminfo, store it in the history array when it's
5761 * new.
5764 read_viminfo_history(virp)
5765 vir_T *virp;
5767 int type;
5768 long_u len;
5769 char_u *val;
5770 char_u *p;
5772 type = hist_char2type(virp->vir_line[0]);
5773 if (viminfo_hisidx[type] < viminfo_hislen[type])
5775 val = viminfo_readstring(virp, 1, TRUE);
5776 if (val != NULL && *val != NUL)
5778 if (!in_history(type, val + (type == HIST_SEARCH),
5779 viminfo_add_at_front))
5781 /* Need to re-allocate to append the separator byte. */
5782 len = STRLEN(val);
5783 p = lalloc(len + 2, TRUE);
5784 if (p != NULL)
5786 if (type == HIST_SEARCH)
5788 /* Search entry: Move the separator from the first
5789 * column to after the NUL. */
5790 mch_memmove(p, val + 1, (size_t)len);
5791 p[len] = (*val == ' ' ? NUL : *val);
5793 else
5795 /* Not a search entry: No separator in the viminfo
5796 * file, add a NUL separator. */
5797 mch_memmove(p, val, (size_t)len + 1);
5798 p[len + 1] = NUL;
5800 viminfo_history[type][viminfo_hisidx[type]++] = p;
5804 vim_free(val);
5806 return viminfo_readline(virp);
5809 void
5810 finish_viminfo_history()
5812 int idx;
5813 int i;
5814 int type;
5816 for (type = 0; type < HIST_COUNT; ++type)
5818 if (history[type] == NULL)
5819 return;
5820 idx = hisidx[type] + viminfo_hisidx[type];
5821 if (idx >= hislen)
5822 idx -= hislen;
5823 else if (idx < 0)
5824 idx = hislen - 1;
5825 if (viminfo_add_at_front)
5826 hisidx[type] = idx;
5827 else
5829 if (hisidx[type] == -1)
5830 hisidx[type] = hislen - 1;
5833 if (history[type][idx].hisstr != NULL)
5834 break;
5835 if (++idx == hislen)
5836 idx = 0;
5837 } while (idx != hisidx[type]);
5838 if (idx != hisidx[type] && --idx < 0)
5839 idx = hislen - 1;
5841 for (i = 0; i < viminfo_hisidx[type]; i++)
5843 vim_free(history[type][idx].hisstr);
5844 history[type][idx].hisstr = viminfo_history[type][i];
5845 if (--idx < 0)
5846 idx = hislen - 1;
5848 idx += 1;
5849 idx %= hislen;
5850 for (i = 0; i < viminfo_hisidx[type]; i++)
5852 history[type][idx++].hisnum = ++hisnum[type];
5853 idx %= hislen;
5855 vim_free(viminfo_history[type]);
5856 viminfo_history[type] = NULL;
5860 void
5861 write_viminfo_history(fp)
5862 FILE *fp;
5864 int i;
5865 int type;
5866 int num_saved;
5867 char_u *p;
5868 int c;
5870 init_history();
5871 if (hislen == 0)
5872 return;
5873 for (type = 0; type < HIST_COUNT; ++type)
5875 num_saved = get_viminfo_parameter(hist_type2char(type, FALSE));
5876 if (num_saved == 0)
5877 continue;
5878 if (num_saved < 0) /* Use default */
5879 num_saved = hislen;
5880 fprintf(fp, _("\n# %s History (newest to oldest):\n"),
5881 type == HIST_CMD ? _("Command Line") :
5882 type == HIST_SEARCH ? _("Search String") :
5883 type == HIST_EXPR ? _("Expression") :
5884 _("Input Line"));
5885 if (num_saved > hislen)
5886 num_saved = hislen;
5887 i = hisidx[type];
5888 if (i >= 0)
5889 while (num_saved--)
5891 p = history[type][i].hisstr;
5892 if (p != NULL)
5894 fputc(hist_type2char(type, TRUE), fp);
5895 /* For the search history: put the separator in the second
5896 * column; use a space if there isn't one. */
5897 if (type == HIST_SEARCH)
5899 c = p[STRLEN(p) + 1];
5900 putc(c == NUL ? ' ' : c, fp);
5902 viminfo_writestring(fp, p);
5904 if (--i < 0)
5905 i = hislen - 1;
5909 #endif /* FEAT_VIMINFO */
5911 #if defined(FEAT_FKMAP) || defined(PROTO)
5913 * Write a character at the current cursor+offset position.
5914 * It is directly written into the command buffer block.
5916 void
5917 cmd_pchar(c, offset)
5918 int c, offset;
5920 if (ccline.cmdpos + offset >= ccline.cmdlen || ccline.cmdpos + offset < 0)
5922 EMSG(_("E198: cmd_pchar beyond the command length"));
5923 return;
5925 ccline.cmdbuff[ccline.cmdpos + offset] = (char_u)c;
5926 ccline.cmdbuff[ccline.cmdlen] = NUL;
5930 cmd_gchar(offset)
5931 int offset;
5933 if (ccline.cmdpos + offset >= ccline.cmdlen || ccline.cmdpos + offset < 0)
5935 /* EMSG(_("cmd_gchar beyond the command length")); */
5936 return NUL;
5938 return (int)ccline.cmdbuff[ccline.cmdpos + offset];
5940 #endif
5942 #if defined(FEAT_CMDWIN) || defined(PROTO)
5944 * Open a window on the current command line and history. Allow editing in
5945 * the window. Returns when the window is closed.
5946 * Returns:
5947 * CR if the command is to be executed
5948 * Ctrl_C if it is to be abandoned
5949 * K_IGNORE if editing continues
5951 static int
5952 ex_window()
5954 struct cmdline_info save_ccline;
5955 buf_T *old_curbuf = curbuf;
5956 win_T *old_curwin = curwin;
5957 buf_T *bp;
5958 win_T *wp;
5959 int i;
5960 linenr_T lnum;
5961 int histtype;
5962 garray_T winsizes;
5963 char_u typestr[2];
5964 int save_restart_edit = restart_edit;
5965 int save_State = State;
5966 int save_exmode = exmode_active;
5967 #ifdef FEAT_RIGHTLEFT
5968 int save_cmdmsg_rl = cmdmsg_rl;
5969 #endif
5971 /* Can't do this recursively. Can't do it when typing a password. */
5972 if (cmdwin_type != 0
5973 # if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
5974 || cmdline_star > 0
5975 # endif
5978 beep_flush();
5979 return K_IGNORE;
5982 /* Save current window sizes. */
5983 win_size_save(&winsizes);
5985 # ifdef FEAT_AUTOCMD
5986 /* Don't execute autocommands while creating the window. */
5987 block_autocmds();
5988 # endif
5989 /* don't use a new tab page */
5990 cmdmod.tab = 0;
5992 /* Create a window for the command-line buffer. */
5993 if (win_split((int)p_cwh, WSP_BOT) == FAIL)
5995 beep_flush();
5996 # ifdef FEAT_AUTOCMD
5997 unblock_autocmds();
5998 # endif
5999 return K_IGNORE;
6001 cmdwin_type = ccline.cmdfirstc;
6002 if (cmdwin_type == NUL)
6003 cmdwin_type = '-';
6005 /* Create the command-line buffer empty. */
6006 (void)do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE);
6007 (void)setfname(curbuf, (char_u *)"[Command Line]", NULL, TRUE);
6008 set_option_value((char_u *)"bt", 0L, (char_u *)"nofile", OPT_LOCAL);
6009 set_option_value((char_u *)"swf", 0L, NULL, OPT_LOCAL);
6010 curbuf->b_p_ma = TRUE;
6011 # ifdef FEAT_RIGHTLEFT
6012 curwin->w_p_rl = cmdmsg_rl;
6013 cmdmsg_rl = FALSE;
6014 # endif
6015 # ifdef FEAT_SCROLLBIND
6016 curwin->w_p_scb = FALSE;
6017 # endif
6019 # ifdef FEAT_AUTOCMD
6020 /* Do execute autocommands for setting the filetype (load syntax). */
6021 unblock_autocmds();
6022 # endif
6024 /* Showing the prompt may have set need_wait_return, reset it. */
6025 need_wait_return = FALSE;
6027 histtype = hist_char2type(ccline.cmdfirstc);
6028 if (histtype == HIST_CMD || histtype == HIST_DEBUG)
6030 if (p_wc == TAB)
6032 add_map((char_u *)"<buffer> <Tab> <C-X><C-V>", INSERT);
6033 add_map((char_u *)"<buffer> <Tab> a<C-X><C-V>", NORMAL);
6035 set_option_value((char_u *)"ft", 0L, (char_u *)"vim", OPT_LOCAL);
6038 /* Reset 'textwidth' after setting 'filetype' (the Vim filetype plugin
6039 * sets 'textwidth' to 78). */
6040 curbuf->b_p_tw = 0;
6042 /* Fill the buffer with the history. */
6043 init_history();
6044 if (hislen > 0)
6046 i = hisidx[histtype];
6047 if (i >= 0)
6049 lnum = 0;
6052 if (++i == hislen)
6053 i = 0;
6054 if (history[histtype][i].hisstr != NULL)
6055 ml_append(lnum++, history[histtype][i].hisstr,
6056 (colnr_T)0, FALSE);
6058 while (i != hisidx[histtype]);
6062 /* Replace the empty last line with the current command-line and put the
6063 * cursor there. */
6064 ml_replace(curbuf->b_ml.ml_line_count, ccline.cmdbuff, TRUE);
6065 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6066 curwin->w_cursor.col = ccline.cmdpos;
6067 changed_line_abv_curs();
6068 invalidate_botline();
6069 redraw_later(SOME_VALID);
6071 /* Save the command line info, can be used recursively. */
6072 save_ccline = ccline;
6073 ccline.cmdbuff = NULL;
6074 ccline.cmdprompt = NULL;
6076 /* No Ex mode here! */
6077 exmode_active = 0;
6079 State = NORMAL;
6080 # ifdef FEAT_MOUSE
6081 setmouse();
6082 # endif
6084 # ifdef FEAT_AUTOCMD
6085 /* Trigger CmdwinEnter autocommands. */
6086 typestr[0] = cmdwin_type;
6087 typestr[1] = NUL;
6088 apply_autocmds(EVENT_CMDWINENTER, typestr, typestr, FALSE, curbuf);
6089 if (restart_edit != 0) /* autocmd with ":startinsert" */
6090 stuffcharReadbuff(K_NOP);
6091 # endif
6093 i = RedrawingDisabled;
6094 RedrawingDisabled = 0;
6097 * Call the main loop until <CR> or CTRL-C is typed.
6099 cmdwin_result = 0;
6100 main_loop(TRUE, FALSE);
6102 RedrawingDisabled = i;
6104 # ifdef FEAT_AUTOCMD
6105 /* Trigger CmdwinLeave autocommands. */
6106 apply_autocmds(EVENT_CMDWINLEAVE, typestr, typestr, FALSE, curbuf);
6107 # endif
6109 /* Restore the command line info. */
6110 ccline = save_ccline;
6111 cmdwin_type = 0;
6113 exmode_active = save_exmode;
6115 /* Safety check: The old window or buffer was deleted: It's a bug when
6116 * this happens! */
6117 if (!win_valid(old_curwin) || !buf_valid(old_curbuf))
6119 cmdwin_result = Ctrl_C;
6120 EMSG(_("E199: Active window or buffer deleted"));
6122 else
6124 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6125 /* autocmds may abort script processing */
6126 if (aborting() && cmdwin_result != K_IGNORE)
6127 cmdwin_result = Ctrl_C;
6128 # endif
6129 /* Set the new command line from the cmdline buffer. */
6130 vim_free(ccline.cmdbuff);
6131 if (cmdwin_result == K_XF1 || cmdwin_result == K_XF2) /* :qa[!] typed */
6133 char *p = (cmdwin_result == K_XF2) ? "qa" : "qa!";
6135 if (histtype == HIST_CMD)
6137 /* Execute the command directly. */
6138 ccline.cmdbuff = vim_strsave((char_u *)p);
6139 cmdwin_result = CAR;
6141 else
6143 /* First need to cancel what we were doing. */
6144 ccline.cmdbuff = NULL;
6145 stuffcharReadbuff(':');
6146 stuffReadbuff((char_u *)p);
6147 stuffcharReadbuff(CAR);
6150 else if (cmdwin_result == K_XF2) /* :qa typed */
6152 ccline.cmdbuff = vim_strsave((char_u *)"qa");
6153 cmdwin_result = CAR;
6155 else
6156 ccline.cmdbuff = vim_strsave(ml_get_curline());
6157 if (ccline.cmdbuff == NULL)
6158 cmdwin_result = Ctrl_C;
6159 else
6161 ccline.cmdlen = (int)STRLEN(ccline.cmdbuff);
6162 ccline.cmdbufflen = ccline.cmdlen + 1;
6163 ccline.cmdpos = curwin->w_cursor.col;
6164 if (ccline.cmdpos > ccline.cmdlen)
6165 ccline.cmdpos = ccline.cmdlen;
6166 if (cmdwin_result == K_IGNORE)
6168 set_cmdspos_cursor();
6169 redrawcmd();
6173 # ifdef FEAT_AUTOCMD
6174 /* Don't execute autocommands while deleting the window. */
6175 block_autocmds();
6176 # endif
6177 wp = curwin;
6178 bp = curbuf;
6179 win_goto(old_curwin);
6180 win_close(wp, TRUE);
6181 close_buffer(NULL, bp, DOBUF_WIPE);
6183 /* Restore window sizes. */
6184 win_size_restore(&winsizes);
6186 # ifdef FEAT_AUTOCMD
6187 unblock_autocmds();
6188 # endif
6191 ga_clear(&winsizes);
6192 restart_edit = save_restart_edit;
6193 # ifdef FEAT_RIGHTLEFT
6194 cmdmsg_rl = save_cmdmsg_rl;
6195 # endif
6197 State = save_State;
6198 # ifdef FEAT_MOUSE
6199 setmouse();
6200 # endif
6202 return cmdwin_result;
6204 #endif /* FEAT_CMDWIN */
6207 * Used for commands that either take a simple command string argument, or:
6208 * cmd << endmarker
6209 * {script}
6210 * endmarker
6211 * Returns a pointer to allocated memory with {script} or NULL.
6213 char_u *
6214 script_get(eap, cmd)
6215 exarg_T *eap;
6216 char_u *cmd;
6218 char_u *theline;
6219 char *end_pattern = NULL;
6220 char dot[] = ".";
6221 garray_T ga;
6223 if (cmd[0] != '<' || cmd[1] != '<' || eap->getline == NULL)
6224 return NULL;
6226 ga_init2(&ga, 1, 0x400);
6228 if (cmd[2] != NUL)
6229 end_pattern = (char *)skipwhite(cmd + 2);
6230 else
6231 end_pattern = dot;
6233 for (;;)
6235 theline = eap->getline(
6236 #ifdef FEAT_EVAL
6237 eap->cstack->cs_looplevel > 0 ? -1 :
6238 #endif
6239 NUL, eap->cookie, 0);
6241 if (theline == NULL || STRCMP(end_pattern, theline) == 0)
6242 break;
6244 ga_concat(&ga, theline);
6245 ga_append(&ga, '\n');
6246 vim_free(theline);
6248 ga_append(&ga, NUL);
6250 return (char_u *)ga.ga_data;