blob: 9dc78ed5c3c0d88913c14c3b21bd0f7976299c51 [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;
Bram Moolenaarae7dba82019-12-29 13:56:33 +01001585#ifdef FEAT_DIFF
1586 case CMD_diffget:
1587 case CMD_diffput:
1588 // If current buffer is in diff mode, complete buffer names
1589 // which are in diff mode, and different than current buffer.
1590 xp->xp_context = EXPAND_DIFF_BUFFERS;
1591 xp->xp_pattern = arg;
1592 break;
1593#endif
Bram Moolenaard0190392019-08-23 21:17:35 +02001594 case CMD_USER:
1595 case CMD_USER_BUF:
1596 if (compl != EXPAND_NOTHING)
1597 {
1598 // EX_XFILE: file names are handled above
1599 if (!(ea.argt & EX_XFILE))
1600 {
1601#ifdef FEAT_MENU
1602 if (compl == EXPAND_MENUS)
1603 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
1604#endif
1605 if (compl == EXPAND_COMMANDS)
1606 return arg;
1607 if (compl == EXPAND_MAPPINGS)
1608 return set_context_in_map_cmd(xp, (char_u *)"map",
1609 arg, forceit, FALSE, FALSE, CMD_map);
1610 // Find start of last argument.
1611 p = arg;
1612 while (*p)
1613 {
1614 if (*p == ' ')
1615 // argument starts after a space
1616 arg = p + 1;
1617 else if (*p == '\\' && *(p + 1) != NUL)
1618 ++p; // skip over escaped character
1619 MB_PTR_ADV(p);
1620 }
1621 xp->xp_pattern = arg;
1622 }
1623 xp->xp_context = compl;
1624 }
1625 break;
1626
1627 case CMD_map: case CMD_noremap:
1628 case CMD_nmap: case CMD_nnoremap:
1629 case CMD_vmap: case CMD_vnoremap:
1630 case CMD_omap: case CMD_onoremap:
1631 case CMD_imap: case CMD_inoremap:
1632 case CMD_cmap: case CMD_cnoremap:
1633 case CMD_lmap: case CMD_lnoremap:
1634 case CMD_smap: case CMD_snoremap:
1635 case CMD_tmap: case CMD_tnoremap:
1636 case CMD_xmap: case CMD_xnoremap:
1637 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1638 FALSE, FALSE, ea.cmdidx);
1639 case CMD_unmap:
1640 case CMD_nunmap:
1641 case CMD_vunmap:
1642 case CMD_ounmap:
1643 case CMD_iunmap:
1644 case CMD_cunmap:
1645 case CMD_lunmap:
1646 case CMD_sunmap:
1647 case CMD_tunmap:
1648 case CMD_xunmap:
1649 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1650 FALSE, TRUE, ea.cmdidx);
1651 case CMD_mapclear:
1652 case CMD_nmapclear:
1653 case CMD_vmapclear:
1654 case CMD_omapclear:
1655 case CMD_imapclear:
1656 case CMD_cmapclear:
1657 case CMD_lmapclear:
1658 case CMD_smapclear:
1659 case CMD_tmapclear:
1660 case CMD_xmapclear:
1661 xp->xp_context = EXPAND_MAPCLEAR;
1662 xp->xp_pattern = arg;
1663 break;
1664
1665 case CMD_abbreviate: case CMD_noreabbrev:
1666 case CMD_cabbrev: case CMD_cnoreabbrev:
1667 case CMD_iabbrev: case CMD_inoreabbrev:
1668 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1669 TRUE, FALSE, ea.cmdidx);
1670 case CMD_unabbreviate:
1671 case CMD_cunabbrev:
1672 case CMD_iunabbrev:
1673 return set_context_in_map_cmd(xp, cmd, arg, forceit,
1674 TRUE, TRUE, ea.cmdidx);
1675#ifdef FEAT_MENU
1676 case CMD_menu: case CMD_noremenu: case CMD_unmenu:
1677 case CMD_amenu: case CMD_anoremenu: case CMD_aunmenu:
1678 case CMD_nmenu: case CMD_nnoremenu: case CMD_nunmenu:
1679 case CMD_vmenu: case CMD_vnoremenu: case CMD_vunmenu:
1680 case CMD_omenu: case CMD_onoremenu: case CMD_ounmenu:
1681 case CMD_imenu: case CMD_inoremenu: case CMD_iunmenu:
1682 case CMD_cmenu: case CMD_cnoremenu: case CMD_cunmenu:
1683 case CMD_tlmenu: case CMD_tlnoremenu: case CMD_tlunmenu:
1684 case CMD_tmenu: case CMD_tunmenu:
1685 case CMD_popup: case CMD_tearoff: case CMD_emenu:
1686 return set_context_in_menu_cmd(xp, cmd, arg, forceit);
1687#endif
1688
1689 case CMD_colorscheme:
1690 xp->xp_context = EXPAND_COLORS;
1691 xp->xp_pattern = arg;
1692 break;
1693
1694 case CMD_compiler:
1695 xp->xp_context = EXPAND_COMPILER;
1696 xp->xp_pattern = arg;
1697 break;
1698
1699 case CMD_ownsyntax:
1700 xp->xp_context = EXPAND_OWNSYNTAX;
1701 xp->xp_pattern = arg;
1702 break;
1703
1704 case CMD_setfiletype:
1705 xp->xp_context = EXPAND_FILETYPE;
1706 xp->xp_pattern = arg;
1707 break;
1708
1709 case CMD_packadd:
1710 xp->xp_context = EXPAND_PACKADD;
1711 xp->xp_pattern = arg;
1712 break;
1713
1714#if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1715 case CMD_language:
1716 p = skiptowhite(arg);
1717 if (*p == NUL)
1718 {
1719 xp->xp_context = EXPAND_LANGUAGE;
1720 xp->xp_pattern = arg;
1721 }
1722 else
1723 {
1724 if ( STRNCMP(arg, "messages", p - arg) == 0
1725 || STRNCMP(arg, "ctype", p - arg) == 0
1726 || STRNCMP(arg, "time", p - arg) == 0)
1727 {
1728 xp->xp_context = EXPAND_LOCALES;
1729 xp->xp_pattern = skipwhite(p);
1730 }
1731 else
1732 xp->xp_context = EXPAND_NOTHING;
1733 }
1734 break;
1735#endif
1736#if defined(FEAT_PROFILE)
1737 case CMD_profile:
1738 set_context_in_profile_cmd(xp, arg);
1739 break;
1740#endif
1741 case CMD_behave:
1742 xp->xp_context = EXPAND_BEHAVE;
1743 xp->xp_pattern = arg;
1744 break;
1745
1746 case CMD_messages:
1747 xp->xp_context = EXPAND_MESSAGES;
1748 xp->xp_pattern = arg;
1749 break;
1750
1751 case CMD_history:
1752 xp->xp_context = EXPAND_HISTORY;
1753 xp->xp_pattern = arg;
1754 break;
1755#if defined(FEAT_PROFILE)
1756 case CMD_syntime:
1757 xp->xp_context = EXPAND_SYNTIME;
1758 xp->xp_pattern = arg;
1759 break;
1760#endif
1761
1762 case CMD_argdelete:
1763 while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL)
1764 arg = xp->xp_pattern + 1;
1765 xp->xp_context = EXPAND_ARGLIST;
1766 xp->xp_pattern = arg;
1767 break;
1768
1769 default:
1770 break;
1771 }
1772 return NULL;
1773}
1774
Bram Moolenaar66b51422019-08-18 21:44:12 +02001775 void
1776set_cmd_context(
1777 expand_T *xp,
1778 char_u *str, // start of command line
1779 int len, // length of command line (excl. NUL)
1780 int col, // position of cursor
1781 int use_ccline UNUSED) // use ccline for info
1782{
1783#ifdef FEAT_EVAL
1784 cmdline_info_T *ccline = get_cmdline_info();
1785#endif
1786 int old_char = NUL;
1787 char_u *nextcomm;
1788
1789 // Avoid a UMR warning from Purify, only save the character if it has been
1790 // written before.
1791 if (col < len)
1792 old_char = str[col];
1793 str[col] = NUL;
1794 nextcomm = str;
1795
1796#ifdef FEAT_EVAL
1797 if (use_ccline && ccline->cmdfirstc == '=')
1798 {
Bram Moolenaar66b51422019-08-18 21:44:12 +02001799 // pass CMD_SIZE because there is no real command
1800 set_context_for_expression(xp, str, CMD_SIZE);
Bram Moolenaar66b51422019-08-18 21:44:12 +02001801 }
1802 else if (use_ccline && ccline->input_fn)
1803 {
1804 xp->xp_context = ccline->xp_context;
1805 xp->xp_pattern = ccline->cmdbuff;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001806 xp->xp_arg = ccline->xp_arg;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001807 }
1808 else
1809#endif
1810 while (nextcomm != NULL)
1811 nextcomm = set_one_cmd_context(xp, nextcomm);
1812
1813 // Store the string here so that call_user_expand_func() can get to them
1814 // easily.
1815 xp->xp_line = str;
1816 xp->xp_col = col;
1817
1818 str[col] = old_char;
1819}
1820
1821/*
1822 * Expand the command line "str" from context "xp".
1823 * "xp" must have been set by set_cmd_context().
1824 * xp->xp_pattern points into "str", to where the text that is to be expanded
1825 * starts.
1826 * Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
1827 * cursor.
1828 * Returns EXPAND_NOTHING when there is nothing to expand, might insert the
1829 * key that triggered expansion literally.
1830 * Returns EXPAND_OK otherwise.
1831 */
1832 int
1833expand_cmdline(
1834 expand_T *xp,
1835 char_u *str, // start of command line
1836 int col, // position of cursor
1837 int *matchcount, // return: nr of matches
1838 char_u ***matches) // return: array of pointers to matches
1839{
1840 char_u *file_str = NULL;
1841 int options = WILD_ADD_SLASH|WILD_SILENT;
1842
1843 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
1844 {
1845 beep_flush();
1846 return EXPAND_UNSUCCESSFUL; // Something illegal on command line
1847 }
1848 if (xp->xp_context == EXPAND_NOTHING)
1849 {
1850 // Caller can use the character as a normal char instead
1851 return EXPAND_NOTHING;
1852 }
1853
1854 // add star to file name, or convert to regexp if not exp. files.
1855 xp->xp_pattern_len = (int)(str + col - xp->xp_pattern);
1856 file_str = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
1857 if (file_str == NULL)
1858 return EXPAND_UNSUCCESSFUL;
1859
1860 if (p_wic)
1861 options += WILD_ICASE;
1862
1863 // find all files that match the description
1864 if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL)
1865 {
1866 *matchcount = 0;
1867 *matches = NULL;
1868 }
1869 vim_free(file_str);
1870
1871 return EXPAND_OK;
1872}
1873
1874#ifdef FEAT_MULTI_LANG
1875/*
1876 * Cleanup matches for help tags:
1877 * Remove "@ab" if the top of 'helplang' is "ab" and the language of the first
1878 * tag matches it. Otherwise remove "@en" if "en" is the only language.
1879 */
1880 static void
1881cleanup_help_tags(int num_file, char_u **file)
1882{
1883 int i, j;
1884 int len;
1885 char_u buf[4];
1886 char_u *p = buf;
1887
1888 if (p_hlg[0] != NUL && (p_hlg[0] != 'e' || p_hlg[1] != 'n'))
1889 {
1890 *p++ = '@';
1891 *p++ = p_hlg[0];
1892 *p++ = p_hlg[1];
1893 }
1894 *p = NUL;
1895
1896 for (i = 0; i < num_file; ++i)
1897 {
1898 len = (int)STRLEN(file[i]) - 3;
1899 if (len <= 0)
1900 continue;
1901 if (STRCMP(file[i] + len, "@en") == 0)
1902 {
1903 // Sorting on priority means the same item in another language may
1904 // be anywhere. Search all items for a match up to the "@en".
1905 for (j = 0; j < num_file; ++j)
1906 if (j != i && (int)STRLEN(file[j]) == len + 3
1907 && STRNCMP(file[i], file[j], len + 1) == 0)
1908 break;
1909 if (j == num_file)
1910 // item only exists with @en, remove it
1911 file[i][len] = NUL;
1912 }
1913 }
1914
1915 if (*buf != NUL)
1916 for (i = 0; i < num_file; ++i)
1917 {
1918 len = (int)STRLEN(file[i]) - 3;
1919 if (len <= 0)
1920 continue;
1921 if (STRCMP(file[i] + len, buf) == 0)
1922 {
1923 // remove the default language
1924 file[i][len] = NUL;
1925 }
1926 }
1927}
1928#endif
1929
1930/*
Bram Moolenaard0190392019-08-23 21:17:35 +02001931 * Function given to ExpandGeneric() to obtain the possible arguments of the
1932 * ":behave {mswin,xterm}" command.
1933 */
1934 static char_u *
1935get_behave_arg(expand_T *xp UNUSED, int idx)
1936{
1937 if (idx == 0)
1938 return (char_u *)"mswin";
1939 if (idx == 1)
1940 return (char_u *)"xterm";
1941 return NULL;
1942}
1943
1944/*
1945 * Function given to ExpandGeneric() to obtain the possible arguments of the
1946 * ":messages {clear}" command.
1947 */
1948 static char_u *
1949get_messages_arg(expand_T *xp UNUSED, int idx)
1950{
1951 if (idx == 0)
1952 return (char_u *)"clear";
1953 return NULL;
1954}
1955
1956 static char_u *
1957get_mapclear_arg(expand_T *xp UNUSED, int idx)
1958{
1959 if (idx == 0)
1960 return (char_u *)"<buffer>";
1961 return NULL;
1962}
1963
1964/*
Bram Moolenaar66b51422019-08-18 21:44:12 +02001965 * Do the expansion based on xp->xp_context and "pat".
1966 */
1967 static int
1968ExpandFromContext(
1969 expand_T *xp,
1970 char_u *pat,
1971 int *num_file,
1972 char_u ***file,
1973 int options) // WILD_ flags
1974{
Bram Moolenaar66b51422019-08-18 21:44:12 +02001975 regmatch_T regmatch;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001976 int ret;
1977 int flags;
1978
1979 flags = EW_DIR; // include directories
1980 if (options & WILD_LIST_NOTFOUND)
1981 flags |= EW_NOTFOUND;
1982 if (options & WILD_ADD_SLASH)
1983 flags |= EW_ADDSLASH;
1984 if (options & WILD_KEEP_ALL)
1985 flags |= EW_KEEPALL;
1986 if (options & WILD_SILENT)
1987 flags |= EW_SILENT;
Bram Moolenaarb40c2572019-10-19 21:01:05 +02001988 if (options & WILD_NOERROR)
1989 flags |= EW_NOERROR;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001990 if (options & WILD_ALLLINKS)
1991 flags |= EW_ALLLINKS;
1992
1993 if (xp->xp_context == EXPAND_FILES
1994 || xp->xp_context == EXPAND_DIRECTORIES
1995 || xp->xp_context == EXPAND_FILES_IN_PATH)
1996 {
1997 // Expand file or directory names.
1998 int free_pat = FALSE;
1999 int i;
2000
2001 // for ":set path=" and ":set tags=" halve backslashes for escaped
2002 // space
2003 if (xp->xp_backslash != XP_BS_NONE)
2004 {
2005 free_pat = TRUE;
2006 pat = vim_strsave(pat);
2007 for (i = 0; pat[i]; ++i)
2008 if (pat[i] == '\\')
2009 {
2010 if (xp->xp_backslash == XP_BS_THREE
2011 && pat[i + 1] == '\\'
2012 && pat[i + 2] == '\\'
2013 && pat[i + 3] == ' ')
2014 STRMOVE(pat + i, pat + i + 3);
2015 if (xp->xp_backslash == XP_BS_ONE
2016 && pat[i + 1] == ' ')
2017 STRMOVE(pat + i, pat + i + 1);
2018 }
2019 }
2020
2021 if (xp->xp_context == EXPAND_FILES)
2022 flags |= EW_FILE;
2023 else if (xp->xp_context == EXPAND_FILES_IN_PATH)
2024 flags |= (EW_FILE | EW_PATH);
2025 else
2026 flags = (flags | EW_DIR) & ~EW_FILE;
2027 if (options & WILD_ICASE)
2028 flags |= EW_ICASE;
2029
2030 // Expand wildcards, supporting %:h and the like.
2031 ret = expand_wildcards_eval(&pat, num_file, file, flags);
2032 if (free_pat)
2033 vim_free(pat);
2034#ifdef BACKSLASH_IN_FILENAME
2035 if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0)
2036 {
2037 int i;
2038
2039 for (i = 0; i < *num_file; ++i)
2040 {
2041 char_u *ptr = (*file)[i];
2042
2043 while (*ptr != NUL)
2044 {
2045 if (p_csl[0] == 's' && *ptr == '\\')
2046 *ptr = '/';
2047 else if (p_csl[0] == 'b' && *ptr == '/')
2048 *ptr = '\\';
2049 ptr += (*mb_ptr2len)(ptr);
2050 }
2051 }
2052 }
2053#endif
2054 return ret;
2055 }
2056
2057 *file = (char_u **)"";
2058 *num_file = 0;
2059 if (xp->xp_context == EXPAND_HELP)
2060 {
2061 // With an empty argument we would get all the help tags, which is
2062 // very slow. Get matches for "help" instead.
2063 if (find_help_tags(*pat == NUL ? (char_u *)"help" : pat,
2064 num_file, file, FALSE) == OK)
2065 {
2066#ifdef FEAT_MULTI_LANG
2067 cleanup_help_tags(*num_file, *file);
2068#endif
2069 return OK;
2070 }
2071 return FAIL;
2072 }
2073
Bram Moolenaar66b51422019-08-18 21:44:12 +02002074 if (xp->xp_context == EXPAND_SHELLCMD)
2075 return expand_shellcmd(pat, num_file, file, flags);
2076 if (xp->xp_context == EXPAND_OLD_SETTING)
2077 return ExpandOldSetting(num_file, file);
2078 if (xp->xp_context == EXPAND_BUFFERS)
2079 return ExpandBufnames(pat, num_file, file, options);
Bram Moolenaarae7dba82019-12-29 13:56:33 +01002080#ifdef FEAT_DIFF
2081 if (xp->xp_context == EXPAND_DIFF_BUFFERS)
2082 return ExpandBufnames(pat, num_file, file, options | BUF_DIFF_FILTER);
2083#endif
Bram Moolenaar66b51422019-08-18 21:44:12 +02002084 if (xp->xp_context == EXPAND_TAGS
2085 || xp->xp_context == EXPAND_TAGS_LISTFILES)
2086 return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
2087 if (xp->xp_context == EXPAND_COLORS)
2088 {
2089 char *directories[] = {"colors", NULL};
2090 return ExpandRTDir(pat, DIP_START + DIP_OPT, num_file, file,
2091 directories);
2092 }
2093 if (xp->xp_context == EXPAND_COMPILER)
2094 {
2095 char *directories[] = {"compiler", NULL};
2096 return ExpandRTDir(pat, 0, num_file, file, directories);
2097 }
2098 if (xp->xp_context == EXPAND_OWNSYNTAX)
2099 {
2100 char *directories[] = {"syntax", NULL};
2101 return ExpandRTDir(pat, 0, num_file, file, directories);
2102 }
2103 if (xp->xp_context == EXPAND_FILETYPE)
2104 {
2105 char *directories[] = {"syntax", "indent", "ftplugin", NULL};
2106 return ExpandRTDir(pat, 0, num_file, file, directories);
2107 }
2108# if defined(FEAT_EVAL)
2109 if (xp->xp_context == EXPAND_USER_LIST)
2110 return ExpandUserList(xp, num_file, file);
2111# endif
2112 if (xp->xp_context == EXPAND_PACKADD)
2113 return ExpandPackAddDir(pat, num_file, file);
2114
2115 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2116 if (regmatch.regprog == NULL)
2117 return FAIL;
2118
2119 // set ignore-case according to p_ic, p_scs and pat
2120 regmatch.rm_ic = ignorecase(pat);
2121
2122 if (xp->xp_context == EXPAND_SETTINGS
2123 || xp->xp_context == EXPAND_BOOL_SETTINGS)
2124 ret = ExpandSettings(xp, &regmatch, num_file, file);
2125 else if (xp->xp_context == EXPAND_MAPPINGS)
2126 ret = ExpandMappings(&regmatch, num_file, file);
2127# if defined(FEAT_EVAL)
2128 else if (xp->xp_context == EXPAND_USER_DEFINED)
2129 ret = ExpandUserDefined(xp, &regmatch, num_file, file);
2130# endif
2131 else
2132 {
2133 static struct expgen
2134 {
2135 int context;
2136 char_u *((*func)(expand_T *, int));
2137 int ic;
2138 int escaped;
2139 } tab[] =
2140 {
2141 {EXPAND_COMMANDS, get_command_name, FALSE, TRUE},
2142 {EXPAND_BEHAVE, get_behave_arg, TRUE, TRUE},
2143 {EXPAND_MAPCLEAR, get_mapclear_arg, TRUE, TRUE},
2144 {EXPAND_MESSAGES, get_messages_arg, TRUE, TRUE},
2145 {EXPAND_HISTORY, get_history_arg, TRUE, TRUE},
2146 {EXPAND_USER_COMMANDS, get_user_commands, FALSE, TRUE},
2147 {EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, FALSE, TRUE},
2148 {EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE, TRUE},
2149 {EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE, TRUE},
2150 {EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE, TRUE},
2151# ifdef FEAT_EVAL
2152 {EXPAND_USER_VARS, get_user_var_name, FALSE, TRUE},
2153 {EXPAND_FUNCTIONS, get_function_name, FALSE, TRUE},
2154 {EXPAND_USER_FUNC, get_user_func_name, FALSE, TRUE},
2155 {EXPAND_EXPRESSION, get_expr_name, FALSE, TRUE},
2156# endif
2157# ifdef FEAT_MENU
2158 {EXPAND_MENUS, get_menu_name, FALSE, TRUE},
2159 {EXPAND_MENUNAMES, get_menu_names, FALSE, TRUE},
2160# endif
2161# ifdef FEAT_SYN_HL
2162 {EXPAND_SYNTAX, get_syntax_name, TRUE, TRUE},
2163# endif
2164# ifdef FEAT_PROFILE
2165 {EXPAND_SYNTIME, get_syntime_arg, TRUE, TRUE},
2166# endif
2167 {EXPAND_HIGHLIGHT, get_highlight_name, TRUE, TRUE},
2168 {EXPAND_EVENTS, get_event_name, TRUE, TRUE},
2169 {EXPAND_AUGROUP, get_augroup_name, TRUE, TRUE},
2170# ifdef FEAT_CSCOPE
2171 {EXPAND_CSCOPE, get_cscope_name, TRUE, TRUE},
2172# endif
2173# ifdef FEAT_SIGNS
2174 {EXPAND_SIGN, get_sign_name, TRUE, TRUE},
2175# endif
2176# ifdef FEAT_PROFILE
2177 {EXPAND_PROFILE, get_profile_name, TRUE, TRUE},
2178# endif
2179# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
2180 {EXPAND_LANGUAGE, get_lang_arg, TRUE, FALSE},
2181 {EXPAND_LOCALES, get_locales, TRUE, FALSE},
2182# endif
2183 {EXPAND_ENV_VARS, get_env_name, TRUE, TRUE},
2184 {EXPAND_USER, get_users, TRUE, FALSE},
2185 {EXPAND_ARGLIST, get_arglist_name, TRUE, FALSE},
2186 };
2187 int i;
2188
2189 // Find a context in the table and call the ExpandGeneric() with the
2190 // right function to do the expansion.
2191 ret = FAIL;
2192 for (i = 0; i < (int)(sizeof(tab) / sizeof(struct expgen)); ++i)
2193 if (xp->xp_context == tab[i].context)
2194 {
2195 if (tab[i].ic)
2196 regmatch.rm_ic = TRUE;
2197 ret = ExpandGeneric(xp, &regmatch, num_file, file,
2198 tab[i].func, tab[i].escaped);
2199 break;
2200 }
2201 }
2202
2203 vim_regfree(regmatch.regprog);
2204
2205 return ret;
Bram Moolenaar66b51422019-08-18 21:44:12 +02002206}
2207
Bram Moolenaar66b51422019-08-18 21:44:12 +02002208/*
2209 * Expand a list of names.
2210 *
2211 * Generic function for command line completion. It calls a function to
2212 * obtain strings, one by one. The strings are matched against a regexp
2213 * program. Matching strings are copied into an array, which is returned.
2214 *
2215 * Returns OK when no problems encountered, FAIL for error (out of memory).
2216 */
2217 int
2218ExpandGeneric(
2219 expand_T *xp,
2220 regmatch_T *regmatch,
2221 int *num_file,
2222 char_u ***file,
2223 char_u *((*func)(expand_T *, int)),
2224 // returns a string from the list
2225 int escaped)
2226{
2227 int i;
2228 int count = 0;
2229 int round;
2230 char_u *str;
2231
2232 // do this loop twice:
2233 // round == 0: count the number of matching names
2234 // round == 1: copy the matching names into allocated memory
2235 for (round = 0; round <= 1; ++round)
2236 {
2237 for (i = 0; ; ++i)
2238 {
2239 str = (*func)(xp, i);
2240 if (str == NULL) // end of list
2241 break;
2242 if (*str == NUL) // skip empty strings
2243 continue;
2244
2245 if (vim_regexec(regmatch, str, (colnr_T)0))
2246 {
2247 if (round)
2248 {
2249 if (escaped)
2250 str = vim_strsave_escaped(str, (char_u *)" \t\\.");
2251 else
2252 str = vim_strsave(str);
2253 (*file)[count] = str;
2254# ifdef FEAT_MENU
2255 if (func == get_menu_names && str != NULL)
2256 {
2257 // test for separator added by get_menu_names()
2258 str += STRLEN(str) - 1;
2259 if (*str == '\001')
2260 *str = '.';
2261 }
2262# endif
2263 }
2264 ++count;
2265 }
2266 }
2267 if (round == 0)
2268 {
2269 if (count == 0)
2270 return OK;
2271 *num_file = count;
2272 *file = ALLOC_MULT(char_u *, count);
2273 if (*file == NULL)
2274 {
2275 *file = (char_u **)"";
2276 return FAIL;
2277 }
2278 count = 0;
2279 }
2280 }
2281
2282 // Sort the results. Keep menu's in the specified order.
2283 if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
2284 {
2285 if (xp->xp_context == EXPAND_EXPRESSION
2286 || xp->xp_context == EXPAND_FUNCTIONS
2287 || xp->xp_context == EXPAND_USER_FUNC)
2288 // <SNR> functions should be sorted to the end.
2289 qsort((void *)*file, (size_t)*num_file, sizeof(char_u *),
2290 sort_func_compare);
2291 else
2292 sort_strings(*file, *num_file);
2293 }
2294
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002295#if defined(FEAT_SYN_HL)
Bram Moolenaar66b51422019-08-18 21:44:12 +02002296 // Reset the variables used for special highlight names expansion, so that
2297 // they don't show up when getting normal highlight names by ID.
2298 reset_expand_highlight();
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002299#endif
Bram Moolenaar66b51422019-08-18 21:44:12 +02002300
2301 return OK;
2302}
2303
2304/*
2305 * Complete a shell command.
2306 * Returns FAIL or OK;
2307 */
2308 static int
2309expand_shellcmd(
2310 char_u *filepat, // pattern to match with command names
2311 int *num_file, // return: number of matches
2312 char_u ***file, // return: array with matches
2313 int flagsarg) // EW_ flags
2314{
2315 char_u *pat;
2316 int i;
2317 char_u *path = NULL;
2318 int mustfree = FALSE;
2319 garray_T ga;
2320 char_u *buf = alloc(MAXPATHL);
2321 size_t l;
2322 char_u *s, *e;
2323 int flags = flagsarg;
2324 int ret;
2325 int did_curdir = FALSE;
2326 hashtab_T found_ht;
2327 hashitem_T *hi;
2328 hash_T hash;
2329
2330 if (buf == NULL)
2331 return FAIL;
2332
2333 // for ":set path=" and ":set tags=" halve backslashes for escaped
2334 // space
2335 pat = vim_strsave(filepat);
2336 for (i = 0; pat[i]; ++i)
2337 if (pat[i] == '\\' && pat[i + 1] == ' ')
2338 STRMOVE(pat + i, pat + i + 1);
2339
2340 flags |= EW_FILE | EW_EXEC | EW_SHELLCMD;
2341
2342 if (pat[0] == '.' && (vim_ispathsep(pat[1])
2343 || (pat[1] == '.' && vim_ispathsep(pat[2]))))
2344 path = (char_u *)".";
2345 else
2346 {
2347 // For an absolute name we don't use $PATH.
2348 if (!mch_isFullName(pat))
2349 path = vim_getenv((char_u *)"PATH", &mustfree);
2350 if (path == NULL)
2351 path = (char_u *)"";
2352 }
2353
2354 // Go over all directories in $PATH. Expand matches in that directory and
2355 // collect them in "ga". When "." is not in $PATH also expand for the
2356 // current directory, to find "subdir/cmd".
2357 ga_init2(&ga, (int)sizeof(char *), 10);
2358 hash_init(&found_ht);
2359 for (s = path; ; s = e)
2360 {
2361# if defined(MSWIN)
2362 e = vim_strchr(s, ';');
2363# else
2364 e = vim_strchr(s, ':');
2365# endif
2366 if (e == NULL)
2367 e = s + STRLEN(s);
2368
2369 if (*s == NUL)
2370 {
2371 if (did_curdir)
2372 break;
2373 // Find directories in the current directory, path is empty.
2374 did_curdir = TRUE;
2375 flags |= EW_DIR;
2376 }
2377 else if (STRNCMP(s, ".", (int)(e - s)) == 0)
2378 {
2379 did_curdir = TRUE;
2380 flags |= EW_DIR;
2381 }
2382 else
2383 // Do not match directories inside a $PATH item.
2384 flags &= ~EW_DIR;
2385
2386 l = e - s;
2387 if (l > MAXPATHL - 5)
2388 break;
2389 vim_strncpy(buf, s, l);
2390 add_pathsep(buf);
2391 l = STRLEN(buf);
2392 vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
2393
2394 // Expand matches in one directory of $PATH.
2395 ret = expand_wildcards(1, &buf, num_file, file, flags);
2396 if (ret == OK)
2397 {
2398 if (ga_grow(&ga, *num_file) == FAIL)
2399 FreeWild(*num_file, *file);
2400 else
2401 {
2402 for (i = 0; i < *num_file; ++i)
2403 {
2404 char_u *name = (*file)[i];
2405
2406 if (STRLEN(name) > l)
2407 {
2408 // Check if this name was already found.
2409 hash = hash_hash(name + l);
2410 hi = hash_lookup(&found_ht, name + l, hash);
2411 if (HASHITEM_EMPTY(hi))
2412 {
2413 // Remove the path that was prepended.
2414 STRMOVE(name, name + l);
2415 ((char_u **)ga.ga_data)[ga.ga_len++] = name;
2416 hash_add_item(&found_ht, hi, name, hash);
2417 name = NULL;
2418 }
2419 }
2420 vim_free(name);
2421 }
2422 vim_free(*file);
2423 }
2424 }
2425 if (*e != NUL)
2426 ++e;
2427 }
2428 *file = ga.ga_data;
2429 *num_file = ga.ga_len;
2430
2431 vim_free(buf);
2432 vim_free(pat);
2433 if (mustfree)
2434 vim_free(path);
2435 hash_clear(&found_ht);
2436 return OK;
2437}
2438
2439# if defined(FEAT_EVAL)
2440/*
2441 * Call "user_expand_func()" to invoke a user defined Vim script function and
2442 * return the result (either a string or a List).
2443 */
2444 static void *
2445call_user_expand_func(
2446 void *(*user_expand_func)(char_u *, int, typval_T *),
2447 expand_T *xp,
2448 int *num_file,
2449 char_u ***file)
2450{
2451 cmdline_info_T *ccline = get_cmdline_info();
2452 int keep = 0;
2453 typval_T args[4];
2454 sctx_T save_current_sctx = current_sctx;
2455 char_u *pat = NULL;
2456 void *ret;
2457
2458 if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL)
2459 return NULL;
2460 *num_file = 0;
2461 *file = NULL;
2462
2463 if (ccline->cmdbuff != NULL)
2464 {
2465 keep = ccline->cmdbuff[ccline->cmdlen];
2466 ccline->cmdbuff[ccline->cmdlen] = 0;
2467 }
2468
2469 pat = vim_strnsave(xp->xp_pattern, xp->xp_pattern_len);
2470
2471 args[0].v_type = VAR_STRING;
2472 args[0].vval.v_string = pat;
2473 args[1].v_type = VAR_STRING;
2474 args[1].vval.v_string = xp->xp_line;
2475 args[2].v_type = VAR_NUMBER;
2476 args[2].vval.v_number = xp->xp_col;
2477 args[3].v_type = VAR_UNKNOWN;
2478
2479 current_sctx = xp->xp_script_ctx;
2480
2481 ret = user_expand_func(xp->xp_arg, 3, args);
2482
2483 current_sctx = save_current_sctx;
2484 if (ccline->cmdbuff != NULL)
2485 ccline->cmdbuff[ccline->cmdlen] = keep;
2486
2487 vim_free(pat);
2488 return ret;
2489}
2490
2491/*
2492 * Expand names with a function defined by the user.
2493 */
2494 static int
2495ExpandUserDefined(
2496 expand_T *xp,
2497 regmatch_T *regmatch,
2498 int *num_file,
2499 char_u ***file)
2500{
2501 char_u *retstr;
2502 char_u *s;
2503 char_u *e;
2504 int keep;
2505 garray_T ga;
2506 int skip;
2507
2508 retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
2509 if (retstr == NULL)
2510 return FAIL;
2511
2512 ga_init2(&ga, (int)sizeof(char *), 3);
2513 for (s = retstr; *s != NUL; s = e)
2514 {
2515 e = vim_strchr(s, '\n');
2516 if (e == NULL)
2517 e = s + STRLEN(s);
2518 keep = *e;
2519 *e = NUL;
2520
2521 skip = xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0;
2522 *e = keep;
2523
2524 if (!skip)
2525 {
2526 if (ga_grow(&ga, 1) == FAIL)
2527 break;
2528 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
2529 ++ga.ga_len;
2530 }
2531
2532 if (*e != NUL)
2533 ++e;
2534 }
2535 vim_free(retstr);
2536 *file = ga.ga_data;
2537 *num_file = ga.ga_len;
2538 return OK;
2539}
2540
2541/*
2542 * Expand names with a list returned by a function defined by the user.
2543 */
2544 static int
2545ExpandUserList(
2546 expand_T *xp,
2547 int *num_file,
2548 char_u ***file)
2549{
2550 list_T *retlist;
2551 listitem_T *li;
2552 garray_T ga;
2553
2554 retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
2555 if (retlist == NULL)
2556 return FAIL;
2557
2558 ga_init2(&ga, (int)sizeof(char *), 3);
2559 // Loop over the items in the list.
2560 for (li = retlist->lv_first; li != NULL; li = li->li_next)
2561 {
2562 if (li->li_tv.v_type != VAR_STRING || li->li_tv.vval.v_string == NULL)
2563 continue; // Skip non-string items and empty strings
2564
2565 if (ga_grow(&ga, 1) == FAIL)
2566 break;
2567
2568 ((char_u **)ga.ga_data)[ga.ga_len] =
2569 vim_strsave(li->li_tv.vval.v_string);
2570 ++ga.ga_len;
2571 }
2572 list_unref(retlist);
2573
2574 *file = ga.ga_data;
2575 *num_file = ga.ga_len;
2576 return OK;
2577}
2578# endif
2579
2580/*
Bram Moolenaar66b51422019-08-18 21:44:12 +02002581 * Expand "file" for all comma-separated directories in "path".
2582 * Adds the matches to "ga". Caller must init "ga".
2583 */
2584 void
2585globpath(
2586 char_u *path,
2587 char_u *file,
2588 garray_T *ga,
2589 int expand_options)
2590{
2591 expand_T xpc;
2592 char_u *buf;
2593 int i;
2594 int num_p;
2595 char_u **p;
2596
2597 buf = alloc(MAXPATHL);
2598 if (buf == NULL)
2599 return;
2600
2601 ExpandInit(&xpc);
2602 xpc.xp_context = EXPAND_FILES;
2603
2604 // Loop over all entries in {path}.
2605 while (*path != NUL)
2606 {
2607 // Copy one item of the path to buf[] and concatenate the file name.
2608 copy_option_part(&path, buf, MAXPATHL, ",");
2609 if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
2610 {
2611# if defined(MSWIN)
2612 // Using the platform's path separator (\) makes vim incorrectly
2613 // treat it as an escape character, use '/' instead.
2614 if (*buf != NUL && !after_pathsep(buf, buf + STRLEN(buf)))
2615 STRCAT(buf, "/");
2616# else
2617 add_pathsep(buf);
2618# endif
2619 STRCAT(buf, file);
2620 if (ExpandFromContext(&xpc, buf, &num_p, &p,
2621 WILD_SILENT|expand_options) != FAIL && num_p > 0)
2622 {
2623 ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT|expand_options);
2624
2625 if (ga_grow(ga, num_p) == OK)
2626 {
2627 for (i = 0; i < num_p; ++i)
2628 {
2629 ((char_u **)ga->ga_data)[ga->ga_len] =
2630 vim_strnsave(p[i], (int)STRLEN(p[i]));
2631 ++ga->ga_len;
2632 }
2633 }
2634
2635 FreeWild(num_p, p);
2636 }
2637 }
2638 }
2639
2640 vim_free(buf);
2641}
Bram Moolenaar66b51422019-08-18 21:44:12 +02002642
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002643#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar66b51422019-08-18 21:44:12 +02002644/*
2645 * "getcompletion()" function
2646 */
2647 void
2648f_getcompletion(typval_T *argvars, typval_T *rettv)
2649{
2650 char_u *pat;
2651 expand_T xpc;
2652 int filtered = FALSE;
2653 int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH
2654 | WILD_NO_BEEP;
2655
2656 if (argvars[2].v_type != VAR_UNKNOWN)
2657 filtered = tv_get_number_chk(&argvars[2], NULL);
2658
2659 if (p_wic)
2660 options |= WILD_ICASE;
2661
2662 // For filtered results, 'wildignore' is used
2663 if (!filtered)
2664 options |= WILD_KEEP_ALL;
2665
2666 ExpandInit(&xpc);
2667 xpc.xp_pattern = tv_get_string(&argvars[0]);
2668 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2669 xpc.xp_context = cmdcomplete_str_to_type(tv_get_string(&argvars[1]));
2670 if (xpc.xp_context == EXPAND_NOTHING)
2671 {
2672 if (argvars[1].v_type == VAR_STRING)
2673 semsg(_(e_invarg2), argvars[1].vval.v_string);
2674 else
2675 emsg(_(e_invarg));
2676 return;
2677 }
2678
2679# if defined(FEAT_MENU)
2680 if (xpc.xp_context == EXPAND_MENUS)
2681 {
2682 set_context_in_menu_cmd(&xpc, (char_u *)"menu", xpc.xp_pattern, FALSE);
2683 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2684 }
2685# endif
2686# ifdef FEAT_CSCOPE
2687 if (xpc.xp_context == EXPAND_CSCOPE)
2688 {
2689 set_context_in_cscope_cmd(&xpc, xpc.xp_pattern, CMD_cscope);
2690 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2691 }
2692# endif
2693# ifdef FEAT_SIGNS
2694 if (xpc.xp_context == EXPAND_SIGN)
2695 {
2696 set_context_in_sign_cmd(&xpc, xpc.xp_pattern);
2697 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
2698 }
2699# endif
2700
2701 pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
2702 if ((rettv_list_alloc(rettv) != FAIL) && (pat != NULL))
2703 {
2704 int i;
2705
2706 ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP);
2707
2708 for (i = 0; i < xpc.xp_numfiles; i++)
2709 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
2710 }
2711 vim_free(pat);
2712 ExpandCleanup(&xpc);
2713}
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002714#endif // FEAT_EVAL