blob: 1a7f9f2ecd5430dadf645d3345380f016c578701 [file] [log] [blame]
Bram Moolenaar66b51422019-08-18 21:44:12 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * cmdexpand.c: functions for command-line completion
12 */
13
14#include "vim.h"
15
16static int cmd_showtail; // Only show path tail in lists ?
17
18static void set_expand_context(expand_T *xp);
19static int ExpandFromContext(expand_T *xp, char_u *, int *, char_u ***, int);
20static int expand_showtail(expand_T *xp);
Bram Moolenaar66b51422019-08-18 21:44:12 +020021static int expand_shellcmd(char_u *filepat, int *num_file, char_u ***file, int flagsarg);
Bram Moolenaar0a52df52019-08-18 22:26:31 +020022#if defined(FEAT_EVAL)
Bram Moolenaar66b51422019-08-18 21:44:12 +020023static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char_u ***file);
24static int ExpandUserList(expand_T *xp, int *num_file, char_u ***file);
Bram Moolenaar66b51422019-08-18 21:44:12 +020025#endif
26
Bram Moolenaar66b51422019-08-18 21:44:12 +020027 static int
28sort_func_compare(const void *s1, const void *s2)
29{
30 char_u *p1 = *(char_u **)s1;
31 char_u *p2 = *(char_u **)s2;
32
33 if (*p1 != '<' && *p2 == '<') return -1;
34 if (*p1 == '<' && *p2 != '<') return 1;
35 return STRCMP(p1, p2);
36}
Bram Moolenaar66b51422019-08-18 21:44:12 +020037
38 static void
39ExpandEscape(
40 expand_T *xp,
41 char_u *str,
42 int numfiles,
43 char_u **files,
44 int options)
45{
46 int i;
47 char_u *p;
48
49 // May change home directory back to "~"
50 if (options & WILD_HOME_REPLACE)
51 tilde_replace(str, numfiles, files);
52
53 if (options & WILD_ESCAPE)
54 {
55 if (xp->xp_context == EXPAND_FILES
56 || xp->xp_context == EXPAND_FILES_IN_PATH
57 || xp->xp_context == EXPAND_SHELLCMD
58 || xp->xp_context == EXPAND_BUFFERS
59 || xp->xp_context == EXPAND_DIRECTORIES)
60 {
61 // Insert a backslash into a file name before a space, \, %, #
62 // and wildmatch characters, except '~'.
63 for (i = 0; i < numfiles; ++i)
64 {
65 // for ":set path=" we need to escape spaces twice
66 if (xp->xp_backslash == XP_BS_THREE)
67 {
68 p = vim_strsave_escaped(files[i], (char_u *)" ");
69 if (p != NULL)
70 {
71 vim_free(files[i]);
72 files[i] = p;
73#if defined(BACKSLASH_IN_FILENAME)
74 p = vim_strsave_escaped(files[i], (char_u *)" ");
75 if (p != NULL)
76 {
77 vim_free(files[i]);
78 files[i] = p;
79 }
80#endif
81 }
82 }
83#ifdef BACKSLASH_IN_FILENAME
84 p = vim_strsave_fnameescape(files[i], FALSE);
85#else
86 p = vim_strsave_fnameescape(files[i], xp->xp_shell);
87#endif
88 if (p != NULL)
89 {
90 vim_free(files[i]);
91 files[i] = p;
92 }
93
94 // If 'str' starts with "\~", replace "~" at start of
95 // files[i] with "\~".
96 if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~')
97 escape_fname(&files[i]);
98 }
99 xp->xp_backslash = XP_BS_NONE;
100
101 // If the first file starts with a '+' escape it. Otherwise it
102 // could be seen as "+cmd".
103 if (*files[0] == '+')
104 escape_fname(&files[0]);
105 }
106 else if (xp->xp_context == EXPAND_TAGS)
107 {
108 // Insert a backslash before characters in a tag name that
109 // would terminate the ":tag" command.
110 for (i = 0; i < numfiles; ++i)
111 {
112 p = vim_strsave_escaped(files[i], (char_u *)"\\|\"");
113 if (p != NULL)
114 {
115 vim_free(files[i]);
116 files[i] = p;
117 }
118 }
119 }
120 }
121}
122
123/*
124 * Return FAIL if this is not an appropriate context in which to do
125 * completion of anything, return OK if it is (even if there are no matches).
126 * For the caller, this means that the character is just passed through like a
127 * normal character (instead of being expanded). This allows :s/^I^D etc.
128 */
129 int
130nextwild(
131 expand_T *xp,
132 int type,
133 int options, // extra options for ExpandOne()
134 int escape) // if TRUE, escape the returned matches
135{
136 cmdline_info_T *ccline = get_cmdline_info();
137 int i, j;
138 char_u *p1;
139 char_u *p2;
140 int difflen;
141 int v;
142
143 if (xp->xp_numfiles == -1)
144 {
145 set_expand_context(xp);
146 cmd_showtail = expand_showtail(xp);
147 }
148
149 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
150 {
151 beep_flush();
152 return OK; // Something illegal on command line
153 }
154 if (xp->xp_context == EXPAND_NOTHING)
155 {
156 // Caller can use the character as a normal char instead
157 return FAIL;
158 }
159
160 msg_puts("..."); // show that we are busy
161 out_flush();
162
163 i = (int)(xp->xp_pattern - ccline->cmdbuff);
164 xp->xp_pattern_len = ccline->cmdpos - i;
165
166 if (type == WILD_NEXT || type == WILD_PREV)
167 {
168 // Get next/previous match for a previous expanded pattern.
169 p2 = ExpandOne(xp, NULL, NULL, 0, type);
170 }
171 else
172 {
173 // Translate string into pattern and expand it.
174 if ((p1 = addstar(xp->xp_pattern, xp->xp_pattern_len,
175 xp->xp_context)) == NULL)
176 p2 = NULL;
177 else
178 {
179 int use_options = options |
180 WILD_HOME_REPLACE|WILD_ADD_SLASH|WILD_SILENT;
181 if (escape)
182 use_options |= WILD_ESCAPE;
183
184 if (p_wic)
185 use_options += WILD_ICASE;
186 p2 = ExpandOne(xp, p1,
187 vim_strnsave(&ccline->cmdbuff[i], xp->xp_pattern_len),
188 use_options, type);
189 vim_free(p1);
190 // longest match: make sure it is not shorter, happens with :help
191 if (p2 != NULL && type == WILD_LONGEST)
192 {
193 for (j = 0; j < xp->xp_pattern_len; ++j)
194 if (ccline->cmdbuff[i + j] == '*'
195 || ccline->cmdbuff[i + j] == '?')
196 break;
197 if ((int)STRLEN(p2) < j)
198 VIM_CLEAR(p2);
199 }
200 }
201 }
202
203 if (p2 != NULL && !got_int)
204 {
205 difflen = (int)STRLEN(p2) - xp->xp_pattern_len;
206 if (ccline->cmdlen + difflen + 4 > ccline->cmdbufflen)
207 {
208 v = realloc_cmdbuff(ccline->cmdlen + difflen + 4);
209 xp->xp_pattern = ccline->cmdbuff + i;
210 }
211 else
212 v = OK;
213 if (v == OK)
214 {
215 mch_memmove(&ccline->cmdbuff[ccline->cmdpos + difflen],
216 &ccline->cmdbuff[ccline->cmdpos],
217 (size_t)(ccline->cmdlen - ccline->cmdpos + 1));
218 mch_memmove(&ccline->cmdbuff[i], p2, STRLEN(p2));
219 ccline->cmdlen += difflen;
220 ccline->cmdpos += difflen;
221 }
222 }
223 vim_free(p2);
224
225 redrawcmd();
226 cursorcmd();
227
228 // When expanding a ":map" command and no matches are found, assume that
229 // the key is supposed to be inserted literally
230 if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL)
231 return FAIL;
232
233 if (xp->xp_numfiles <= 0 && p2 == NULL)
234 beep_flush();
235 else if (xp->xp_numfiles == 1)
236 // free expanded pattern
237 (void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE);
238
239 return OK;
240}
241
242/*
243 * Do wildcard expansion on the string 'str'.
244 * Chars that should not be expanded must be preceded with a backslash.
245 * Return a pointer to allocated memory containing the new string.
246 * Return NULL for failure.
247 *
248 * "orig" is the originally expanded string, copied to allocated memory. It
249 * should either be kept in orig_save or freed. When "mode" is WILD_NEXT or
250 * WILD_PREV "orig" should be NULL.
251 *
252 * Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode"
253 * is WILD_EXPAND_FREE or WILD_ALL.
254 *
255 * mode = WILD_FREE: just free previously expanded matches
256 * mode = WILD_EXPAND_FREE: normal expansion, do not keep matches
257 * mode = WILD_EXPAND_KEEP: normal expansion, keep matches
258 * mode = WILD_NEXT: use next match in multiple match, wrap to first
259 * mode = WILD_PREV: use previous match in multiple match, wrap to first
260 * mode = WILD_ALL: return all matches concatenated
261 * mode = WILD_LONGEST: return longest matched part
262 * mode = WILD_ALL_KEEP: get all matches, keep matches
263 *
264 * options = WILD_LIST_NOTFOUND: list entries without a match
265 * options = WILD_HOME_REPLACE: do home_replace() for buffer names
266 * options = WILD_USE_NL: Use '\n' for WILD_ALL
267 * options = WILD_NO_BEEP: Don't beep for multiple matches
268 * options = WILD_ADD_SLASH: add a slash after directory names
269 * options = WILD_KEEP_ALL: don't remove 'wildignore' entries
270 * options = WILD_SILENT: don't print warning messages
271 * options = WILD_ESCAPE: put backslash before special chars
272 * options = WILD_ICASE: ignore case for files
273 *
274 * The variables xp->xp_context and xp->xp_backslash must have been set!
275 */
276 char_u *
277ExpandOne(
278 expand_T *xp,
279 char_u *str,
280 char_u *orig, // allocated copy of original of expanded string
281 int options,
282 int mode)
283{
284 char_u *ss = NULL;
285 static int findex;
286 static char_u *orig_save = NULL; // kept value of orig
287 int orig_saved = FALSE;
288 int i;
289 long_u len;
290 int non_suf_match; // number without matching suffix
291
292 // first handle the case of using an old match
293 if (mode == WILD_NEXT || mode == WILD_PREV)
294 {
295 if (xp->xp_numfiles > 0)
296 {
297 if (mode == WILD_PREV)
298 {
299 if (findex == -1)
300 findex = xp->xp_numfiles;
301 --findex;
302 }
303 else // mode == WILD_NEXT
304 ++findex;
305
306 // When wrapping around, return the original string, set findex to
307 // -1.
308 if (findex < 0)
309 {
310 if (orig_save == NULL)
311 findex = xp->xp_numfiles - 1;
312 else
313 findex = -1;
314 }
315 if (findex >= xp->xp_numfiles)
316 {
317 if (orig_save == NULL)
318 findex = 0;
319 else
320 findex = -1;
321 }
322#ifdef FEAT_WILDMENU
323 if (p_wmnu)
324 win_redr_status_matches(xp, xp->xp_numfiles, xp->xp_files,
325 findex, cmd_showtail);
326#endif
327 if (findex == -1)
328 return vim_strsave(orig_save);
329 return vim_strsave(xp->xp_files[findex]);
330 }
331 else
332 return NULL;
333 }
334
335 // free old names
336 if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST)
337 {
338 FreeWild(xp->xp_numfiles, xp->xp_files);
339 xp->xp_numfiles = -1;
340 VIM_CLEAR(orig_save);
341 }
342 findex = 0;
343
344 if (mode == WILD_FREE) // only release file name
345 return NULL;
346
347 if (xp->xp_numfiles == -1)
348 {
349 vim_free(orig_save);
350 orig_save = orig;
351 orig_saved = TRUE;
352
353 // Do the expansion.
354 if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files,
355 options) == FAIL)
356 {
357#ifdef FNAME_ILLEGAL
358 // Illegal file name has been silently skipped. But when there
359 // are wildcards, the real problem is that there was no match,
360 // causing the pattern to be added, which has illegal characters.
361 if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND))
362 semsg(_(e_nomatch2), str);
363#endif
364 }
365 else if (xp->xp_numfiles == 0)
366 {
367 if (!(options & WILD_SILENT))
368 semsg(_(e_nomatch2), str);
369 }
370 else
371 {
372 // Escape the matches for use on the command line.
373 ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
374
375 // Check for matching suffixes in file names.
376 if (mode != WILD_ALL && mode != WILD_ALL_KEEP
377 && mode != WILD_LONGEST)
378 {
379 if (xp->xp_numfiles)
380 non_suf_match = xp->xp_numfiles;
381 else
382 non_suf_match = 1;
383 if ((xp->xp_context == EXPAND_FILES
384 || xp->xp_context == EXPAND_DIRECTORIES)
385 && xp->xp_numfiles > 1)
386 {
387 // More than one match; check suffix.
388 // The files will have been sorted on matching suffix in
389 // expand_wildcards, only need to check the first two.
390 non_suf_match = 0;
391 for (i = 0; i < 2; ++i)
392 if (match_suffix(xp->xp_files[i]))
393 ++non_suf_match;
394 }
395 if (non_suf_match != 1)
396 {
397 // Can we ever get here unless it's while expanding
398 // interactively? If not, we can get rid of this all
399 // together. Don't really want to wait for this message
400 // (and possibly have to hit return to continue!).
401 if (!(options & WILD_SILENT))
402 emsg(_(e_toomany));
403 else if (!(options & WILD_NO_BEEP))
404 beep_flush();
405 }
406 if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE))
407 ss = vim_strsave(xp->xp_files[0]);
408 }
409 }
410 }
411
412 // Find longest common part
413 if (mode == WILD_LONGEST && xp->xp_numfiles > 0)
414 {
415 int mb_len = 1;
416 int c0, ci;
417
418 for (len = 0; xp->xp_files[0][len]; len += mb_len)
419 {
420 if (has_mbyte)
421 {
422 mb_len = (*mb_ptr2len)(&xp->xp_files[0][len]);
423 c0 =(* mb_ptr2char)(&xp->xp_files[0][len]);
424 }
425 else
426 c0 = xp->xp_files[0][len];
427 for (i = 1; i < xp->xp_numfiles; ++i)
428 {
429 if (has_mbyte)
430 ci =(* mb_ptr2char)(&xp->xp_files[i][len]);
431 else
432 ci = xp->xp_files[i][len];
433 if (p_fic && (xp->xp_context == EXPAND_DIRECTORIES
434 || xp->xp_context == EXPAND_FILES
435 || xp->xp_context == EXPAND_SHELLCMD
436 || xp->xp_context == EXPAND_BUFFERS))
437 {
438 if (MB_TOLOWER(c0) != MB_TOLOWER(ci))
439 break;
440 }
441 else if (c0 != ci)
442 break;
443 }
444 if (i < xp->xp_numfiles)
445 {
446 if (!(options & WILD_NO_BEEP))
447 vim_beep(BO_WILD);
448 break;
449 }
450 }
451
452 ss = alloc(len + 1);
453 if (ss)
454 vim_strncpy(ss, xp->xp_files[0], (size_t)len);
455 findex = -1; // next p_wc gets first one
456 }
457
458 // Concatenate all matching names
459 if (mode == WILD_ALL && xp->xp_numfiles > 0)
460 {
461 len = 0;
462 for (i = 0; i < xp->xp_numfiles; ++i)
463 len += (long_u)STRLEN(xp->xp_files[i]) + 1;
464 ss = alloc(len);
465 if (ss != NULL)
466 {
467 *ss = NUL;
468 for (i = 0; i < xp->xp_numfiles; ++i)
469 {
470 STRCAT(ss, xp->xp_files[i]);
471 if (i != xp->xp_numfiles - 1)
472 STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " ");
473 }
474 }
475 }
476
477 if (mode == WILD_EXPAND_FREE || mode == WILD_ALL)
478 ExpandCleanup(xp);
479
480 // Free "orig" if it wasn't stored in "orig_save".
481 if (!orig_saved)
482 vim_free(orig);
483
484 return ss;
485}
486
487/*
488 * Prepare an expand structure for use.
489 */
490 void
491ExpandInit(expand_T *xp)
492{
493 xp->xp_pattern = NULL;
494 xp->xp_pattern_len = 0;
495 xp->xp_backslash = XP_BS_NONE;
496#ifndef BACKSLASH_IN_FILENAME
497 xp->xp_shell = FALSE;
498#endif
499 xp->xp_numfiles = -1;
500 xp->xp_files = NULL;
Bram Moolenaar0a52df52019-08-18 22:26:31 +0200501#if defined(FEAT_EVAL)
Bram Moolenaar66b51422019-08-18 21:44:12 +0200502 xp->xp_arg = NULL;
503#endif
504 xp->xp_line = NULL;
505}
506
507/*
508 * Cleanup an expand structure after use.
509 */
510 void
511ExpandCleanup(expand_T *xp)
512{
513 if (xp->xp_numfiles >= 0)
514 {
515 FreeWild(xp->xp_numfiles, xp->xp_files);
516 xp->xp_numfiles = -1;
517 }
518}
519
520/*
521 * Show all matches for completion on the command line.
522 * Returns EXPAND_NOTHING when the character that triggered expansion should
523 * be inserted like a normal character.
524 */
525 int
526showmatches(expand_T *xp, int wildmenu UNUSED)
527{
528 cmdline_info_T *ccline = get_cmdline_info();
529#define L_SHOWFILE(m) (showtail ? sm_gettail(files_found[m]) : files_found[m])
530 int num_files;
531 char_u **files_found;
532 int i, j, k;
533 int maxlen;
534 int lines;
535 int columns;
536 char_u *p;
537 int lastlen;
538 int attr;
539 int showtail;
540
541 if (xp->xp_numfiles == -1)
542 {
543 set_expand_context(xp);
544 i = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos,
545 &num_files, &files_found);
546 showtail = expand_showtail(xp);
547 if (i != EXPAND_OK)
548 return i;
549
550 }
551 else
552 {
553 num_files = xp->xp_numfiles;
554 files_found = xp->xp_files;
555 showtail = cmd_showtail;
556 }
557
558#ifdef FEAT_WILDMENU
559 if (!wildmenu)
560 {
561#endif
562 msg_didany = FALSE; // lines_left will be set
563 msg_start(); // prepare for paging
564 msg_putchar('\n');
565 out_flush();
566 cmdline_row = msg_row;
567 msg_didany = FALSE; // lines_left will be set again
568 msg_start(); // prepare for paging
569#ifdef FEAT_WILDMENU
570 }
571#endif
572
573 if (got_int)
574 got_int = FALSE; // only int. the completion, not the cmd line
575#ifdef FEAT_WILDMENU
576 else if (wildmenu)
577 win_redr_status_matches(xp, num_files, files_found, -1, showtail);
578#endif
579 else
580 {
581 // find the length of the longest file name
582 maxlen = 0;
583 for (i = 0; i < num_files; ++i)
584 {
585 if (!showtail && (xp->xp_context == EXPAND_FILES
586 || xp->xp_context == EXPAND_SHELLCMD
587 || xp->xp_context == EXPAND_BUFFERS))
588 {
589 home_replace(NULL, files_found[i], NameBuff, MAXPATHL, TRUE);
590 j = vim_strsize(NameBuff);
591 }
592 else
593 j = vim_strsize(L_SHOWFILE(i));
594 if (j > maxlen)
595 maxlen = j;
596 }
597
598 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
599 lines = num_files;
600 else
601 {
602 // compute the number of columns and lines for the listing
603 maxlen += 2; // two spaces between file names
604 columns = ((int)Columns + 2) / maxlen;
605 if (columns < 1)
606 columns = 1;
607 lines = (num_files + columns - 1) / columns;
608 }
609
610 attr = HL_ATTR(HLF_D); // find out highlighting for directories
611
612 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
613 {
614 msg_puts_attr(_("tagname"), HL_ATTR(HLF_T));
615 msg_clr_eos();
616 msg_advance(maxlen - 3);
617 msg_puts_attr(_(" kind file\n"), HL_ATTR(HLF_T));
618 }
619
620 // list the files line by line
621 for (i = 0; i < lines; ++i)
622 {
623 lastlen = 999;
624 for (k = i; k < num_files; k += lines)
625 {
626 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
627 {
628 msg_outtrans_attr(files_found[k], HL_ATTR(HLF_D));
629 p = files_found[k] + STRLEN(files_found[k]) + 1;
630 msg_advance(maxlen + 1);
631 msg_puts((char *)p);
632 msg_advance(maxlen + 3);
633 msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D));
634 break;
635 }
636 for (j = maxlen - lastlen; --j >= 0; )
637 msg_putchar(' ');
638 if (xp->xp_context == EXPAND_FILES
639 || xp->xp_context == EXPAND_SHELLCMD
640 || xp->xp_context == EXPAND_BUFFERS)
641 {
642 // highlight directories
643 if (xp->xp_numfiles != -1)
644 {
645 char_u *halved_slash;
646 char_u *exp_path;
Bram Moolenaarf1552d02019-08-21 12:54:18 +0200647 char_u *path;
Bram Moolenaar66b51422019-08-18 21:44:12 +0200648
649 // Expansion was done before and special characters
650 // were escaped, need to halve backslashes. Also
651 // $HOME has been replaced with ~/.
652 exp_path = expand_env_save_opt(files_found[k], TRUE);
Bram Moolenaarf1552d02019-08-21 12:54:18 +0200653 path = exp_path != NULL ? exp_path : files_found[k];
654 halved_slash = backslash_halve_save(path);
Bram Moolenaar66b51422019-08-18 21:44:12 +0200655 j = mch_isdir(halved_slash != NULL ? halved_slash
656 : files_found[k]);
657 vim_free(exp_path);
Bram Moolenaarf1552d02019-08-21 12:54:18 +0200658 if (halved_slash != path)
659 vim_free(halved_slash);
Bram Moolenaar66b51422019-08-18 21:44:12 +0200660 }
661 else
662 // Expansion was done here, file names are literal.
663 j = mch_isdir(files_found[k]);
664 if (showtail)
665 p = L_SHOWFILE(k);
666 else
667 {
668 home_replace(NULL, files_found[k], NameBuff, MAXPATHL,
669 TRUE);
670 p = NameBuff;
671 }
672 }
673 else
674 {
675 j = FALSE;
676 p = L_SHOWFILE(k);
677 }
678 lastlen = msg_outtrans_attr(p, j ? attr : 0);
679 }
680 if (msg_col > 0) // when not wrapped around
681 {
682 msg_clr_eos();
683 msg_putchar('\n');
684 }
685 out_flush(); // show one line at a time
686 if (got_int)
687 {
688 got_int = FALSE;
689 break;
690 }
691 }
692
693 // we redraw the command below the lines that we have just listed
694 // This is a bit tricky, but it saves a lot of screen updating.
695 cmdline_row = msg_row; // will put it back later
696 }
697
698 if (xp->xp_numfiles == -1)
699 FreeWild(num_files, files_found);
700
701 return EXPAND_OK;
702}
703
704/*
705 * Private gettail for showmatches() (and win_redr_status_matches()):
706 * Find tail of file name path, but ignore trailing "/".
707 */
708 char_u *
709sm_gettail(char_u *s)
710{
711 char_u *p;
712 char_u *t = s;
713 int had_sep = FALSE;
714
715 for (p = s; *p != NUL; )
716 {
717 if (vim_ispathsep(*p)
718#ifdef BACKSLASH_IN_FILENAME
719 && !rem_backslash(p)
720#endif
721 )
722 had_sep = TRUE;
723 else if (had_sep)
724 {
725 t = p;
726 had_sep = FALSE;
727 }
728 MB_PTR_ADV(p);
729 }
730 return t;
731}
732
733/*
734 * Return TRUE if we only need to show the tail of completion matches.
735 * When not completing file names or there is a wildcard in the path FALSE is
736 * returned.
737 */
738 static int
739expand_showtail(expand_T *xp)
740{
741 char_u *s;
742 char_u *end;
743
744 // When not completing file names a "/" may mean something different.
745 if (xp->xp_context != EXPAND_FILES
746 && xp->xp_context != EXPAND_SHELLCMD
747 && xp->xp_context != EXPAND_DIRECTORIES)
748 return FALSE;
749
750 end = gettail(xp->xp_pattern);
751 if (end == xp->xp_pattern) // there is no path separator
752 return FALSE;
753
754 for (s = xp->xp_pattern; s < end; s++)
755 {
756 // Skip escaped wildcards. Only when the backslash is not a path
757 // separator, on DOS the '*' "path\*\file" must not be skipped.
758 if (rem_backslash(s))
759 ++s;
760 else if (vim_strchr((char_u *)"*?[", *s) != NULL)
761 return FALSE;
762 }
763 return TRUE;
764}
765
766/*
767 * Prepare a string for expansion.
768 * When expanding file names: The string will be used with expand_wildcards().
769 * Copy "fname[len]" into allocated memory and add a '*' at the end.
770 * When expanding other names: The string will be used with regcomp(). Copy
771 * the name into allocated memory and prepend "^".
772 */
773 char_u *
774addstar(
775 char_u *fname,
776 int len,
777 int context) // EXPAND_FILES etc.
778{
779 char_u *retval;
780 int i, j;
781 int new_len;
782 char_u *tail;
783 int ends_in_star;
784
785 if (context != EXPAND_FILES
786 && context != EXPAND_FILES_IN_PATH
787 && context != EXPAND_SHELLCMD
788 && context != EXPAND_DIRECTORIES)
789 {
790 // Matching will be done internally (on something other than files).
791 // So we convert the file-matching-type wildcards into our kind for
792 // use with vim_regcomp(). First work out how long it will be:
793
794 // For help tags the translation is done in find_help_tags().
795 // For a tag pattern starting with "/" no translation is needed.
796 if (context == EXPAND_HELP
797 || context == EXPAND_COLORS
798 || context == EXPAND_COMPILER
799 || context == EXPAND_OWNSYNTAX
800 || context == EXPAND_FILETYPE
801 || context == EXPAND_PACKADD
802 || ((context == EXPAND_TAGS_LISTFILES
803 || context == EXPAND_TAGS)
804 && fname[0] == '/'))
805 retval = vim_strnsave(fname, len);
806 else
807 {
808 new_len = len + 2; // +2 for '^' at start, NUL at end
809 for (i = 0; i < len; i++)
810 {
811 if (fname[i] == '*' || fname[i] == '~')
812 new_len++; // '*' needs to be replaced by ".*"
813 // '~' needs to be replaced by "\~"
814
815 // Buffer names are like file names. "." should be literal
816 if (context == EXPAND_BUFFERS && fname[i] == '.')
817 new_len++; // "." becomes "\."
818
819 // Custom expansion takes care of special things, match
820 // backslashes literally (perhaps also for other types?)
821 if ((context == EXPAND_USER_DEFINED
822 || context == EXPAND_USER_LIST) && fname[i] == '\\')
823 new_len++; // '\' becomes "\\"
824 }
825 retval = alloc(new_len);
826 if (retval != NULL)
827 {
828 retval[0] = '^';
829 j = 1;
830 for (i = 0; i < len; i++, j++)
831 {
832 // Skip backslash. But why? At least keep it for custom
833 // expansion.
834 if (context != EXPAND_USER_DEFINED
835 && context != EXPAND_USER_LIST
836 && fname[i] == '\\'
837 && ++i == len)
838 break;
839
840 switch (fname[i])
841 {
842 case '*': retval[j++] = '.';
843 break;
844 case '~': retval[j++] = '\\';
845 break;
846 case '?': retval[j] = '.';
847 continue;
848 case '.': if (context == EXPAND_BUFFERS)
849 retval[j++] = '\\';
850 break;
851 case '\\': if (context == EXPAND_USER_DEFINED
852 || context == EXPAND_USER_LIST)
853 retval[j++] = '\\';
854 break;
855 }
856 retval[j] = fname[i];
857 }
858 retval[j] = NUL;
859 }
860 }
861 }
862 else
863 {
864 retval = alloc(len + 4);
865 if (retval != NULL)
866 {
867 vim_strncpy(retval, fname, len);
868
869 // Don't add a star to *, ~, ~user, $var or `cmd`.
870 // * would become **, which walks the whole tree.
871 // ~ would be at the start of the file name, but not the tail.
872 // $ could be anywhere in the tail.
873 // ` could be anywhere in the file name.
874 // When the name ends in '$' don't add a star, remove the '$'.
875 tail = gettail(retval);
876 ends_in_star = (len > 0 && retval[len - 1] == '*');
877#ifndef BACKSLASH_IN_FILENAME
878 for (i = len - 2; i >= 0; --i)
879 {
880 if (retval[i] != '\\')
881 break;
882 ends_in_star = !ends_in_star;
883 }
884#endif
885 if ((*retval != '~' || tail != retval)
886 && !ends_in_star
887 && vim_strchr(tail, '$') == NULL
888 && vim_strchr(retval, '`') == NULL)
889 retval[len++] = '*';
890 else if (len > 0 && retval[len - 1] == '$')
891 --len;
892 retval[len] = NUL;
893 }
894 }
895 return retval;
896}
897
898/*
899 * Must parse the command line so far to work out what context we are in.
900 * Completion can then be done based on that context.
901 * This routine sets the variables:
902 * xp->xp_pattern The start of the pattern to be expanded within
903 * the command line (ends at the cursor).
904 * xp->xp_context The type of thing to expand. Will be one of:
905 *
906 * EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on
907 * the command line, like an unknown command. Caller
908 * should beep.
909 * EXPAND_NOTHING Unrecognised context for completion, use char like
910 * a normal char, rather than for completion. eg
911 * :s/^I/
912 * EXPAND_COMMANDS Cursor is still touching the command, so complete
913 * it.
914 * EXPAND_BUFFERS Complete file names for :buf and :sbuf commands.
915 * EXPAND_FILES After command with EX_XFILE set, or after setting
916 * with P_EXPAND set. eg :e ^I, :w>>^I
917 * EXPAND_DIRECTORIES In some cases this is used instead of the latter
918 * when we know only directories are of interest. eg
919 * :set dir=^I
920 * EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd".
921 * EXPAND_SETTINGS Complete variable names. eg :set d^I
922 * EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I
923 * EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I
924 * EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect
925 * EXPAND_HELP Complete tags from the file 'helpfile'/tags
926 * EXPAND_EVENTS Complete event names
927 * EXPAND_SYNTAX Complete :syntax command arguments
928 * EXPAND_HIGHLIGHT Complete highlight (syntax) group names
929 * EXPAND_AUGROUP Complete autocommand group names
930 * EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I
931 * EXPAND_MAPPINGS Complete mapping and abbreviation names,
932 * eg :unmap a^I , :cunab x^I
933 * EXPAND_FUNCTIONS Complete internal or user defined function names,
934 * eg :call sub^I
935 * EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I
936 * EXPAND_EXPRESSION Complete internal or user defined function/variable
937 * names in expressions, eg :while s^I
938 * EXPAND_ENV_VARS Complete environment variable names
939 * EXPAND_USER Complete user names
940 */
941 static void
942set_expand_context(expand_T *xp)
943{
944 cmdline_info_T *ccline = get_cmdline_info();
945
946 // only expansion for ':', '>' and '=' command-lines
947 if (ccline->cmdfirstc != ':'
948#ifdef FEAT_EVAL
949 && ccline->cmdfirstc != '>' && ccline->cmdfirstc != '='
950 && !ccline->input_fn
951#endif
952 )
953 {
954 xp->xp_context = EXPAND_NOTHING;
955 return;
956 }
957 set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, TRUE);
958}
959
Bram Moolenaard0190392019-08-23 21:17:35 +0200960/*
961 * This is all pretty much copied from do_one_cmd(), with all the extra stuff
962 * we don't need/want deleted. Maybe this could be done better if we didn't
963 * repeat all this stuff. The only problem is that they may not stay
964 * perfectly compatible with each other, but then the command line syntax
965 * probably won't change that much -- webb.
966 */
967 static char_u *
968set_one_cmd_context(
969 expand_T *xp,
970 char_u *buff) // buffer for command string
971{
972 char_u *p;
973 char_u *cmd, *arg;
974 int len = 0;
975 exarg_T ea;
976 int compl = EXPAND_NOTHING;
977 int delim;
978 int forceit = FALSE;
979 int usefilter = FALSE; // filter instead of file name
980
981 ExpandInit(xp);
982 xp->xp_pattern = buff;
983 xp->xp_context = EXPAND_COMMANDS; // Default until we get past command
984 ea.argt = 0;
985
986 // 1. skip comment lines and leading space, colons or bars
987 for (cmd = buff; vim_strchr((char_u *)" \t:|", *cmd) != NULL; cmd++)
988 ;
989 xp->xp_pattern = cmd;
990
991 if (*cmd == NUL)
992 return NULL;
993 if (*cmd == '"') // ignore comment lines
994 {
995 xp->xp_context = EXPAND_NOTHING;
996 return NULL;
997 }
998
999 // 3. Skip over the range to find the command.
1000 cmd = skip_range(cmd, &xp->xp_context);
1001 xp->xp_pattern = cmd;
1002 if (*cmd == NUL)
1003 return NULL;
1004 if (*cmd == '"')
1005 {
1006 xp->xp_context = EXPAND_NOTHING;
1007 return NULL;
1008 }
1009
1010 if (*cmd == '|' || *cmd == '\n')
1011 return cmd + 1; // There's another command
1012
1013 // Isolate the command and search for it in the command table.
1014 // Exceptions:
1015 // - the 'k' command can directly be followed by any character, but
1016 // do accept "keepmarks", "keepalt" and "keepjumps".
1017 // - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r'
1018 if (*cmd == 'k' && cmd[1] != 'e')
1019 {
1020 ea.cmdidx = CMD_k;
1021 p = cmd + 1;
1022 }
1023 else
1024 {
1025 p = cmd;
1026 while (ASCII_ISALPHA(*p) || *p == '*') // Allow * wild card
1027 ++p;
1028 // a user command may contain digits
1029 if (ASCII_ISUPPER(cmd[0]))
1030 while (ASCII_ISALNUM(*p) || *p == '*')
1031 ++p;
1032 // for python 3.x: ":py3*" commands completion
1033 if (cmd[0] == 'p' && cmd[1] == 'y' && p == cmd + 2 && *p == '3')
1034 {
1035 ++p;
1036 while (ASCII_ISALPHA(*p) || *p == '*')
1037 ++p;
1038 }
1039 // check for non-alpha command
1040 if (p == cmd && vim_strchr((char_u *)"@*!=><&~#", *p) != NULL)
1041 ++p;
1042 len = (int)(p - cmd);
1043
1044 if (len == 0)
1045 {
1046 xp->xp_context = EXPAND_UNSUCCESSFUL;
1047 return NULL;
1048 }
1049
1050 ea.cmdidx = excmd_get_cmdidx(cmd, len);
1051
1052 if (cmd[0] >= 'A' && cmd[0] <= 'Z')
1053 while (ASCII_ISALNUM(*p) || *p == '*') // Allow * wild card
1054 ++p;
1055 }
1056
1057 // If the cursor is touching the command, and it ends in an alpha-numeric
1058 // character, complete the command name.
1059 if (*p == NUL && ASCII_ISALNUM(p[-1]))
1060 return NULL;
1061
1062 if (ea.cmdidx == CMD_SIZE)
1063 {
1064 if (*cmd == 's' && vim_strchr((char_u *)"cgriI", cmd[1]) != NULL)
1065 {
1066 ea.cmdidx = CMD_substitute;
1067 p = cmd + 1;
1068 }
1069 else if (cmd[0] >= 'A' && cmd[0] <= 'Z')
1070 {
1071 ea.cmd = cmd;
1072 p = find_ucmd(&ea, p, NULL, xp, &compl);
1073 if (p == NULL)
1074 ea.cmdidx = CMD_SIZE; // ambiguous user command
1075 }
1076 }
1077 if (ea.cmdidx == CMD_SIZE)
1078 {
1079 // Not still touching the command and it was an illegal one
1080 xp->xp_context = EXPAND_UNSUCCESSFUL;
1081 return NULL;
1082 }
1083
1084 xp->xp_context = EXPAND_NOTHING; // Default now that we're past command
1085
1086 if (*p == '!') // forced commands
1087 {
1088 forceit = TRUE;
1089 ++p;
1090 }
1091
1092 // 6. parse arguments
1093 if (!IS_USER_CMDIDX(ea.cmdidx))
1094 ea.argt = excmd_get_argt(ea.cmdidx);
1095
1096 arg = skipwhite(p);
1097
1098 if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update)
1099 {
1100 if (*arg == '>') // append
1101 {
1102 if (*++arg == '>')
1103 ++arg;
1104 arg = skipwhite(arg);
1105 }
1106 else if (*arg == '!' && ea.cmdidx == CMD_write) // :w !filter
1107 {
1108 ++arg;
1109 usefilter = TRUE;
1110 }
1111 }
1112
1113 if (ea.cmdidx == CMD_read)
1114 {
1115 usefilter = forceit; // :r! filter if forced
1116 if (*arg == '!') // :r !filter
1117 {
1118 ++arg;
1119 usefilter = TRUE;
1120 }
1121 }
1122
1123 if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift)
1124 {
1125 while (*arg == *cmd) // allow any number of '>' or '<'
1126 ++arg;
1127 arg = skipwhite(arg);
1128 }
1129
1130 // Does command allow "+command"?
1131 if ((ea.argt & EX_CMDARG) && !usefilter && *arg == '+')
1132 {
1133 // Check if we're in the +command
1134 p = arg + 1;
1135 arg = skip_cmd_arg(arg, FALSE);
1136
1137 // Still touching the command after '+'?
1138 if (*arg == NUL)
1139 return p;
1140
1141 // Skip space(s) after +command to get to the real argument
1142 arg = skipwhite(arg);
1143 }
1144
1145 // Check for '|' to separate commands and '"' to start comments.
1146 // Don't do this for ":read !cmd" and ":write !cmd".
1147 if ((ea.argt & EX_TRLBAR) && !usefilter)
1148 {
1149 p = arg;
1150 // ":redir @" is not the start of a comment
1151 if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"')
1152 p += 2;
1153 while (*p)
1154 {
1155 if (*p == Ctrl_V)
1156 {
1157 if (p[1] != NUL)
1158 ++p;
1159 }
1160 else if ( (*p == '"' && !(ea.argt & EX_NOTRLCOM))
1161 || *p == '|' || *p == '\n')
1162 {
1163 if (*(p - 1) != '\\')
1164 {
1165 if (*p == '|' || *p == '\n')
1166 return p + 1;
1167 return NULL; // It's a comment
1168 }
1169 }
1170 MB_PTR_ADV(p);
1171 }
1172 }
1173
1174 if (!(ea.argt & EX_EXTRA) && *arg != NUL
1175 && vim_strchr((char_u *)"|\"", *arg) == NULL)
1176 // no arguments allowed but there is something
1177 return NULL;
1178
1179 // Find start of last argument (argument just before cursor):
1180 p = buff;
1181 xp->xp_pattern = p;
1182 len = (int)STRLEN(buff);
1183 while (*p && p < buff + len)
1184 {
1185 if (*p == ' ' || *p == TAB)
1186 {
1187 // argument starts after a space
1188 xp->xp_pattern = ++p;
1189 }
1190 else
1191 {
1192 if (*p == '\\' && *(p + 1) != NUL)
1193 ++p; // skip over escaped character
1194 MB_PTR_ADV(p);
1195 }
1196 }
1197
1198 if (ea.argt & EX_XFILE)
1199 {
1200 int c;
1201 int in_quote = FALSE;
1202 char_u *bow = NULL; // Beginning of word
1203
1204 // Allow spaces within back-quotes to count as part of the argument
1205 // being expanded.
1206 xp->xp_pattern = skipwhite(arg);
1207 p = xp->xp_pattern;
1208 while (*p != NUL)
1209 {
1210 if (has_mbyte)
1211 c = mb_ptr2char(p);
1212 else
1213 c = *p;
1214 if (c == '\\' && p[1] != NUL)
1215 ++p;
1216 else if (c == '`')
1217 {
1218 if (!in_quote)
1219 {
1220 xp->xp_pattern = p;
1221 bow = p + 1;
1222 }
1223 in_quote = !in_quote;
1224 }
1225 // An argument can contain just about everything, except
1226 // characters that end the command and white space.
1227 else if (c == '|' || c == '\n' || c == '"' || (VIM_ISWHITE(c)
1228#ifdef SPACE_IN_FILENAME
1229 && (!(ea.argt & EX_NOSPC) || usefilter)
1230#endif
1231 ))
1232 {
1233 len = 0; // avoid getting stuck when space is in 'isfname'
1234 while (*p != NUL)
1235 {
1236 if (has_mbyte)
1237 c = mb_ptr2char(p);
1238 else
1239 c = *p;
1240 if (c == '`' || vim_isfilec_or_wc(c))
1241 break;
1242 if (has_mbyte)
1243 len = (*mb_ptr2len)(p);
1244 else
1245 len = 1;
1246 MB_PTR_ADV(p);
1247 }
1248 if (in_quote)
1249 bow = p;
1250 else
1251 xp->xp_pattern = p;
1252 p -= len;
1253 }
1254 MB_PTR_ADV(p);
1255 }
1256
1257 // If we are still inside the quotes, and we passed a space, just
1258 // expand from there.
1259 if (bow != NULL && in_quote)
1260 xp->xp_pattern = bow;
1261 xp->xp_context = EXPAND_FILES;
1262
1263 // For a shell command more chars need to be escaped.
1264 if (usefilter || ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal)
1265 {
1266#ifndef BACKSLASH_IN_FILENAME
1267 xp->xp_shell = TRUE;
1268#endif
1269 // When still after the command name expand executables.
1270 if (xp->xp_pattern == skipwhite(arg))
1271 xp->xp_context = EXPAND_SHELLCMD;
1272 }
1273
1274 // Check for environment variable
1275 if (*xp->xp_pattern == '$'
1276#if defined(MSWIN)
1277 || *xp->xp_pattern == '%'
1278#endif
1279 )
1280 {
1281 for (p = xp->xp_pattern + 1; *p != NUL; ++p)
1282 if (!vim_isIDc(*p))
1283 break;
1284 if (*p == NUL)
1285 {
1286 xp->xp_context = EXPAND_ENV_VARS;
1287 ++xp->xp_pattern;
1288 // Avoid that the assignment uses EXPAND_FILES again.
1289 if (compl != EXPAND_USER_DEFINED && compl != EXPAND_USER_LIST)
1290 compl = EXPAND_ENV_VARS;
1291 }
1292 }
1293 // Check for user names
1294 if (*xp->xp_pattern == '~')
1295 {
1296 for (p = xp->xp_pattern + 1; *p != NUL && *p != '/'; ++p)
1297 ;
1298 // Complete ~user only if it partially matches a user name.
1299 // A full match ~user<Tab> will be replaced by user's home
1300 // directory i.e. something like ~user<Tab> -> /home/user/
1301 if (*p == NUL && p > xp->xp_pattern + 1
1302 && match_user(xp->xp_pattern + 1) >= 1)
1303 {
1304 xp->xp_context = EXPAND_USER;
1305 ++xp->xp_pattern;
1306 }
1307 }
1308 }
1309
1310 // 6. Switch on command name.
1311 switch (ea.cmdidx)
1312 {
1313 case CMD_find:
1314 case CMD_sfind:
1315 case CMD_tabfind:
1316 if (xp->xp_context == EXPAND_FILES)
1317 xp->xp_context = EXPAND_FILES_IN_PATH;
1318 break;
1319 case CMD_cd:
1320 case CMD_chdir:
1321 case CMD_tcd:
1322 case CMD_tchdir:
1323 case CMD_lcd:
1324 case CMD_lchdir:
1325 if (xp->xp_context == EXPAND_FILES)
1326 xp->xp_context = EXPAND_DIRECTORIES;
1327 break;
1328 case CMD_help:
1329 xp->xp_context = EXPAND_HELP;
1330 xp->xp_pattern = arg;
1331 break;
1332
1333 // Command modifiers: return the argument.
1334 // Also for commands with an argument that is a command.
1335 case CMD_aboveleft:
1336 case CMD_argdo:
1337 case CMD_belowright:
1338 case CMD_botright:
1339 case CMD_browse:
1340 case CMD_bufdo:
1341 case CMD_cdo:
1342 case CMD_cfdo:
1343 case CMD_confirm:
1344 case CMD_debug:
1345 case CMD_folddoclosed:
1346 case CMD_folddoopen:
1347 case CMD_hide:
1348 case CMD_keepalt:
1349 case CMD_keepjumps:
1350 case CMD_keepmarks:
1351 case CMD_keeppatterns:
1352 case CMD_ldo:
1353 case CMD_leftabove:
1354 case CMD_lfdo:
1355 case CMD_lockmarks:
1356 case CMD_noautocmd:
1357 case CMD_noswapfile:
1358 case CMD_rightbelow:
1359 case CMD_sandbox:
1360 case CMD_silent:
1361 case CMD_tab:
1362 case CMD_tabdo:
1363 case CMD_topleft:
1364 case CMD_verbose:
1365 case CMD_vertical:
1366 case CMD_windo:
1367 return arg;
1368
1369 case CMD_filter:
1370 if (*arg != NUL)
1371 arg = skip_vimgrep_pat(arg, NULL, NULL);
1372 if (arg == NULL || *arg == NUL)
1373 {
1374 xp->xp_context = EXPAND_NOTHING;
1375 return NULL;
1376 }
1377 return skipwhite(arg);
1378
1379#ifdef FEAT_SEARCH_EXTRA
1380 case CMD_match:
1381 if (*arg == NUL || !ends_excmd(*arg))
1382 {
1383 // also complete "None"
1384 set_context_in_echohl_cmd(xp, arg);
1385 arg = skipwhite(skiptowhite(arg));
1386 if (*arg != NUL)
1387 {
1388 xp->xp_context = EXPAND_NOTHING;
1389 arg = skip_regexp(arg + 1, *arg, p_magic, NULL);
1390 }
1391 }
1392 return find_nextcmd(arg);
1393#endif
1394
1395 // All completion for the +cmdline_compl feature goes here.
1396
1397 case CMD_command:
1398 return set_context_in_user_cmd(xp, arg);
1399
1400 case CMD_delcommand:
1401 xp->xp_context = EXPAND_USER_COMMANDS;
1402 xp->xp_pattern = arg;
1403 break;
1404
1405 case CMD_global:
1406 case CMD_vglobal:
1407 delim = *arg; // get the delimiter
1408 if (delim)
1409 ++arg; // skip delimiter if there is one
1410
1411 while (arg[0] != NUL && arg[0] != delim)
1412 {
1413 if (arg[0] == '\\' && arg[1] != NUL)
1414 ++arg;
1415 ++arg;
1416 }
1417 if (arg[0] != NUL)
1418 return arg + 1;
1419 break;
1420 case CMD_and:
1421 case CMD_substitute:
1422 delim = *arg;
1423 if (delim)
1424 {
1425 // skip "from" part
1426 ++arg;
1427 arg = skip_regexp(arg, delim, p_magic, NULL);
1428 }
1429 // skip "to" part
1430 while (arg[0] != NUL && arg[0] != delim)
1431 {
1432 if (arg[0] == '\\' && arg[1] != NUL)
1433 ++arg;
1434 ++arg;
1435 }
1436 if (arg[0] != NUL) // skip delimiter
1437 ++arg;
1438 while (arg[0] && vim_strchr((char_u *)"|\"#", arg[0]) == NULL)
1439 ++arg;
1440 if (arg[0] != NUL)
1441 return arg;
1442 break;
1443 case CMD_isearch:
1444 case CMD_dsearch:
1445 case CMD_ilist:
1446 case CMD_dlist:
1447 case CMD_ijump:
1448 case CMD_psearch:
1449 case CMD_djump:
1450 case CMD_isplit:
1451 case CMD_dsplit:
1452 arg = skipwhite(skipdigits(arg)); // skip count
1453 if (*arg == '/') // Match regexp, not just whole words
1454 {
1455 for (++arg; *arg && *arg != '/'; arg++)
1456 if (*arg == '\\' && arg[1] != NUL)
1457 arg++;
1458 if (*arg)
1459 {
1460 arg = skipwhite(arg + 1);
1461
1462 // Check for trailing illegal characters
1463 if (*arg && vim_strchr((char_u *)"|\"\n", *arg) == NULL)
1464 xp->xp_context = EXPAND_NOTHING;
1465 else
1466 return arg;
1467 }
1468 }
1469 break;
1470
1471 case CMD_autocmd:
1472 return set_context_in_autocmd(xp, arg, FALSE);
1473 case CMD_doautocmd:
1474 case CMD_doautoall:
1475 return set_context_in_autocmd(xp, arg, TRUE);
1476 case CMD_set:
1477 set_context_in_set_cmd(xp, arg, 0);
1478 break;
1479 case CMD_setglobal:
1480 set_context_in_set_cmd(xp, arg, OPT_GLOBAL);
1481 break;
1482 case CMD_setlocal:
1483 set_context_in_set_cmd(xp, arg, OPT_LOCAL);
1484 break;
1485 case CMD_tag:
1486 case CMD_stag:
1487 case CMD_ptag:
1488 case CMD_ltag:
1489 case CMD_tselect:
1490 case CMD_stselect:
1491 case CMD_ptselect:
1492 case CMD_tjump:
1493 case CMD_stjump:
1494 case CMD_ptjump:
1495 if (*p_wop != NUL)
1496 xp->xp_context = EXPAND_TAGS_LISTFILES;
1497 else
1498 xp->xp_context = EXPAND_TAGS;
1499 xp->xp_pattern = arg;
1500 break;
1501 case CMD_augroup:
1502 xp->xp_context = EXPAND_AUGROUP;
1503 xp->xp_pattern = arg;
1504 break;
1505#ifdef FEAT_SYN_HL
1506 case CMD_syntax:
1507 set_context_in_syntax_cmd(xp, arg);
1508 break;
1509#endif
1510#ifdef FEAT_EVAL
Bram Moolenaar8f76e6b2019-11-26 16:50:30 +01001511 case CMD_const:
Bram Moolenaard0190392019-08-23 21:17:35 +02001512 case CMD_let:
1513 case CMD_if:
1514 case CMD_elseif:
1515 case CMD_while:
1516 case CMD_for:
1517 case CMD_echo:
1518 case CMD_echon:
1519 case CMD_execute:
1520 case CMD_echomsg:
1521 case CMD_echoerr:
1522 case CMD_call:
1523 case CMD_return:
1524 case CMD_cexpr:
1525 case CMD_caddexpr:
1526 case CMD_cgetexpr:
1527 case CMD_lexpr:
1528 case CMD_laddexpr:
1529 case CMD_lgetexpr:
1530 set_context_for_expression(xp, arg, ea.cmdidx);
1531 break;
1532
1533 case CMD_unlet:
1534 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
1535 arg = xp->xp_pattern + 1;
1536
1537 xp->xp_context = EXPAND_USER_VARS;
1538 xp->xp_pattern = arg;
1539
1540 if (*xp->xp_pattern == '$')
1541 {
1542 xp->xp_context = EXPAND_ENV_VARS;
1543 ++xp->xp_pattern;
1544 }
1545
1546 break;
1547
1548 case CMD_function:
1549 case CMD_delfunction:
1550 xp->xp_context = EXPAND_USER_FUNC;
1551 xp->xp_pattern = arg;
1552 break;
1553
1554 case CMD_echohl:
1555 set_context_in_echohl_cmd(xp, arg);
1556 break;
1557#endif
1558 case CMD_highlight:
1559 set_context_in_highlight_cmd(xp, arg);
1560 break;
1561#ifdef FEAT_CSCOPE
1562 case CMD_cscope:
1563 case CMD_lcscope:
1564 case CMD_scscope:
1565 set_context_in_cscope_cmd(xp, arg, ea.cmdidx);
1566 break;
1567#endif
1568#ifdef FEAT_SIGNS
1569 case CMD_sign:
1570 set_context_in_sign_cmd(xp, arg);
1571 break;
1572#endif
1573 case CMD_bdelete:
1574 case CMD_bwipeout:
1575 case CMD_bunload:
1576 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
1577 arg = xp->xp_pattern + 1;
1578 // FALLTHROUGH
1579 case CMD_buffer:
1580 case CMD_sbuffer:
1581 case CMD_checktime:
1582 xp->xp_context = EXPAND_BUFFERS;
1583 xp->xp_pattern = arg;
1584 break;
1585
1586 case CMD_USER:
1587 case CMD_USER_BUF:
1588 if (compl != EXPAND_NOTHING)
1589 {
1590 // EX_XFILE: file names are handled above
1591 if (!(ea.argt & EX_XFILE))
1592 {
1593#ifdef FEAT_MENU
1594 if (compl == EXPAND_MENUS)
1595 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
1596#endif
1597 if (compl == EXPAND_COMMANDS)
1598 return arg;
1599 if (compl == EXPAND_MAPPINGS)
1600 return set_context_in_map_cmd(xp, (char_u *)"map",
1601 arg, forceit, FALSE, FALSE, CMD_map);
1602 // Find start of last argument.
1603 p = arg;
1604 while (*p)
1605 {
1606 if (*p == ' ')
1607 // argument starts after a space
1608 arg = p + 1;
1609 else if (*p == '\\' && *(p + 1) != NUL)
1610 ++p; // skip over escaped character
1611 MB_PTR_ADV(p);
1612 }
1613 xp->xp_pattern = arg;
1614 }
1615 xp->xp_context = compl;
1616 }
1617 break;
1618
1619 case CMD_map: case CMD_noremap:
1620 case CMD_nmap: case CMD_nnoremap:
1621 case CMD_vmap: case CMD_vnoremap:
1622 case CMD_omap: case CMD_onoremap:
1623 case CMD_imap: case CMD_inoremap:
1624 case CMD_cmap: case CMD_cnoremap:
1625 case CMD_lmap: case CMD_lnoremap:
1626 case CMD_smap: case CMD_snoremap:
1627 case CMD_tmap: case CMD_tnoremap:
1628 case CMD_xmap: case CMD_xnoremap:
1629 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1630 FALSE, FALSE, ea.cmdidx);
1631 case CMD_unmap:
1632 case CMD_nunmap:
1633 case CMD_vunmap:
1634 case CMD_ounmap:
1635 case CMD_iunmap:
1636 case CMD_cunmap:
1637 case CMD_lunmap:
1638 case CMD_sunmap:
1639 case CMD_tunmap:
1640 case CMD_xunmap:
1641 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1642 FALSE, TRUE, ea.cmdidx);
1643 case CMD_mapclear:
1644 case CMD_nmapclear:
1645 case CMD_vmapclear:
1646 case CMD_omapclear:
1647 case CMD_imapclear:
1648 case CMD_cmapclear:
1649 case CMD_lmapclear:
1650 case CMD_smapclear:
1651 case CMD_tmapclear:
1652 case CMD_xmapclear:
1653 xp->xp_context = EXPAND_MAPCLEAR;
1654 xp->xp_pattern = arg;
1655 break;
1656
1657 case CMD_abbreviate: case CMD_noreabbrev:
1658 case CMD_cabbrev: case CMD_cnoreabbrev:
1659 case CMD_iabbrev: case CMD_inoreabbrev:
1660 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1661 TRUE, FALSE, ea.cmdidx);
1662 case CMD_unabbreviate:
1663 case CMD_cunabbrev:
1664 case CMD_iunabbrev:
1665 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1666 TRUE, TRUE, ea.cmdidx);
1667#ifdef FEAT_MENU
1668 case CMD_menu: case CMD_noremenu: case CMD_unmenu:
1669 case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu:
1670 case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu:
1671 case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu:
1672 case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu:
1673 case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu:
1674 case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu:
1675 case CMD_tlmenu: case CMD_tlnoremenu: case CMD_tlunmenu:
1676 case CMD_tmenu: case CMD_tunmenu:
1677 case CMD_popup: case CMD_tearoff: case CMD_emenu:
1678 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
1679#endif
1680
1681 case CMD_colorscheme:
1682 xp->xp_context = EXPAND_COLORS;
1683 xp->xp_pattern = arg;
1684 break;
1685
1686 case CMD_compiler:
1687 xp->xp_context = EXPAND_COMPILER;
1688 xp->xp_pattern = arg;
1689 break;
1690
1691 case CMD_ownsyntax:
1692 xp->xp_context = EXPAND_OWNSYNTAX;
1693 xp->xp_pattern = arg;
1694 break;
1695
1696 case CMD_setfiletype:
1697 xp->xp_context = EXPAND_FILETYPE;
1698 xp->xp_pattern = arg;
1699 break;
1700
1701 case CMD_packadd:
1702 xp->xp_context = EXPAND_PACKADD;
1703 xp->xp_pattern = arg;
1704 break;
1705
1706#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1707 case CMD_language:
1708 p = skiptowhite(arg);
1709 if (*p == NUL)
1710 {
1711 xp->xp_context = EXPAND_LANGUAGE;
1712 xp->xp_pattern = arg;
1713 }
1714 else
1715 {
1716 if ( STRNCMP(arg, "messages", p - arg) == 0
1717 || STRNCMP(arg, "ctype", p - arg) == 0
1718 || STRNCMP(arg, "time", p - arg) == 0)
1719 {
1720 xp->xp_context = EXPAND_LOCALES;
1721 xp->xp_pattern = skipwhite(p);
1722 }
1723 else
1724 xp->xp_context = EXPAND_NOTHING;
1725 }
1726 break;
1727#endif
1728#if defined(FEAT_PROFILE)
1729 case CMD_profile:
1730 set_context_in_profile_cmd(xp, arg);
1731 break;
1732#endif
1733 case CMD_behave:
1734 xp->xp_context = EXPAND_BEHAVE;
1735 xp->xp_pattern = arg;
1736 break;
1737
1738 case CMD_messages:
1739 xp->xp_context = EXPAND_MESSAGES;
1740 xp->xp_pattern = arg;
1741 break;
1742
1743 case CMD_history:
1744 xp->xp_context = EXPAND_HISTORY;
1745 xp->xp_pattern = arg;
1746 break;
1747#if defined(FEAT_PROFILE)
1748 case CMD_syntime:
1749 xp->xp_context = EXPAND_SYNTIME;
1750 xp->xp_pattern = arg;
1751 break;
1752#endif
1753
1754 case CMD_argdelete:
1755 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
1756 arg = xp->xp_pattern + 1;
1757 xp->xp_context = EXPAND_ARGLIST;
1758 xp->xp_pattern = arg;
1759 break;
1760
1761 default:
1762 break;
1763 }
1764 return NULL;
1765}
1766
Bram Moolenaar66b51422019-08-18 21:44:12 +02001767 void
1768set_cmd_context(
1769 expand_T *xp,
1770 char_u *str, // start of command line
1771 int len, // length of command line (excl. NUL)
1772 int col, // position of cursor
1773 int use_ccline UNUSED) // use ccline for info
1774{
1775#ifdef FEAT_EVAL
1776 cmdline_info_T *ccline = get_cmdline_info();
1777#endif
1778 int old_char = NUL;
1779 char_u *nextcomm;
1780
1781 // Avoid a UMR warning from Purify, only save the character if it has been
1782 // written before.
1783 if (col < len)
1784 old_char = str[col];
1785 str[col] = NUL;
1786 nextcomm = str;
1787
1788#ifdef FEAT_EVAL
1789 if (use_ccline && ccline->cmdfirstc == '=')
1790 {
Bram Moolenaar66b51422019-08-18 21:44:12 +02001791 // pass CMD_SIZE because there is no real command
1792 set_context_for_expression(xp, str, CMD_SIZE);
Bram Moolenaar66b51422019-08-18 21:44:12 +02001793 }
1794 else if (use_ccline && ccline->input_fn)
1795 {
1796 xp->xp_context = ccline->xp_context;
1797 xp->xp_pattern = ccline->cmdbuff;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001798 xp->xp_arg = ccline->xp_arg;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001799 }
1800 else
1801#endif
1802 while (nextcomm != NULL)
1803 nextcomm = set_one_cmd_context(xp, nextcomm);
1804
1805 // Store the string here so that call_user_expand_func() can get to them
1806 // easily.
1807 xp->xp_line = str;
1808 xp->xp_col = col;
1809
1810 str[col] = old_char;
1811}
1812
1813/*
1814 * Expand the command line "str" from context "xp".
1815 * "xp" must have been set by set_cmd_context().
1816 * xp->xp_pattern points into "str", to where the text that is to be expanded
1817 * starts.
1818 * Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
1819 * cursor.
1820 * Returns EXPAND_NOTHING when there is nothing to expand, might insert the
1821 * key that triggered expansion literally.
1822 * Returns EXPAND_OK otherwise.
1823 */
1824 int
1825expand_cmdline(
1826 expand_T *xp,
1827 char_u *str, // start of command line
1828 int col, // position of cursor
1829 int *matchcount, // return: nr of matches
1830 char_u ***matches) // return: array of pointers to matches
1831{
1832 char_u *file_str = NULL;
1833 int options = WILD_ADD_SLASH|WILD_SILENT;
1834
1835 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
1836 {
1837 beep_flush();
1838 return EXPAND_UNSUCCESSFUL; // Something illegal on command line
1839 }
1840 if (xp->xp_context == EXPAND_NOTHING)
1841 {
1842 // Caller can use the character as a normal char instead
1843 return EXPAND_NOTHING;
1844 }
1845
1846 // add star to file name, or convert to regexp if not exp. files.
1847 xp->xp_pattern_len = (int)(str + col - xp->xp_pattern);
1848 file_str = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
1849 if (file_str == NULL)
1850 return EXPAND_UNSUCCESSFUL;
1851
1852 if (p_wic)
1853 options += WILD_ICASE;
1854
1855 // find all files that match the description
1856 if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL)
1857 {
1858 *matchcount = 0;
1859 *matches = NULL;
1860 }
1861 vim_free(file_str);
1862
1863 return EXPAND_OK;
1864}
1865
1866#ifdef FEAT_MULTI_LANG
1867/*
1868 * Cleanup matches for help tags:
1869 * Remove "@ab" if the top of 'helplang' is "ab" and the language of the first
1870 * tag matches it. Otherwise remove "@en" if "en" is the only language.
1871 */
1872 static void
1873cleanup_help_tags(int num_file, char_u **file)
1874{
1875 int i, j;
1876 int len;
1877 char_u buf[4];
1878 char_u *p = buf;
1879
1880 if (p_hlg[0] != NUL && (p_hlg[0] != 'e' || p_hlg[1] != 'n'))
1881 {
1882 *p++ = '@';
1883 *p++ = p_hlg[0];
1884 *p++ = p_hlg[1];
1885 }
1886 *p = NUL;
1887
1888 for (i = 0; i < num_file; ++i)
1889 {
1890 len = (int)STRLEN(file[i]) - 3;
1891 if (len <= 0)
1892 continue;
1893 if (STRCMP(file[i] + len, "@en") == 0)
1894 {
1895 // Sorting on priority means the same item in another language may
1896 // be anywhere. Search all items for a match up to the "@en".
1897 for (j = 0; j < num_file; ++j)
1898 if (j != i && (int)STRLEN(file[j]) == len + 3
1899 && STRNCMP(file[i], file[j], len + 1) == 0)
1900 break;
1901 if (j == num_file)
1902 // item only exists with @en, remove it
1903 file[i][len] = NUL;
1904 }
1905 }
1906
1907 if (*buf != NUL)
1908 for (i = 0; i < num_file; ++i)
1909 {
1910 len = (int)STRLEN(file[i]) - 3;
1911 if (len <= 0)
1912 continue;
1913 if (STRCMP(file[i] + len, buf) == 0)
1914 {
1915 // remove the default language
1916 file[i][len] = NUL;
1917 }
1918 }
1919}
1920#endif
1921
1922/*
Bram Moolenaard0190392019-08-23 21:17:35 +02001923 * Function given to ExpandGeneric() to obtain the possible arguments of the
1924 * ":behave {mswin,xterm}" command.
1925 */
1926 static char_u *
1927get_behave_arg(expand_T *xp UNUSED, int idx)
1928{
1929 if (idx == 0)
1930 return (char_u *)"mswin";
1931 if (idx == 1)
1932 return (char_u *)"xterm";
1933 return NULL;
1934}
1935
1936/*
1937 * Function given to ExpandGeneric() to obtain the possible arguments of the
1938 * ":messages {clear}" command.
1939 */
1940 static char_u *
1941get_messages_arg(expand_T *xp UNUSED, int idx)
1942{
1943 if (idx == 0)
1944 return (char_u *)"clear";
1945 return NULL;
1946}
1947
1948 static char_u *
1949get_mapclear_arg(expand_T *xp UNUSED, int idx)
1950{
1951 if (idx == 0)
1952 return (char_u *)"<buffer>";
1953 return NULL;
1954}
1955
1956/*
Bram Moolenaar66b51422019-08-18 21:44:12 +02001957 * Do the expansion based on xp->xp_context and "pat".
1958 */
1959 static int
1960ExpandFromContext(
1961 expand_T *xp,
1962 char_u *pat,
1963 int *num_file,
1964 char_u ***file,
1965 int options) // WILD_ flags
1966{
Bram Moolenaar66b51422019-08-18 21:44:12 +02001967 regmatch_T regmatch;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001968 int ret;
1969 int flags;
1970
1971 flags = EW_DIR; // include directories
1972 if (options & WILD_LIST_NOTFOUND)
1973 flags |= EW_NOTFOUND;
1974 if (options & WILD_ADD_SLASH)
1975 flags |= EW_ADDSLASH;
1976 if (options & WILD_KEEP_ALL)
1977 flags |= EW_KEEPALL;
1978 if (options & WILD_SILENT)
1979 flags |= EW_SILENT;
Bram Moolenaarb40c2572019-10-19 21:01:05 +02001980 if (options & WILD_NOERROR)
1981 flags |= EW_NOERROR;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001982 if (options & WILD_ALLLINKS)
1983 flags |= EW_ALLLINKS;
1984
1985 if (xp->xp_context == EXPAND_FILES
1986 || xp->xp_context == EXPAND_DIRECTORIES
1987 || xp->xp_context == EXPAND_FILES_IN_PATH)
1988 {
1989 // Expand file or directory names.
1990 int free_pat = FALSE;
1991 int i;
1992
1993 // for ":set path=" and ":set tags=" halve backslashes for escaped
1994 // space
1995 if (xp->xp_backslash != XP_BS_NONE)
1996 {
1997 free_pat = TRUE;
1998 pat = vim_strsave(pat);
1999 for (i = 0; pat[i]; ++i)
2000 if (pat[i] == '\\')
2001 {
2002 if (xp->xp_backslash == XP_BS_THREE
2003 && pat[i + 1] == '\\'
2004 && pat[i + 2] == '\\'
2005 && pat[i + 3] == ' ')
2006 STRMOVE(pat + i, pat + i + 3);
2007 if (xp->xp_backslash == XP_BS_ONE
2008 && pat[i + 1] == ' ')
2009 STRMOVE(pat + i, pat + i + 1);
2010 }
2011 }
2012
2013 if (xp->xp_context == EXPAND_FILES)
2014 flags |= EW_FILE;
2015 else if (xp->xp_context == EXPAND_FILES_IN_PATH)
2016 flags |= (EW_FILE | EW_PATH);
2017 else
2018 flags = (flags | EW_DIR) & ~EW_FILE;
2019 if (options & WILD_ICASE)
2020 flags |= EW_ICASE;
2021
2022 // Expand wildcards, supporting %:h and the like.
2023 ret = expand_wildcards_eval(&pat, num_file, file, flags);
2024 if (free_pat)
2025 vim_free(pat);
2026#ifdef BACKSLASH_IN_FILENAME
2027 if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0)
2028 {
2029 int i;
2030
2031 for (i = 0; i < *num_file; ++i)
2032 {
2033 char_u *ptr = (*file)[i];
2034
2035 while (*ptr != NUL)
2036 {
2037 if (p_csl[0] == 's' && *ptr == '\\')
2038 *ptr = '/';
2039 else if (p_csl[0] == 'b' && *ptr == '/')
2040 *ptr = '\\';
2041 ptr += (*mb_ptr2len)(ptr);
2042 }
2043 }
2044 }
2045#endif
2046 return ret;
2047 }
2048
2049 *file = (char_u **)"";
2050 *num_file = 0;
2051 if (xp->xp_context == EXPAND_HELP)
2052 {
2053 // With an empty argument we would get all the help tags, which is
2054 // very slow. Get matches for "help" instead.
2055 if (find_help_tags(*pat == NUL ? (char_u *)"help" : pat,
2056 num_file, file, FALSE) == OK)
2057 {
2058#ifdef FEAT_MULTI_LANG
2059 cleanup_help_tags(*num_file, *file);
2060#endif
2061 return OK;
2062 }
2063 return FAIL;
2064 }
2065
Bram Moolenaar66b51422019-08-18 21:44:12 +02002066 if (xp->xp_context == EXPAND_SHELLCMD)
2067 return expand_shellcmd(pat, num_file, file, flags);
2068 if (xp->xp_context == EXPAND_OLD_SETTING)
2069 return ExpandOldSetting(num_file, file);
2070 if (xp->xp_context == EXPAND_BUFFERS)
2071 return ExpandBufnames(pat, num_file, file, options);
2072 if (xp->xp_context == EXPAND_TAGS
2073 || xp->xp_context == EXPAND_TAGS_LISTFILES)
2074 return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
2075 if (xp->xp_context == EXPAND_COLORS)
2076 {
2077 char *directories[] = {"colors", NULL};
2078 return ExpandRTDir(pat, DIP_START + DIP_OPT, num_file, file,
2079 directories);
2080 }
2081 if (xp->xp_context == EXPAND_COMPILER)
2082 {
2083 char *directories[] = {"compiler", NULL};
2084 return ExpandRTDir(pat, 0, num_file, file, directories);
2085 }
2086 if (xp->xp_context == EXPAND_OWNSYNTAX)
2087 {
2088 char *directories[] = {"syntax", NULL};
2089 return ExpandRTDir(pat, 0, num_file, file, directories);
2090 }
2091 if (xp->xp_context == EXPAND_FILETYPE)
2092 {
2093 char *directories[] = {"syntax", "indent", "ftplugin", NULL};
2094 return ExpandRTDir(pat, 0, num_file, file, directories);
2095 }
2096# if defined(FEAT_EVAL)
2097 if (xp->xp_context == EXPAND_USER_LIST)
2098 return ExpandUserList(xp, num_file, file);
2099# endif
2100 if (xp->xp_context == EXPAND_PACKADD)
2101 return ExpandPackAddDir(pat, num_file, file);
2102
2103 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2104 if (regmatch.regprog == NULL)
2105 return FAIL;
2106
2107 // set ignore-case according to p_ic, p_scs and pat
2108 regmatch.rm_ic = ignorecase(pat);
2109
2110 if (xp->xp_context == EXPAND_SETTINGS
2111 || xp->xp_context == EXPAND_BOOL_SETTINGS)
2112 ret = ExpandSettings(xp, &regmatch, num_file, file);
2113 else if (xp->xp_context == EXPAND_MAPPINGS)
2114 ret = ExpandMappings(&regmatch, num_file, file);
2115# if defined(FEAT_EVAL)
2116 else if (xp->xp_context == EXPAND_USER_DEFINED)
2117 ret = ExpandUserDefined(xp, &regmatch, num_file, file);
2118# endif
2119 else
2120 {
2121 static struct expgen
2122 {
2123 int context;
2124 char_u *((*func)(expand_T *, int));
2125 int ic;
2126 int escaped;
2127 } tab[] =
2128 {
2129 {EXPAND_COMMANDS, get_command_name, FALSE, TRUE},
2130 {EXPAND_BEHAVE, get_behave_arg, TRUE, TRUE},
2131 {EXPAND_MAPCLEAR, get_mapclear_arg, TRUE, TRUE},
2132 {EXPAND_MESSAGES, get_messages_arg, TRUE, TRUE},
2133 {EXPAND_HISTORY, get_history_arg, TRUE, TRUE},
2134 {EXPAND_USER_COMMANDS, get_user_commands, FALSE, TRUE},
2135 {EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, FALSE, TRUE},
2136 {EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE, TRUE},
2137 {EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE, TRUE},
2138 {EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE, TRUE},
2139# ifdef FEAT_EVAL
2140 {EXPAND_USER_VARS, get_user_var_name, FALSE, TRUE},
2141 {EXPAND_FUNCTIONS, get_function_name, FALSE, TRUE},
2142 {EXPAND_USER_FUNC, get_user_func_name, FALSE, TRUE},
2143 {EXPAND_EXPRESSION, get_expr_name, FALSE, TRUE},
2144# endif
2145# ifdef FEAT_MENU
2146 {EXPAND_MENUS, get_menu_name, FALSE, TRUE},
2147 {EXPAND_MENUNAMES, get_menu_names, FALSE, TRUE},
2148# endif
2149# ifdef FEAT_SYN_HL
2150 {EXPAND_SYNTAX, get_syntax_name, TRUE, TRUE},
2151# endif
2152# ifdef FEAT_PROFILE
2153 {EXPAND_SYNTIME, get_syntime_arg, TRUE, TRUE},
2154# endif
2155 {EXPAND_HIGHLIGHT, get_highlight_name, TRUE, TRUE},
2156 {EXPAND_EVENTS, get_event_name, TRUE, TRUE},
2157 {EXPAND_AUGROUP, get_augroup_name, TRUE, TRUE},
2158# ifdef FEAT_CSCOPE
2159 {EXPAND_CSCOPE, get_cscope_name, TRUE, TRUE},
2160# endif
2161# ifdef FEAT_SIGNS
2162 {EXPAND_SIGN, get_sign_name, TRUE, TRUE},
2163# endif
2164# ifdef FEAT_PROFILE
2165 {EXPAND_PROFILE, get_profile_name, TRUE, TRUE},
2166# endif
2167# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
2168 {EXPAND_LANGUAGE, get_lang_arg, TRUE, FALSE},
2169 {EXPAND_LOCALES, get_locales, TRUE, FALSE},
2170# endif
2171 {EXPAND_ENV_VARS, get_env_name, TRUE, TRUE},
2172 {EXPAND_USER, get_users, TRUE, FALSE},
2173 {EXPAND_ARGLIST, get_arglist_name, TRUE, FALSE},
2174 };
2175 int i;
2176
2177 // Find a context in the table and call the ExpandGeneric() with the
2178 // right function to do the expansion.
2179 ret = FAIL;
2180 for (i = 0; i < (int)(sizeof(tab) / sizeof(struct expgen)); ++i)
2181 if (xp->xp_context == tab[i].context)
2182 {
2183 if (tab[i].ic)
2184 regmatch.rm_ic = TRUE;
2185 ret = ExpandGeneric(xp, &regmatch, num_file, file,
2186 tab[i].func, tab[i].escaped);
2187 break;
2188 }
2189 }
2190
2191 vim_regfree(regmatch.regprog);
2192
2193 return ret;
Bram Moolenaar66b51422019-08-18 21:44:12 +02002194}
2195
Bram Moolenaar66b51422019-08-18 21:44:12 +02002196/*
2197 * Expand a list of names.
2198 *
2199 * Generic function for command line completion. It calls a function to
2200 * obtain strings, one by one. The strings are matched against a regexp
2201 * program. Matching strings are copied into an array, which is returned.
2202 *
2203 * Returns OK when no problems encountered, FAIL for error (out of memory).
2204 */
2205 int
2206ExpandGeneric(
2207 expand_T *xp,
2208 regmatch_T *regmatch,
2209 int *num_file,
2210 char_u ***file,
2211 char_u *((*func)(expand_T *, int)),
2212 // returns a string from the list
2213 int escaped)
2214{
2215 int i;
2216 int count = 0;
2217 int round;
2218 char_u *str;
2219
2220 // do this loop twice:
2221 // round == 0: count the number of matching names
2222 // round == 1: copy the matching names into allocated memory
2223 for (round = 0; round <= 1; ++round)
2224 {
2225 for (i = 0; ; ++i)
2226 {
2227 str = (*func)(xp, i);
2228 if (str == NULL) // end of list
2229 break;
2230 if (*str == NUL) // skip empty strings
2231 continue;
2232
2233 if (vim_regexec(regmatch, str, (colnr_T)0))
2234 {
2235 if (round)
2236 {
2237 if (escaped)
2238 str = vim_strsave_escaped(str, (char_u *)" \t\\.");
2239 else
2240 str = vim_strsave(str);
2241 (*file)[count] = str;
2242# ifdef FEAT_MENU
2243 if (func == get_menu_names && str != NULL)
2244 {
2245 // test for separator added by get_menu_names()
2246 str += STRLEN(str) - 1;
2247 if (*str == '\001')
2248 *str = '.';
2249 }
2250# endif
2251 }
2252 ++count;
2253 }
2254 }
2255 if (round == 0)
2256 {
2257 if (count == 0)
2258 return OK;
2259 *num_file = count;
2260 *file = ALLOC_MULT(char_u *, count);
2261 if (*file == NULL)
2262 {
2263 *file = (char_u **)"";
2264 return FAIL;
2265 }
2266 count = 0;
2267 }
2268 }
2269
2270 // Sort the results. Keep menu's in the specified order.
2271 if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
2272 {
2273 if (xp->xp_context == EXPAND_EXPRESSION
2274 || xp->xp_context == EXPAND_FUNCTIONS
2275 || xp->xp_context == EXPAND_USER_FUNC)
2276 // <SNR> functions should be sorted to the end.
2277 qsort((void *)*file, (size_t)*num_file, sizeof(char_u *),
2278 sort_func_compare);
2279 else
2280 sort_strings(*file, *num_file);
2281 }
2282
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002283#if defined(FEAT_SYN_HL)
Bram Moolenaar66b51422019-08-18 21:44:12 +02002284 // Reset the variables used for special highlight names expansion, so that
2285 // they don't show up when getting normal highlight names by ID.
2286 reset_expand_highlight();
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002287#endif
Bram Moolenaar66b51422019-08-18 21:44:12 +02002288
2289 return OK;
2290}
2291
2292/*
2293 * Complete a shell command.
2294 * Returns FAIL or OK;
2295 */
2296 static int
2297expand_shellcmd(
2298 char_u *filepat, // pattern to match with command names
2299 int *num_file, // return: number of matches
2300 char_u ***file, // return: array with matches
2301 int flagsarg) // EW_ flags
2302{
2303 char_u *pat;
2304 int i;
2305 char_u *path = NULL;
2306 int mustfree = FALSE;
2307 garray_T ga;
2308 char_u *buf = alloc(MAXPATHL);
2309 size_t l;
2310 char_u *s, *e;
2311 int flags = flagsarg;
2312 int ret;
2313 int did_curdir = FALSE;
2314 hashtab_T found_ht;
2315 hashitem_T *hi;
2316 hash_T hash;
2317
2318 if (buf == NULL)
2319 return FAIL;
2320
2321 // for ":set path=" and ":set tags=" halve backslashes for escaped
2322 // space
2323 pat = vim_strsave(filepat);
2324 for (i = 0; pat[i]; ++i)
2325 if (pat[i] == '\\' && pat[i + 1] == ' ')
2326 STRMOVE(pat + i, pat + i + 1);
2327
2328 flags |= EW_FILE | EW_EXEC | EW_SHELLCMD;
2329
2330 if (pat[0] == '.' && (vim_ispathsep(pat[1])
2331 || (pat[1] == '.' && vim_ispathsep(pat[2]))))
2332 path = (char_u *)".";
2333 else
2334 {
2335 // For an absolute name we don't use $PATH.
2336 if (!mch_isFullName(pat))
2337 path = vim_getenv((char_u *)"PATH", &mustfree);
2338 if (path == NULL)
2339 path = (char_u *)"";
2340 }
2341
2342 // Go over all directories in $PATH. Expand matches in that directory and
2343 // collect them in "ga". When "." is not in $PATH also expand for the
2344 // current directory, to find "subdir/cmd".
2345 ga_init2(&ga, (int)sizeof(char *), 10);
2346 hash_init(&found_ht);
2347 for (s = path; ; s = e)
2348 {
2349# if defined(MSWIN)
2350 e = vim_strchr(s, ';');
2351# else
2352 e = vim_strchr(s, ':');
2353# endif
2354 if (e == NULL)
2355 e = s + STRLEN(s);
2356
2357 if (*s == NUL)
2358 {
2359 if (did_curdir)
2360 break;
2361 // Find directories in the current directory, path is empty.
2362 did_curdir = TRUE;
2363 flags |= EW_DIR;
2364 }
2365 else if (STRNCMP(s, ".", (int)(e - s)) == 0)
2366 {
2367 did_curdir = TRUE;
2368 flags |= EW_DIR;
2369 }
2370 else
2371 // Do not match directories inside a $PATH item.
2372 flags &= ~EW_DIR;
2373
2374 l = e - s;
2375 if (l > MAXPATHL - 5)
2376 break;
2377 vim_strncpy(buf, s, l);
2378 add_pathsep(buf);
2379 l = STRLEN(buf);
2380 vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
2381
2382 // Expand matches in one directory of $PATH.
2383 ret = expand_wildcards(1, &buf, num_file, file, flags);
2384 if (ret == OK)
2385 {
2386 if (ga_grow(&ga, *num_file) == FAIL)
2387 FreeWild(*num_file, *file);
2388 else
2389 {
2390 for (i = 0; i < *num_file; ++i)
2391 {
2392 char_u *name = (*file)[i];
2393
2394 if (STRLEN(name) > l)
2395 {
2396 // Check if this name was already found.
2397 hash = hash_hash(name + l);
2398 hi = hash_lookup(&found_ht, name + l, hash);
2399 if (HASHITEM_EMPTY(hi))
2400 {
2401 // Remove the path that was prepended.
2402 STRMOVE(name, name + l);
2403 ((char_u **)ga.ga_data)[ga.ga_len++] = name;
2404 hash_add_item(&found_ht, hi, name, hash);
2405 name = NULL;
2406 }
2407 }
2408 vim_free(name);
2409 }
2410 vim_free(*file);
2411 }
2412 }
2413 if (*e != NUL)
2414 ++e;
2415 }
2416 *file = ga.ga_data;
2417 *num_file = ga.ga_len;
2418
2419 vim_free(buf);
2420 vim_free(pat);
2421 if (mustfree)
2422 vim_free(path);
2423 hash_clear(&found_ht);
2424 return OK;
2425}
2426
2427# if defined(FEAT_EVAL)
2428/*
2429 * Call "user_expand_func()" to invoke a user defined Vim script function and
2430 * return the result (either a string or a List).
2431 */
2432 static void *
2433call_user_expand_func(
2434 void *(*user_expand_func)(char_u *, int, typval_T *),
2435 expand_T *xp,
2436 int *num_file,
2437 char_u ***file)
2438{
2439 cmdline_info_T *ccline = get_cmdline_info();
2440 int keep = 0;
2441 typval_T args[4];
2442 sctx_T save_current_sctx = current_sctx;
2443 char_u *pat = NULL;
2444 void *ret;
2445
2446 if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL)
2447 return NULL;
2448 *num_file = 0;
2449 *file = NULL;
2450
2451 if (ccline->cmdbuff != NULL)
2452 {
2453 keep = ccline->cmdbuff[ccline->cmdlen];
2454 ccline->cmdbuff[ccline->cmdlen] = 0;
2455 }
2456
2457 pat = vim_strnsave(xp->xp_pattern, xp->xp_pattern_len);
2458
2459 args[0].v_type = VAR_STRING;
2460 args[0].vval.v_string = pat;
2461 args[1].v_type = VAR_STRING;
2462 args[1].vval.v_string = xp->xp_line;
2463 args[2].v_type = VAR_NUMBER;
2464 args[2].vval.v_number = xp->xp_col;
2465 args[3].v_type = VAR_UNKNOWN;
2466
2467 current_sctx = xp->xp_script_ctx;
2468
2469 ret = user_expand_func(xp->xp_arg, 3, args);
2470
2471 current_sctx = save_current_sctx;
2472 if (ccline->cmdbuff != NULL)
2473 ccline->cmdbuff[ccline->cmdlen] = keep;
2474
2475 vim_free(pat);
2476 return ret;
2477}
2478
2479/*
2480 * Expand names with a function defined by the user.
2481 */
2482 static int
2483ExpandUserDefined(
2484 expand_T *xp,
2485 regmatch_T *regmatch,
2486 int *num_file,
2487 char_u ***file)
2488{
2489 char_u *retstr;
2490 char_u *s;
2491 char_u *e;
2492 int keep;
2493 garray_T ga;
2494 int skip;
2495
2496 retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
2497 if (retstr == NULL)
2498 return FAIL;
2499
2500 ga_init2(&ga, (int)sizeof(char *), 3);
2501 for (s = retstr; *s != NUL; s = e)
2502 {
2503 e = vim_strchr(s, '\n');
2504 if (e == NULL)
2505 e = s + STRLEN(s);
2506 keep = *e;
2507 *e = NUL;
2508
2509 skip = xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0;
2510 *e = keep;
2511
2512 if (!skip)
2513 {
2514 if (ga_grow(&ga, 1) == FAIL)
2515 break;
2516 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
2517 ++ga.ga_len;
2518 }
2519
2520 if (*e != NUL)
2521 ++e;
2522 }
2523 vim_free(retstr);
2524 *file = ga.ga_data;
2525 *num_file = ga.ga_len;
2526 return OK;
2527}
2528
2529/*
2530 * Expand names with a list returned by a function defined by the user.
2531 */
2532 static int
2533ExpandUserList(
2534 expand_T *xp,
2535 int *num_file,
2536 char_u ***file)
2537{
2538 list_T *retlist;
2539 listitem_T *li;
2540 garray_T ga;
2541
2542 retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
2543 if (retlist == NULL)
2544 return FAIL;
2545
2546 ga_init2(&ga, (int)sizeof(char *), 3);
2547 // Loop over the items in the list.
2548 for (li = retlist->lv_first; li != NULL; li = li->li_next)
2549 {
2550 if (li->li_tv.v_type != VAR_STRING || li->li_tv.vval.v_string == NULL)
2551 continue; // Skip non-string items and empty strings
2552
2553 if (ga_grow(&ga, 1) == FAIL)
2554 break;
2555
2556 ((char_u **)ga.ga_data)[ga.ga_len] =
2557 vim_strsave(li->li_tv.vval.v_string);
2558 ++ga.ga_len;
2559 }
2560 list_unref(retlist);
2561
2562 *file = ga.ga_data;
2563 *num_file = ga.ga_len;
2564 return OK;
2565}
2566# endif
2567
2568/*
Bram Moolenaar66b51422019-08-18 21:44:12 +02002569 * Expand "file" for all comma-separated directories in "path".
2570 * Adds the matches to "ga". Caller must init "ga".
2571 */
2572 void
2573globpath(
2574 char_u *path,
2575 char_u *file,
2576 garray_T *ga,
2577 int expand_options)
2578{
2579 expand_T xpc;
2580 char_u *buf;
2581 int i;
2582 int num_p;
2583 char_u **p;
2584
2585 buf = alloc(MAXPATHL);
2586 if (buf == NULL)
2587 return;
2588
2589 ExpandInit(&xpc);
2590 xpc.xp_context = EXPAND_FILES;
2591
2592 // Loop over all entries in {path}.
2593 while (*path != NUL)
2594 {
2595 // Copy one item of the path to buf[] and concatenate the file name.
2596 copy_option_part(&path, buf, MAXPATHL, ",");
2597 if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
2598 {
2599# if defined(MSWIN)
2600 // Using the platform's path separator (\) makes vim incorrectly
2601 // treat it as an escape character, use '/' instead.
2602 if (*buf != NUL && !after_pathsep(buf, buf + STRLEN(buf)))
2603 STRCAT(buf, "/");
2604# else
2605 add_pathsep(buf);
2606# endif
2607 STRCAT(buf, file);
2608 if (ExpandFromContext(&xpc, buf, &num_p, &p,
2609 WILD_SILENT|expand_options) != FAIL && num_p > 0)
2610 {
2611 ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT|expand_options);
2612
2613 if (ga_grow(ga, num_p) == OK)
2614 {
2615 for (i = 0; i < num_p; ++i)
2616 {
2617 ((char_u **)ga->ga_data)[ga->ga_len] =
2618 vim_strnsave(p[i], (int)STRLEN(p[i]));
2619 ++ga->ga_len;
2620 }
2621 }
2622
2623 FreeWild(num_p, p);
2624 }
2625 }
2626 }
2627
2628 vim_free(buf);
2629}
Bram Moolenaar66b51422019-08-18 21:44:12 +02002630
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002631#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar66b51422019-08-18 21:44:12 +02002632/*
2633 * "getcompletion()" function
2634 */
2635 void
2636f_getcompletion(typval_T *argvars, typval_T *rettv)
2637{
2638 char_u *pat;
2639 expand_T xpc;
2640 int filtered = FALSE;
2641 int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH
2642 | WILD_NO_BEEP;
2643
2644 if (argvars[2].v_type != VAR_UNKNOWN)
2645 filtered = tv_get_number_chk(&argvars[2], NULL);
2646
2647 if (p_wic)
2648 options |= WILD_ICASE;
2649
2650 // For filtered results, 'wildignore' is used
2651 if (!filtered)
2652 options |= WILD_KEEP_ALL;
2653
2654 ExpandInit(&xpc);
2655 xpc.xp_pattern = tv_get_string(&argvars[0]);
2656 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2657 xpc.xp_context = cmdcomplete_str_to_type(tv_get_string(&argvars[1]));
2658 if (xpc.xp_context == EXPAND_NOTHING)
2659 {
2660 if (argvars[1].v_type == VAR_STRING)
2661 semsg(_(e_invarg2), argvars[1].vval.v_string);
2662 else
2663 emsg(_(e_invarg));
2664 return;
2665 }
2666
2667# if defined(FEAT_MENU)
2668 if (xpc.xp_context == EXPAND_MENUS)
2669 {
2670 set_context_in_menu_cmd(&xpc, (char_u *)"menu", xpc.xp_pattern, FALSE);
2671 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2672 }
2673# endif
2674# ifdef FEAT_CSCOPE
2675 if (xpc.xp_context == EXPAND_CSCOPE)
2676 {
2677 set_context_in_cscope_cmd(&xpc, xpc.xp_pattern, CMD_cscope);
2678 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2679 }
2680# endif
2681# ifdef FEAT_SIGNS
2682 if (xpc.xp_context == EXPAND_SIGN)
2683 {
2684 set_context_in_sign_cmd(&xpc, xpc.xp_pattern);
2685 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2686 }
2687# endif
2688
2689 pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
2690 if ((rettv_list_alloc(rettv) != FAIL) && (pat != NULL))
2691 {
2692 int i;
2693
2694 ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP);
2695
2696 for (i = 0; i < xpc.xp_numfiles; i++)
2697 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
2698 }
2699 vim_free(pat);
2700 ExpandCleanup(&xpc);
2701}
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002702#endif // FEAT_EVAL