Validate screen before constraining window
[MacVim.git] / src / ex_getln.c
blob3f725598ff3e761a6ca2c70e83fb8e1198ec0691
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 expand_T *xpc; /* struct being used for expansion, xp_pattern
35 may point into cmdbuff */
36 int xp_context; /* type of expansion */
37 # ifdef FEAT_EVAL
38 char_u *xp_arg; /* user-defined expansion arg */
39 int input_fn; /* when TRUE Invoked for input() function */
40 # endif
43 /* The current cmdline_info. It is initialized in getcmdline() and after that
44 * used by other functions. When invoking getcmdline() recursively it needs
45 * to be saved with save_cmdline() and restored with restore_cmdline().
46 * TODO: make it local to getcmdline() and pass it around. */
47 static struct cmdline_info ccline;
49 static int cmd_showtail; /* Only show path tail in lists ? */
51 #ifdef FEAT_EVAL
52 static int new_cmdpos; /* position set by set_cmdline_pos() */
53 #endif
55 #ifdef FEAT_CMDHIST
56 typedef struct hist_entry
58 int hisnum; /* identifying number */
59 char_u *hisstr; /* actual entry, separator char after the NUL */
60 } histentry_T;
62 static histentry_T *(history[HIST_COUNT]) = {NULL, NULL, NULL, NULL, NULL};
63 static int hisidx[HIST_COUNT] = {-1, -1, -1, -1, -1}; /* lastused entry */
64 static int hisnum[HIST_COUNT] = {0, 0, 0, 0, 0};
65 /* identifying (unique) number of newest history entry */
66 static int hislen = 0; /* actual length of history tables */
68 static int hist_char2type __ARGS((int c));
70 static int in_history __ARGS((int, char_u *, int));
71 # ifdef FEAT_EVAL
72 static int calc_hist_idx __ARGS((int histype, int num));
73 # endif
74 #endif
76 #ifdef FEAT_RIGHTLEFT
77 static int cmd_hkmap = 0; /* Hebrew mapping during command line */
78 #endif
80 #ifdef FEAT_FKMAP
81 static int cmd_fkmap = 0; /* Farsi mapping during command line */
82 #endif
84 static int cmdline_charsize __ARGS((int idx));
85 static void set_cmdspos __ARGS((void));
86 static void set_cmdspos_cursor __ARGS((void));
87 #ifdef FEAT_MBYTE
88 static void correct_cmdspos __ARGS((int idx, int cells));
89 #endif
90 static void alloc_cmdbuff __ARGS((int len));
91 static int realloc_cmdbuff __ARGS((int len));
92 static void draw_cmdline __ARGS((int start, int len));
93 static void save_cmdline __ARGS((struct cmdline_info *ccp));
94 static void restore_cmdline __ARGS((struct cmdline_info *ccp));
95 static int cmdline_paste __ARGS((int regname, int literally, int remcr));
96 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
97 static void redrawcmd_preedit __ARGS((void));
98 #endif
99 #ifdef FEAT_WILDMENU
100 static void cmdline_del __ARGS((int from));
101 #endif
102 static void redrawcmdprompt __ARGS((void));
103 static void cursorcmd __ARGS((void));
104 static int ccheck_abbr __ARGS((int));
105 static int nextwild __ARGS((expand_T *xp, int type, int options));
106 static void escape_fname __ARGS((char_u **pp));
107 static int showmatches __ARGS((expand_T *xp, int wildmenu));
108 static void set_expand_context __ARGS((expand_T *xp));
109 static int ExpandFromContext __ARGS((expand_T *xp, char_u *, int *, char_u ***, int));
110 static int expand_showtail __ARGS((expand_T *xp));
111 #ifdef FEAT_CMDL_COMPL
112 static int expand_shellcmd __ARGS((char_u *filepat, int *num_file, char_u ***file, int flagsarg));
113 static int ExpandRTDir __ARGS((char_u *pat, int *num_file, char_u ***file, char *dirname));
114 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
115 static int ExpandUserDefined __ARGS((expand_T *xp, regmatch_T *regmatch, int *num_file, char_u ***file));
116 static int ExpandUserList __ARGS((expand_T *xp, int *num_file, char_u ***file));
117 # endif
118 #endif
120 #ifdef FEAT_CMDWIN
121 static int ex_window __ARGS((void));
122 #endif
125 * getcmdline() - accept a command line starting with firstc.
127 * firstc == ':' get ":" command line.
128 * firstc == '/' or '?' get search pattern
129 * firstc == '=' get expression
130 * firstc == '@' get text for input() function
131 * firstc == '>' get text for debug mode
132 * firstc == NUL get text for :insert command
133 * firstc == -1 like NUL, and break on CTRL-C
135 * The line is collected in ccline.cmdbuff, which is reallocated to fit the
136 * command line.
138 * Careful: getcmdline() can be called recursively!
140 * Return pointer to allocated string if there is a commandline, NULL
141 * otherwise.
143 /*ARGSUSED*/
144 char_u *
145 getcmdline(firstc, count, indent)
146 int firstc;
147 long count; /* only used for incremental search */
148 int indent; /* indent for inside conditionals */
150 int c;
151 int i;
152 int j;
153 int gotesc = FALSE; /* TRUE when <ESC> just typed */
154 int do_abbr; /* when TRUE check for abbr. */
155 #ifdef FEAT_CMDHIST
156 char_u *lookfor = NULL; /* string to match */
157 int hiscnt; /* current history line in use */
158 int histype; /* history type to be used */
159 #endif
160 #ifdef FEAT_SEARCH_EXTRA
161 pos_T old_cursor;
162 colnr_T old_curswant;
163 colnr_T old_leftcol;
164 linenr_T old_topline;
165 # ifdef FEAT_DIFF
166 int old_topfill;
167 # endif
168 linenr_T old_botline;
169 int did_incsearch = FALSE;
170 int incsearch_postponed = FALSE;
171 #endif
172 int did_wild_list = FALSE; /* did wild_list() recently */
173 int wim_index = 0; /* index in wim_flags[] */
174 int res;
175 int save_msg_scroll = msg_scroll;
176 int save_State = State; /* remember State when called */
177 int some_key_typed = FALSE; /* one of the keys was typed */
178 #ifdef FEAT_MOUSE
179 /* mouse drag and release events are ignored, unless they are
180 * preceded with a mouse down event */
181 int ignore_drag_release = TRUE;
182 #endif
183 #ifdef FEAT_EVAL
184 int break_ctrl_c = FALSE;
185 #endif
186 expand_T xpc;
187 long *b_im_ptr = NULL;
188 #if defined(FEAT_WILDMENU) || defined(FEAT_EVAL) || defined(FEAT_SEARCH_EXTRA)
189 /* Everything that may work recursively should save and restore the
190 * current command line in save_ccline. That includes update_screen(), a
191 * custom status line may invoke ":normal". */
192 struct cmdline_info save_ccline;
193 #endif
195 #ifdef FEAT_SNIFF
196 want_sniff_request = 0;
197 #endif
198 #ifdef FEAT_EVAL
199 if (firstc == -1)
201 firstc = NUL;
202 break_ctrl_c = TRUE;
204 #endif
205 #ifdef FEAT_RIGHTLEFT
206 /* start without Hebrew mapping for a command line */
207 if (firstc == ':' || firstc == '=' || firstc == '>')
208 cmd_hkmap = 0;
209 #endif
211 ccline.overstrike = FALSE; /* always start in insert mode */
212 #ifdef FEAT_SEARCH_EXTRA
213 old_cursor = curwin->w_cursor; /* needs to be restored later */
214 old_curswant = curwin->w_curswant;
215 old_leftcol = curwin->w_leftcol;
216 old_topline = curwin->w_topline;
217 # ifdef FEAT_DIFF
218 old_topfill = curwin->w_topfill;
219 # endif
220 old_botline = curwin->w_botline;
221 #endif
224 * set some variables for redrawcmd()
226 ccline.cmdfirstc = (firstc == '@' ? 0 : firstc);
227 ccline.cmdindent = (firstc > 0 ? indent : 0);
229 /* alloc initial ccline.cmdbuff */
230 alloc_cmdbuff(exmode_active ? 250 : indent + 1);
231 if (ccline.cmdbuff == NULL)
232 return NULL; /* out of memory */
233 ccline.cmdlen = ccline.cmdpos = 0;
234 ccline.cmdbuff[0] = NUL;
236 /* autoindent for :insert and :append */
237 if (firstc <= 0)
239 copy_spaces(ccline.cmdbuff, indent);
240 ccline.cmdbuff[indent] = NUL;
241 ccline.cmdpos = indent;
242 ccline.cmdspos = indent;
243 ccline.cmdlen = indent;
246 ExpandInit(&xpc);
247 ccline.xpc = &xpc;
249 #ifdef FEAT_RIGHTLEFT
250 if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
251 && (firstc == '/' || firstc == '?'))
252 cmdmsg_rl = TRUE;
253 else
254 cmdmsg_rl = FALSE;
255 #endif
257 redir_off = TRUE; /* don't redirect the typed command */
258 if (!cmd_silent)
260 i = msg_scrolled;
261 msg_scrolled = 0; /* avoid wait_return message */
262 gotocmdline(TRUE);
263 msg_scrolled += i;
264 redrawcmdprompt(); /* draw prompt or indent */
265 set_cmdspos();
267 xpc.xp_context = EXPAND_NOTHING;
268 xpc.xp_backslash = XP_BS_NONE;
269 #ifndef BACKSLASH_IN_FILENAME
270 xpc.xp_shell = FALSE;
271 #endif
273 #if defined(FEAT_EVAL)
274 if (ccline.input_fn)
276 xpc.xp_context = ccline.xp_context;
277 xpc.xp_pattern = ccline.cmdbuff;
278 # if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
279 xpc.xp_arg = ccline.xp_arg;
280 # endif
282 #endif
285 * Avoid scrolling when called by a recursive do_cmdline(), e.g. when
286 * doing ":@0" when register 0 doesn't contain a CR.
288 msg_scroll = FALSE;
290 State = CMDLINE;
292 if (firstc == '/' || firstc == '?' || firstc == '@')
294 /* Use ":lmap" mappings for search pattern and input(). */
295 if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
296 b_im_ptr = &curbuf->b_p_iminsert;
297 else
298 b_im_ptr = &curbuf->b_p_imsearch;
299 if (*b_im_ptr == B_IMODE_LMAP)
300 State |= LANGMAP;
301 #ifdef USE_IM_CONTROL
302 im_set_active(*b_im_ptr == B_IMODE_IM);
303 #endif
305 #ifdef USE_IM_CONTROL
306 else if (p_imcmdline)
307 im_set_active(TRUE);
308 #endif
310 #ifdef FEAT_MOUSE
311 setmouse();
312 #endif
313 #ifdef CURSOR_SHAPE
314 ui_cursor_shape(); /* may show different cursor shape */
315 #endif
317 /* When inside an autocommand for writing "exiting" may be set and
318 * terminal mode set to cooked. Need to set raw mode here then. */
319 settmode(TMODE_RAW);
321 #ifdef FEAT_CMDHIST
322 init_history();
323 hiscnt = hislen; /* set hiscnt to impossible history value */
324 histype = hist_char2type(firstc);
325 #endif
327 #ifdef FEAT_DIGRAPHS
328 do_digraph(-1); /* init digraph typahead */
329 #endif
332 * Collect the command string, handling editing keys.
334 for (;;)
336 redir_off = TRUE; /* Don't redirect the typed command.
337 Repeated, because a ":redir" inside
338 completion may switch it on. */
339 #ifdef USE_ON_FLY_SCROLL
340 dont_scroll = FALSE; /* allow scrolling here */
341 #endif
342 quit_more = FALSE; /* reset after CTRL-D which had a more-prompt */
344 cursorcmd(); /* set the cursor on the right spot */
346 /* Get a character. Ignore K_IGNORE, it should not do anything, such
347 * as stop completion. */
350 c = safe_vgetc();
351 } while (c == K_IGNORE);
353 if (KeyTyped)
355 some_key_typed = TRUE;
356 #ifdef FEAT_RIGHTLEFT
357 if (cmd_hkmap)
358 c = hkmap(c);
359 # ifdef FEAT_FKMAP
360 if (cmd_fkmap)
361 c = cmdl_fkmap(c);
362 # endif
363 if (cmdmsg_rl && !KeyStuffed)
365 /* Invert horizontal movements and operations. Only when
366 * typed by the user directly, not when the result of a
367 * mapping. */
368 switch (c)
370 case K_RIGHT: c = K_LEFT; break;
371 case K_S_RIGHT: c = K_S_LEFT; break;
372 case K_C_RIGHT: c = K_C_LEFT; break;
373 case K_LEFT: c = K_RIGHT; break;
374 case K_S_LEFT: c = K_S_RIGHT; break;
375 case K_C_LEFT: c = K_C_RIGHT; break;
378 #endif
382 * Ignore got_int when CTRL-C was typed here.
383 * Don't ignore it in :global, we really need to break then, e.g., for
384 * ":g/pat/normal /pat" (without the <CR>).
385 * Don't ignore it for the input() function.
387 if ((c == Ctrl_C
388 #ifdef UNIX
389 || c == intr_char
390 #endif
392 #if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
393 && firstc != '@'
394 #endif
395 #ifdef FEAT_EVAL
396 && !break_ctrl_c
397 #endif
398 && !global_busy)
399 got_int = FALSE;
401 #ifdef FEAT_CMDHIST
402 /* free old command line when finished moving around in the history
403 * list */
404 if (lookfor != NULL
405 && c != K_S_DOWN && c != K_S_UP
406 && c != K_DOWN && c != K_UP
407 && c != K_PAGEDOWN && c != K_PAGEUP
408 && c != K_KPAGEDOWN && c != K_KPAGEUP
409 && c != K_LEFT && c != K_RIGHT
410 && (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
412 vim_free(lookfor);
413 lookfor = NULL;
415 #endif
418 * When there are matching completions to select <S-Tab> works like
419 * CTRL-P (unless 'wc' is <S-Tab>).
421 if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)
422 c = Ctrl_P;
424 #ifdef FEAT_WILDMENU
425 /* Special translations for 'wildmenu' */
426 if (did_wild_list && p_wmnu)
428 if (c == K_LEFT)
429 c = Ctrl_P;
430 else if (c == K_RIGHT)
431 c = Ctrl_N;
433 /* Hitting CR after "emenu Name.": complete submenu */
434 if (xpc.xp_context == EXPAND_MENUNAMES && p_wmnu
435 && ccline.cmdpos > 1
436 && ccline.cmdbuff[ccline.cmdpos - 1] == '.'
437 && ccline.cmdbuff[ccline.cmdpos - 2] != '\\'
438 && (c == '\n' || c == '\r' || c == K_KENTER))
439 c = K_DOWN;
440 #endif
442 /* free expanded names when finished walking through matches */
443 if (xpc.xp_numfiles != -1
444 && !(c == p_wc && KeyTyped) && c != p_wcm
445 && c != Ctrl_N && c != Ctrl_P && c != Ctrl_A
446 && c != Ctrl_L)
448 (void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
449 did_wild_list = FALSE;
450 #ifdef FEAT_WILDMENU
451 if (!p_wmnu || (c != K_UP && c != K_DOWN))
452 #endif
453 xpc.xp_context = EXPAND_NOTHING;
454 wim_index = 0;
455 #ifdef FEAT_WILDMENU
456 if (p_wmnu && wild_menu_showing != 0)
458 int skt = KeyTyped;
459 int old_RedrawingDisabled = RedrawingDisabled;
461 if (ccline.input_fn)
462 RedrawingDisabled = 0;
464 if (wild_menu_showing == WM_SCROLLED)
466 /* Entered command line, move it up */
467 cmdline_row--;
468 redrawcmd();
470 else if (save_p_ls != -1)
472 /* restore 'laststatus' and 'winminheight' */
473 p_ls = save_p_ls;
474 p_wmh = save_p_wmh;
475 last_status(FALSE);
476 save_cmdline(&save_ccline);
477 update_screen(VALID); /* redraw the screen NOW */
478 restore_cmdline(&save_ccline);
479 redrawcmd();
480 save_p_ls = -1;
482 else
484 # ifdef FEAT_VERTSPLIT
485 win_redraw_last_status(topframe);
486 # else
487 lastwin->w_redr_status = TRUE;
488 # endif
489 redraw_statuslines();
491 KeyTyped = skt;
492 wild_menu_showing = 0;
493 if (ccline.input_fn)
494 RedrawingDisabled = old_RedrawingDisabled;
496 #endif
499 #ifdef FEAT_WILDMENU
500 /* Special translations for 'wildmenu' */
501 if (xpc.xp_context == EXPAND_MENUNAMES && p_wmnu)
503 /* Hitting <Down> after "emenu Name.": complete submenu */
504 if (c == K_DOWN && ccline.cmdpos > 0
505 && ccline.cmdbuff[ccline.cmdpos - 1] == '.')
506 c = p_wc;
507 else if (c == K_UP)
509 /* Hitting <Up>: Remove one submenu name in front of the
510 * cursor */
511 int found = FALSE;
513 j = (int)(xpc.xp_pattern - ccline.cmdbuff);
514 i = 0;
515 while (--j > 0)
517 /* check for start of menu name */
518 if (ccline.cmdbuff[j] == ' '
519 && ccline.cmdbuff[j - 1] != '\\')
521 i = j + 1;
522 break;
524 /* check for start of submenu name */
525 if (ccline.cmdbuff[j] == '.'
526 && ccline.cmdbuff[j - 1] != '\\')
528 if (found)
530 i = j + 1;
531 break;
533 else
534 found = TRUE;
537 if (i > 0)
538 cmdline_del(i);
539 c = p_wc;
540 xpc.xp_context = EXPAND_NOTHING;
543 if ((xpc.xp_context == EXPAND_FILES
544 || xpc.xp_context == EXPAND_DIRECTORIES
545 || xpc.xp_context == EXPAND_SHELLCMD) && p_wmnu)
547 char_u upseg[5];
549 upseg[0] = PATHSEP;
550 upseg[1] = '.';
551 upseg[2] = '.';
552 upseg[3] = PATHSEP;
553 upseg[4] = NUL;
555 if (c == K_DOWN
556 && ccline.cmdpos > 0
557 && ccline.cmdbuff[ccline.cmdpos - 1] == PATHSEP
558 && (ccline.cmdpos < 3
559 || ccline.cmdbuff[ccline.cmdpos - 2] != '.'
560 || ccline.cmdbuff[ccline.cmdpos - 3] != '.'))
562 /* go down a directory */
563 c = p_wc;
565 else if (STRNCMP(xpc.xp_pattern, upseg + 1, 3) == 0 && c == K_DOWN)
567 /* If in a direct ancestor, strip off one ../ to go down */
568 int found = FALSE;
570 j = ccline.cmdpos;
571 i = (int)(xpc.xp_pattern - ccline.cmdbuff);
572 while (--j > i)
574 #ifdef FEAT_MBYTE
575 if (has_mbyte)
576 j -= (*mb_head_off)(ccline.cmdbuff, ccline.cmdbuff + j);
577 #endif
578 if (vim_ispathsep(ccline.cmdbuff[j]))
580 found = TRUE;
581 break;
584 if (found
585 && ccline.cmdbuff[j - 1] == '.'
586 && ccline.cmdbuff[j - 2] == '.'
587 && (vim_ispathsep(ccline.cmdbuff[j - 3]) || j == i + 2))
589 cmdline_del(j - 2);
590 c = p_wc;
593 else if (c == K_UP)
595 /* go up a directory */
596 int found = FALSE;
598 j = ccline.cmdpos - 1;
599 i = (int)(xpc.xp_pattern - ccline.cmdbuff);
600 while (--j > i)
602 #ifdef FEAT_MBYTE
603 if (has_mbyte)
604 j -= (*mb_head_off)(ccline.cmdbuff, ccline.cmdbuff + j);
605 #endif
606 if (vim_ispathsep(ccline.cmdbuff[j])
607 #ifdef BACKSLASH_IN_FILENAME
608 && vim_strchr(" *?[{`$%#", ccline.cmdbuff[j + 1])
609 == NULL
610 #endif
613 if (found)
615 i = j + 1;
616 break;
618 else
619 found = TRUE;
623 if (!found)
624 j = i;
625 else if (STRNCMP(ccline.cmdbuff + j, upseg, 4) == 0)
626 j += 4;
627 else if (STRNCMP(ccline.cmdbuff + j, upseg + 1, 3) == 0
628 && j == i)
629 j += 3;
630 else
631 j = 0;
632 if (j > 0)
634 /* TODO this is only for DOS/UNIX systems - need to put in
635 * machine-specific stuff here and in upseg init */
636 cmdline_del(j);
637 put_on_cmdline(upseg + 1, 3, FALSE);
639 else if (ccline.cmdpos > i)
640 cmdline_del(i);
641 c = p_wc;
644 #if 0 /* If enabled <Down> on a file takes you _completely_ out of wildmenu */
645 if (p_wmnu
646 && (xpc.xp_context == EXPAND_FILES
647 || xpc.xp_context == EXPAND_MENUNAMES)
648 && (c == K_UP || c == K_DOWN))
649 xpc.xp_context = EXPAND_NOTHING;
650 #endif
652 #endif /* FEAT_WILDMENU */
654 /* CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
655 * mode when 'insertmode' is set, CTRL-\ e prompts for an expression. */
656 if (c == Ctrl_BSL)
658 ++no_mapping;
659 ++allow_keys;
660 c = plain_vgetc();
661 --no_mapping;
662 --allow_keys;
663 /* CTRL-\ e doesn't work when obtaining an expression. */
664 if (c != Ctrl_N && c != Ctrl_G
665 && (c != 'e' || ccline.cmdfirstc == '='))
667 vungetc(c);
668 c = Ctrl_BSL;
670 #ifdef FEAT_EVAL
671 else if (c == 'e')
673 char_u *p = NULL;
676 * Replace the command line with the result of an expression.
677 * Need to save and restore the current command line, to be
678 * able to enter a new one...
680 if (ccline.cmdpos == ccline.cmdlen)
681 new_cmdpos = 99999; /* keep it at the end */
682 else
683 new_cmdpos = ccline.cmdpos;
685 save_cmdline(&save_ccline);
686 c = get_expr_register();
687 restore_cmdline(&save_ccline);
688 if (c == '=')
690 /* Need to save and restore ccline. And set "textlock"
691 * to avoid nasty things like going to another buffer when
692 * evaluating an expression. */
693 save_cmdline(&save_ccline);
694 ++textlock;
695 p = get_expr_line();
696 --textlock;
697 restore_cmdline(&save_ccline);
699 if (p != NULL && realloc_cmdbuff((int)STRLEN(p) + 1) == OK)
701 ccline.cmdlen = (int)STRLEN(p);
702 STRCPY(ccline.cmdbuff, p);
703 vim_free(p);
705 /* Restore the cursor or use the position set with
706 * set_cmdline_pos(). */
707 if (new_cmdpos > ccline.cmdlen)
708 ccline.cmdpos = ccline.cmdlen;
709 else
710 ccline.cmdpos = new_cmdpos;
712 KeyTyped = FALSE; /* Don't do p_wc completion. */
713 redrawcmd();
714 goto cmdline_changed;
717 beep_flush();
718 c = ESC;
720 #endif
721 else
723 if (c == Ctrl_G && p_im && restart_edit == 0)
724 restart_edit = 'a';
725 gotesc = TRUE; /* will free ccline.cmdbuff after putting it
726 in history */
727 goto returncmd; /* back to Normal mode */
731 #ifdef FEAT_CMDWIN
732 if (c == cedit_key || c == K_CMDWIN)
735 * Open a window to edit the command line (and history).
737 c = ex_window();
738 some_key_typed = TRUE;
740 # ifdef FEAT_DIGRAPHS
741 else
742 # endif
743 #endif
744 #ifdef FEAT_DIGRAPHS
745 c = do_digraph(c);
746 #endif
748 if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
749 && (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
751 /* In Ex mode a backslash escapes a newline. */
752 if (exmode_active
753 && c != ESC
754 && ccline.cmdpos == ccline.cmdlen
755 && ccline.cmdpos > 0
756 && ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
758 if (c == K_KENTER)
759 c = '\n';
761 else
763 gotesc = FALSE; /* Might have typed ESC previously, don't
764 truncate the cmdline now. */
765 if (ccheck_abbr(c + ABBR_OFF))
766 goto cmdline_changed;
767 if (!cmd_silent)
769 windgoto(msg_row, 0);
770 out_flush();
772 break;
777 * Completion for 'wildchar' or 'wildcharm' key.
778 * - hitting <ESC> twice means: abandon command line.
779 * - wildcard expansion is only done when the 'wildchar' key is really
780 * typed, not when it comes from a macro
782 if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
784 if (xpc.xp_numfiles > 0) /* typed p_wc at least twice */
786 /* if 'wildmode' contains "list" may still need to list */
787 if (xpc.xp_numfiles > 1
788 && !did_wild_list
789 && (wim_flags[wim_index] & WIM_LIST))
791 (void)showmatches(&xpc, FALSE);
792 redrawcmd();
793 did_wild_list = TRUE;
795 if (wim_flags[wim_index] & WIM_LONGEST)
796 res = nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
797 else if (wim_flags[wim_index] & WIM_FULL)
798 res = nextwild(&xpc, WILD_NEXT, WILD_NO_BEEP);
799 else
800 res = OK; /* don't insert 'wildchar' now */
802 else /* typed p_wc first time */
804 wim_index = 0;
805 j = ccline.cmdpos;
806 /* if 'wildmode' first contains "longest", get longest
807 * common part */
808 if (wim_flags[0] & WIM_LONGEST)
809 res = nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
810 else
811 res = nextwild(&xpc, WILD_EXPAND_KEEP, WILD_NO_BEEP);
813 /* if interrupted while completing, behave like it failed */
814 if (got_int)
816 (void)vpeekc(); /* remove <C-C> from input stream */
817 got_int = FALSE; /* don't abandon the command line */
818 (void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
819 #ifdef FEAT_WILDMENU
820 xpc.xp_context = EXPAND_NOTHING;
821 #endif
822 goto cmdline_changed;
825 /* when more than one match, and 'wildmode' first contains
826 * "list", or no change and 'wildmode' contains "longest,list",
827 * list all matches */
828 if (res == OK && xpc.xp_numfiles > 1)
830 /* a "longest" that didn't do anything is skipped (but not
831 * "list:longest") */
832 if (wim_flags[0] == WIM_LONGEST && ccline.cmdpos == j)
833 wim_index = 1;
834 if ((wim_flags[wim_index] & WIM_LIST)
835 #ifdef FEAT_WILDMENU
836 || (p_wmnu && (wim_flags[wim_index] & WIM_FULL) != 0)
837 #endif
840 if (!(wim_flags[0] & WIM_LONGEST))
842 #ifdef FEAT_WILDMENU
843 int p_wmnu_save = p_wmnu;
844 p_wmnu = 0;
845 #endif
846 nextwild(&xpc, WILD_PREV, 0); /* remove match */
847 #ifdef FEAT_WILDMENU
848 p_wmnu = p_wmnu_save;
849 #endif
851 #ifdef FEAT_WILDMENU
852 (void)showmatches(&xpc, p_wmnu
853 && ((wim_flags[wim_index] & WIM_LIST) == 0));
854 #else
855 (void)showmatches(&xpc, FALSE);
856 #endif
857 redrawcmd();
858 did_wild_list = TRUE;
859 if (wim_flags[wim_index] & WIM_LONGEST)
860 nextwild(&xpc, WILD_LONGEST, WILD_NO_BEEP);
861 else if (wim_flags[wim_index] & WIM_FULL)
862 nextwild(&xpc, WILD_NEXT, WILD_NO_BEEP);
864 else
865 vim_beep();
867 #ifdef FEAT_WILDMENU
868 else if (xpc.xp_numfiles == -1)
869 xpc.xp_context = EXPAND_NOTHING;
870 #endif
872 if (wim_index < 3)
873 ++wim_index;
874 if (c == ESC)
875 gotesc = TRUE;
876 if (res == OK)
877 goto cmdline_changed;
880 gotesc = FALSE;
882 /* <S-Tab> goes to last match, in a clumsy way */
883 if (c == K_S_TAB && KeyTyped)
885 if (nextwild(&xpc, WILD_EXPAND_KEEP, 0) == OK
886 && nextwild(&xpc, WILD_PREV, 0) == OK
887 && nextwild(&xpc, WILD_PREV, 0) == OK)
888 goto cmdline_changed;
891 if (c == NUL || c == K_ZERO) /* NUL is stored as NL */
892 c = NL;
894 do_abbr = TRUE; /* default: check for abbreviation */
897 * Big switch for a typed command line character.
899 switch (c)
901 case K_BS:
902 case Ctrl_H:
903 case K_DEL:
904 case K_KDEL:
905 case Ctrl_W:
906 #ifdef FEAT_FKMAP
907 if (cmd_fkmap && c == K_BS)
908 c = K_DEL;
909 #endif
910 if (c == K_KDEL)
911 c = K_DEL;
914 * delete current character is the same as backspace on next
915 * character, except at end of line
917 if (c == K_DEL && ccline.cmdpos != ccline.cmdlen)
918 ++ccline.cmdpos;
919 #ifdef FEAT_MBYTE
920 if (has_mbyte && c == K_DEL)
921 ccline.cmdpos += mb_off_next(ccline.cmdbuff,
922 ccline.cmdbuff + ccline.cmdpos);
923 #endif
924 if (ccline.cmdpos > 0)
926 char_u *p;
928 j = ccline.cmdpos;
929 p = ccline.cmdbuff + j;
930 #ifdef FEAT_MBYTE
931 if (has_mbyte)
933 p = mb_prevptr(ccline.cmdbuff, p);
934 if (c == Ctrl_W)
936 while (p > ccline.cmdbuff && vim_isspace(*p))
937 p = mb_prevptr(ccline.cmdbuff, p);
938 i = mb_get_class(p);
939 while (p > ccline.cmdbuff && mb_get_class(p) == i)
940 p = mb_prevptr(ccline.cmdbuff, p);
941 if (mb_get_class(p) != i)
942 p += (*mb_ptr2len)(p);
945 else
946 #endif
947 if (c == Ctrl_W)
949 while (p > ccline.cmdbuff && vim_isspace(p[-1]))
950 --p;
951 i = vim_iswordc(p[-1]);
952 while (p > ccline.cmdbuff && !vim_isspace(p[-1])
953 && vim_iswordc(p[-1]) == i)
954 --p;
956 else
957 --p;
958 ccline.cmdpos = (int)(p - ccline.cmdbuff);
959 ccline.cmdlen -= j - ccline.cmdpos;
960 i = ccline.cmdpos;
961 while (i < ccline.cmdlen)
962 ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
964 /* Truncate at the end, required for multi-byte chars. */
965 ccline.cmdbuff[ccline.cmdlen] = NUL;
966 redrawcmd();
968 else if (ccline.cmdlen == 0 && c != Ctrl_W
969 && ccline.cmdprompt == NULL && indent == 0)
971 /* In ex and debug mode it doesn't make sense to return. */
972 if (exmode_active
973 #ifdef FEAT_EVAL
974 || ccline.cmdfirstc == '>'
975 #endif
977 goto cmdline_not_changed;
979 vim_free(ccline.cmdbuff); /* no commandline to return */
980 ccline.cmdbuff = NULL;
981 if (!cmd_silent)
983 #ifdef FEAT_RIGHTLEFT
984 if (cmdmsg_rl)
985 msg_col = Columns;
986 else
987 #endif
988 msg_col = 0;
989 msg_putchar(' '); /* delete ':' */
991 redraw_cmdline = TRUE;
992 goto returncmd; /* back to cmd mode */
994 goto cmdline_changed;
996 case K_INS:
997 case K_KINS:
998 #ifdef FEAT_FKMAP
999 /* if Farsi mode set, we are in reverse insert mode -
1000 Do not change the mode */
1001 if (cmd_fkmap)
1002 beep_flush();
1003 else
1004 #endif
1005 ccline.overstrike = !ccline.overstrike;
1006 #ifdef CURSOR_SHAPE
1007 ui_cursor_shape(); /* may show different cursor shape */
1008 #endif
1009 goto cmdline_not_changed;
1011 case Ctrl_HAT:
1012 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
1014 /* ":lmap" mappings exists, toggle use of mappings. */
1015 State ^= LANGMAP;
1016 #ifdef USE_IM_CONTROL
1017 im_set_active(FALSE); /* Disable input method */
1018 #endif
1019 if (b_im_ptr != NULL)
1021 if (State & LANGMAP)
1022 *b_im_ptr = B_IMODE_LMAP;
1023 else
1024 *b_im_ptr = B_IMODE_NONE;
1027 #ifdef USE_IM_CONTROL
1028 else
1030 /* There are no ":lmap" mappings, toggle IM. When
1031 * 'imdisable' is set don't try getting the status, it's
1032 * always off. */
1033 if ((p_imdisable && b_im_ptr != NULL)
1034 ? *b_im_ptr == B_IMODE_IM : im_get_status())
1036 im_set_active(FALSE); /* Disable input method */
1037 if (b_im_ptr != NULL)
1038 *b_im_ptr = B_IMODE_NONE;
1040 else
1042 im_set_active(TRUE); /* Enable input method */
1043 if (b_im_ptr != NULL)
1044 *b_im_ptr = B_IMODE_IM;
1047 #endif
1048 if (b_im_ptr != NULL)
1050 if (b_im_ptr == &curbuf->b_p_iminsert)
1051 set_iminsert_global();
1052 else
1053 set_imsearch_global();
1055 #ifdef CURSOR_SHAPE
1056 ui_cursor_shape(); /* may show different cursor shape */
1057 #endif
1058 #if defined(FEAT_WINDOWS) && defined(FEAT_KEYMAP)
1059 /* Show/unshow value of 'keymap' in status lines later. */
1060 status_redraw_curbuf();
1061 #endif
1062 goto cmdline_not_changed;
1064 /* case '@': only in very old vi */
1065 case Ctrl_U:
1066 /* delete all characters left of the cursor */
1067 j = ccline.cmdpos;
1068 ccline.cmdlen -= j;
1069 i = ccline.cmdpos = 0;
1070 while (i < ccline.cmdlen)
1071 ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
1072 /* Truncate at the end, required for multi-byte chars. */
1073 ccline.cmdbuff[ccline.cmdlen] = NUL;
1074 redrawcmd();
1075 goto cmdline_changed;
1077 #ifdef FEAT_CLIPBOARD
1078 case Ctrl_Y:
1079 /* Copy the modeless selection, if there is one. */
1080 if (clip_star.state != SELECT_CLEARED)
1082 if (clip_star.state == SELECT_DONE)
1083 clip_copy_modeless_selection(TRUE);
1084 goto cmdline_not_changed;
1086 break;
1087 #endif
1089 case ESC: /* get here if p_wc != ESC or when ESC typed twice */
1090 case Ctrl_C:
1091 /* In exmode it doesn't make sense to return. Except when
1092 * ":normal" runs out of characters. */
1093 if (exmode_active
1094 #ifdef FEAT_EX_EXTRA
1095 && (ex_normal_busy == 0 || typebuf.tb_len > 0)
1096 #endif
1098 goto cmdline_not_changed;
1100 gotesc = TRUE; /* will free ccline.cmdbuff after
1101 putting it in history */
1102 goto returncmd; /* back to cmd mode */
1104 case Ctrl_R: /* insert register */
1105 #ifdef USE_ON_FLY_SCROLL
1106 dont_scroll = TRUE; /* disallow scrolling here */
1107 #endif
1108 putcmdline('"', TRUE);
1109 ++no_mapping;
1110 i = c = plain_vgetc(); /* CTRL-R <char> */
1111 if (i == Ctrl_O)
1112 i = Ctrl_R; /* CTRL-R CTRL-O == CTRL-R CTRL-R */
1113 if (i == Ctrl_R)
1114 c = plain_vgetc(); /* CTRL-R CTRL-R <char> */
1115 --no_mapping;
1116 #ifdef FEAT_EVAL
1118 * Insert the result of an expression.
1119 * Need to save the current command line, to be able to enter
1120 * a new one...
1122 new_cmdpos = -1;
1123 if (c == '=')
1125 if (ccline.cmdfirstc == '=')/* can't do this recursively */
1127 beep_flush();
1128 c = ESC;
1130 else
1132 save_cmdline(&save_ccline);
1133 c = get_expr_register();
1134 restore_cmdline(&save_ccline);
1137 #endif
1138 if (c != ESC) /* use ESC to cancel inserting register */
1140 cmdline_paste(c, i == Ctrl_R, FALSE);
1142 #ifdef FEAT_EVAL
1143 /* When there was a serious error abort getting the
1144 * command line. */
1145 if (aborting())
1147 gotesc = TRUE; /* will free ccline.cmdbuff after
1148 putting it in history */
1149 goto returncmd; /* back to cmd mode */
1151 #endif
1152 KeyTyped = FALSE; /* Don't do p_wc completion. */
1153 #ifdef FEAT_EVAL
1154 if (new_cmdpos >= 0)
1156 /* set_cmdline_pos() was used */
1157 if (new_cmdpos > ccline.cmdlen)
1158 ccline.cmdpos = ccline.cmdlen;
1159 else
1160 ccline.cmdpos = new_cmdpos;
1162 #endif
1164 redrawcmd();
1165 goto cmdline_changed;
1167 case Ctrl_D:
1168 if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
1169 break; /* Use ^D as normal char instead */
1171 redrawcmd();
1172 continue; /* don't do incremental search now */
1174 case K_RIGHT:
1175 case K_S_RIGHT:
1176 case K_C_RIGHT:
1179 if (ccline.cmdpos >= ccline.cmdlen)
1180 break;
1181 i = cmdline_charsize(ccline.cmdpos);
1182 if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
1183 break;
1184 ccline.cmdspos += i;
1185 #ifdef FEAT_MBYTE
1186 if (has_mbyte)
1187 ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
1188 + ccline.cmdpos);
1189 else
1190 #endif
1191 ++ccline.cmdpos;
1193 while ((c == K_S_RIGHT || c == K_C_RIGHT
1194 || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
1195 && ccline.cmdbuff[ccline.cmdpos] != ' ');
1196 #ifdef FEAT_MBYTE
1197 if (has_mbyte)
1198 set_cmdspos_cursor();
1199 #endif
1200 goto cmdline_not_changed;
1202 case K_LEFT:
1203 case K_S_LEFT:
1204 case K_C_LEFT:
1205 if (ccline.cmdpos == 0)
1206 goto cmdline_not_changed;
1209 --ccline.cmdpos;
1210 #ifdef FEAT_MBYTE
1211 if (has_mbyte) /* move to first byte of char */
1212 ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
1213 ccline.cmdbuff + ccline.cmdpos);
1214 #endif
1215 ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
1217 while (ccline.cmdpos > 0
1218 && (c == K_S_LEFT || c == K_C_LEFT
1219 || (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
1220 && ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
1221 #ifdef FEAT_MBYTE
1222 if (has_mbyte)
1223 set_cmdspos_cursor();
1224 #endif
1225 goto cmdline_not_changed;
1227 case K_IGNORE:
1228 /* Ignore mouse event or ex_window() result. */
1229 goto cmdline_not_changed;
1231 #ifdef FEAT_GUI_W32
1232 /* On Win32 ignore <M-F4>, we get it when closing the window was
1233 * cancelled. */
1234 case K_F4:
1235 if (mod_mask == MOD_MASK_ALT)
1237 redrawcmd(); /* somehow the cmdline is cleared */
1238 goto cmdline_not_changed;
1240 break;
1241 #endif
1243 #ifdef FEAT_MOUSE
1244 case K_MIDDLEDRAG:
1245 case K_MIDDLERELEASE:
1246 goto cmdline_not_changed; /* Ignore mouse */
1248 case K_MIDDLEMOUSE:
1249 # ifdef FEAT_GUI
1250 /* When GUI is active, also paste when 'mouse' is empty */
1251 if (!gui.in_use)
1252 # endif
1253 if (!mouse_has(MOUSE_COMMAND))
1254 goto cmdline_not_changed; /* Ignore mouse */
1255 # ifdef FEAT_CLIPBOARD
1256 if (clip_star.available)
1257 cmdline_paste('*', TRUE, TRUE);
1258 else
1259 # endif
1260 cmdline_paste(0, TRUE, TRUE);
1261 redrawcmd();
1262 goto cmdline_changed;
1264 # ifdef FEAT_DND
1265 case K_DROP:
1266 cmdline_paste('~', TRUE, FALSE);
1267 redrawcmd();
1268 goto cmdline_changed;
1269 # endif
1271 case K_LEFTDRAG:
1272 case K_LEFTRELEASE:
1273 case K_RIGHTDRAG:
1274 case K_RIGHTRELEASE:
1275 /* Ignore drag and release events when the button-down wasn't
1276 * seen before. */
1277 if (ignore_drag_release)
1278 goto cmdline_not_changed;
1279 /* FALLTHROUGH */
1280 case K_LEFTMOUSE:
1281 case K_RIGHTMOUSE:
1282 if (c == K_LEFTRELEASE || c == K_RIGHTRELEASE)
1283 ignore_drag_release = TRUE;
1284 else
1285 ignore_drag_release = FALSE;
1286 # ifdef FEAT_GUI
1287 /* When GUI is active, also move when 'mouse' is empty */
1288 if (!gui.in_use)
1289 # endif
1290 if (!mouse_has(MOUSE_COMMAND))
1291 goto cmdline_not_changed; /* Ignore mouse */
1292 # ifdef FEAT_CLIPBOARD
1293 if (mouse_row < cmdline_row && clip_star.available)
1295 int button, is_click, is_drag;
1298 * Handle modeless selection.
1300 button = get_mouse_button(KEY2TERMCAP1(c),
1301 &is_click, &is_drag);
1302 if (mouse_model_popup() && button == MOUSE_LEFT
1303 && (mod_mask & MOD_MASK_SHIFT))
1305 /* Translate shift-left to right button. */
1306 button = MOUSE_RIGHT;
1307 mod_mask &= ~MOD_MASK_SHIFT;
1309 clip_modeless(button, is_click, is_drag);
1310 goto cmdline_not_changed;
1312 # endif
1314 set_cmdspos();
1315 for (ccline.cmdpos = 0; ccline.cmdpos < ccline.cmdlen;
1316 ++ccline.cmdpos)
1318 i = cmdline_charsize(ccline.cmdpos);
1319 if (mouse_row <= cmdline_row + ccline.cmdspos / Columns
1320 && mouse_col < ccline.cmdspos % Columns + i)
1321 break;
1322 # ifdef FEAT_MBYTE
1323 if (has_mbyte)
1325 /* Count ">" for double-wide char that doesn't fit. */
1326 correct_cmdspos(ccline.cmdpos, i);
1327 ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
1328 + ccline.cmdpos) - 1;
1330 # endif
1331 ccline.cmdspos += i;
1333 goto cmdline_not_changed;
1335 /* Mouse scroll wheel: ignored here */
1336 case K_MOUSEDOWN:
1337 case K_MOUSEUP:
1338 /* Alternate buttons ignored here */
1339 case K_X1MOUSE:
1340 case K_X1DRAG:
1341 case K_X1RELEASE:
1342 case K_X2MOUSE:
1343 case K_X2DRAG:
1344 case K_X2RELEASE:
1345 goto cmdline_not_changed;
1347 #endif /* FEAT_MOUSE */
1349 #ifdef FEAT_GUI
1350 case K_LEFTMOUSE_NM: /* mousefocus click, ignored */
1351 case K_LEFTRELEASE_NM:
1352 goto cmdline_not_changed;
1354 case K_VER_SCROLLBAR:
1355 if (msg_scrolled == 0)
1357 gui_do_scroll();
1358 redrawcmd();
1360 goto cmdline_not_changed;
1362 case K_HOR_SCROLLBAR:
1363 if (msg_scrolled == 0)
1365 gui_do_horiz_scroll();
1366 redrawcmd();
1368 goto cmdline_not_changed;
1369 #endif
1370 #ifdef FEAT_GUI_TABLINE
1371 case K_TABLINE:
1372 case K_TABMENU:
1373 /* Don't want to change any tabs here. Make sure the same tab
1374 * is still selected. */
1375 if (gui_use_tabline())
1376 gui_mch_set_curtab(tabpage_index(curtab));
1377 goto cmdline_not_changed;
1378 #endif
1380 case K_SELECT: /* end of Select mode mapping - ignore */
1381 goto cmdline_not_changed;
1383 case Ctrl_B: /* begin of command line */
1384 case K_HOME:
1385 case K_KHOME:
1386 case K_S_HOME:
1387 case K_C_HOME:
1388 ccline.cmdpos = 0;
1389 set_cmdspos();
1390 goto cmdline_not_changed;
1392 case Ctrl_E: /* end of command line */
1393 case K_END:
1394 case K_KEND:
1395 case K_S_END:
1396 case K_C_END:
1397 ccline.cmdpos = ccline.cmdlen;
1398 set_cmdspos_cursor();
1399 goto cmdline_not_changed;
1401 case Ctrl_A: /* all matches */
1402 if (nextwild(&xpc, WILD_ALL, 0) == FAIL)
1403 break;
1404 goto cmdline_changed;
1406 case Ctrl_L:
1407 #ifdef FEAT_SEARCH_EXTRA
1408 if (p_is && !cmd_silent && (firstc == '/' || firstc == '?'))
1410 /* Add a character from under the cursor for 'incsearch' */
1411 if (did_incsearch
1412 && !equalpos(curwin->w_cursor, old_cursor))
1414 c = gchar_cursor();
1415 if (c != NUL)
1417 if (c == firstc || vim_strchr((char_u *)(
1418 p_magic ? "\\^$.*[" : "\\^$"), c)
1419 != NULL)
1421 /* put a backslash before special characters */
1422 stuffcharReadbuff(c);
1423 c = '\\';
1425 break;
1428 goto cmdline_not_changed;
1430 #endif
1432 /* completion: longest common part */
1433 if (nextwild(&xpc, WILD_LONGEST, 0) == FAIL)
1434 break;
1435 goto cmdline_changed;
1437 case Ctrl_N: /* next match */
1438 case Ctrl_P: /* previous match */
1439 if (xpc.xp_numfiles > 0)
1441 if (nextwild(&xpc, (c == Ctrl_P) ? WILD_PREV : WILD_NEXT, 0)
1442 == FAIL)
1443 break;
1444 goto cmdline_changed;
1447 #ifdef FEAT_CMDHIST
1448 case K_UP:
1449 case K_DOWN:
1450 case K_S_UP:
1451 case K_S_DOWN:
1452 case K_PAGEUP:
1453 case K_KPAGEUP:
1454 case K_PAGEDOWN:
1455 case K_KPAGEDOWN:
1456 if (hislen == 0 || firstc == NUL) /* no history */
1457 goto cmdline_not_changed;
1459 i = hiscnt;
1461 /* save current command string so it can be restored later */
1462 if (lookfor == NULL)
1464 if ((lookfor = vim_strsave(ccline.cmdbuff)) == NULL)
1465 goto cmdline_not_changed;
1466 lookfor[ccline.cmdpos] = NUL;
1469 j = (int)STRLEN(lookfor);
1470 for (;;)
1472 /* one step backwards */
1473 if (c == K_UP|| c == K_S_UP || c == Ctrl_P
1474 || c == K_PAGEUP || c == K_KPAGEUP)
1476 if (hiscnt == hislen) /* first time */
1477 hiscnt = hisidx[histype];
1478 else if (hiscnt == 0 && hisidx[histype] != hislen - 1)
1479 hiscnt = hislen - 1;
1480 else if (hiscnt != hisidx[histype] + 1)
1481 --hiscnt;
1482 else /* at top of list */
1484 hiscnt = i;
1485 break;
1488 else /* one step forwards */
1490 /* on last entry, clear the line */
1491 if (hiscnt == hisidx[histype])
1493 hiscnt = hislen;
1494 break;
1497 /* not on a history line, nothing to do */
1498 if (hiscnt == hislen)
1499 break;
1500 if (hiscnt == hislen - 1) /* wrap around */
1501 hiscnt = 0;
1502 else
1503 ++hiscnt;
1505 if (hiscnt < 0 || history[histype][hiscnt].hisstr == NULL)
1507 hiscnt = i;
1508 break;
1510 if ((c != K_UP && c != K_DOWN)
1511 || hiscnt == i
1512 || STRNCMP(history[histype][hiscnt].hisstr,
1513 lookfor, (size_t)j) == 0)
1514 break;
1517 if (hiscnt != i) /* jumped to other entry */
1519 char_u *p;
1520 int len;
1521 int old_firstc;
1523 vim_free(ccline.cmdbuff);
1524 xpc.xp_context = EXPAND_NOTHING;
1525 if (hiscnt == hislen)
1526 p = lookfor; /* back to the old one */
1527 else
1528 p = history[histype][hiscnt].hisstr;
1530 if (histype == HIST_SEARCH
1531 && p != lookfor
1532 && (old_firstc = p[STRLEN(p) + 1]) != firstc)
1534 /* Correct for the separator character used when
1535 * adding the history entry vs the one used now.
1536 * First loop: count length.
1537 * Second loop: copy the characters. */
1538 for (i = 0; i <= 1; ++i)
1540 len = 0;
1541 for (j = 0; p[j] != NUL; ++j)
1543 /* Replace old sep with new sep, unless it is
1544 * escaped. */
1545 if (p[j] == old_firstc
1546 && (j == 0 || p[j - 1] != '\\'))
1548 if (i > 0)
1549 ccline.cmdbuff[len] = firstc;
1551 else
1553 /* Escape new sep, unless it is already
1554 * escaped. */
1555 if (p[j] == firstc
1556 && (j == 0 || p[j - 1] != '\\'))
1558 if (i > 0)
1559 ccline.cmdbuff[len] = '\\';
1560 ++len;
1562 if (i > 0)
1563 ccline.cmdbuff[len] = p[j];
1565 ++len;
1567 if (i == 0)
1569 alloc_cmdbuff(len);
1570 if (ccline.cmdbuff == NULL)
1571 goto returncmd;
1574 ccline.cmdbuff[len] = NUL;
1576 else
1578 alloc_cmdbuff((int)STRLEN(p));
1579 if (ccline.cmdbuff == NULL)
1580 goto returncmd;
1581 STRCPY(ccline.cmdbuff, p);
1584 ccline.cmdpos = ccline.cmdlen = (int)STRLEN(ccline.cmdbuff);
1585 redrawcmd();
1586 goto cmdline_changed;
1588 beep_flush();
1589 goto cmdline_not_changed;
1590 #endif
1592 case Ctrl_V:
1593 case Ctrl_Q:
1594 #ifdef FEAT_MOUSE
1595 ignore_drag_release = TRUE;
1596 #endif
1597 putcmdline('^', TRUE);
1598 c = get_literal(); /* get next (two) character(s) */
1599 do_abbr = FALSE; /* don't do abbreviation now */
1600 #ifdef FEAT_MBYTE
1601 /* may need to remove ^ when composing char was typed */
1602 if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
1604 draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
1605 msg_putchar(' ');
1606 cursorcmd();
1608 #endif
1609 break;
1611 #ifdef FEAT_DIGRAPHS
1612 case Ctrl_K:
1613 #ifdef FEAT_MOUSE
1614 ignore_drag_release = TRUE;
1615 #endif
1616 putcmdline('?', TRUE);
1617 #ifdef USE_ON_FLY_SCROLL
1618 dont_scroll = TRUE; /* disallow scrolling here */
1619 #endif
1620 c = get_digraph(TRUE);
1621 if (c != NUL)
1622 break;
1624 redrawcmd();
1625 goto cmdline_not_changed;
1626 #endif /* FEAT_DIGRAPHS */
1628 #ifdef FEAT_RIGHTLEFT
1629 case Ctrl__: /* CTRL-_: switch language mode */
1630 if (!p_ari)
1631 break;
1632 #ifdef FEAT_FKMAP
1633 if (p_altkeymap)
1635 cmd_fkmap = !cmd_fkmap;
1636 if (cmd_fkmap) /* in Farsi always in Insert mode */
1637 ccline.overstrike = FALSE;
1639 else /* Hebrew is default */
1640 #endif
1641 cmd_hkmap = !cmd_hkmap;
1642 goto cmdline_not_changed;
1643 #endif
1645 default:
1646 #ifdef UNIX
1647 if (c == intr_char)
1649 gotesc = TRUE; /* will free ccline.cmdbuff after
1650 putting it in history */
1651 goto returncmd; /* back to Normal mode */
1653 #endif
1655 * Normal character with no special meaning. Just set mod_mask
1656 * to 0x0 so that typing Shift-Space in the GUI doesn't enter
1657 * the string <S-Space>. This should only happen after ^V.
1659 if (!IS_SPECIAL(c))
1660 mod_mask = 0x0;
1661 break;
1664 * End of switch on command line character.
1665 * We come here if we have a normal character.
1668 if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c)) && ccheck_abbr(
1669 #ifdef FEAT_MBYTE
1670 /* Add ABBR_OFF for characters above 0x100, this is
1671 * what check_abbr() expects. */
1672 (has_mbyte && c >= 0x100) ? (c + ABBR_OFF) :
1673 #endif
1675 goto cmdline_changed;
1678 * put the character in the command line
1680 if (IS_SPECIAL(c) || mod_mask != 0)
1681 put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
1682 else
1684 #ifdef FEAT_MBYTE
1685 if (has_mbyte)
1687 j = (*mb_char2bytes)(c, IObuff);
1688 IObuff[j] = NUL; /* exclude composing chars */
1689 put_on_cmdline(IObuff, j, TRUE);
1691 else
1692 #endif
1694 IObuff[0] = c;
1695 put_on_cmdline(IObuff, 1, TRUE);
1698 goto cmdline_changed;
1701 * This part implements incremental searches for "/" and "?"
1702 * Jump to cmdline_not_changed when a character has been read but the command
1703 * line did not change. Then we only search and redraw if something changed in
1704 * the past.
1705 * Jump to cmdline_changed when the command line did change.
1706 * (Sorry for the goto's, I know it is ugly).
1708 cmdline_not_changed:
1709 #ifdef FEAT_SEARCH_EXTRA
1710 if (!incsearch_postponed)
1711 continue;
1712 #endif
1714 cmdline_changed:
1715 #ifdef FEAT_SEARCH_EXTRA
1717 * 'incsearch' highlighting.
1719 if (p_is && !cmd_silent && (firstc == '/' || firstc == '?'))
1721 pos_T end_pos;
1722 #ifdef FEAT_RELTIME
1723 proftime_T tm;
1724 #endif
1726 /* if there is a character waiting, search and redraw later */
1727 if (char_avail())
1729 incsearch_postponed = TRUE;
1730 continue;
1732 incsearch_postponed = FALSE;
1733 curwin->w_cursor = old_cursor; /* start at old position */
1735 /* If there is no command line, don't do anything */
1736 if (ccline.cmdlen == 0)
1737 i = 0;
1738 else
1740 cursor_off(); /* so the user knows we're busy */
1741 out_flush();
1742 ++emsg_off; /* So it doesn't beep if bad expr */
1743 #ifdef FEAT_RELTIME
1744 /* Set the time limit to half a second. */
1745 profile_setlimit(500L, &tm);
1746 #endif
1747 i = do_search(NULL, firstc, ccline.cmdbuff, count,
1748 SEARCH_KEEP + SEARCH_OPT + SEARCH_NOOF + SEARCH_PEEK,
1749 #ifdef FEAT_RELTIME
1751 #else
1752 NULL
1753 #endif
1755 --emsg_off;
1756 /* if interrupted while searching, behave like it failed */
1757 if (got_int)
1759 (void)vpeekc(); /* remove <C-C> from input stream */
1760 got_int = FALSE; /* don't abandon the command line */
1761 i = 0;
1763 else if (char_avail())
1764 /* cancelled searching because a char was typed */
1765 incsearch_postponed = TRUE;
1767 if (i != 0)
1768 highlight_match = TRUE; /* highlight position */
1769 else
1770 highlight_match = FALSE; /* remove highlight */
1772 /* first restore the old curwin values, so the screen is
1773 * positioned in the same way as the actual search command */
1774 curwin->w_leftcol = old_leftcol;
1775 curwin->w_topline = old_topline;
1776 # ifdef FEAT_DIFF
1777 curwin->w_topfill = old_topfill;
1778 # endif
1779 curwin->w_botline = old_botline;
1780 changed_cline_bef_curs();
1781 update_topline();
1783 if (i != 0)
1785 pos_T save_pos = curwin->w_cursor;
1788 * First move cursor to end of match, then to the start. This
1789 * moves the whole match onto the screen when 'nowrap' is set.
1791 curwin->w_cursor.lnum += search_match_lines;
1792 curwin->w_cursor.col = search_match_endcol;
1793 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
1795 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
1796 coladvance((colnr_T)MAXCOL);
1798 validate_cursor();
1799 end_pos = curwin->w_cursor;
1800 curwin->w_cursor = save_pos;
1802 else
1803 end_pos = curwin->w_cursor; /* shutup gcc 4 */
1805 validate_cursor();
1806 # ifdef FEAT_WINDOWS
1807 /* May redraw the status line to show the cursor position. */
1808 if (p_ru && curwin->w_status_height > 0)
1809 curwin->w_redr_status = TRUE;
1810 # endif
1812 save_cmdline(&save_ccline);
1813 update_screen(SOME_VALID);
1814 restore_cmdline(&save_ccline);
1816 /* Leave it at the end to make CTRL-R CTRL-W work. */
1817 if (i != 0)
1818 curwin->w_cursor = end_pos;
1820 msg_starthere();
1821 redrawcmdline();
1822 did_incsearch = TRUE;
1824 #else /* FEAT_SEARCH_EXTRA */
1826 #endif
1828 #ifdef FEAT_RIGHTLEFT
1829 if (cmdmsg_rl
1830 # ifdef FEAT_ARABIC
1831 || (p_arshape && !p_tbidi && enc_utf8)
1832 # endif
1834 /* Always redraw the whole command line to fix shaping and
1835 * right-left typing. Not efficient, but it works. */
1836 redrawcmd();
1837 #endif
1840 returncmd:
1842 #ifdef FEAT_RIGHTLEFT
1843 cmdmsg_rl = FALSE;
1844 #endif
1846 #ifdef FEAT_FKMAP
1847 cmd_fkmap = 0;
1848 #endif
1850 ExpandCleanup(&xpc);
1851 ccline.xpc = NULL;
1853 #ifdef FEAT_SEARCH_EXTRA
1854 if (did_incsearch)
1856 curwin->w_cursor = old_cursor;
1857 curwin->w_curswant = old_curswant;
1858 curwin->w_leftcol = old_leftcol;
1859 curwin->w_topline = old_topline;
1860 # ifdef FEAT_DIFF
1861 curwin->w_topfill = old_topfill;
1862 # endif
1863 curwin->w_botline = old_botline;
1864 highlight_match = FALSE;
1865 validate_cursor(); /* needed for TAB */
1866 redraw_later(SOME_VALID);
1868 #endif
1870 if (ccline.cmdbuff != NULL)
1873 * Put line in history buffer (":" and "=" only when it was typed).
1875 #ifdef FEAT_CMDHIST
1876 if (ccline.cmdlen && firstc != NUL
1877 && (some_key_typed || histype == HIST_SEARCH))
1879 add_to_history(histype, ccline.cmdbuff, TRUE,
1880 histype == HIST_SEARCH ? firstc : NUL);
1881 if (firstc == ':')
1883 vim_free(new_last_cmdline);
1884 new_last_cmdline = vim_strsave(ccline.cmdbuff);
1887 #endif
1889 if (gotesc) /* abandon command line */
1891 vim_free(ccline.cmdbuff);
1892 ccline.cmdbuff = NULL;
1893 if (msg_scrolled == 0)
1894 compute_cmdrow();
1895 MSG("");
1896 redraw_cmdline = TRUE;
1901 * If the screen was shifted up, redraw the whole screen (later).
1902 * If the line is too long, clear it, so ruler and shown command do
1903 * not get printed in the middle of it.
1905 msg_check();
1906 msg_scroll = save_msg_scroll;
1907 redir_off = FALSE;
1909 /* When the command line was typed, no need for a wait-return prompt. */
1910 if (some_key_typed)
1911 need_wait_return = FALSE;
1913 State = save_State;
1914 #ifdef USE_IM_CONTROL
1915 if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)
1916 im_save_status(b_im_ptr);
1917 im_set_active(FALSE);
1918 #endif
1919 #ifdef FEAT_MOUSE
1920 setmouse();
1921 #endif
1922 #ifdef CURSOR_SHAPE
1923 ui_cursor_shape(); /* may show different cursor shape */
1924 #endif
1927 char_u *p = ccline.cmdbuff;
1929 /* Make ccline empty, getcmdline() may try to use it. */
1930 ccline.cmdbuff = NULL;
1931 return p;
1935 #if (defined(FEAT_CRYPT) || defined(FEAT_EVAL)) || defined(PROTO)
1937 * Get a command line with a prompt.
1938 * This is prepared to be called recursively from getcmdline() (e.g. by
1939 * f_input() when evaluating an expression from CTRL-R =).
1940 * Returns the command line in allocated memory, or NULL.
1942 char_u *
1943 getcmdline_prompt(firstc, prompt, attr, xp_context, xp_arg)
1944 int firstc;
1945 char_u *prompt; /* command line prompt */
1946 int attr; /* attributes for prompt */
1947 int xp_context; /* type of expansion */
1948 char_u *xp_arg; /* user-defined expansion argument */
1950 char_u *s;
1951 struct cmdline_info save_ccline;
1952 int msg_col_save = msg_col;
1954 save_cmdline(&save_ccline);
1955 ccline.cmdprompt = prompt;
1956 ccline.cmdattr = attr;
1957 # ifdef FEAT_EVAL
1958 ccline.xp_context = xp_context;
1959 ccline.xp_arg = xp_arg;
1960 ccline.input_fn = (firstc == '@');
1961 # endif
1962 s = getcmdline(firstc, 1L, 0);
1963 restore_cmdline(&save_ccline);
1964 /* Restore msg_col, the prompt from input() may have changed it. */
1965 msg_col = msg_col_save;
1967 return s;
1969 #endif
1972 * Return TRUE when the text must not be changed and we can't switch to
1973 * another window or buffer. Used when editing the command line, evaluating
1974 * 'balloonexpr', etc.
1977 text_locked()
1979 #ifdef FEAT_CMDWIN
1980 if (cmdwin_type != 0)
1981 return TRUE;
1982 #endif
1983 return textlock != 0;
1987 * Give an error message for a command that isn't allowed while the cmdline
1988 * window is open or editing the cmdline in another way.
1990 void
1991 text_locked_msg()
1993 #ifdef FEAT_CMDWIN
1994 if (cmdwin_type != 0)
1995 EMSG(_(e_cmdwin));
1996 else
1997 #endif
1998 EMSG(_(e_secure));
2001 #if defined(FEAT_AUTOCMD) || defined(PROTO)
2003 * Check if "curbuf_lock" or "allbuf_lock" is set and return TRUE when it is
2004 * and give an error message.
2007 curbuf_locked()
2009 if (curbuf_lock > 0)
2011 EMSG(_("E788: Not allowed to edit another buffer now"));
2012 return TRUE;
2014 return allbuf_locked();
2018 * Check if "allbuf_lock" is set and return TRUE when it is and give an error
2019 * message.
2022 allbuf_locked()
2024 if (allbuf_lock > 0)
2026 EMSG(_("E811: Not allowed to change buffer information now"));
2027 return TRUE;
2029 return FALSE;
2031 #endif
2033 static int
2034 cmdline_charsize(idx)
2035 int idx;
2037 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
2038 if (cmdline_star > 0) /* showing '*', always 1 position */
2039 return 1;
2040 #endif
2041 return ptr2cells(ccline.cmdbuff + idx);
2045 * Compute the offset of the cursor on the command line for the prompt and
2046 * indent.
2048 static void
2049 set_cmdspos()
2051 if (ccline.cmdfirstc != NUL)
2052 ccline.cmdspos = 1 + ccline.cmdindent;
2053 else
2054 ccline.cmdspos = 0 + ccline.cmdindent;
2058 * Compute the screen position for the cursor on the command line.
2060 static void
2061 set_cmdspos_cursor()
2063 int i, m, c;
2065 set_cmdspos();
2066 if (KeyTyped)
2068 m = Columns * Rows;
2069 if (m < 0) /* overflow, Columns or Rows at weird value */
2070 m = MAXCOL;
2072 else
2073 m = MAXCOL;
2074 for (i = 0; i < ccline.cmdlen && i < ccline.cmdpos; ++i)
2076 c = cmdline_charsize(i);
2077 #ifdef FEAT_MBYTE
2078 /* Count ">" for double-wide multi-byte char that doesn't fit. */
2079 if (has_mbyte)
2080 correct_cmdspos(i, c);
2081 #endif
2082 /* If the cmdline doesn't fit, show cursor on last visible char.
2083 * Don't move the cursor itself, so we can still append. */
2084 if ((ccline.cmdspos += c) >= m)
2086 ccline.cmdspos -= c;
2087 break;
2089 #ifdef FEAT_MBYTE
2090 if (has_mbyte)
2091 i += (*mb_ptr2len)(ccline.cmdbuff + i) - 1;
2092 #endif
2096 #ifdef FEAT_MBYTE
2098 * Check if the character at "idx", which is "cells" wide, is a multi-byte
2099 * character that doesn't fit, so that a ">" must be displayed.
2101 static void
2102 correct_cmdspos(idx, cells)
2103 int idx;
2104 int cells;
2106 if ((*mb_ptr2len)(ccline.cmdbuff + idx) > 1
2107 && (*mb_ptr2cells)(ccline.cmdbuff + idx) > 1
2108 && ccline.cmdspos % Columns + cells > Columns)
2109 ccline.cmdspos++;
2111 #endif
2114 * Get an Ex command line for the ":" command.
2116 /* ARGSUSED */
2117 char_u *
2118 getexline(c, dummy, indent)
2119 int c; /* normally ':', NUL for ":append" */
2120 void *dummy; /* cookie not used */
2121 int indent; /* indent for inside conditionals */
2123 /* When executing a register, remove ':' that's in front of each line. */
2124 if (exec_from_reg && vpeekc() == ':')
2125 (void)vgetc();
2126 return getcmdline(c, 1L, indent);
2130 * Get an Ex command line for Ex mode.
2131 * In Ex mode we only use the OS supplied line editing features and no
2132 * mappings or abbreviations.
2133 * Returns a string in allocated memory or NULL.
2135 /* ARGSUSED */
2136 char_u *
2137 getexmodeline(promptc, dummy, indent)
2138 int promptc; /* normally ':', NUL for ":append" and '?' for
2139 :s prompt */
2140 void *dummy; /* cookie not used */
2141 int indent; /* indent for inside conditionals */
2143 garray_T line_ga;
2144 char_u *pend;
2145 int startcol = 0;
2146 int c1 = 0;
2147 int escaped = FALSE; /* CTRL-V typed */
2148 int vcol = 0;
2149 char_u *p;
2150 int prev_char;
2152 /* Switch cursor on now. This avoids that it happens after the "\n", which
2153 * confuses the system function that computes tabstops. */
2154 cursor_on();
2156 /* always start in column 0; write a newline if necessary */
2157 compute_cmdrow();
2158 if ((msg_col || msg_didout) && promptc != '?')
2159 msg_putchar('\n');
2160 if (promptc == ':')
2162 /* indent that is only displayed, not in the line itself */
2163 if (p_prompt)
2164 msg_putchar(':');
2165 while (indent-- > 0)
2166 msg_putchar(' ');
2167 startcol = msg_col;
2170 ga_init2(&line_ga, 1, 30);
2172 /* autoindent for :insert and :append is in the line itself */
2173 if (promptc <= 0)
2175 vcol = indent;
2176 while (indent >= 8)
2178 ga_append(&line_ga, TAB);
2179 msg_puts((char_u *)" ");
2180 indent -= 8;
2182 while (indent-- > 0)
2184 ga_append(&line_ga, ' ');
2185 msg_putchar(' ');
2188 ++no_mapping;
2189 ++allow_keys;
2192 * Get the line, one character at a time.
2194 got_int = FALSE;
2195 while (!got_int)
2197 if (ga_grow(&line_ga, 40) == FAIL)
2198 break;
2199 pend = (char_u *)line_ga.ga_data + line_ga.ga_len;
2201 /* Get one character at a time. Don't use inchar(), it can't handle
2202 * special characters. */
2203 prev_char = c1;
2204 c1 = vgetc();
2207 * Handle line editing.
2208 * Previously this was left to the system, putting the terminal in
2209 * cooked mode, but then CTRL-D and CTRL-T can't be used properly.
2211 if (got_int)
2213 msg_putchar('\n');
2214 break;
2217 if (!escaped)
2219 /* CR typed means "enter", which is NL */
2220 if (c1 == '\r')
2221 c1 = '\n';
2223 if (c1 == BS || c1 == K_BS
2224 || c1 == DEL || c1 == K_DEL || c1 == K_KDEL)
2226 if (line_ga.ga_len > 0)
2228 --line_ga.ga_len;
2229 goto redraw;
2231 continue;
2234 if (c1 == Ctrl_U)
2236 msg_col = startcol;
2237 msg_clr_eos();
2238 line_ga.ga_len = 0;
2239 continue;
2242 if (c1 == Ctrl_T)
2244 p = (char_u *)line_ga.ga_data;
2245 p[line_ga.ga_len] = NUL;
2246 indent = get_indent_str(p, 8);
2247 indent += curbuf->b_p_sw - indent % curbuf->b_p_sw;
2248 add_indent:
2249 while (get_indent_str(p, 8) < indent)
2251 char_u *s = skipwhite(p);
2253 ga_grow(&line_ga, 1);
2254 mch_memmove(s + 1, s, line_ga.ga_len - (s - p) + 1);
2255 *s = ' ';
2256 ++line_ga.ga_len;
2258 redraw:
2259 /* redraw the line */
2260 msg_col = startcol;
2261 vcol = 0;
2262 for (p = (char_u *)line_ga.ga_data;
2263 p < (char_u *)line_ga.ga_data + line_ga.ga_len; ++p)
2265 if (*p == TAB)
2269 msg_putchar(' ');
2270 } while (++vcol % 8);
2272 else
2274 msg_outtrans_len(p, 1);
2275 vcol += char2cells(*p);
2278 msg_clr_eos();
2279 windgoto(msg_row, msg_col);
2280 continue;
2283 if (c1 == Ctrl_D)
2285 /* Delete one shiftwidth. */
2286 p = (char_u *)line_ga.ga_data;
2287 if (prev_char == '0' || prev_char == '^')
2289 if (prev_char == '^')
2290 ex_keep_indent = TRUE;
2291 indent = 0;
2292 p[--line_ga.ga_len] = NUL;
2294 else
2296 p[line_ga.ga_len] = NUL;
2297 indent = get_indent_str(p, 8);
2298 --indent;
2299 indent -= indent % curbuf->b_p_sw;
2301 while (get_indent_str(p, 8) > indent)
2303 char_u *s = skipwhite(p);
2305 mch_memmove(s - 1, s, line_ga.ga_len - (s - p) + 1);
2306 --line_ga.ga_len;
2308 goto add_indent;
2311 if (c1 == Ctrl_V || c1 == Ctrl_Q)
2313 escaped = TRUE;
2314 continue;
2317 /* Ignore special key codes: mouse movement, K_IGNORE, etc. */
2318 if (IS_SPECIAL(c1))
2319 continue;
2322 if (IS_SPECIAL(c1))
2323 c1 = '?';
2324 ((char_u *)line_ga.ga_data)[line_ga.ga_len] = c1;
2325 if (c1 == '\n')
2326 msg_putchar('\n');
2327 else if (c1 == TAB)
2329 /* Don't use chartabsize(), 'ts' can be different */
2332 msg_putchar(' ');
2333 } while (++vcol % 8);
2335 else
2337 msg_outtrans_len(
2338 ((char_u *)line_ga.ga_data) + line_ga.ga_len, 1);
2339 vcol += char2cells(c1);
2341 ++line_ga.ga_len;
2342 escaped = FALSE;
2344 windgoto(msg_row, msg_col);
2345 pend = (char_u *)(line_ga.ga_data) + line_ga.ga_len;
2347 /* we are done when a NL is entered, but not when it comes after a
2348 * backslash */
2349 if (line_ga.ga_len > 0 && pend[-1] == '\n'
2350 && (line_ga.ga_len <= 1 || pend[-2] != '\\'))
2352 --line_ga.ga_len;
2353 --pend;
2354 *pend = NUL;
2355 break;
2359 --no_mapping;
2360 --allow_keys;
2362 /* make following messages go to the next line */
2363 msg_didout = FALSE;
2364 msg_col = 0;
2365 if (msg_row < Rows - 1)
2366 ++msg_row;
2367 emsg_on_display = FALSE; /* don't want ui_delay() */
2369 if (got_int)
2370 ga_clear(&line_ga);
2372 return (char_u *)line_ga.ga_data;
2375 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
2376 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
2378 * Return TRUE if ccline.overstrike is on.
2381 cmdline_overstrike()
2383 return ccline.overstrike;
2387 * Return TRUE if the cursor is at the end of the cmdline.
2390 cmdline_at_end()
2392 return (ccline.cmdpos >= ccline.cmdlen);
2394 #endif
2396 #if (defined(FEAT_XIM) && (defined(FEAT_GUI_GTK))) || defined(PROTO)
2398 * Return the virtual column number at the current cursor position.
2399 * This is used by the IM code to obtain the start of the preedit string.
2401 colnr_T
2402 cmdline_getvcol_cursor()
2404 if (ccline.cmdbuff == NULL || ccline.cmdpos > ccline.cmdlen)
2405 return MAXCOL;
2407 # ifdef FEAT_MBYTE
2408 if (has_mbyte)
2410 colnr_T col;
2411 int i = 0;
2413 for (col = 0; i < ccline.cmdpos; ++col)
2414 i += (*mb_ptr2len)(ccline.cmdbuff + i);
2416 return col;
2418 else
2419 # endif
2420 return ccline.cmdpos;
2422 #endif
2424 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2426 * If part of the command line is an IM preedit string, redraw it with
2427 * IM feedback attributes. The cursor position is restored after drawing.
2429 static void
2430 redrawcmd_preedit()
2432 if ((State & CMDLINE)
2433 && xic != NULL
2434 /* && im_get_status() doesn't work when using SCIM */
2435 && !p_imdisable
2436 && im_is_preediting())
2438 int cmdpos = 0;
2439 int cmdspos;
2440 int old_row;
2441 int old_col;
2442 colnr_T col;
2444 old_row = msg_row;
2445 old_col = msg_col;
2446 cmdspos = ((ccline.cmdfirstc != NUL) ? 1 : 0) + ccline.cmdindent;
2448 # ifdef FEAT_MBYTE
2449 if (has_mbyte)
2451 for (col = 0; col < preedit_start_col
2452 && cmdpos < ccline.cmdlen; ++col)
2454 cmdspos += (*mb_ptr2cells)(ccline.cmdbuff + cmdpos);
2455 cmdpos += (*mb_ptr2len)(ccline.cmdbuff + cmdpos);
2458 else
2459 # endif
2461 cmdspos += preedit_start_col;
2462 cmdpos += preedit_start_col;
2465 msg_row = cmdline_row + (cmdspos / (int)Columns);
2466 msg_col = cmdspos % (int)Columns;
2467 if (msg_row >= Rows)
2468 msg_row = Rows - 1;
2470 for (col = 0; cmdpos < ccline.cmdlen; ++col)
2472 int char_len;
2473 int char_attr;
2475 char_attr = im_get_feedback_attr(col);
2476 if (char_attr < 0)
2477 break; /* end of preedit string */
2479 # ifdef FEAT_MBYTE
2480 if (has_mbyte)
2481 char_len = (*mb_ptr2len)(ccline.cmdbuff + cmdpos);
2482 else
2483 # endif
2484 char_len = 1;
2486 msg_outtrans_len_attr(ccline.cmdbuff + cmdpos, char_len, char_attr);
2487 cmdpos += char_len;
2490 msg_row = old_row;
2491 msg_col = old_col;
2494 #endif /* FEAT_XIM && FEAT_GUI_GTK */
2497 * Allocate a new command line buffer.
2498 * Assigns the new buffer to ccline.cmdbuff and ccline.cmdbufflen.
2499 * Returns the new value of ccline.cmdbuff and ccline.cmdbufflen.
2501 static void
2502 alloc_cmdbuff(len)
2503 int len;
2506 * give some extra space to avoid having to allocate all the time
2508 if (len < 80)
2509 len = 100;
2510 else
2511 len += 20;
2513 ccline.cmdbuff = alloc(len); /* caller should check for out-of-memory */
2514 ccline.cmdbufflen = len;
2518 * Re-allocate the command line to length len + something extra.
2519 * return FAIL for failure, OK otherwise
2521 static int
2522 realloc_cmdbuff(len)
2523 int len;
2525 char_u *p;
2527 p = ccline.cmdbuff;
2528 alloc_cmdbuff(len); /* will get some more */
2529 if (ccline.cmdbuff == NULL) /* out of memory */
2531 ccline.cmdbuff = p; /* keep the old one */
2532 return FAIL;
2534 mch_memmove(ccline.cmdbuff, p, (size_t)ccline.cmdlen + 1);
2535 vim_free(p);
2537 if (ccline.xpc != NULL
2538 && ccline.xpc->xp_pattern != NULL
2539 && ccline.xpc->xp_context != EXPAND_NOTHING
2540 && ccline.xpc->xp_context != EXPAND_UNSUCCESSFUL)
2542 int i = (int)(ccline.xpc->xp_pattern - p);
2544 /* If xp_pattern points inside the old cmdbuff it needs to be adjusted
2545 * to point into the newly allocated memory. */
2546 if (i >= 0 && i <= ccline.cmdlen)
2547 ccline.xpc->xp_pattern = ccline.cmdbuff + i;
2550 return OK;
2553 #if defined(FEAT_ARABIC) || defined(PROTO)
2554 static char_u *arshape_buf = NULL;
2556 # if defined(EXITFREE) || defined(PROTO)
2557 void
2558 free_cmdline_buf()
2560 vim_free(arshape_buf);
2562 # endif
2563 #endif
2566 * Draw part of the cmdline at the current cursor position. But draw stars
2567 * when cmdline_star is TRUE.
2569 static void
2570 draw_cmdline(start, len)
2571 int start;
2572 int len;
2574 #if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
2575 int i;
2577 if (cmdline_star > 0)
2578 for (i = 0; i < len; ++i)
2580 msg_putchar('*');
2581 # ifdef FEAT_MBYTE
2582 if (has_mbyte)
2583 i += (*mb_ptr2len)(ccline.cmdbuff + start + i) - 1;
2584 # endif
2586 else
2587 #endif
2588 #ifdef FEAT_ARABIC
2589 if (p_arshape && !p_tbidi && enc_utf8 && len > 0)
2591 static int buflen = 0;
2592 char_u *p;
2593 int j;
2594 int newlen = 0;
2595 int mb_l;
2596 int pc, pc1 = 0;
2597 int prev_c = 0;
2598 int prev_c1 = 0;
2599 int u8c;
2600 int u8cc[MAX_MCO];
2601 int nc = 0;
2604 * Do arabic shaping into a temporary buffer. This is very
2605 * inefficient!
2607 if (len * 2 + 2 > buflen)
2609 /* Re-allocate the buffer. We keep it around to avoid a lot of
2610 * alloc()/free() calls. */
2611 vim_free(arshape_buf);
2612 buflen = len * 2 + 2;
2613 arshape_buf = alloc(buflen);
2614 if (arshape_buf == NULL)
2615 return; /* out of memory */
2618 if (utf_iscomposing(utf_ptr2char(ccline.cmdbuff + start)))
2620 /* Prepend a space to draw the leading composing char on. */
2621 arshape_buf[0] = ' ';
2622 newlen = 1;
2625 for (j = start; j < start + len; j += mb_l)
2627 p = ccline.cmdbuff + j;
2628 u8c = utfc_ptr2char_len(p, u8cc, start + len - j);
2629 mb_l = utfc_ptr2len_len(p, start + len - j);
2630 if (ARABIC_CHAR(u8c))
2632 /* Do Arabic shaping. */
2633 if (cmdmsg_rl)
2635 /* displaying from right to left */
2636 pc = prev_c;
2637 pc1 = prev_c1;
2638 prev_c1 = u8cc[0];
2639 if (j + mb_l >= start + len)
2640 nc = NUL;
2641 else
2642 nc = utf_ptr2char(p + mb_l);
2644 else
2646 /* displaying from left to right */
2647 if (j + mb_l >= start + len)
2648 pc = NUL;
2649 else
2651 int pcc[MAX_MCO];
2653 pc = utfc_ptr2char_len(p + mb_l, pcc,
2654 start + len - j - mb_l);
2655 pc1 = pcc[0];
2657 nc = prev_c;
2659 prev_c = u8c;
2661 u8c = arabic_shape(u8c, NULL, &u8cc[0], pc, pc1, nc);
2663 newlen += (*mb_char2bytes)(u8c, arshape_buf + newlen);
2664 if (u8cc[0] != 0)
2666 newlen += (*mb_char2bytes)(u8cc[0], arshape_buf + newlen);
2667 if (u8cc[1] != 0)
2668 newlen += (*mb_char2bytes)(u8cc[1],
2669 arshape_buf + newlen);
2672 else
2674 prev_c = u8c;
2675 mch_memmove(arshape_buf + newlen, p, mb_l);
2676 newlen += mb_l;
2680 msg_outtrans_len(arshape_buf, newlen);
2682 else
2683 #endif
2684 msg_outtrans_len(ccline.cmdbuff + start, len);
2688 * Put a character on the command line. Shifts the following text to the
2689 * right when "shift" is TRUE. Used for CTRL-V, CTRL-K, etc.
2690 * "c" must be printable (fit in one display cell)!
2692 void
2693 putcmdline(c, shift)
2694 int c;
2695 int shift;
2697 if (cmd_silent)
2698 return;
2699 msg_no_more = TRUE;
2700 msg_putchar(c);
2701 if (shift)
2702 draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
2703 msg_no_more = FALSE;
2704 cursorcmd();
2708 * Undo a putcmdline(c, FALSE).
2710 void
2711 unputcmdline()
2713 if (cmd_silent)
2714 return;
2715 msg_no_more = TRUE;
2716 if (ccline.cmdlen == ccline.cmdpos)
2717 msg_putchar(' ');
2718 else
2719 draw_cmdline(ccline.cmdpos, 1);
2720 msg_no_more = FALSE;
2721 cursorcmd();
2725 * Put the given string, of the given length, onto the command line.
2726 * If len is -1, then STRLEN() is used to calculate the length.
2727 * If 'redraw' is TRUE then the new part of the command line, and the remaining
2728 * part will be redrawn, otherwise it will not. If this function is called
2729 * twice in a row, then 'redraw' should be FALSE and redrawcmd() should be
2730 * called afterwards.
2733 put_on_cmdline(str, len, redraw)
2734 char_u *str;
2735 int len;
2736 int redraw;
2738 int retval;
2739 int i;
2740 int m;
2741 int c;
2743 if (len < 0)
2744 len = (int)STRLEN(str);
2746 /* Check if ccline.cmdbuff needs to be longer */
2747 if (ccline.cmdlen + len + 1 >= ccline.cmdbufflen)
2748 retval = realloc_cmdbuff(ccline.cmdlen + len);
2749 else
2750 retval = OK;
2751 if (retval == OK)
2753 if (!ccline.overstrike)
2755 mch_memmove(ccline.cmdbuff + ccline.cmdpos + len,
2756 ccline.cmdbuff + ccline.cmdpos,
2757 (size_t)(ccline.cmdlen - ccline.cmdpos));
2758 ccline.cmdlen += len;
2760 else
2762 #ifdef FEAT_MBYTE
2763 if (has_mbyte)
2765 /* Count nr of characters in the new string. */
2766 m = 0;
2767 for (i = 0; i < len; i += (*mb_ptr2len)(str + i))
2768 ++m;
2769 /* Count nr of bytes in cmdline that are overwritten by these
2770 * characters. */
2771 for (i = ccline.cmdpos; i < ccline.cmdlen && m > 0;
2772 i += (*mb_ptr2len)(ccline.cmdbuff + i))
2773 --m;
2774 if (i < ccline.cmdlen)
2776 mch_memmove(ccline.cmdbuff + ccline.cmdpos + len,
2777 ccline.cmdbuff + i, (size_t)(ccline.cmdlen - i));
2778 ccline.cmdlen += ccline.cmdpos + len - i;
2780 else
2781 ccline.cmdlen = ccline.cmdpos + len;
2783 else
2784 #endif
2785 if (ccline.cmdpos + len > ccline.cmdlen)
2786 ccline.cmdlen = ccline.cmdpos + len;
2788 mch_memmove(ccline.cmdbuff + ccline.cmdpos, str, (size_t)len);
2789 ccline.cmdbuff[ccline.cmdlen] = NUL;
2791 #ifdef FEAT_MBYTE
2792 if (enc_utf8)
2794 /* When the inserted text starts with a composing character,
2795 * backup to the character before it. There could be two of them.
2797 i = 0;
2798 c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
2799 while (ccline.cmdpos > 0 && utf_iscomposing(c))
2801 i = (*mb_head_off)(ccline.cmdbuff,
2802 ccline.cmdbuff + ccline.cmdpos - 1) + 1;
2803 ccline.cmdpos -= i;
2804 len += i;
2805 c = utf_ptr2char(ccline.cmdbuff + ccline.cmdpos);
2807 # ifdef FEAT_ARABIC
2808 if (i == 0 && ccline.cmdpos > 0 && arabic_maycombine(c))
2810 /* Check the previous character for Arabic combining pair. */
2811 i = (*mb_head_off)(ccline.cmdbuff,
2812 ccline.cmdbuff + ccline.cmdpos - 1) + 1;
2813 if (arabic_combine(utf_ptr2char(ccline.cmdbuff
2814 + ccline.cmdpos - i), c))
2816 ccline.cmdpos -= i;
2817 len += i;
2819 else
2820 i = 0;
2822 # endif
2823 if (i != 0)
2825 /* Also backup the cursor position. */
2826 i = ptr2cells(ccline.cmdbuff + ccline.cmdpos);
2827 ccline.cmdspos -= i;
2828 msg_col -= i;
2829 if (msg_col < 0)
2831 msg_col += Columns;
2832 --msg_row;
2836 #endif
2838 if (redraw && !cmd_silent)
2840 msg_no_more = TRUE;
2841 i = cmdline_row;
2842 draw_cmdline(ccline.cmdpos, ccline.cmdlen - ccline.cmdpos);
2843 /* Avoid clearing the rest of the line too often. */
2844 if (cmdline_row != i || ccline.overstrike)
2845 msg_clr_eos();
2846 msg_no_more = FALSE;
2848 #ifdef FEAT_FKMAP
2850 * If we are in Farsi command mode, the character input must be in
2851 * Insert mode. So do not advance the cmdpos.
2853 if (!cmd_fkmap)
2854 #endif
2856 if (KeyTyped)
2858 m = Columns * Rows;
2859 if (m < 0) /* overflow, Columns or Rows at weird value */
2860 m = MAXCOL;
2862 else
2863 m = MAXCOL;
2864 for (i = 0; i < len; ++i)
2866 c = cmdline_charsize(ccline.cmdpos);
2867 #ifdef FEAT_MBYTE
2868 /* count ">" for a double-wide char that doesn't fit. */
2869 if (has_mbyte)
2870 correct_cmdspos(ccline.cmdpos, c);
2871 #endif
2872 /* Stop cursor at the end of the screen, but do increment the
2873 * insert position, so that entering a very long command
2874 * works, even though you can't see it. */
2875 if (ccline.cmdspos + c < m)
2876 ccline.cmdspos += c;
2877 #ifdef FEAT_MBYTE
2878 if (has_mbyte)
2880 c = (*mb_ptr2len)(ccline.cmdbuff + ccline.cmdpos) - 1;
2881 if (c > len - i - 1)
2882 c = len - i - 1;
2883 ccline.cmdpos += c;
2884 i += c;
2886 #endif
2887 ++ccline.cmdpos;
2891 if (redraw)
2892 msg_check();
2893 return retval;
2896 static struct cmdline_info prev_ccline;
2897 static int prev_ccline_used = FALSE;
2900 * Save ccline, because obtaining the "=" register may execute "normal :cmd"
2901 * and overwrite it. But get_cmdline_str() may need it, thus make it
2902 * available globally in prev_ccline.
2904 static void
2905 save_cmdline(ccp)
2906 struct cmdline_info *ccp;
2908 if (!prev_ccline_used)
2910 vim_memset(&prev_ccline, 0, sizeof(struct cmdline_info));
2911 prev_ccline_used = TRUE;
2913 *ccp = prev_ccline;
2914 prev_ccline = ccline;
2915 ccline.cmdbuff = NULL;
2916 ccline.cmdprompt = NULL;
2917 ccline.xpc = NULL;
2921 * Restore ccline after it has been saved with save_cmdline().
2923 static void
2924 restore_cmdline(ccp)
2925 struct cmdline_info *ccp;
2927 ccline = prev_ccline;
2928 prev_ccline = *ccp;
2931 #if defined(FEAT_EVAL) || defined(PROTO)
2933 * Save the command line into allocated memory. Returns a pointer to be
2934 * passed to restore_cmdline_alloc() later.
2935 * Returns NULL when failed.
2937 char_u *
2938 save_cmdline_alloc()
2940 struct cmdline_info *p;
2942 p = (struct cmdline_info *)alloc((unsigned)sizeof(struct cmdline_info));
2943 if (p != NULL)
2944 save_cmdline(p);
2945 return (char_u *)p;
2949 * Restore the command line from the return value of save_cmdline_alloc().
2951 void
2952 restore_cmdline_alloc(p)
2953 char_u *p;
2955 if (p != NULL)
2957 restore_cmdline((struct cmdline_info *)p);
2958 vim_free(p);
2961 #endif
2964 * paste a yank register into the command line.
2965 * used by CTRL-R command in command-line mode
2966 * insert_reg() can't be used here, because special characters from the
2967 * register contents will be interpreted as commands.
2969 * return FAIL for failure, OK otherwise
2971 static int
2972 cmdline_paste(regname, literally, remcr)
2973 int regname;
2974 int literally; /* Insert text literally instead of "as typed" */
2975 int remcr; /* remove trailing CR */
2977 long i;
2978 char_u *arg;
2979 char_u *p;
2980 int allocated;
2981 struct cmdline_info save_ccline;
2983 /* check for valid regname; also accept special characters for CTRL-R in
2984 * the command line */
2985 if (regname != Ctrl_F && regname != Ctrl_P && regname != Ctrl_W
2986 && regname != Ctrl_A && !valid_yank_reg(regname, FALSE))
2987 return FAIL;
2989 /* A register containing CTRL-R can cause an endless loop. Allow using
2990 * CTRL-C to break the loop. */
2991 line_breakcheck();
2992 if (got_int)
2993 return FAIL;
2995 #ifdef FEAT_CLIPBOARD
2996 regname = may_get_selection(regname);
2997 #endif
2999 /* Need to save and restore ccline. And set "textlock" to avoid nasty
3000 * things like going to another buffer when evaluating an expression. */
3001 save_cmdline(&save_ccline);
3002 ++textlock;
3003 i = get_spec_reg(regname, &arg, &allocated, TRUE);
3004 --textlock;
3005 restore_cmdline(&save_ccline);
3007 if (i)
3009 /* Got the value of a special register in "arg". */
3010 if (arg == NULL)
3011 return FAIL;
3013 /* When 'incsearch' is set and CTRL-R CTRL-W used: skip the duplicate
3014 * part of the word. */
3015 p = arg;
3016 if (p_is && regname == Ctrl_W)
3018 char_u *w;
3019 int len;
3021 /* Locate start of last word in the cmd buffer. */
3022 for (w = ccline.cmdbuff + ccline.cmdlen; w > ccline.cmdbuff; )
3024 #ifdef FEAT_MBYTE
3025 if (has_mbyte)
3027 len = (*mb_head_off)(ccline.cmdbuff, w - 1) + 1;
3028 if (!vim_iswordc(mb_ptr2char(w - len)))
3029 break;
3030 w -= len;
3032 else
3033 #endif
3035 if (!vim_iswordc(w[-1]))
3036 break;
3037 --w;
3040 len = (int)((ccline.cmdbuff + ccline.cmdlen) - w);
3041 if (p_ic ? STRNICMP(w, arg, len) == 0 : STRNCMP(w, arg, len) == 0)
3042 p += len;
3045 cmdline_paste_str(p, literally);
3046 if (allocated)
3047 vim_free(arg);
3048 return OK;
3051 return cmdline_paste_reg(regname, literally, remcr);
3055 * Put a string on the command line.
3056 * When "literally" is TRUE, insert literally.
3057 * When "literally" is FALSE, insert as typed, but don't leave the command
3058 * line.
3060 void
3061 cmdline_paste_str(s, literally)
3062 char_u *s;
3063 int literally;
3065 int c, cv;
3067 if (literally)
3068 put_on_cmdline(s, -1, TRUE);
3069 else
3070 while (*s != NUL)
3072 cv = *s;
3073 if (cv == Ctrl_V && s[1])
3074 ++s;
3075 #ifdef FEAT_MBYTE
3076 if (has_mbyte)
3077 c = mb_cptr2char_adv(&s);
3078 else
3079 #endif
3080 c = *s++;
3081 if (cv == Ctrl_V || c == ESC || c == Ctrl_C || c == CAR || c == NL
3082 #ifdef UNIX
3083 || c == intr_char
3084 #endif
3085 || (c == Ctrl_BSL && *s == Ctrl_N))
3086 stuffcharReadbuff(Ctrl_V);
3087 stuffcharReadbuff(c);
3091 #ifdef FEAT_WILDMENU
3093 * Delete characters on the command line, from "from" to the current
3094 * position.
3096 static void
3097 cmdline_del(from)
3098 int from;
3100 mch_memmove(ccline.cmdbuff + from, ccline.cmdbuff + ccline.cmdpos,
3101 (size_t)(ccline.cmdlen - ccline.cmdpos + 1));
3102 ccline.cmdlen -= ccline.cmdpos - from;
3103 ccline.cmdpos = from;
3105 #endif
3108 * this function is called when the screen size changes and with incremental
3109 * search
3111 void
3112 redrawcmdline()
3114 if (cmd_silent)
3115 return;
3116 need_wait_return = FALSE;
3117 compute_cmdrow();
3118 redrawcmd();
3119 cursorcmd();
3122 static void
3123 redrawcmdprompt()
3125 int i;
3127 if (cmd_silent)
3128 return;
3129 if (ccline.cmdfirstc != NUL)
3130 msg_putchar(ccline.cmdfirstc);
3131 if (ccline.cmdprompt != NULL)
3133 msg_puts_attr(ccline.cmdprompt, ccline.cmdattr);
3134 ccline.cmdindent = msg_col + (msg_row - cmdline_row) * Columns;
3135 /* do the reverse of set_cmdspos() */
3136 if (ccline.cmdfirstc != NUL)
3137 --ccline.cmdindent;
3139 else
3140 for (i = ccline.cmdindent; i > 0; --i)
3141 msg_putchar(' ');
3145 * Redraw what is currently on the command line.
3147 void
3148 redrawcmd()
3150 if (cmd_silent)
3151 return;
3153 /* when 'incsearch' is set there may be no command line while redrawing */
3154 if (ccline.cmdbuff == NULL)
3156 windgoto(cmdline_row, 0);
3157 msg_clr_eos();
3158 return;
3161 msg_start();
3162 redrawcmdprompt();
3164 /* Don't use more prompt, truncate the cmdline if it doesn't fit. */
3165 msg_no_more = TRUE;
3166 draw_cmdline(0, ccline.cmdlen);
3167 msg_clr_eos();
3168 msg_no_more = FALSE;
3170 set_cmdspos_cursor();
3173 * An emsg() before may have set msg_scroll. This is used in normal mode,
3174 * in cmdline mode we can reset them now.
3176 msg_scroll = FALSE; /* next message overwrites cmdline */
3178 /* Typing ':' at the more prompt may set skip_redraw. We don't want this
3179 * in cmdline mode */
3180 skip_redraw = FALSE;
3183 void
3184 compute_cmdrow()
3186 if (exmode_active || msg_scrolled != 0)
3187 cmdline_row = Rows - 1;
3188 else
3189 cmdline_row = W_WINROW(lastwin) + lastwin->w_height
3190 + W_STATUS_HEIGHT(lastwin);
3193 static void
3194 cursorcmd()
3196 if (cmd_silent)
3197 return;
3199 #ifdef FEAT_RIGHTLEFT
3200 if (cmdmsg_rl)
3202 msg_row = cmdline_row + (ccline.cmdspos / (int)(Columns - 1));
3203 msg_col = (int)Columns - (ccline.cmdspos % (int)(Columns - 1)) - 1;
3204 if (msg_row <= 0)
3205 msg_row = Rows - 1;
3207 else
3208 #endif
3210 msg_row = cmdline_row + (ccline.cmdspos / (int)Columns);
3211 msg_col = ccline.cmdspos % (int)Columns;
3212 if (msg_row >= Rows)
3213 msg_row = Rows - 1;
3216 windgoto(msg_row, msg_col);
3217 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
3218 redrawcmd_preedit();
3219 #endif
3220 #ifdef MCH_CURSOR_SHAPE
3221 mch_update_cursor();
3222 #endif
3225 void
3226 gotocmdline(clr)
3227 int clr;
3229 msg_start();
3230 #ifdef FEAT_RIGHTLEFT
3231 if (cmdmsg_rl)
3232 msg_col = Columns - 1;
3233 else
3234 #endif
3235 msg_col = 0; /* always start in column 0 */
3236 if (clr) /* clear the bottom line(s) */
3237 msg_clr_eos(); /* will reset clear_cmdline */
3238 windgoto(cmdline_row, 0);
3242 * Check the word in front of the cursor for an abbreviation.
3243 * Called when the non-id character "c" has been entered.
3244 * When an abbreviation is recognized it is removed from the text with
3245 * backspaces and the replacement string is inserted, followed by "c".
3247 static int
3248 ccheck_abbr(c)
3249 int c;
3251 if (p_paste || no_abbr) /* no abbreviations or in paste mode */
3252 return FALSE;
3254 return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, 0);
3258 * Return FAIL if this is not an appropriate context in which to do
3259 * completion of anything, return OK if it is (even if there are no matches).
3260 * For the caller, this means that the character is just passed through like a
3261 * normal character (instead of being expanded). This allows :s/^I^D etc.
3263 static int
3264 nextwild(xp, type, options)
3265 expand_T *xp;
3266 int type;
3267 int options; /* extra options for ExpandOne() */
3269 int i, j;
3270 char_u *p1;
3271 char_u *p2;
3272 int oldlen;
3273 int difflen;
3274 int v;
3276 if (xp->xp_numfiles == -1)
3278 set_expand_context(xp);
3279 cmd_showtail = expand_showtail(xp);
3282 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
3284 beep_flush();
3285 return OK; /* Something illegal on command line */
3287 if (xp->xp_context == EXPAND_NOTHING)
3289 /* Caller can use the character as a normal char instead */
3290 return FAIL;
3293 MSG_PUTS("..."); /* show that we are busy */
3294 out_flush();
3296 i = (int)(xp->xp_pattern - ccline.cmdbuff);
3297 oldlen = ccline.cmdpos - i;
3299 if (type == WILD_NEXT || type == WILD_PREV)
3302 * Get next/previous match for a previous expanded pattern.
3304 p2 = ExpandOne(xp, NULL, NULL, 0, type);
3306 else
3309 * Translate string into pattern and expand it.
3311 if ((p1 = addstar(&ccline.cmdbuff[i], oldlen, xp->xp_context)) == NULL)
3312 p2 = NULL;
3313 else
3315 p2 = ExpandOne(xp, p1, vim_strnsave(&ccline.cmdbuff[i], oldlen),
3316 WILD_HOME_REPLACE|WILD_ADD_SLASH|WILD_SILENT|WILD_ESCAPE
3317 |options, type);
3318 vim_free(p1);
3319 /* longest match: make sure it is not shorter (happens with :help */
3320 if (p2 != NULL && type == WILD_LONGEST)
3322 for (j = 0; j < oldlen; ++j)
3323 if (ccline.cmdbuff[i + j] == '*'
3324 || ccline.cmdbuff[i + j] == '?')
3325 break;
3326 if ((int)STRLEN(p2) < j)
3328 vim_free(p2);
3329 p2 = NULL;
3335 if (p2 != NULL && !got_int)
3337 difflen = (int)STRLEN(p2) - oldlen;
3338 if (ccline.cmdlen + difflen > ccline.cmdbufflen - 4)
3340 v = realloc_cmdbuff(ccline.cmdlen + difflen);
3341 xp->xp_pattern = ccline.cmdbuff + i;
3343 else
3344 v = OK;
3345 if (v == OK)
3347 mch_memmove(&ccline.cmdbuff[ccline.cmdpos + difflen],
3348 &ccline.cmdbuff[ccline.cmdpos],
3349 (size_t)(ccline.cmdlen - ccline.cmdpos + 1));
3350 mch_memmove(&ccline.cmdbuff[i], p2, STRLEN(p2));
3351 ccline.cmdlen += difflen;
3352 ccline.cmdpos += difflen;
3355 vim_free(p2);
3357 redrawcmd();
3358 cursorcmd();
3360 /* When expanding a ":map" command and no matches are found, assume that
3361 * the key is supposed to be inserted literally */
3362 if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL)
3363 return FAIL;
3365 if (xp->xp_numfiles <= 0 && p2 == NULL)
3366 beep_flush();
3367 else if (xp->xp_numfiles == 1)
3368 /* free expanded pattern */
3369 (void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE);
3371 return OK;
3375 * Do wildcard expansion on the string 'str'.
3376 * Chars that should not be expanded must be preceded with a backslash.
3377 * Return a pointer to allocated memory containing the new string.
3378 * Return NULL for failure.
3380 * "orig" is the originally expanded string, copied to allocated memory. It
3381 * should either be kept in orig_save or freed. When "mode" is WILD_NEXT or
3382 * WILD_PREV "orig" should be NULL.
3384 * Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode"
3385 * is WILD_EXPAND_FREE or WILD_ALL.
3387 * mode = WILD_FREE: just free previously expanded matches
3388 * mode = WILD_EXPAND_FREE: normal expansion, do not keep matches
3389 * mode = WILD_EXPAND_KEEP: normal expansion, keep matches
3390 * mode = WILD_NEXT: use next match in multiple match, wrap to first
3391 * mode = WILD_PREV: use previous match in multiple match, wrap to first
3392 * mode = WILD_ALL: return all matches concatenated
3393 * mode = WILD_LONGEST: return longest matched part
3395 * options = WILD_LIST_NOTFOUND: list entries without a match
3396 * options = WILD_HOME_REPLACE: do home_replace() for buffer names
3397 * options = WILD_USE_NL: Use '\n' for WILD_ALL
3398 * options = WILD_NO_BEEP: Don't beep for multiple matches
3399 * options = WILD_ADD_SLASH: add a slash after directory names
3400 * options = WILD_KEEP_ALL: don't remove 'wildignore' entries
3401 * options = WILD_SILENT: don't print warning messages
3402 * options = WILD_ESCAPE: put backslash before special chars
3404 * The variables xp->xp_context and xp->xp_backslash must have been set!
3406 char_u *
3407 ExpandOne(xp, str, orig, options, mode)
3408 expand_T *xp;
3409 char_u *str;
3410 char_u *orig; /* allocated copy of original of expanded string */
3411 int options;
3412 int mode;
3414 char_u *ss = NULL;
3415 static int findex;
3416 static char_u *orig_save = NULL; /* kept value of orig */
3417 int orig_saved = FALSE;
3418 int i;
3419 long_u len;
3420 int non_suf_match; /* number without matching suffix */
3423 * first handle the case of using an old match
3425 if (mode == WILD_NEXT || mode == WILD_PREV)
3427 if (xp->xp_numfiles > 0)
3429 if (mode == WILD_PREV)
3431 if (findex == -1)
3432 findex = xp->xp_numfiles;
3433 --findex;
3435 else /* mode == WILD_NEXT */
3436 ++findex;
3439 * When wrapping around, return the original string, set findex to
3440 * -1.
3442 if (findex < 0)
3444 if (orig_save == NULL)
3445 findex = xp->xp_numfiles - 1;
3446 else
3447 findex = -1;
3449 if (findex >= xp->xp_numfiles)
3451 if (orig_save == NULL)
3452 findex = 0;
3453 else
3454 findex = -1;
3456 #ifdef FEAT_WILDMENU
3457 if (p_wmnu)
3458 win_redr_status_matches(xp, xp->xp_numfiles, xp->xp_files,
3459 findex, cmd_showtail);
3460 #endif
3461 if (findex == -1)
3462 return vim_strsave(orig_save);
3463 return vim_strsave(xp->xp_files[findex]);
3465 else
3466 return NULL;
3469 /* free old names */
3470 if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST)
3472 FreeWild(xp->xp_numfiles, xp->xp_files);
3473 xp->xp_numfiles = -1;
3474 vim_free(orig_save);
3475 orig_save = NULL;
3477 findex = 0;
3479 if (mode == WILD_FREE) /* only release file name */
3480 return NULL;
3482 if (xp->xp_numfiles == -1)
3484 vim_free(orig_save);
3485 orig_save = orig;
3486 orig_saved = TRUE;
3489 * Do the expansion.
3491 if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files,
3492 options) == FAIL)
3494 #ifdef FNAME_ILLEGAL
3495 /* Illegal file name has been silently skipped. But when there
3496 * are wildcards, the real problem is that there was no match,
3497 * causing the pattern to be added, which has illegal characters.
3499 if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND))
3500 EMSG2(_(e_nomatch2), str);
3501 #endif
3503 else if (xp->xp_numfiles == 0)
3505 if (!(options & WILD_SILENT))
3506 EMSG2(_(e_nomatch2), str);
3508 else
3510 /* Escape the matches for use on the command line. */
3511 ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
3514 * Check for matching suffixes in file names.
3516 if (mode != WILD_ALL && mode != WILD_LONGEST)
3518 if (xp->xp_numfiles)
3519 non_suf_match = xp->xp_numfiles;
3520 else
3521 non_suf_match = 1;
3522 if ((xp->xp_context == EXPAND_FILES
3523 || xp->xp_context == EXPAND_DIRECTORIES)
3524 && xp->xp_numfiles > 1)
3527 * More than one match; check suffix.
3528 * The files will have been sorted on matching suffix in
3529 * expand_wildcards, only need to check the first two.
3531 non_suf_match = 0;
3532 for (i = 0; i < 2; ++i)
3533 if (match_suffix(xp->xp_files[i]))
3534 ++non_suf_match;
3536 if (non_suf_match != 1)
3538 /* Can we ever get here unless it's while expanding
3539 * interactively? If not, we can get rid of this all
3540 * together. Don't really want to wait for this message
3541 * (and possibly have to hit return to continue!).
3543 if (!(options & WILD_SILENT))
3544 EMSG(_(e_toomany));
3545 else if (!(options & WILD_NO_BEEP))
3546 beep_flush();
3548 if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE))
3549 ss = vim_strsave(xp->xp_files[0]);
3554 /* Find longest common part */
3555 if (mode == WILD_LONGEST && xp->xp_numfiles > 0)
3557 for (len = 0; xp->xp_files[0][len]; ++len)
3559 for (i = 0; i < xp->xp_numfiles; ++i)
3561 #ifdef CASE_INSENSITIVE_FILENAME
3562 if (xp->xp_context == EXPAND_DIRECTORIES
3563 || xp->xp_context == EXPAND_FILES
3564 || xp->xp_context == EXPAND_SHELLCMD
3565 || xp->xp_context == EXPAND_BUFFERS)
3567 if (TOLOWER_LOC(xp->xp_files[i][len]) !=
3568 TOLOWER_LOC(xp->xp_files[0][len]))
3569 break;
3571 else
3572 #endif
3573 if (xp->xp_files[i][len] != xp->xp_files[0][len])
3574 break;
3576 if (i < xp->xp_numfiles)
3578 if (!(options & WILD_NO_BEEP))
3579 vim_beep();
3580 break;
3583 ss = alloc((unsigned)len + 1);
3584 if (ss)
3585 vim_strncpy(ss, xp->xp_files[0], (size_t)len);
3586 findex = -1; /* next p_wc gets first one */
3589 /* Concatenate all matching names */
3590 if (mode == WILD_ALL && xp->xp_numfiles > 0)
3592 len = 0;
3593 for (i = 0; i < xp->xp_numfiles; ++i)
3594 len += (long_u)STRLEN(xp->xp_files[i]) + 1;
3595 ss = lalloc(len, TRUE);
3596 if (ss != NULL)
3598 *ss = NUL;
3599 for (i = 0; i < xp->xp_numfiles; ++i)
3601 STRCAT(ss, xp->xp_files[i]);
3602 if (i != xp->xp_numfiles - 1)
3603 STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " ");
3608 if (mode == WILD_EXPAND_FREE || mode == WILD_ALL)
3609 ExpandCleanup(xp);
3611 /* Free "orig" if it wasn't stored in "orig_save". */
3612 if (!orig_saved)
3613 vim_free(orig);
3615 return ss;
3619 * Prepare an expand structure for use.
3621 void
3622 ExpandInit(xp)
3623 expand_T *xp;
3625 xp->xp_pattern = NULL;
3626 xp->xp_backslash = XP_BS_NONE;
3627 #ifndef BACKSLASH_IN_FILENAME
3628 xp->xp_shell = FALSE;
3629 #endif
3630 xp->xp_numfiles = -1;
3631 xp->xp_files = NULL;
3632 #if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL) && defined(FEAT_CMDL_COMPL)
3633 xp->xp_arg = NULL;
3634 #endif
3638 * Cleanup an expand structure after use.
3640 void
3641 ExpandCleanup(xp)
3642 expand_T *xp;
3644 if (xp->xp_numfiles >= 0)
3646 FreeWild(xp->xp_numfiles, xp->xp_files);
3647 xp->xp_numfiles = -1;
3651 void
3652 ExpandEscape(xp, str, numfiles, files, options)
3653 expand_T *xp;
3654 char_u *str;
3655 int numfiles;
3656 char_u **files;
3657 int options;
3659 int i;
3660 char_u *p;
3663 * May change home directory back to "~"
3665 if (options & WILD_HOME_REPLACE)
3666 tilde_replace(str, numfiles, files);
3668 if (options & WILD_ESCAPE)
3670 if (xp->xp_context == EXPAND_FILES
3671 || xp->xp_context == EXPAND_SHELLCMD
3672 || xp->xp_context == EXPAND_BUFFERS
3673 || xp->xp_context == EXPAND_DIRECTORIES)
3676 * Insert a backslash into a file name before a space, \, %, #
3677 * and wildmatch characters, except '~'.
3679 for (i = 0; i < numfiles; ++i)
3681 /* for ":set path=" we need to escape spaces twice */
3682 if (xp->xp_backslash == XP_BS_THREE)
3684 p = vim_strsave_escaped(files[i], (char_u *)" ");
3685 if (p != NULL)
3687 vim_free(files[i]);
3688 files[i] = p;
3689 #if defined(BACKSLASH_IN_FILENAME)
3690 p = vim_strsave_escaped(files[i], (char_u *)" ");
3691 if (p != NULL)
3693 vim_free(files[i]);
3694 files[i] = p;
3696 #endif
3699 #ifdef BACKSLASH_IN_FILENAME
3700 p = vim_strsave_fnameescape(files[i], FALSE);
3701 #else
3702 p = vim_strsave_fnameescape(files[i], xp->xp_shell);
3703 #endif
3704 if (p != NULL)
3706 vim_free(files[i]);
3707 files[i] = p;
3710 /* If 'str' starts with "\~", replace "~" at start of
3711 * files[i] with "\~". */
3712 if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~')
3713 escape_fname(&files[i]);
3715 xp->xp_backslash = XP_BS_NONE;
3717 /* If the first file starts with a '+' escape it. Otherwise it
3718 * could be seen as "+cmd". */
3719 if (*files[0] == '+')
3720 escape_fname(&files[0]);
3722 else if (xp->xp_context == EXPAND_TAGS)
3725 * Insert a backslash before characters in a tag name that
3726 * would terminate the ":tag" command.
3728 for (i = 0; i < numfiles; ++i)
3730 p = vim_strsave_escaped(files[i], (char_u *)"\\|\"");
3731 if (p != NULL)
3733 vim_free(files[i]);
3734 files[i] = p;
3742 * Escape special characters in "fname" for when used as a file name argument
3743 * after a Vim command, or, when "shell" is non-zero, a shell command.
3744 * Returns the result in allocated memory.
3746 char_u *
3747 vim_strsave_fnameescape(fname, shell)
3748 char_u *fname;
3749 int shell;
3751 char_u *p;
3752 #ifdef BACKSLASH_IN_FILENAME
3753 char_u buf[20];
3754 int j = 0;
3756 /* Don't escape '[' and '{' if they are in 'isfname'. */
3757 for (p = PATH_ESC_CHARS; *p != NUL; ++p)
3758 if ((*p != '[' && *p != '{') || !vim_isfilec(*p))
3759 buf[j++] = *p;
3760 buf[j] = NUL;
3761 p = vim_strsave_escaped(fname, buf);
3762 #else
3763 p = vim_strsave_escaped(fname, shell ? SHELL_ESC_CHARS : PATH_ESC_CHARS);
3764 if (shell && csh_like_shell() && p != NULL)
3766 char_u *s;
3768 /* For csh and similar shells need to put two backslashes before '!'.
3769 * One is taken by Vim, one by the shell. */
3770 s = vim_strsave_escaped(p, (char_u *)"!");
3771 vim_free(p);
3772 p = s;
3774 #endif
3776 /* '>' and '+' are special at the start of some commands, e.g. ":edit" and
3777 * ":write". "cd -" has a special meaning. */
3778 if (*p == '>' || *p == '+' || (*p == '-' && p[1] == NUL))
3779 escape_fname(&p);
3781 return p;
3785 * Put a backslash before the file name in "pp", which is in allocated memory.
3787 static void
3788 escape_fname(pp)
3789 char_u **pp;
3791 char_u *p;
3793 p = alloc((unsigned)(STRLEN(*pp) + 2));
3794 if (p != NULL)
3796 p[0] = '\\';
3797 STRCPY(p + 1, *pp);
3798 vim_free(*pp);
3799 *pp = p;
3804 * For each file name in files[num_files]:
3805 * If 'orig_pat' starts with "~/", replace the home directory with "~".
3807 void
3808 tilde_replace(orig_pat, num_files, files)
3809 char_u *orig_pat;
3810 int num_files;
3811 char_u **files;
3813 int i;
3814 char_u *p;
3816 if (orig_pat[0] == '~' && vim_ispathsep(orig_pat[1]))
3818 for (i = 0; i < num_files; ++i)
3820 p = home_replace_save(NULL, files[i]);
3821 if (p != NULL)
3823 vim_free(files[i]);
3824 files[i] = p;
3831 * Show all matches for completion on the command line.
3832 * Returns EXPAND_NOTHING when the character that triggered expansion should
3833 * be inserted like a normal character.
3835 /*ARGSUSED*/
3836 static int
3837 showmatches(xp, wildmenu)
3838 expand_T *xp;
3839 int wildmenu;
3841 #define L_SHOWFILE(m) (showtail ? sm_gettail(files_found[m]) : files_found[m])
3842 int num_files;
3843 char_u **files_found;
3844 int i, j, k;
3845 int maxlen;
3846 int lines;
3847 int columns;
3848 char_u *p;
3849 int lastlen;
3850 int attr;
3851 int showtail;
3853 if (xp->xp_numfiles == -1)
3855 set_expand_context(xp);
3856 i = expand_cmdline(xp, ccline.cmdbuff, ccline.cmdpos,
3857 &num_files, &files_found);
3858 showtail = expand_showtail(xp);
3859 if (i != EXPAND_OK)
3860 return i;
3863 else
3865 num_files = xp->xp_numfiles;
3866 files_found = xp->xp_files;
3867 showtail = cmd_showtail;
3870 #ifdef FEAT_WILDMENU
3871 if (!wildmenu)
3873 #endif
3874 msg_didany = FALSE; /* lines_left will be set */
3875 msg_start(); /* prepare for paging */
3876 msg_putchar('\n');
3877 out_flush();
3878 cmdline_row = msg_row;
3879 msg_didany = FALSE; /* lines_left will be set again */
3880 msg_start(); /* prepare for paging */
3881 #ifdef FEAT_WILDMENU
3883 #endif
3885 if (got_int)
3886 got_int = FALSE; /* only int. the completion, not the cmd line */
3887 #ifdef FEAT_WILDMENU
3888 else if (wildmenu)
3889 win_redr_status_matches(xp, num_files, files_found, 0, showtail);
3890 #endif
3891 else
3893 /* find the length of the longest file name */
3894 maxlen = 0;
3895 for (i = 0; i < num_files; ++i)
3897 if (!showtail && (xp->xp_context == EXPAND_FILES
3898 || xp->xp_context == EXPAND_SHELLCMD
3899 || xp->xp_context == EXPAND_BUFFERS))
3901 home_replace(NULL, files_found[i], NameBuff, MAXPATHL, TRUE);
3902 j = vim_strsize(NameBuff);
3904 else
3905 j = vim_strsize(L_SHOWFILE(i));
3906 if (j > maxlen)
3907 maxlen = j;
3910 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
3911 lines = num_files;
3912 else
3914 /* compute the number of columns and lines for the listing */
3915 maxlen += 2; /* two spaces between file names */
3916 columns = ((int)Columns + 2) / maxlen;
3917 if (columns < 1)
3918 columns = 1;
3919 lines = (num_files + columns - 1) / columns;
3922 attr = hl_attr(HLF_D); /* find out highlighting for directories */
3924 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
3926 MSG_PUTS_ATTR(_("tagname"), hl_attr(HLF_T));
3927 msg_clr_eos();
3928 msg_advance(maxlen - 3);
3929 MSG_PUTS_ATTR(_(" kind file\n"), hl_attr(HLF_T));
3932 /* list the files line by line */
3933 for (i = 0; i < lines; ++i)
3935 lastlen = 999;
3936 for (k = i; k < num_files; k += lines)
3938 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
3940 msg_outtrans_attr(files_found[k], hl_attr(HLF_D));
3941 p = files_found[k] + STRLEN(files_found[k]) + 1;
3942 msg_advance(maxlen + 1);
3943 msg_puts(p);
3944 msg_advance(maxlen + 3);
3945 msg_puts_long_attr(p + 2, hl_attr(HLF_D));
3946 break;
3948 for (j = maxlen - lastlen; --j >= 0; )
3949 msg_putchar(' ');
3950 if (xp->xp_context == EXPAND_FILES
3951 || xp->xp_context == EXPAND_SHELLCMD
3952 || xp->xp_context == EXPAND_BUFFERS)
3954 /* highlight directories */
3955 j = (mch_isdir(files_found[k]));
3956 if (showtail)
3957 p = L_SHOWFILE(k);
3958 else
3960 home_replace(NULL, files_found[k], NameBuff, MAXPATHL,
3961 TRUE);
3962 p = NameBuff;
3965 else
3967 j = FALSE;
3968 p = L_SHOWFILE(k);
3970 lastlen = msg_outtrans_attr(p, j ? attr : 0);
3972 if (msg_col > 0) /* when not wrapped around */
3974 msg_clr_eos();
3975 msg_putchar('\n');
3977 out_flush(); /* show one line at a time */
3978 if (got_int)
3980 got_int = FALSE;
3981 break;
3986 * we redraw the command below the lines that we have just listed
3987 * This is a bit tricky, but it saves a lot of screen updating.
3989 cmdline_row = msg_row; /* will put it back later */
3992 if (xp->xp_numfiles == -1)
3993 FreeWild(num_files, files_found);
3995 return EXPAND_OK;
3999 * Private gettail for showmatches() (and win_redr_status_matches()):
4000 * Find tail of file name path, but ignore trailing "/".
4002 char_u *
4003 sm_gettail(s)
4004 char_u *s;
4006 char_u *p;
4007 char_u *t = s;
4008 int had_sep = FALSE;
4010 for (p = s; *p != NUL; )
4012 if (vim_ispathsep(*p)
4013 #ifdef BACKSLASH_IN_FILENAME
4014 && !rem_backslash(p)
4015 #endif
4017 had_sep = TRUE;
4018 else if (had_sep)
4020 t = p;
4021 had_sep = FALSE;
4023 mb_ptr_adv(p);
4025 return t;
4029 * Return TRUE if we only need to show the tail of completion matches.
4030 * When not completing file names or there is a wildcard in the path FALSE is
4031 * returned.
4033 static int
4034 expand_showtail(xp)
4035 expand_T *xp;
4037 char_u *s;
4038 char_u *end;
4040 /* When not completing file names a "/" may mean something different. */
4041 if (xp->xp_context != EXPAND_FILES
4042 && xp->xp_context != EXPAND_SHELLCMD
4043 && xp->xp_context != EXPAND_DIRECTORIES)
4044 return FALSE;
4046 end = gettail(xp->xp_pattern);
4047 if (end == xp->xp_pattern) /* there is no path separator */
4048 return FALSE;
4050 for (s = xp->xp_pattern; s < end; s++)
4052 /* Skip escaped wildcards. Only when the backslash is not a path
4053 * separator, on DOS the '*' "path\*\file" must not be skipped. */
4054 if (rem_backslash(s))
4055 ++s;
4056 else if (vim_strchr((char_u *)"*?[", *s) != NULL)
4057 return FALSE;
4059 return TRUE;
4063 * Prepare a string for expansion.
4064 * When expanding file names: The string will be used with expand_wildcards().
4065 * Copy the file name into allocated memory and add a '*' at the end.
4066 * When expanding other names: The string will be used with regcomp(). Copy
4067 * the name into allocated memory and prepend "^".
4069 char_u *
4070 addstar(fname, len, context)
4071 char_u *fname;
4072 int len;
4073 int context; /* EXPAND_FILES etc. */
4075 char_u *retval;
4076 int i, j;
4077 int new_len;
4078 char_u *tail;
4080 if (context != EXPAND_FILES
4081 && context != EXPAND_SHELLCMD
4082 && context != EXPAND_DIRECTORIES)
4085 * Matching will be done internally (on something other than files).
4086 * So we convert the file-matching-type wildcards into our kind for
4087 * use with vim_regcomp(). First work out how long it will be:
4090 /* For help tags the translation is done in find_help_tags().
4091 * For a tag pattern starting with "/" no translation is needed. */
4092 if (context == EXPAND_HELP
4093 || context == EXPAND_COLORS
4094 || context == EXPAND_COMPILER
4095 || (context == EXPAND_TAGS && fname[0] == '/'))
4096 retval = vim_strnsave(fname, len);
4097 else
4099 new_len = len + 2; /* +2 for '^' at start, NUL at end */
4100 for (i = 0; i < len; i++)
4102 if (fname[i] == '*' || fname[i] == '~')
4103 new_len++; /* '*' needs to be replaced by ".*"
4104 '~' needs to be replaced by "\~" */
4106 /* Buffer names are like file names. "." should be literal */
4107 if (context == EXPAND_BUFFERS && fname[i] == '.')
4108 new_len++; /* "." becomes "\." */
4110 /* Custom expansion takes care of special things, match
4111 * backslashes literally (perhaps also for other types?) */
4112 if ((context == EXPAND_USER_DEFINED
4113 || context == EXPAND_USER_LIST) && fname[i] == '\\')
4114 new_len++; /* '\' becomes "\\" */
4116 retval = alloc(new_len);
4117 if (retval != NULL)
4119 retval[0] = '^';
4120 j = 1;
4121 for (i = 0; i < len; i++, j++)
4123 /* Skip backslash. But why? At least keep it for custom
4124 * expansion. */
4125 if (context != EXPAND_USER_DEFINED
4126 && context != EXPAND_USER_LIST
4127 && fname[i] == '\\'
4128 && ++i == len)
4129 break;
4131 switch (fname[i])
4133 case '*': retval[j++] = '.';
4134 break;
4135 case '~': retval[j++] = '\\';
4136 break;
4137 case '?': retval[j] = '.';
4138 continue;
4139 case '.': if (context == EXPAND_BUFFERS)
4140 retval[j++] = '\\';
4141 break;
4142 case '\\': if (context == EXPAND_USER_DEFINED
4143 || context == EXPAND_USER_LIST)
4144 retval[j++] = '\\';
4145 break;
4147 retval[j] = fname[i];
4149 retval[j] = NUL;
4153 else
4155 retval = alloc(len + 4);
4156 if (retval != NULL)
4158 vim_strncpy(retval, fname, len);
4161 * Don't add a star to *, ~, ~user, $var or `cmd`.
4162 * * would become **, which walks the whole tree.
4163 * ~ would be at the start of the file name, but not the tail.
4164 * $ could be anywhere in the tail.
4165 * ` could be anywhere in the file name.
4166 * When the name ends in '$' don't add a star, remove the '$'.
4168 tail = gettail(retval);
4169 if ((*retval != '~' || tail != retval)
4170 && (len == 0 || retval[len - 1] != '*')
4171 && vim_strchr(tail, '$') == NULL
4172 && vim_strchr(retval, '`') == NULL)
4173 retval[len++] = '*';
4174 else if (len > 0 && retval[len - 1] == '$')
4175 --len;
4176 retval[len] = NUL;
4179 return retval;
4183 * Must parse the command line so far to work out what context we are in.
4184 * Completion can then be done based on that context.
4185 * This routine sets the variables:
4186 * xp->xp_pattern The start of the pattern to be expanded within
4187 * the command line (ends at the cursor).
4188 * xp->xp_context The type of thing to expand. Will be one of:
4190 * EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on
4191 * the command line, like an unknown command. Caller
4192 * should beep.
4193 * EXPAND_NOTHING Unrecognised context for completion, use char like
4194 * a normal char, rather than for completion. eg
4195 * :s/^I/
4196 * EXPAND_COMMANDS Cursor is still touching the command, so complete
4197 * it.
4198 * EXPAND_BUFFERS Complete file names for :buf and :sbuf commands.
4199 * EXPAND_FILES After command with XFILE set, or after setting
4200 * with P_EXPAND set. eg :e ^I, :w>>^I
4201 * EXPAND_DIRECTORIES In some cases this is used instead of the latter
4202 * when we know only directories are of interest. eg
4203 * :set dir=^I
4204 * EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd".
4205 * EXPAND_SETTINGS Complete variable names. eg :set d^I
4206 * EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I
4207 * EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I
4208 * EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect
4209 * EXPAND_HELP Complete tags from the file 'helpfile'/tags
4210 * EXPAND_EVENTS Complete event names
4211 * EXPAND_SYNTAX Complete :syntax command arguments
4212 * EXPAND_HIGHLIGHT Complete highlight (syntax) group names
4213 * EXPAND_AUGROUP Complete autocommand group names
4214 * EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I
4215 * EXPAND_MAPPINGS Complete mapping and abbreviation names,
4216 * eg :unmap a^I , :cunab x^I
4217 * EXPAND_FUNCTIONS Complete internal or user defined function names,
4218 * eg :call sub^I
4219 * EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I
4220 * EXPAND_EXPRESSION Complete internal or user defined function/variable
4221 * names in expressions, eg :while s^I
4222 * EXPAND_ENV_VARS Complete environment variable names
4224 static void
4225 set_expand_context(xp)
4226 expand_T *xp;
4228 /* only expansion for ':', '>' and '=' command-lines */
4229 if (ccline.cmdfirstc != ':'
4230 #ifdef FEAT_EVAL
4231 && ccline.cmdfirstc != '>' && ccline.cmdfirstc != '='
4232 && !ccline.input_fn
4233 #endif
4236 xp->xp_context = EXPAND_NOTHING;
4237 return;
4239 set_cmd_context(xp, ccline.cmdbuff, ccline.cmdlen, ccline.cmdpos);
4242 void
4243 set_cmd_context(xp, str, len, col)
4244 expand_T *xp;
4245 char_u *str; /* start of command line */
4246 int len; /* length of command line (excl. NUL) */
4247 int col; /* position of cursor */
4249 int old_char = NUL;
4250 char_u *nextcomm;
4253 * Avoid a UMR warning from Purify, only save the character if it has been
4254 * written before.
4256 if (col < len)
4257 old_char = str[col];
4258 str[col] = NUL;
4259 nextcomm = str;
4261 #ifdef FEAT_EVAL
4262 if (ccline.cmdfirstc == '=')
4264 # ifdef FEAT_CMDL_COMPL
4265 /* pass CMD_SIZE because there is no real command */
4266 set_context_for_expression(xp, str, CMD_SIZE);
4267 # endif
4269 else if (ccline.input_fn)
4271 xp->xp_context = ccline.xp_context;
4272 xp->xp_pattern = ccline.cmdbuff;
4273 # if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
4274 xp->xp_arg = ccline.xp_arg;
4275 # endif
4277 else
4278 #endif
4279 while (nextcomm != NULL)
4280 nextcomm = set_one_cmd_context(xp, nextcomm);
4282 str[col] = old_char;
4286 * Expand the command line "str" from context "xp".
4287 * "xp" must have been set by set_cmd_context().
4288 * xp->xp_pattern points into "str", to where the text that is to be expanded
4289 * starts.
4290 * Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
4291 * cursor.
4292 * Returns EXPAND_NOTHING when there is nothing to expand, might insert the
4293 * key that triggered expansion literally.
4294 * Returns EXPAND_OK otherwise.
4297 expand_cmdline(xp, str, col, matchcount, matches)
4298 expand_T *xp;
4299 char_u *str; /* start of command line */
4300 int col; /* position of cursor */
4301 int *matchcount; /* return: nr of matches */
4302 char_u ***matches; /* return: array of pointers to matches */
4304 char_u *file_str = NULL;
4306 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
4308 beep_flush();
4309 return EXPAND_UNSUCCESSFUL; /* Something illegal on command line */
4311 if (xp->xp_context == EXPAND_NOTHING)
4313 /* Caller can use the character as a normal char instead */
4314 return EXPAND_NOTHING;
4317 /* add star to file name, or convert to regexp if not exp. files. */
4318 file_str = addstar(xp->xp_pattern,
4319 (int)(str + col - xp->xp_pattern), xp->xp_context);
4320 if (file_str == NULL)
4321 return EXPAND_UNSUCCESSFUL;
4323 /* find all files that match the description */
4324 if (ExpandFromContext(xp, file_str, matchcount, matches,
4325 WILD_ADD_SLASH|WILD_SILENT) == FAIL)
4327 *matchcount = 0;
4328 *matches = NULL;
4330 vim_free(file_str);
4332 return EXPAND_OK;
4335 #ifdef FEAT_MULTI_LANG
4337 * Cleanup matches for help tags: remove "@en" if "en" is the only language.
4339 static void cleanup_help_tags __ARGS((int num_file, char_u **file));
4341 static void
4342 cleanup_help_tags(num_file, file)
4343 int num_file;
4344 char_u **file;
4346 int i, j;
4347 int len;
4349 for (i = 0; i < num_file; ++i)
4351 len = (int)STRLEN(file[i]) - 3;
4352 if (len > 0 && STRCMP(file[i] + len, "@en") == 0)
4354 /* Sorting on priority means the same item in another language may
4355 * be anywhere. Search all items for a match up to the "@en". */
4356 for (j = 0; j < num_file; ++j)
4357 if (j != i
4358 && (int)STRLEN(file[j]) == len + 3
4359 && STRNCMP(file[i], file[j], len + 1) == 0)
4360 break;
4361 if (j == num_file)
4362 file[i][len] = NUL;
4366 #endif
4369 * Do the expansion based on xp->xp_context and "pat".
4371 static int
4372 ExpandFromContext(xp, pat, num_file, file, options)
4373 expand_T *xp;
4374 char_u *pat;
4375 int *num_file;
4376 char_u ***file;
4377 int options;
4379 #ifdef FEAT_CMDL_COMPL
4380 regmatch_T regmatch;
4381 #endif
4382 int ret;
4383 int flags;
4385 flags = EW_DIR; /* include directories */
4386 if (options & WILD_LIST_NOTFOUND)
4387 flags |= EW_NOTFOUND;
4388 if (options & WILD_ADD_SLASH)
4389 flags |= EW_ADDSLASH;
4390 if (options & WILD_KEEP_ALL)
4391 flags |= EW_KEEPALL;
4392 if (options & WILD_SILENT)
4393 flags |= EW_SILENT;
4395 if (xp->xp_context == EXPAND_FILES || xp->xp_context == EXPAND_DIRECTORIES)
4398 * Expand file or directory names.
4400 int free_pat = FALSE;
4401 int i;
4403 /* for ":set path=" and ":set tags=" halve backslashes for escaped
4404 * space */
4405 if (xp->xp_backslash != XP_BS_NONE)
4407 free_pat = TRUE;
4408 pat = vim_strsave(pat);
4409 for (i = 0; pat[i]; ++i)
4410 if (pat[i] == '\\')
4412 if (xp->xp_backslash == XP_BS_THREE
4413 && pat[i + 1] == '\\'
4414 && pat[i + 2] == '\\'
4415 && pat[i + 3] == ' ')
4416 STRMOVE(pat + i, pat + i + 3);
4417 if (xp->xp_backslash == XP_BS_ONE
4418 && pat[i + 1] == ' ')
4419 STRMOVE(pat + i, pat + i + 1);
4423 if (xp->xp_context == EXPAND_FILES)
4424 flags |= EW_FILE;
4425 else
4426 flags = (flags | EW_DIR) & ~EW_FILE;
4427 ret = expand_wildcards(1, &pat, num_file, file, flags);
4428 if (free_pat)
4429 vim_free(pat);
4430 return ret;
4433 *file = (char_u **)"";
4434 *num_file = 0;
4435 if (xp->xp_context == EXPAND_HELP)
4437 /* With an empty argument we would get all the help tags, which is
4438 * very slow. Get matches for "help" instead. */
4439 if (find_help_tags(*pat == NUL ? (char_u *)"help" : pat,
4440 num_file, file, FALSE) == OK)
4442 #ifdef FEAT_MULTI_LANG
4443 cleanup_help_tags(*num_file, *file);
4444 #endif
4445 return OK;
4447 return FAIL;
4450 #ifndef FEAT_CMDL_COMPL
4451 return FAIL;
4452 #else
4453 if (xp->xp_context == EXPAND_SHELLCMD)
4454 return expand_shellcmd(pat, num_file, file, flags);
4455 if (xp->xp_context == EXPAND_OLD_SETTING)
4456 return ExpandOldSetting(num_file, file);
4457 if (xp->xp_context == EXPAND_BUFFERS)
4458 return ExpandBufnames(pat, num_file, file, options);
4459 if (xp->xp_context == EXPAND_TAGS
4460 || xp->xp_context == EXPAND_TAGS_LISTFILES)
4461 return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
4462 if (xp->xp_context == EXPAND_COLORS)
4463 return ExpandRTDir(pat, num_file, file, "colors");
4464 if (xp->xp_context == EXPAND_COMPILER)
4465 return ExpandRTDir(pat, num_file, file, "compiler");
4466 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
4467 if (xp->xp_context == EXPAND_USER_LIST)
4468 return ExpandUserList(xp, num_file, file);
4469 # endif
4471 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
4472 if (regmatch.regprog == NULL)
4473 return FAIL;
4475 /* set ignore-case according to p_ic, p_scs and pat */
4476 regmatch.rm_ic = ignorecase(pat);
4478 if (xp->xp_context == EXPAND_SETTINGS
4479 || xp->xp_context == EXPAND_BOOL_SETTINGS)
4480 ret = ExpandSettings(xp, &regmatch, num_file, file);
4481 else if (xp->xp_context == EXPAND_MAPPINGS)
4482 ret = ExpandMappings(&regmatch, num_file, file);
4483 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
4484 else if (xp->xp_context == EXPAND_USER_DEFINED)
4485 ret = ExpandUserDefined(xp, &regmatch, num_file, file);
4486 # endif
4487 else
4489 static struct expgen
4491 int context;
4492 char_u *((*func)__ARGS((expand_T *, int)));
4493 int ic;
4494 } tab[] =
4496 {EXPAND_COMMANDS, get_command_name, FALSE},
4497 #ifdef FEAT_USR_CMDS
4498 {EXPAND_USER_COMMANDS, get_user_commands, FALSE},
4499 {EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE},
4500 {EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE},
4501 {EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE},
4502 #endif
4503 #ifdef FEAT_EVAL
4504 {EXPAND_USER_VARS, get_user_var_name, FALSE},
4505 {EXPAND_FUNCTIONS, get_function_name, FALSE},
4506 {EXPAND_USER_FUNC, get_user_func_name, FALSE},
4507 {EXPAND_EXPRESSION, get_expr_name, FALSE},
4508 #endif
4509 #ifdef FEAT_MENU
4510 {EXPAND_MENUS, get_menu_name, FALSE},
4511 {EXPAND_MENUNAMES, get_menu_names, FALSE},
4512 #endif
4513 #ifdef FEAT_SYN_HL
4514 {EXPAND_SYNTAX, get_syntax_name, TRUE},
4515 #endif
4516 {EXPAND_HIGHLIGHT, get_highlight_name, TRUE},
4517 #ifdef FEAT_AUTOCMD
4518 {EXPAND_EVENTS, get_event_name, TRUE},
4519 {EXPAND_AUGROUP, get_augroup_name, TRUE},
4520 #endif
4521 #ifdef FEAT_CSCOPE
4522 {EXPAND_CSCOPE, get_cscope_name, TRUE},
4523 #endif
4524 #if (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
4525 && (defined(FEAT_GETTEXT) || defined(FEAT_MBYTE))
4526 {EXPAND_LANGUAGE, get_lang_arg, TRUE},
4527 #endif
4528 {EXPAND_ENV_VARS, get_env_name, TRUE},
4529 #ifdef FEAT_GUI_MACVIM
4530 {EXPAND_MACACTION, get_macaction_name, FALSE},
4531 #endif
4533 int i;
4536 * Find a context in the table and call the ExpandGeneric() with the
4537 * right function to do the expansion.
4539 ret = FAIL;
4540 for (i = 0; i < sizeof(tab) / sizeof(struct expgen); ++i)
4541 if (xp->xp_context == tab[i].context)
4543 if (tab[i].ic)
4544 regmatch.rm_ic = TRUE;
4545 ret = ExpandGeneric(xp, &regmatch, num_file, file, tab[i].func);
4546 break;
4550 vim_free(regmatch.regprog);
4552 return ret;
4553 #endif /* FEAT_CMDL_COMPL */
4556 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4558 * Expand a list of names.
4560 * Generic function for command line completion. It calls a function to
4561 * obtain strings, one by one. The strings are matched against a regexp
4562 * program. Matching strings are copied into an array, which is returned.
4564 * Returns OK when no problems encountered, FAIL for error (out of memory).
4567 ExpandGeneric(xp, regmatch, num_file, file, func)
4568 expand_T *xp;
4569 regmatch_T *regmatch;
4570 int *num_file;
4571 char_u ***file;
4572 char_u *((*func)__ARGS((expand_T *, int)));
4573 /* returns a string from the list */
4575 int i;
4576 int count = 0;
4577 int round;
4578 char_u *str;
4580 /* do this loop twice:
4581 * round == 0: count the number of matching names
4582 * round == 1: copy the matching names into allocated memory
4584 for (round = 0; round <= 1; ++round)
4586 for (i = 0; ; ++i)
4588 str = (*func)(xp, i);
4589 if (str == NULL) /* end of list */
4590 break;
4591 if (*str == NUL) /* skip empty strings */
4592 continue;
4594 if (vim_regexec(regmatch, str, (colnr_T)0))
4596 if (round)
4598 str = vim_strsave_escaped(str, (char_u *)" \t\\.");
4599 (*file)[count] = str;
4600 #ifdef FEAT_MENU
4601 if (func == get_menu_names && str != NULL)
4603 /* test for separator added by get_menu_names() */
4604 str += STRLEN(str) - 1;
4605 if (*str == '\001')
4606 *str = '.';
4608 #endif
4610 ++count;
4613 if (round == 0)
4615 if (count == 0)
4616 return OK;
4617 *num_file = count;
4618 *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
4619 if (*file == NULL)
4621 *file = (char_u **)"";
4622 return FAIL;
4624 count = 0;
4628 /* Sort the results. Keep menu's in the specified order. */
4629 if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
4630 sort_strings(*file, *num_file);
4632 #ifdef FEAT_CMDL_COMPL
4633 /* Reset the variables used for special highlight names expansion, so that
4634 * they don't show up when getting normal highlight names by ID. */
4635 reset_expand_highlight();
4636 #endif
4638 return OK;
4642 * Complete a shell command.
4643 * Returns FAIL or OK;
4645 static int
4646 expand_shellcmd(filepat, num_file, file, flagsarg)
4647 char_u *filepat; /* pattern to match with command names */
4648 int *num_file; /* return: number of matches */
4649 char_u ***file; /* return: array with matches */
4650 int flagsarg; /* EW_ flags */
4652 char_u *pat;
4653 int i;
4654 char_u *path;
4655 int mustfree = FALSE;
4656 garray_T ga;
4657 char_u *buf = alloc(MAXPATHL);
4658 size_t l;
4659 char_u *s, *e;
4660 int flags = flagsarg;
4661 int ret;
4663 if (buf == NULL)
4664 return FAIL;
4666 /* for ":set path=" and ":set tags=" halve backslashes for escaped
4667 * space */
4668 pat = vim_strsave(filepat);
4669 for (i = 0; pat[i]; ++i)
4670 if (pat[i] == '\\' && pat[i + 1] == ' ')
4671 STRMOVE(pat + i, pat + i + 1);
4673 flags |= EW_FILE | EW_EXEC;
4675 /* For an absolute name we don't use $PATH. */
4676 if (mch_isFullName(pat))
4677 path = (char_u *)" ";
4678 else if ((pat[0] == '.' && (vim_ispathsep(pat[1])
4679 || (pat[1] == '.' && vim_ispathsep(pat[2])))))
4680 path = (char_u *)".";
4681 else
4682 path = vim_getenv((char_u *)"PATH", &mustfree);
4685 * Go over all directories in $PATH. Expand matches in that directory and
4686 * collect them in "ga".
4688 ga_init2(&ga, (int)sizeof(char *), 10);
4689 for (s = path; *s != NUL; s = e)
4691 if (*s == ' ')
4692 ++s; /* Skip space used for absolute path name. */
4694 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4695 e = vim_strchr(s, ';');
4696 #else
4697 e = vim_strchr(s, ':');
4698 #endif
4699 if (e == NULL)
4700 e = s + STRLEN(s);
4702 l = e - s;
4703 if (l > MAXPATHL - 5)
4704 break;
4705 vim_strncpy(buf, s, l);
4706 add_pathsep(buf);
4707 l = STRLEN(buf);
4708 vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
4710 /* Expand matches in one directory of $PATH. */
4711 ret = expand_wildcards(1, &buf, num_file, file, flags);
4712 if (ret == OK)
4714 if (ga_grow(&ga, *num_file) == FAIL)
4715 FreeWild(*num_file, *file);
4716 else
4718 for (i = 0; i < *num_file; ++i)
4720 s = (*file)[i];
4721 if (STRLEN(s) > l)
4723 /* Remove the path again. */
4724 STRMOVE(s, s + l);
4725 ((char_u **)ga.ga_data)[ga.ga_len++] = s;
4727 else
4728 vim_free(s);
4730 vim_free(*file);
4733 if (*e != NUL)
4734 ++e;
4736 *file = ga.ga_data;
4737 *num_file = ga.ga_len;
4739 vim_free(buf);
4740 vim_free(pat);
4741 if (mustfree)
4742 vim_free(path);
4743 return OK;
4747 # if defined(FEAT_USR_CMDS) && defined(FEAT_EVAL)
4748 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));
4751 * Call "user_expand_func()" to invoke a user defined VimL function and return
4752 * the result (either a string or a List).
4754 static void *
4755 call_user_expand_func(user_expand_func, xp, num_file, file)
4756 void *(*user_expand_func) __ARGS((char_u *, int, char_u **, int));
4757 expand_T *xp;
4758 int *num_file;
4759 char_u ***file;
4761 char_u keep;
4762 char_u num[50];
4763 char_u *args[3];
4764 int save_current_SID = current_SID;
4765 void *ret;
4766 struct cmdline_info save_ccline;
4768 if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0')
4769 return NULL;
4770 *num_file = 0;
4771 *file = NULL;
4773 if (ccline.cmdbuff == NULL)
4775 /* Completion from Insert mode, pass fake arguments. */
4776 keep = 0;
4777 sprintf((char *)num, "%d", (int)STRLEN(xp->xp_pattern));
4778 args[1] = xp->xp_pattern;
4780 else
4782 /* Completion on the command line, pass real arguments. */
4783 keep = ccline.cmdbuff[ccline.cmdlen];
4784 ccline.cmdbuff[ccline.cmdlen] = 0;
4785 sprintf((char *)num, "%d", ccline.cmdpos);
4786 args[1] = ccline.cmdbuff;
4788 args[0] = xp->xp_pattern;
4789 args[2] = num;
4791 /* Save the cmdline, we don't know what the function may do. */
4792 save_ccline = ccline;
4793 ccline.cmdbuff = NULL;
4794 ccline.cmdprompt = NULL;
4795 current_SID = xp->xp_scriptID;
4797 ret = user_expand_func(xp->xp_arg, 3, args, FALSE);
4799 ccline = save_ccline;
4800 current_SID = save_current_SID;
4801 if (ccline.cmdbuff != NULL)
4802 ccline.cmdbuff[ccline.cmdlen] = keep;
4804 return ret;
4808 * Expand names with a function defined by the user.
4810 static int
4811 ExpandUserDefined(xp, regmatch, num_file, file)
4812 expand_T *xp;
4813 regmatch_T *regmatch;
4814 int *num_file;
4815 char_u ***file;
4817 char_u *retstr;
4818 char_u *s;
4819 char_u *e;
4820 char_u keep;
4821 garray_T ga;
4823 retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
4824 if (retstr == NULL)
4825 return FAIL;
4827 ga_init2(&ga, (int)sizeof(char *), 3);
4828 for (s = retstr; *s != NUL; s = e)
4830 e = vim_strchr(s, '\n');
4831 if (e == NULL)
4832 e = s + STRLEN(s);
4833 keep = *e;
4834 *e = 0;
4836 if (xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0)
4838 *e = keep;
4839 if (*e != NUL)
4840 ++e;
4841 continue;
4844 if (ga_grow(&ga, 1) == FAIL)
4845 break;
4847 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
4848 ++ga.ga_len;
4850 *e = keep;
4851 if (*e != NUL)
4852 ++e;
4854 vim_free(retstr);
4855 *file = ga.ga_data;
4856 *num_file = ga.ga_len;
4857 return OK;
4861 * Expand names with a list returned by a function defined by the user.
4863 static int
4864 ExpandUserList(xp, num_file, file)
4865 expand_T *xp;
4866 int *num_file;
4867 char_u ***file;
4869 list_T *retlist;
4870 listitem_T *li;
4871 garray_T ga;
4873 retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
4874 if (retlist == NULL)
4875 return FAIL;
4877 ga_init2(&ga, (int)sizeof(char *), 3);
4878 /* Loop over the items in the list. */
4879 for (li = retlist->lv_first; li != NULL; li = li->li_next)
4881 if (li->li_tv.v_type != VAR_STRING)
4882 continue; /* Skip non-string items */
4884 if (ga_grow(&ga, 1) == FAIL)
4885 break;
4887 ((char_u **)ga.ga_data)[ga.ga_len] =
4888 vim_strsave(li->li_tv.vval.v_string);
4889 ++ga.ga_len;
4891 list_unref(retlist);
4893 *file = ga.ga_data;
4894 *num_file = ga.ga_len;
4895 return OK;
4897 #endif
4900 * Expand color scheme names: 'runtimepath'/colors/{pat}.vim
4901 * or compiler names.
4903 static int
4904 ExpandRTDir(pat, num_file, file, dirname)
4905 char_u *pat;
4906 int *num_file;
4907 char_u ***file;
4908 char *dirname; /* "colors" or "compiler" */
4910 char_u *all;
4911 char_u *s;
4912 char_u *e;
4913 garray_T ga;
4915 *num_file = 0;
4916 *file = NULL;
4917 s = alloc((unsigned)(STRLEN(pat) + STRLEN(dirname) + 7));
4918 if (s == NULL)
4919 return FAIL;
4920 sprintf((char *)s, "%s/%s*.vim", dirname, pat);
4921 all = globpath(p_rtp, s, 0);
4922 vim_free(s);
4923 if (all == NULL)
4924 return FAIL;
4926 ga_init2(&ga, (int)sizeof(char *), 3);
4927 for (s = all; *s != NUL; s = e)
4929 e = vim_strchr(s, '\n');
4930 if (e == NULL)
4931 e = s + STRLEN(s);
4932 if (ga_grow(&ga, 1) == FAIL)
4933 break;
4934 if (e - 4 > s && STRNICMP(e - 4, ".vim", 4) == 0)
4936 for (s = e - 4; s > all; mb_ptr_back(all, s))
4937 if (*s == '\n' || vim_ispathsep(*s))
4938 break;
4939 ++s;
4940 ((char_u **)ga.ga_data)[ga.ga_len] =
4941 vim_strnsave(s, (int)(e - s - 4));
4942 ++ga.ga_len;
4944 if (*e != NUL)
4945 ++e;
4947 vim_free(all);
4948 *file = ga.ga_data;
4949 *num_file = ga.ga_len;
4950 return OK;
4953 #endif
4955 #if defined(FEAT_CMDL_COMPL) || defined(FEAT_EVAL) || defined(PROTO)
4957 * Expand "file" for all comma-separated directories in "path".
4958 * Returns an allocated string with all matches concatenated, separated by
4959 * newlines. Returns NULL for an error or no matches.
4961 char_u *
4962 globpath(path, file, expand_options)
4963 char_u *path;
4964 char_u *file;
4965 int expand_options;
4967 expand_T xpc;
4968 char_u *buf;
4969 garray_T ga;
4970 int i;
4971 int len;
4972 int num_p;
4973 char_u **p;
4974 char_u *cur = NULL;
4976 buf = alloc(MAXPATHL);
4977 if (buf == NULL)
4978 return NULL;
4980 ExpandInit(&xpc);
4981 xpc.xp_context = EXPAND_FILES;
4983 ga_init2(&ga, 1, 100);
4985 /* Loop over all entries in {path}. */
4986 while (*path != NUL)
4988 /* Copy one item of the path to buf[] and concatenate the file name. */
4989 copy_option_part(&path, buf, MAXPATHL, ",");
4990 if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
4992 add_pathsep(buf);
4993 STRCAT(buf, file);
4994 if (ExpandFromContext(&xpc, buf, &num_p, &p,
4995 WILD_SILENT|expand_options) != FAIL && num_p > 0)
4997 ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT|expand_options);
4998 for (len = 0, i = 0; i < num_p; ++i)
4999 len += (int)STRLEN(p[i]) + 1;
5001 /* Concatenate new results to previous ones. */
5002 if (ga_grow(&ga, len) == OK)
5004 cur = (char_u *)ga.ga_data + ga.ga_len;
5005 for (i = 0; i < num_p; ++i)
5007 STRCPY(cur, p[i]);
5008 cur += STRLEN(p[i]);
5009 *cur++ = '\n';
5011 ga.ga_len += len;
5013 FreeWild(num_p, p);
5017 if (cur != NULL)
5018 *--cur = 0; /* Replace trailing newline with NUL */
5020 vim_free(buf);
5021 return (char_u *)ga.ga_data;
5024 #endif
5026 #if defined(FEAT_CMDHIST) || defined(PROTO)
5028 /*********************************
5029 * Command line history stuff *
5030 *********************************/
5033 * Translate a history character to the associated type number.
5035 static int
5036 hist_char2type(c)
5037 int c;
5039 if (c == ':')
5040 return HIST_CMD;
5041 if (c == '=')
5042 return HIST_EXPR;
5043 if (c == '@')
5044 return HIST_INPUT;
5045 if (c == '>')
5046 return HIST_DEBUG;
5047 return HIST_SEARCH; /* must be '?' or '/' */
5051 * Table of history names.
5052 * These names are used in :history and various hist...() functions.
5053 * It is sufficient to give the significant prefix of a history name.
5056 static char *(history_names[]) =
5058 "cmd",
5059 "search",
5060 "expr",
5061 "input",
5062 "debug",
5063 NULL
5067 * init_history() - Initialize the command line history.
5068 * Also used to re-allocate the history when the size changes.
5070 void
5071 init_history()
5073 int newlen; /* new length of history table */
5074 histentry_T *temp;
5075 int i;
5076 int j;
5077 int type;
5080 * If size of history table changed, reallocate it
5082 newlen = (int)p_hi;
5083 if (newlen != hislen) /* history length changed */
5085 for (type = 0; type < HIST_COUNT; ++type) /* adjust the tables */
5087 if (newlen)
5089 temp = (histentry_T *)lalloc(
5090 (long_u)(newlen * sizeof(histentry_T)), TRUE);
5091 if (temp == NULL) /* out of memory! */
5093 if (type == 0) /* first one: just keep the old length */
5095 newlen = hislen;
5096 break;
5098 /* Already changed one table, now we can only have zero
5099 * length for all tables. */
5100 newlen = 0;
5101 type = -1;
5102 continue;
5105 else
5106 temp = NULL;
5107 if (newlen == 0 || temp != NULL)
5109 if (hisidx[type] < 0) /* there are no entries yet */
5111 for (i = 0; i < newlen; ++i)
5113 temp[i].hisnum = 0;
5114 temp[i].hisstr = NULL;
5117 else if (newlen > hislen) /* array becomes bigger */
5119 for (i = 0; i <= hisidx[type]; ++i)
5120 temp[i] = history[type][i];
5121 j = i;
5122 for ( ; i <= newlen - (hislen - hisidx[type]); ++i)
5124 temp[i].hisnum = 0;
5125 temp[i].hisstr = NULL;
5127 for ( ; j < hislen; ++i, ++j)
5128 temp[i] = history[type][j];
5130 else /* array becomes smaller or 0 */
5132 j = hisidx[type];
5133 for (i = newlen - 1; ; --i)
5135 if (i >= 0) /* copy newest entries */
5136 temp[i] = history[type][j];
5137 else /* remove older entries */
5138 vim_free(history[type][j].hisstr);
5139 if (--j < 0)
5140 j = hislen - 1;
5141 if (j == hisidx[type])
5142 break;
5144 hisidx[type] = newlen - 1;
5146 vim_free(history[type]);
5147 history[type] = temp;
5150 hislen = newlen;
5155 * Check if command line 'str' is already in history.
5156 * If 'move_to_front' is TRUE, matching entry is moved to end of history.
5158 static int
5159 in_history(type, str, move_to_front)
5160 int type;
5161 char_u *str;
5162 int move_to_front; /* Move the entry to the front if it exists */
5164 int i;
5165 int last_i = -1;
5167 if (hisidx[type] < 0)
5168 return FALSE;
5169 i = hisidx[type];
5172 if (history[type][i].hisstr == NULL)
5173 return FALSE;
5174 if (STRCMP(str, history[type][i].hisstr) == 0)
5176 if (!move_to_front)
5177 return TRUE;
5178 last_i = i;
5179 break;
5181 if (--i < 0)
5182 i = hislen - 1;
5183 } while (i != hisidx[type]);
5185 if (last_i >= 0)
5187 str = history[type][i].hisstr;
5188 while (i != hisidx[type])
5190 if (++i >= hislen)
5191 i = 0;
5192 history[type][last_i] = history[type][i];
5193 last_i = i;
5195 history[type][i].hisstr = str;
5196 history[type][i].hisnum = ++hisnum[type];
5197 return TRUE;
5199 return FALSE;
5203 * Convert history name (from table above) to its HIST_ equivalent.
5204 * When "name" is empty, return "cmd" history.
5205 * Returns -1 for unknown history name.
5208 get_histtype(name)
5209 char_u *name;
5211 int i;
5212 int len = (int)STRLEN(name);
5214 /* No argument: use current history. */
5215 if (len == 0)
5216 return hist_char2type(ccline.cmdfirstc);
5218 for (i = 0; history_names[i] != NULL; ++i)
5219 if (STRNICMP(name, history_names[i], len) == 0)
5220 return i;
5222 if (vim_strchr((char_u *)":=@>?/", name[0]) != NULL && name[1] == NUL)
5223 return hist_char2type(name[0]);
5225 return -1;
5228 static int last_maptick = -1; /* last seen maptick */
5231 * Add the given string to the given history. If the string is already in the
5232 * history then it is moved to the front. "histype" may be one of he HIST_
5233 * values.
5235 void
5236 add_to_history(histype, new_entry, in_map, sep)
5237 int histype;
5238 char_u *new_entry;
5239 int in_map; /* consider maptick when inside a mapping */
5240 int sep; /* separator character used (search hist) */
5242 histentry_T *hisptr;
5243 int len;
5245 if (hislen == 0) /* no history */
5246 return;
5249 * Searches inside the same mapping overwrite each other, so that only
5250 * the last line is kept. Be careful not to remove a line that was moved
5251 * down, only lines that were added.
5253 if (histype == HIST_SEARCH && in_map)
5255 if (maptick == last_maptick)
5257 /* Current line is from the same mapping, remove it */
5258 hisptr = &history[HIST_SEARCH][hisidx[HIST_SEARCH]];
5259 vim_free(hisptr->hisstr);
5260 hisptr->hisstr = NULL;
5261 hisptr->hisnum = 0;
5262 --hisnum[histype];
5263 if (--hisidx[HIST_SEARCH] < 0)
5264 hisidx[HIST_SEARCH] = hislen - 1;
5266 last_maptick = -1;
5268 if (!in_history(histype, new_entry, TRUE))
5270 if (++hisidx[histype] == hislen)
5271 hisidx[histype] = 0;
5272 hisptr = &history[histype][hisidx[histype]];
5273 vim_free(hisptr->hisstr);
5275 /* Store the separator after the NUL of the string. */
5276 len = (int)STRLEN(new_entry);
5277 hisptr->hisstr = vim_strnsave(new_entry, len + 2);
5278 if (hisptr->hisstr != NULL)
5279 hisptr->hisstr[len + 1] = sep;
5281 hisptr->hisnum = ++hisnum[histype];
5282 if (histype == HIST_SEARCH && in_map)
5283 last_maptick = maptick;
5287 #if defined(FEAT_EVAL) || defined(PROTO)
5290 * Get identifier of newest history entry.
5291 * "histype" may be one of the HIST_ values.
5294 get_history_idx(histype)
5295 int histype;
5297 if (hislen == 0 || histype < 0 || histype >= HIST_COUNT
5298 || hisidx[histype] < 0)
5299 return -1;
5301 return history[histype][hisidx[histype]].hisnum;
5304 static struct cmdline_info *get_ccline_ptr __ARGS((void));
5307 * Get pointer to the command line info to use. cmdline_paste() may clear
5308 * ccline and put the previous value in prev_ccline.
5310 static struct cmdline_info *
5311 get_ccline_ptr()
5313 if ((State & CMDLINE) == 0)
5314 return NULL;
5315 if (ccline.cmdbuff != NULL)
5316 return &ccline;
5317 if (prev_ccline_used && prev_ccline.cmdbuff != NULL)
5318 return &prev_ccline;
5319 return NULL;
5323 * Get the current command line in allocated memory.
5324 * Only works when the command line is being edited.
5325 * Returns NULL when something is wrong.
5327 char_u *
5328 get_cmdline_str()
5330 struct cmdline_info *p = get_ccline_ptr();
5332 if (p == NULL)
5333 return NULL;
5334 return vim_strnsave(p->cmdbuff, p->cmdlen);
5338 * Get the current command line position, counted in bytes.
5339 * Zero is the first position.
5340 * Only works when the command line is being edited.
5341 * Returns -1 when something is wrong.
5344 get_cmdline_pos()
5346 struct cmdline_info *p = get_ccline_ptr();
5348 if (p == NULL)
5349 return -1;
5350 return p->cmdpos;
5354 * Set the command line byte position to "pos". Zero is the first position.
5355 * Only works when the command line is being edited.
5356 * Returns 1 when failed, 0 when OK.
5359 set_cmdline_pos(pos)
5360 int pos;
5362 struct cmdline_info *p = get_ccline_ptr();
5364 if (p == NULL)
5365 return 1;
5367 /* The position is not set directly but after CTRL-\ e or CTRL-R = has
5368 * changed the command line. */
5369 if (pos < 0)
5370 new_cmdpos = 0;
5371 else
5372 new_cmdpos = pos;
5373 return 0;
5377 * Get the current command-line type.
5378 * Returns ':' or '/' or '?' or '@' or '>' or '-'
5379 * Only works when the command line is being edited.
5380 * Returns NUL when something is wrong.
5383 get_cmdline_type()
5385 struct cmdline_info *p = get_ccline_ptr();
5387 if (p == NULL)
5388 return NUL;
5389 if (p->cmdfirstc == NUL)
5390 return (p->input_fn) ? '@' : '-';
5391 return p->cmdfirstc;
5395 * Calculate history index from a number:
5396 * num > 0: seen as identifying number of a history entry
5397 * num < 0: relative position in history wrt newest entry
5398 * "histype" may be one of the HIST_ values.
5400 static int
5401 calc_hist_idx(histype, num)
5402 int histype;
5403 int num;
5405 int i;
5406 histentry_T *hist;
5407 int wrapped = FALSE;
5409 if (hislen == 0 || histype < 0 || histype >= HIST_COUNT
5410 || (i = hisidx[histype]) < 0 || num == 0)
5411 return -1;
5413 hist = history[histype];
5414 if (num > 0)
5416 while (hist[i].hisnum > num)
5417 if (--i < 0)
5419 if (wrapped)
5420 break;
5421 i += hislen;
5422 wrapped = TRUE;
5424 if (hist[i].hisnum == num && hist[i].hisstr != NULL)
5425 return i;
5427 else if (-num <= hislen)
5429 i += num + 1;
5430 if (i < 0)
5431 i += hislen;
5432 if (hist[i].hisstr != NULL)
5433 return i;
5435 return -1;
5439 * Get a history entry by its index.
5440 * "histype" may be one of the HIST_ values.
5442 char_u *
5443 get_history_entry(histype, idx)
5444 int histype;
5445 int idx;
5447 idx = calc_hist_idx(histype, idx);
5448 if (idx >= 0)
5449 return history[histype][idx].hisstr;
5450 else
5451 return (char_u *)"";
5455 * Clear all entries of a history.
5456 * "histype" may be one of the HIST_ values.
5459 clr_history(histype)
5460 int histype;
5462 int i;
5463 histentry_T *hisptr;
5465 if (hislen != 0 && histype >= 0 && histype < HIST_COUNT)
5467 hisptr = history[histype];
5468 for (i = hislen; i--;)
5470 vim_free(hisptr->hisstr);
5471 hisptr->hisnum = 0;
5472 hisptr++->hisstr = NULL;
5474 hisidx[histype] = -1; /* mark history as cleared */
5475 hisnum[histype] = 0; /* reset identifier counter */
5476 return OK;
5478 return FAIL;
5482 * Remove all entries matching {str} from a history.
5483 * "histype" may be one of the HIST_ values.
5486 del_history_entry(histype, str)
5487 int histype;
5488 char_u *str;
5490 regmatch_T regmatch;
5491 histentry_T *hisptr;
5492 int idx;
5493 int i;
5494 int last;
5495 int found = FALSE;
5497 regmatch.regprog = NULL;
5498 regmatch.rm_ic = FALSE; /* always match case */
5499 if (hislen != 0
5500 && histype >= 0
5501 && histype < HIST_COUNT
5502 && *str != NUL
5503 && (idx = hisidx[histype]) >= 0
5504 && (regmatch.regprog = vim_regcomp(str, RE_MAGIC + RE_STRING))
5505 != NULL)
5507 i = last = idx;
5510 hisptr = &history[histype][i];
5511 if (hisptr->hisstr == NULL)
5512 break;
5513 if (vim_regexec(&regmatch, hisptr->hisstr, (colnr_T)0))
5515 found = TRUE;
5516 vim_free(hisptr->hisstr);
5517 hisptr->hisstr = NULL;
5518 hisptr->hisnum = 0;
5520 else
5522 if (i != last)
5524 history[histype][last] = *hisptr;
5525 hisptr->hisstr = NULL;
5526 hisptr->hisnum = 0;
5528 if (--last < 0)
5529 last += hislen;
5531 if (--i < 0)
5532 i += hislen;
5533 } while (i != idx);
5534 if (history[histype][idx].hisstr == NULL)
5535 hisidx[histype] = -1;
5537 vim_free(regmatch.regprog);
5538 return found;
5542 * Remove an indexed entry from a history.
5543 * "histype" may be one of the HIST_ values.
5546 del_history_idx(histype, idx)
5547 int histype;
5548 int idx;
5550 int i, j;
5552 i = calc_hist_idx(histype, idx);
5553 if (i < 0)
5554 return FALSE;
5555 idx = hisidx[histype];
5556 vim_free(history[histype][i].hisstr);
5558 /* When deleting the last added search string in a mapping, reset
5559 * last_maptick, so that the last added search string isn't deleted again.
5561 if (histype == HIST_SEARCH && maptick == last_maptick && i == idx)
5562 last_maptick = -1;
5564 while (i != idx)
5566 j = (i + 1) % hislen;
5567 history[histype][i] = history[histype][j];
5568 i = j;
5570 history[histype][i].hisstr = NULL;
5571 history[histype][i].hisnum = 0;
5572 if (--i < 0)
5573 i += hislen;
5574 hisidx[histype] = i;
5575 return TRUE;
5578 #endif /* FEAT_EVAL */
5580 #if defined(FEAT_CRYPT) || defined(PROTO)
5582 * Very specific function to remove the value in ":set key=val" from the
5583 * history.
5585 void
5586 remove_key_from_history()
5588 char_u *p;
5589 int i;
5591 i = hisidx[HIST_CMD];
5592 if (i < 0)
5593 return;
5594 p = history[HIST_CMD][i].hisstr;
5595 if (p != NULL)
5596 for ( ; *p; ++p)
5597 if (STRNCMP(p, "key", 3) == 0 && !isalpha(p[3]))
5599 p = vim_strchr(p + 3, '=');
5600 if (p == NULL)
5601 break;
5602 ++p;
5603 for (i = 0; p[i] && !vim_iswhite(p[i]); ++i)
5604 if (p[i] == '\\' && p[i + 1])
5605 ++i;
5606 STRMOVE(p, p + i);
5607 --p;
5610 #endif
5612 #endif /* FEAT_CMDHIST */
5614 #if defined(FEAT_QUICKFIX) || defined(FEAT_CMDHIST) || defined(PROTO)
5616 * Get indices "num1,num2" that specify a range within a list (not a range of
5617 * text lines in a buffer!) from a string. Used for ":history" and ":clist".
5618 * Returns OK if parsed successfully, otherwise FAIL.
5621 get_list_range(str, num1, num2)
5622 char_u **str;
5623 int *num1;
5624 int *num2;
5626 int len;
5627 int first = FALSE;
5628 long num;
5630 *str = skipwhite(*str);
5631 if (**str == '-' || vim_isdigit(**str)) /* parse "from" part of range */
5633 vim_str2nr(*str, NULL, &len, FALSE, FALSE, &num, NULL);
5634 *str += len;
5635 *num1 = (int)num;
5636 first = TRUE;
5638 *str = skipwhite(*str);
5639 if (**str == ',') /* parse "to" part of range */
5641 *str = skipwhite(*str + 1);
5642 vim_str2nr(*str, NULL, &len, FALSE, FALSE, &num, NULL);
5643 if (len > 0)
5645 *num2 = (int)num;
5646 *str = skipwhite(*str + len);
5648 else if (!first) /* no number given at all */
5649 return FAIL;
5651 else if (first) /* only one number given */
5652 *num2 = *num1;
5653 return OK;
5655 #endif
5657 #if defined(FEAT_CMDHIST) || defined(PROTO)
5659 * :history command - print a history
5661 void
5662 ex_history(eap)
5663 exarg_T *eap;
5665 histentry_T *hist;
5666 int histype1 = HIST_CMD;
5667 int histype2 = HIST_CMD;
5668 int hisidx1 = 1;
5669 int hisidx2 = -1;
5670 int idx;
5671 int i, j, k;
5672 char_u *end;
5673 char_u *arg = eap->arg;
5675 if (hislen == 0)
5677 MSG(_("'history' option is zero"));
5678 return;
5681 if (!(VIM_ISDIGIT(*arg) || *arg == '-' || *arg == ','))
5683 end = arg;
5684 while (ASCII_ISALPHA(*end)
5685 || vim_strchr((char_u *)":=@>/?", *end) != NULL)
5686 end++;
5687 i = *end;
5688 *end = NUL;
5689 histype1 = get_histtype(arg);
5690 if (histype1 == -1)
5692 if (STRICMP(arg, "all") == 0)
5694 histype1 = 0;
5695 histype2 = HIST_COUNT-1;
5697 else
5699 *end = i;
5700 EMSG(_(e_trailing));
5701 return;
5704 else
5705 histype2 = histype1;
5706 *end = i;
5708 else
5709 end = arg;
5710 if (!get_list_range(&end, &hisidx1, &hisidx2) || *end != NUL)
5712 EMSG(_(e_trailing));
5713 return;
5716 for (; !got_int && histype1 <= histype2; ++histype1)
5718 STRCPY(IObuff, "\n # ");
5719 STRCAT(STRCAT(IObuff, history_names[histype1]), " history");
5720 MSG_PUTS_TITLE(IObuff);
5721 idx = hisidx[histype1];
5722 hist = history[histype1];
5723 j = hisidx1;
5724 k = hisidx2;
5725 if (j < 0)
5726 j = (-j > hislen) ? 0 : hist[(hislen+j+idx+1) % hislen].hisnum;
5727 if (k < 0)
5728 k = (-k > hislen) ? 0 : hist[(hislen+k+idx+1) % hislen].hisnum;
5729 if (idx >= 0 && j <= k)
5730 for (i = idx + 1; !got_int; ++i)
5732 if (i == hislen)
5733 i = 0;
5734 if (hist[i].hisstr != NULL
5735 && hist[i].hisnum >= j && hist[i].hisnum <= k)
5737 msg_putchar('\n');
5738 sprintf((char *)IObuff, "%c%6d ", i == idx ? '>' : ' ',
5739 hist[i].hisnum);
5740 if (vim_strsize(hist[i].hisstr) > (int)Columns - 10)
5741 trunc_string(hist[i].hisstr, IObuff + STRLEN(IObuff),
5742 (int)Columns - 10);
5743 else
5744 STRCAT(IObuff, hist[i].hisstr);
5745 msg_outtrans(IObuff);
5746 out_flush();
5748 if (i == idx)
5749 break;
5753 #endif
5755 #if (defined(FEAT_VIMINFO) && defined(FEAT_CMDHIST)) || defined(PROTO)
5756 static char_u **viminfo_history[HIST_COUNT] = {NULL, NULL, NULL, NULL};
5757 static int viminfo_hisidx[HIST_COUNT] = {0, 0, 0, 0};
5758 static int viminfo_hislen[HIST_COUNT] = {0, 0, 0, 0};
5759 static int viminfo_add_at_front = FALSE;
5761 static int hist_type2char __ARGS((int type, int use_question));
5764 * Translate a history type number to the associated character.
5766 static int
5767 hist_type2char(type, use_question)
5768 int type;
5769 int use_question; /* use '?' instead of '/' */
5771 if (type == HIST_CMD)
5772 return ':';
5773 if (type == HIST_SEARCH)
5775 if (use_question)
5776 return '?';
5777 else
5778 return '/';
5780 if (type == HIST_EXPR)
5781 return '=';
5782 return '@';
5786 * Prepare for reading the history from the viminfo file.
5787 * This allocates history arrays to store the read history lines.
5789 void
5790 prepare_viminfo_history(asklen)
5791 int asklen;
5793 int i;
5794 int num;
5795 int type;
5796 int len;
5798 init_history();
5799 viminfo_add_at_front = (asklen != 0);
5800 if (asklen > hislen)
5801 asklen = hislen;
5803 for (type = 0; type < HIST_COUNT; ++type)
5806 * Count the number of empty spaces in the history list. If there are
5807 * more spaces available than we request, then fill them up.
5809 for (i = 0, num = 0; i < hislen; i++)
5810 if (history[type][i].hisstr == NULL)
5811 num++;
5812 len = asklen;
5813 if (num > len)
5814 len = num;
5815 if (len <= 0)
5816 viminfo_history[type] = NULL;
5817 else
5818 viminfo_history[type] =
5819 (char_u **)lalloc((long_u)(len * sizeof(char_u *)), FALSE);
5820 if (viminfo_history[type] == NULL)
5821 len = 0;
5822 viminfo_hislen[type] = len;
5823 viminfo_hisidx[type] = 0;
5828 * Accept a line from the viminfo, store it in the history array when it's
5829 * new.
5832 read_viminfo_history(virp)
5833 vir_T *virp;
5835 int type;
5836 long_u len;
5837 char_u *val;
5838 char_u *p;
5840 type = hist_char2type(virp->vir_line[0]);
5841 if (viminfo_hisidx[type] < viminfo_hislen[type])
5843 val = viminfo_readstring(virp, 1, TRUE);
5844 if (val != NULL && *val != NUL)
5846 if (!in_history(type, val + (type == HIST_SEARCH),
5847 viminfo_add_at_front))
5849 /* Need to re-allocate to append the separator byte. */
5850 len = STRLEN(val);
5851 p = lalloc(len + 2, TRUE);
5852 if (p != NULL)
5854 if (type == HIST_SEARCH)
5856 /* Search entry: Move the separator from the first
5857 * column to after the NUL. */
5858 mch_memmove(p, val + 1, (size_t)len);
5859 p[len] = (*val == ' ' ? NUL : *val);
5861 else
5863 /* Not a search entry: No separator in the viminfo
5864 * file, add a NUL separator. */
5865 mch_memmove(p, val, (size_t)len + 1);
5866 p[len + 1] = NUL;
5868 viminfo_history[type][viminfo_hisidx[type]++] = p;
5872 vim_free(val);
5874 return viminfo_readline(virp);
5877 void
5878 finish_viminfo_history()
5880 int idx;
5881 int i;
5882 int type;
5884 for (type = 0; type < HIST_COUNT; ++type)
5886 if (history[type] == NULL)
5887 return;
5888 idx = hisidx[type] + viminfo_hisidx[type];
5889 if (idx >= hislen)
5890 idx -= hislen;
5891 else if (idx < 0)
5892 idx = hislen - 1;
5893 if (viminfo_add_at_front)
5894 hisidx[type] = idx;
5895 else
5897 if (hisidx[type] == -1)
5898 hisidx[type] = hislen - 1;
5901 if (history[type][idx].hisstr != NULL)
5902 break;
5903 if (++idx == hislen)
5904 idx = 0;
5905 } while (idx != hisidx[type]);
5906 if (idx != hisidx[type] && --idx < 0)
5907 idx = hislen - 1;
5909 for (i = 0; i < viminfo_hisidx[type]; i++)
5911 vim_free(history[type][idx].hisstr);
5912 history[type][idx].hisstr = viminfo_history[type][i];
5913 if (--idx < 0)
5914 idx = hislen - 1;
5916 idx += 1;
5917 idx %= hislen;
5918 for (i = 0; i < viminfo_hisidx[type]; i++)
5920 history[type][idx++].hisnum = ++hisnum[type];
5921 idx %= hislen;
5923 vim_free(viminfo_history[type]);
5924 viminfo_history[type] = NULL;
5928 void
5929 write_viminfo_history(fp)
5930 FILE *fp;
5932 int i;
5933 int type;
5934 int num_saved;
5935 char_u *p;
5936 int c;
5938 init_history();
5939 if (hislen == 0)
5940 return;
5941 for (type = 0; type < HIST_COUNT; ++type)
5943 num_saved = get_viminfo_parameter(hist_type2char(type, FALSE));
5944 if (num_saved == 0)
5945 continue;
5946 if (num_saved < 0) /* Use default */
5947 num_saved = hislen;
5948 fprintf(fp, _("\n# %s History (newest to oldest):\n"),
5949 type == HIST_CMD ? _("Command Line") :
5950 type == HIST_SEARCH ? _("Search String") :
5951 type == HIST_EXPR ? _("Expression") :
5952 _("Input Line"));
5953 if (num_saved > hislen)
5954 num_saved = hislen;
5955 i = hisidx[type];
5956 if (i >= 0)
5957 while (num_saved--)
5959 p = history[type][i].hisstr;
5960 if (p != NULL)
5962 fputc(hist_type2char(type, TRUE), fp);
5963 /* For the search history: put the separator in the second
5964 * column; use a space if there isn't one. */
5965 if (type == HIST_SEARCH)
5967 c = p[STRLEN(p) + 1];
5968 putc(c == NUL ? ' ' : c, fp);
5970 viminfo_writestring(fp, p);
5972 if (--i < 0)
5973 i = hislen - 1;
5977 #endif /* FEAT_VIMINFO */
5979 #if defined(FEAT_FKMAP) || defined(PROTO)
5981 * Write a character at the current cursor+offset position.
5982 * It is directly written into the command buffer block.
5984 void
5985 cmd_pchar(c, offset)
5986 int c, offset;
5988 if (ccline.cmdpos + offset >= ccline.cmdlen || ccline.cmdpos + offset < 0)
5990 EMSG(_("E198: cmd_pchar beyond the command length"));
5991 return;
5993 ccline.cmdbuff[ccline.cmdpos + offset] = (char_u)c;
5994 ccline.cmdbuff[ccline.cmdlen] = NUL;
5998 cmd_gchar(offset)
5999 int offset;
6001 if (ccline.cmdpos + offset >= ccline.cmdlen || ccline.cmdpos + offset < 0)
6003 /* EMSG(_("cmd_gchar beyond the command length")); */
6004 return NUL;
6006 return (int)ccline.cmdbuff[ccline.cmdpos + offset];
6008 #endif
6010 #if defined(FEAT_CMDWIN) || defined(PROTO)
6012 * Open a window on the current command line and history. Allow editing in
6013 * the window. Returns when the window is closed.
6014 * Returns:
6015 * CR if the command is to be executed
6016 * Ctrl_C if it is to be abandoned
6017 * K_IGNORE if editing continues
6019 static int
6020 ex_window()
6022 struct cmdline_info save_ccline;
6023 buf_T *old_curbuf = curbuf;
6024 win_T *old_curwin = curwin;
6025 buf_T *bp;
6026 win_T *wp;
6027 int i;
6028 linenr_T lnum;
6029 int histtype;
6030 garray_T winsizes;
6031 #ifdef FEAT_AUTOCMD
6032 char_u typestr[2];
6033 #endif
6034 int save_restart_edit = restart_edit;
6035 int save_State = State;
6036 int save_exmode = exmode_active;
6037 #ifdef FEAT_RIGHTLEFT
6038 int save_cmdmsg_rl = cmdmsg_rl;
6039 #endif
6041 /* Can't do this recursively. Can't do it when typing a password. */
6042 if (cmdwin_type != 0
6043 # if defined(FEAT_CRYPT) || defined(FEAT_EVAL)
6044 || cmdline_star > 0
6045 # endif
6048 beep_flush();
6049 return K_IGNORE;
6052 /* Save current window sizes. */
6053 win_size_save(&winsizes);
6055 # ifdef FEAT_AUTOCMD
6056 /* Don't execute autocommands while creating the window. */
6057 block_autocmds();
6058 # endif
6059 /* don't use a new tab page */
6060 cmdmod.tab = 0;
6062 /* Create a window for the command-line buffer. */
6063 if (win_split((int)p_cwh, WSP_BOT) == FAIL)
6065 beep_flush();
6066 # ifdef FEAT_AUTOCMD
6067 unblock_autocmds();
6068 # endif
6069 return K_IGNORE;
6071 cmdwin_type = get_cmdline_type();
6073 /* Create the command-line buffer empty. */
6074 (void)do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE, NULL);
6075 (void)setfname(curbuf, (char_u *)"[Command Line]", NULL, TRUE);
6076 set_option_value((char_u *)"bt", 0L, (char_u *)"nofile", OPT_LOCAL);
6077 set_option_value((char_u *)"swf", 0L, NULL, OPT_LOCAL);
6078 curbuf->b_p_ma = TRUE;
6079 # ifdef FEAT_RIGHTLEFT
6080 curwin->w_p_rl = cmdmsg_rl;
6081 cmdmsg_rl = FALSE;
6082 # endif
6083 # ifdef FEAT_SCROLLBIND
6084 curwin->w_p_scb = FALSE;
6085 # endif
6087 # ifdef FEAT_AUTOCMD
6088 /* Do execute autocommands for setting the filetype (load syntax). */
6089 unblock_autocmds();
6090 # endif
6092 /* Showing the prompt may have set need_wait_return, reset it. */
6093 need_wait_return = FALSE;
6095 histtype = hist_char2type(cmdwin_type);
6096 if (histtype == HIST_CMD || histtype == HIST_DEBUG)
6098 if (p_wc == TAB)
6100 add_map((char_u *)"<buffer> <Tab> <C-X><C-V>", INSERT);
6101 add_map((char_u *)"<buffer> <Tab> a<C-X><C-V>", NORMAL);
6103 set_option_value((char_u *)"ft", 0L, (char_u *)"vim", OPT_LOCAL);
6106 /* Reset 'textwidth' after setting 'filetype' (the Vim filetype plugin
6107 * sets 'textwidth' to 78). */
6108 curbuf->b_p_tw = 0;
6110 /* Fill the buffer with the history. */
6111 init_history();
6112 if (hislen > 0)
6114 i = hisidx[histtype];
6115 if (i >= 0)
6117 lnum = 0;
6120 if (++i == hislen)
6121 i = 0;
6122 if (history[histtype][i].hisstr != NULL)
6123 ml_append(lnum++, history[histtype][i].hisstr,
6124 (colnr_T)0, FALSE);
6126 while (i != hisidx[histtype]);
6130 /* Replace the empty last line with the current command-line and put the
6131 * cursor there. */
6132 ml_replace(curbuf->b_ml.ml_line_count, ccline.cmdbuff, TRUE);
6133 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
6134 curwin->w_cursor.col = ccline.cmdpos;
6135 changed_line_abv_curs();
6136 invalidate_botline();
6137 redraw_later(SOME_VALID);
6139 /* Save the command line info, can be used recursively. */
6140 save_ccline = ccline;
6141 ccline.cmdbuff = NULL;
6142 ccline.cmdprompt = NULL;
6144 /* No Ex mode here! */
6145 exmode_active = 0;
6147 State = NORMAL;
6148 # ifdef FEAT_MOUSE
6149 setmouse();
6150 # endif
6152 # ifdef FEAT_AUTOCMD
6153 /* Trigger CmdwinEnter autocommands. */
6154 typestr[0] = cmdwin_type;
6155 typestr[1] = NUL;
6156 apply_autocmds(EVENT_CMDWINENTER, typestr, typestr, FALSE, curbuf);
6157 if (restart_edit != 0) /* autocmd with ":startinsert" */
6158 stuffcharReadbuff(K_NOP);
6159 # endif
6161 i = RedrawingDisabled;
6162 RedrawingDisabled = 0;
6165 * Call the main loop until <CR> or CTRL-C is typed.
6167 cmdwin_result = 0;
6168 main_loop(TRUE, FALSE);
6170 RedrawingDisabled = i;
6172 # ifdef FEAT_AUTOCMD
6173 /* Trigger CmdwinLeave autocommands. */
6174 apply_autocmds(EVENT_CMDWINLEAVE, typestr, typestr, FALSE, curbuf);
6175 # endif
6177 /* Restore the command line info. */
6178 ccline = save_ccline;
6179 cmdwin_type = 0;
6181 exmode_active = save_exmode;
6183 /* Safety check: The old window or buffer was deleted: It's a bug when
6184 * this happens! */
6185 if (!win_valid(old_curwin) || !buf_valid(old_curbuf))
6187 cmdwin_result = Ctrl_C;
6188 EMSG(_("E199: Active window or buffer deleted"));
6190 else
6192 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
6193 /* autocmds may abort script processing */
6194 if (aborting() && cmdwin_result != K_IGNORE)
6195 cmdwin_result = Ctrl_C;
6196 # endif
6197 /* Set the new command line from the cmdline buffer. */
6198 vim_free(ccline.cmdbuff);
6199 if (cmdwin_result == K_XF1 || cmdwin_result == K_XF2) /* :qa[!] typed */
6201 char *p = (cmdwin_result == K_XF2) ? "qa" : "qa!";
6203 if (histtype == HIST_CMD)
6205 /* Execute the command directly. */
6206 ccline.cmdbuff = vim_strsave((char_u *)p);
6207 cmdwin_result = CAR;
6209 else
6211 /* First need to cancel what we were doing. */
6212 ccline.cmdbuff = NULL;
6213 stuffcharReadbuff(':');
6214 stuffReadbuff((char_u *)p);
6215 stuffcharReadbuff(CAR);
6218 else if (cmdwin_result == K_XF2) /* :qa typed */
6220 ccline.cmdbuff = vim_strsave((char_u *)"qa");
6221 cmdwin_result = CAR;
6223 else
6224 ccline.cmdbuff = vim_strsave(ml_get_curline());
6225 if (ccline.cmdbuff == NULL)
6226 cmdwin_result = Ctrl_C;
6227 else
6229 ccline.cmdlen = (int)STRLEN(ccline.cmdbuff);
6230 ccline.cmdbufflen = ccline.cmdlen + 1;
6231 ccline.cmdpos = curwin->w_cursor.col;
6232 if (ccline.cmdpos > ccline.cmdlen)
6233 ccline.cmdpos = ccline.cmdlen;
6234 if (cmdwin_result == K_IGNORE)
6236 set_cmdspos_cursor();
6237 redrawcmd();
6241 # ifdef FEAT_AUTOCMD
6242 /* Don't execute autocommands while deleting the window. */
6243 block_autocmds();
6244 # endif
6245 wp = curwin;
6246 bp = curbuf;
6247 win_goto(old_curwin);
6248 win_close(wp, TRUE);
6249 close_buffer(NULL, bp, DOBUF_WIPE);
6251 /* Restore window sizes. */
6252 win_size_restore(&winsizes);
6254 # ifdef FEAT_AUTOCMD
6255 unblock_autocmds();
6256 # endif
6259 ga_clear(&winsizes);
6260 restart_edit = save_restart_edit;
6261 # ifdef FEAT_RIGHTLEFT
6262 cmdmsg_rl = save_cmdmsg_rl;
6263 # endif
6265 State = save_State;
6266 # ifdef FEAT_MOUSE
6267 setmouse();
6268 # endif
6270 return cmdwin_result;
6272 #endif /* FEAT_CMDWIN */
6275 * Used for commands that either take a simple command string argument, or:
6276 * cmd << endmarker
6277 * {script}
6278 * endmarker
6279 * Returns a pointer to allocated memory with {script} or NULL.
6281 char_u *
6282 script_get(eap, cmd)
6283 exarg_T *eap;
6284 char_u *cmd;
6286 char_u *theline;
6287 char *end_pattern = NULL;
6288 char dot[] = ".";
6289 garray_T ga;
6291 if (cmd[0] != '<' || cmd[1] != '<' || eap->getline == NULL)
6292 return NULL;
6294 ga_init2(&ga, 1, 0x400);
6296 if (cmd[2] != NUL)
6297 end_pattern = (char *)skipwhite(cmd + 2);
6298 else
6299 end_pattern = dot;
6301 for (;;)
6303 theline = eap->getline(
6304 #ifdef FEAT_EVAL
6305 eap->cstack->cs_looplevel > 0 ? -1 :
6306 #endif
6307 NUL, eap->cookie, 0);
6309 if (theline == NULL || STRCMP(end_pattern, theline) == 0)
6311 vim_free(theline);
6312 break;
6315 ga_concat(&ga, theline);
6316 ga_append(&ga, '\n');
6317 vim_free(theline);
6319 ga_append(&ga, NUL);
6321 return (char_u *)ga.ga_data;