blob: 59d84419c61d2848bb9a957a8346c5ce17c454a7 [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);
22static int ExpandRTDir(char_u *pat, int flags, int *num_file, char_u ***file, char *dirname[]);
23static int ExpandPackAddDir(char_u *pat, int *num_file, char_u ***file);
Bram Moolenaar0a52df52019-08-18 22:26:31 +020024#if defined(FEAT_EVAL)
Bram Moolenaar66b51422019-08-18 21:44:12 +020025static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char_u ***file);
26static int ExpandUserList(expand_T *xp, int *num_file, char_u ***file);
Bram Moolenaar66b51422019-08-18 21:44:12 +020027#endif
28
Bram Moolenaar66b51422019-08-18 21:44:12 +020029 static int
30sort_func_compare(const void *s1, const void *s2)
31{
32 char_u *p1 = *(char_u **)s1;
33 char_u *p2 = *(char_u **)s2;
34
35 if (*p1 != '<' && *p2 == '<') return -1;
36 if (*p1 == '<' && *p2 != '<') return 1;
37 return STRCMP(p1, p2);
38}
Bram Moolenaar66b51422019-08-18 21:44:12 +020039
40 static void
41ExpandEscape(
42 expand_T *xp,
43 char_u *str,
44 int numfiles,
45 char_u **files,
46 int options)
47{
48 int i;
49 char_u *p;
50
51 // May change home directory back to "~"
52 if (options & WILD_HOME_REPLACE)
53 tilde_replace(str, numfiles, files);
54
55 if (options & WILD_ESCAPE)
56 {
57 if (xp->xp_context == EXPAND_FILES
58 || xp->xp_context == EXPAND_FILES_IN_PATH
59 || xp->xp_context == EXPAND_SHELLCMD
60 || xp->xp_context == EXPAND_BUFFERS
61 || xp->xp_context == EXPAND_DIRECTORIES)
62 {
63 // Insert a backslash into a file name before a space, \, %, #
64 // and wildmatch characters, except '~'.
65 for (i = 0; i < numfiles; ++i)
66 {
67 // for ":set path=" we need to escape spaces twice
68 if (xp->xp_backslash == XP_BS_THREE)
69 {
70 p = vim_strsave_escaped(files[i], (char_u *)" ");
71 if (p != NULL)
72 {
73 vim_free(files[i]);
74 files[i] = p;
75#if defined(BACKSLASH_IN_FILENAME)
76 p = vim_strsave_escaped(files[i], (char_u *)" ");
77 if (p != NULL)
78 {
79 vim_free(files[i]);
80 files[i] = p;
81 }
82#endif
83 }
84 }
85#ifdef BACKSLASH_IN_FILENAME
86 p = vim_strsave_fnameescape(files[i], FALSE);
87#else
88 p = vim_strsave_fnameescape(files[i], xp->xp_shell);
89#endif
90 if (p != NULL)
91 {
92 vim_free(files[i]);
93 files[i] = p;
94 }
95
96 // If 'str' starts with "\~", replace "~" at start of
97 // files[i] with "\~".
98 if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~')
99 escape_fname(&files[i]);
100 }
101 xp->xp_backslash = XP_BS_NONE;
102
103 // If the first file starts with a '+' escape it. Otherwise it
104 // could be seen as "+cmd".
105 if (*files[0] == '+')
106 escape_fname(&files[0]);
107 }
108 else if (xp->xp_context == EXPAND_TAGS)
109 {
110 // Insert a backslash before characters in a tag name that
111 // would terminate the ":tag" command.
112 for (i = 0; i < numfiles; ++i)
113 {
114 p = vim_strsave_escaped(files[i], (char_u *)"\\|\"");
115 if (p != NULL)
116 {
117 vim_free(files[i]);
118 files[i] = p;
119 }
120 }
121 }
122 }
123}
124
125/*
126 * Return FAIL if this is not an appropriate context in which to do
127 * completion of anything, return OK if it is (even if there are no matches).
128 * For the caller, this means that the character is just passed through like a
129 * normal character (instead of being expanded). This allows :s/^I^D etc.
130 */
131 int
132nextwild(
133 expand_T *xp,
134 int type,
135 int options, // extra options for ExpandOne()
136 int escape) // if TRUE, escape the returned matches
137{
138 cmdline_info_T *ccline = get_cmdline_info();
139 int i, j;
140 char_u *p1;
141 char_u *p2;
142 int difflen;
143 int v;
144
145 if (xp->xp_numfiles == -1)
146 {
147 set_expand_context(xp);
148 cmd_showtail = expand_showtail(xp);
149 }
150
151 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
152 {
153 beep_flush();
154 return OK; // Something illegal on command line
155 }
156 if (xp->xp_context == EXPAND_NOTHING)
157 {
158 // Caller can use the character as a normal char instead
159 return FAIL;
160 }
161
162 msg_puts("..."); // show that we are busy
163 out_flush();
164
165 i = (int)(xp->xp_pattern - ccline->cmdbuff);
166 xp->xp_pattern_len = ccline->cmdpos - i;
167
168 if (type == WILD_NEXT || type == WILD_PREV)
169 {
170 // Get next/previous match for a previous expanded pattern.
171 p2 = ExpandOne(xp, NULL, NULL, 0, type);
172 }
173 else
174 {
175 // Translate string into pattern and expand it.
176 if ((p1 = addstar(xp->xp_pattern, xp->xp_pattern_len,
177 xp->xp_context)) == NULL)
178 p2 = NULL;
179 else
180 {
181 int use_options = options |
182 WILD_HOME_REPLACE|WILD_ADD_SLASH|WILD_SILENT;
183 if (escape)
184 use_options |= WILD_ESCAPE;
185
186 if (p_wic)
187 use_options += WILD_ICASE;
188 p2 = ExpandOne(xp, p1,
189 vim_strnsave(&ccline->cmdbuff[i], xp->xp_pattern_len),
190 use_options, type);
191 vim_free(p1);
192 // longest match: make sure it is not shorter, happens with :help
193 if (p2 != NULL && type == WILD_LONGEST)
194 {
195 for (j = 0; j < xp->xp_pattern_len; ++j)
196 if (ccline->cmdbuff[i + j] == '*'
197 || ccline->cmdbuff[i + j] == '?')
198 break;
199 if ((int)STRLEN(p2) < j)
200 VIM_CLEAR(p2);
201 }
202 }
203 }
204
205 if (p2 != NULL && !got_int)
206 {
207 difflen = (int)STRLEN(p2) - xp->xp_pattern_len;
208 if (ccline->cmdlen + difflen + 4 > ccline->cmdbufflen)
209 {
210 v = realloc_cmdbuff(ccline->cmdlen + difflen + 4);
211 xp->xp_pattern = ccline->cmdbuff + i;
212 }
213 else
214 v = OK;
215 if (v == OK)
216 {
217 mch_memmove(&ccline->cmdbuff[ccline->cmdpos + difflen],
218 &ccline->cmdbuff[ccline->cmdpos],
219 (size_t)(ccline->cmdlen - ccline->cmdpos + 1));
220 mch_memmove(&ccline->cmdbuff[i], p2, STRLEN(p2));
221 ccline->cmdlen += difflen;
222 ccline->cmdpos += difflen;
223 }
224 }
225 vim_free(p2);
226
227 redrawcmd();
228 cursorcmd();
229
230 // When expanding a ":map" command and no matches are found, assume that
231 // the key is supposed to be inserted literally
232 if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL)
233 return FAIL;
234
235 if (xp->xp_numfiles <= 0 && p2 == NULL)
236 beep_flush();
237 else if (xp->xp_numfiles == 1)
238 // free expanded pattern
239 (void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE);
240
241 return OK;
242}
243
244/*
245 * Do wildcard expansion on the string 'str'.
246 * Chars that should not be expanded must be preceded with a backslash.
247 * Return a pointer to allocated memory containing the new string.
248 * Return NULL for failure.
249 *
250 * "orig" is the originally expanded string, copied to allocated memory. It
251 * should either be kept in orig_save or freed. When "mode" is WILD_NEXT or
252 * WILD_PREV "orig" should be NULL.
253 *
254 * Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode"
255 * is WILD_EXPAND_FREE or WILD_ALL.
256 *
257 * mode = WILD_FREE: just free previously expanded matches
258 * mode = WILD_EXPAND_FREE: normal expansion, do not keep matches
259 * mode = WILD_EXPAND_KEEP: normal expansion, keep matches
260 * mode = WILD_NEXT: use next match in multiple match, wrap to first
261 * mode = WILD_PREV: use previous match in multiple match, wrap to first
262 * mode = WILD_ALL: return all matches concatenated
263 * mode = WILD_LONGEST: return longest matched part
264 * mode = WILD_ALL_KEEP: get all matches, keep matches
265 *
266 * options = WILD_LIST_NOTFOUND: list entries without a match
267 * options = WILD_HOME_REPLACE: do home_replace() for buffer names
268 * options = WILD_USE_NL: Use '\n' for WILD_ALL
269 * options = WILD_NO_BEEP: Don't beep for multiple matches
270 * options = WILD_ADD_SLASH: add a slash after directory names
271 * options = WILD_KEEP_ALL: don't remove 'wildignore' entries
272 * options = WILD_SILENT: don't print warning messages
273 * options = WILD_ESCAPE: put backslash before special chars
274 * options = WILD_ICASE: ignore case for files
275 *
276 * The variables xp->xp_context and xp->xp_backslash must have been set!
277 */
278 char_u *
279ExpandOne(
280 expand_T *xp,
281 char_u *str,
282 char_u *orig, // allocated copy of original of expanded string
283 int options,
284 int mode)
285{
286 char_u *ss = NULL;
287 static int findex;
288 static char_u *orig_save = NULL; // kept value of orig
289 int orig_saved = FALSE;
290 int i;
291 long_u len;
292 int non_suf_match; // number without matching suffix
293
294 // first handle the case of using an old match
295 if (mode == WILD_NEXT || mode == WILD_PREV)
296 {
297 if (xp->xp_numfiles > 0)
298 {
299 if (mode == WILD_PREV)
300 {
301 if (findex == -1)
302 findex = xp->xp_numfiles;
303 --findex;
304 }
305 else // mode == WILD_NEXT
306 ++findex;
307
308 // When wrapping around, return the original string, set findex to
309 // -1.
310 if (findex < 0)
311 {
312 if (orig_save == NULL)
313 findex = xp->xp_numfiles - 1;
314 else
315 findex = -1;
316 }
317 if (findex >= xp->xp_numfiles)
318 {
319 if (orig_save == NULL)
320 findex = 0;
321 else
322 findex = -1;
323 }
324#ifdef FEAT_WILDMENU
325 if (p_wmnu)
326 win_redr_status_matches(xp, xp->xp_numfiles, xp->xp_files,
327 findex, cmd_showtail);
328#endif
329 if (findex == -1)
330 return vim_strsave(orig_save);
331 return vim_strsave(xp->xp_files[findex]);
332 }
333 else
334 return NULL;
335 }
336
337 // free old names
338 if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST)
339 {
340 FreeWild(xp->xp_numfiles, xp->xp_files);
341 xp->xp_numfiles = -1;
342 VIM_CLEAR(orig_save);
343 }
344 findex = 0;
345
346 if (mode == WILD_FREE) // only release file name
347 return NULL;
348
349 if (xp->xp_numfiles == -1)
350 {
351 vim_free(orig_save);
352 orig_save = orig;
353 orig_saved = TRUE;
354
355 // Do the expansion.
356 if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files,
357 options) == FAIL)
358 {
359#ifdef FNAME_ILLEGAL
360 // Illegal file name has been silently skipped. But when there
361 // are wildcards, the real problem is that there was no match,
362 // causing the pattern to be added, which has illegal characters.
363 if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND))
364 semsg(_(e_nomatch2), str);
365#endif
366 }
367 else if (xp->xp_numfiles == 0)
368 {
369 if (!(options & WILD_SILENT))
370 semsg(_(e_nomatch2), str);
371 }
372 else
373 {
374 // Escape the matches for use on the command line.
375 ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options);
376
377 // Check for matching suffixes in file names.
378 if (mode != WILD_ALL && mode != WILD_ALL_KEEP
379 && mode != WILD_LONGEST)
380 {
381 if (xp->xp_numfiles)
382 non_suf_match = xp->xp_numfiles;
383 else
384 non_suf_match = 1;
385 if ((xp->xp_context == EXPAND_FILES
386 || xp->xp_context == EXPAND_DIRECTORIES)
387 && xp->xp_numfiles > 1)
388 {
389 // More than one match; check suffix.
390 // The files will have been sorted on matching suffix in
391 // expand_wildcards, only need to check the first two.
392 non_suf_match = 0;
393 for (i = 0; i < 2; ++i)
394 if (match_suffix(xp->xp_files[i]))
395 ++non_suf_match;
396 }
397 if (non_suf_match != 1)
398 {
399 // Can we ever get here unless it's while expanding
400 // interactively? If not, we can get rid of this all
401 // together. Don't really want to wait for this message
402 // (and possibly have to hit return to continue!).
403 if (!(options & WILD_SILENT))
404 emsg(_(e_toomany));
405 else if (!(options & WILD_NO_BEEP))
406 beep_flush();
407 }
408 if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE))
409 ss = vim_strsave(xp->xp_files[0]);
410 }
411 }
412 }
413
414 // Find longest common part
415 if (mode == WILD_LONGEST && xp->xp_numfiles > 0)
416 {
417 int mb_len = 1;
418 int c0, ci;
419
420 for (len = 0; xp->xp_files[0][len]; len += mb_len)
421 {
422 if (has_mbyte)
423 {
424 mb_len = (*mb_ptr2len)(&xp->xp_files[0][len]);
425 c0 =(* mb_ptr2char)(&xp->xp_files[0][len]);
426 }
427 else
428 c0 = xp->xp_files[0][len];
429 for (i = 1; i < xp->xp_numfiles; ++i)
430 {
431 if (has_mbyte)
432 ci =(* mb_ptr2char)(&xp->xp_files[i][len]);
433 else
434 ci = xp->xp_files[i][len];
435 if (p_fic && (xp->xp_context == EXPAND_DIRECTORIES
436 || xp->xp_context == EXPAND_FILES
437 || xp->xp_context == EXPAND_SHELLCMD
438 || xp->xp_context == EXPAND_BUFFERS))
439 {
440 if (MB_TOLOWER(c0) != MB_TOLOWER(ci))
441 break;
442 }
443 else if (c0 != ci)
444 break;
445 }
446 if (i < xp->xp_numfiles)
447 {
448 if (!(options & WILD_NO_BEEP))
449 vim_beep(BO_WILD);
450 break;
451 }
452 }
453
454 ss = alloc(len + 1);
455 if (ss)
456 vim_strncpy(ss, xp->xp_files[0], (size_t)len);
457 findex = -1; // next p_wc gets first one
458 }
459
460 // Concatenate all matching names
461 if (mode == WILD_ALL && xp->xp_numfiles > 0)
462 {
463 len = 0;
464 for (i = 0; i < xp->xp_numfiles; ++i)
465 len += (long_u)STRLEN(xp->xp_files[i]) + 1;
466 ss = alloc(len);
467 if (ss != NULL)
468 {
469 *ss = NUL;
470 for (i = 0; i < xp->xp_numfiles; ++i)
471 {
472 STRCAT(ss, xp->xp_files[i]);
473 if (i != xp->xp_numfiles - 1)
474 STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " ");
475 }
476 }
477 }
478
479 if (mode == WILD_EXPAND_FREE || mode == WILD_ALL)
480 ExpandCleanup(xp);
481
482 // Free "orig" if it wasn't stored in "orig_save".
483 if (!orig_saved)
484 vim_free(orig);
485
486 return ss;
487}
488
489/*
490 * Prepare an expand structure for use.
491 */
492 void
493ExpandInit(expand_T *xp)
494{
495 xp->xp_pattern = NULL;
496 xp->xp_pattern_len = 0;
497 xp->xp_backslash = XP_BS_NONE;
498#ifndef BACKSLASH_IN_FILENAME
499 xp->xp_shell = FALSE;
500#endif
501 xp->xp_numfiles = -1;
502 xp->xp_files = NULL;
Bram Moolenaar0a52df52019-08-18 22:26:31 +0200503#if defined(FEAT_EVAL)
Bram Moolenaar66b51422019-08-18 21:44:12 +0200504 xp->xp_arg = NULL;
505#endif
506 xp->xp_line = NULL;
507}
508
509/*
510 * Cleanup an expand structure after use.
511 */
512 void
513ExpandCleanup(expand_T *xp)
514{
515 if (xp->xp_numfiles >= 0)
516 {
517 FreeWild(xp->xp_numfiles, xp->xp_files);
518 xp->xp_numfiles = -1;
519 }
520}
521
522/*
523 * Show all matches for completion on the command line.
524 * Returns EXPAND_NOTHING when the character that triggered expansion should
525 * be inserted like a normal character.
526 */
527 int
528showmatches(expand_T *xp, int wildmenu UNUSED)
529{
530 cmdline_info_T *ccline = get_cmdline_info();
531#define L_SHOWFILE(m) (showtail ? sm_gettail(files_found[m]) : files_found[m])
532 int num_files;
533 char_u **files_found;
534 int i, j, k;
535 int maxlen;
536 int lines;
537 int columns;
538 char_u *p;
539 int lastlen;
540 int attr;
541 int showtail;
542
543 if (xp->xp_numfiles == -1)
544 {
545 set_expand_context(xp);
546 i = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos,
547 &num_files, &files_found);
548 showtail = expand_showtail(xp);
549 if (i != EXPAND_OK)
550 return i;
551
552 }
553 else
554 {
555 num_files = xp->xp_numfiles;
556 files_found = xp->xp_files;
557 showtail = cmd_showtail;
558 }
559
560#ifdef FEAT_WILDMENU
561 if (!wildmenu)
562 {
563#endif
564 msg_didany = FALSE; // lines_left will be set
565 msg_start(); // prepare for paging
566 msg_putchar('\n');
567 out_flush();
568 cmdline_row = msg_row;
569 msg_didany = FALSE; // lines_left will be set again
570 msg_start(); // prepare for paging
571#ifdef FEAT_WILDMENU
572 }
573#endif
574
575 if (got_int)
576 got_int = FALSE; // only int. the completion, not the cmd line
577#ifdef FEAT_WILDMENU
578 else if (wildmenu)
579 win_redr_status_matches(xp, num_files, files_found, -1, showtail);
580#endif
581 else
582 {
583 // find the length of the longest file name
584 maxlen = 0;
585 for (i = 0; i < num_files; ++i)
586 {
587 if (!showtail && (xp->xp_context == EXPAND_FILES
588 || xp->xp_context == EXPAND_SHELLCMD
589 || xp->xp_context == EXPAND_BUFFERS))
590 {
591 home_replace(NULL, files_found[i], NameBuff, MAXPATHL, TRUE);
592 j = vim_strsize(NameBuff);
593 }
594 else
595 j = vim_strsize(L_SHOWFILE(i));
596 if (j > maxlen)
597 maxlen = j;
598 }
599
600 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
601 lines = num_files;
602 else
603 {
604 // compute the number of columns and lines for the listing
605 maxlen += 2; // two spaces between file names
606 columns = ((int)Columns + 2) / maxlen;
607 if (columns < 1)
608 columns = 1;
609 lines = (num_files + columns - 1) / columns;
610 }
611
612 attr = HL_ATTR(HLF_D); // find out highlighting for directories
613
614 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
615 {
616 msg_puts_attr(_("tagname"), HL_ATTR(HLF_T));
617 msg_clr_eos();
618 msg_advance(maxlen - 3);
619 msg_puts_attr(_(" kind file\n"), HL_ATTR(HLF_T));
620 }
621
622 // list the files line by line
623 for (i = 0; i < lines; ++i)
624 {
625 lastlen = 999;
626 for (k = i; k < num_files; k += lines)
627 {
628 if (xp->xp_context == EXPAND_TAGS_LISTFILES)
629 {
630 msg_outtrans_attr(files_found[k], HL_ATTR(HLF_D));
631 p = files_found[k] + STRLEN(files_found[k]) + 1;
632 msg_advance(maxlen + 1);
633 msg_puts((char *)p);
634 msg_advance(maxlen + 3);
635 msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D));
636 break;
637 }
638 for (j = maxlen - lastlen; --j >= 0; )
639 msg_putchar(' ');
640 if (xp->xp_context == EXPAND_FILES
641 || xp->xp_context == EXPAND_SHELLCMD
642 || xp->xp_context == EXPAND_BUFFERS)
643 {
644 // highlight directories
645 if (xp->xp_numfiles != -1)
646 {
647 char_u *halved_slash;
648 char_u *exp_path;
Bram Moolenaarf1552d02019-08-21 12:54:18 +0200649 char_u *path;
Bram Moolenaar66b51422019-08-18 21:44:12 +0200650
651 // Expansion was done before and special characters
652 // were escaped, need to halve backslashes. Also
653 // $HOME has been replaced with ~/.
654 exp_path = expand_env_save_opt(files_found[k], TRUE);
Bram Moolenaarf1552d02019-08-21 12:54:18 +0200655 path = exp_path != NULL ? exp_path : files_found[k];
656 halved_slash = backslash_halve_save(path);
Bram Moolenaar66b51422019-08-18 21:44:12 +0200657 j = mch_isdir(halved_slash != NULL ? halved_slash
658 : files_found[k]);
659 vim_free(exp_path);
Bram Moolenaarf1552d02019-08-21 12:54:18 +0200660 if (halved_slash != path)
661 vim_free(halved_slash);
Bram Moolenaar66b51422019-08-18 21:44:12 +0200662 }
663 else
664 // Expansion was done here, file names are literal.
665 j = mch_isdir(files_found[k]);
666 if (showtail)
667 p = L_SHOWFILE(k);
668 else
669 {
670 home_replace(NULL, files_found[k], NameBuff, MAXPATHL,
671 TRUE);
672 p = NameBuff;
673 }
674 }
675 else
676 {
677 j = FALSE;
678 p = L_SHOWFILE(k);
679 }
680 lastlen = msg_outtrans_attr(p, j ? attr : 0);
681 }
682 if (msg_col > 0) // when not wrapped around
683 {
684 msg_clr_eos();
685 msg_putchar('\n');
686 }
687 out_flush(); // show one line at a time
688 if (got_int)
689 {
690 got_int = FALSE;
691 break;
692 }
693 }
694
695 // we redraw the command below the lines that we have just listed
696 // This is a bit tricky, but it saves a lot of screen updating.
697 cmdline_row = msg_row; // will put it back later
698 }
699
700 if (xp->xp_numfiles == -1)
701 FreeWild(num_files, files_found);
702
703 return EXPAND_OK;
704}
705
706/*
707 * Private gettail for showmatches() (and win_redr_status_matches()):
708 * Find tail of file name path, but ignore trailing "/".
709 */
710 char_u *
711sm_gettail(char_u *s)
712{
713 char_u *p;
714 char_u *t = s;
715 int had_sep = FALSE;
716
717 for (p = s; *p != NUL; )
718 {
719 if (vim_ispathsep(*p)
720#ifdef BACKSLASH_IN_FILENAME
721 && !rem_backslash(p)
722#endif
723 )
724 had_sep = TRUE;
725 else if (had_sep)
726 {
727 t = p;
728 had_sep = FALSE;
729 }
730 MB_PTR_ADV(p);
731 }
732 return t;
733}
734
735/*
736 * Return TRUE if we only need to show the tail of completion matches.
737 * When not completing file names or there is a wildcard in the path FALSE is
738 * returned.
739 */
740 static int
741expand_showtail(expand_T *xp)
742{
743 char_u *s;
744 char_u *end;
745
746 // When not completing file names a "/" may mean something different.
747 if (xp->xp_context != EXPAND_FILES
748 && xp->xp_context != EXPAND_SHELLCMD
749 && xp->xp_context != EXPAND_DIRECTORIES)
750 return FALSE;
751
752 end = gettail(xp->xp_pattern);
753 if (end == xp->xp_pattern) // there is no path separator
754 return FALSE;
755
756 for (s = xp->xp_pattern; s < end; s++)
757 {
758 // Skip escaped wildcards. Only when the backslash is not a path
759 // separator, on DOS the '*' "path\*\file" must not be skipped.
760 if (rem_backslash(s))
761 ++s;
762 else if (vim_strchr((char_u *)"*?[", *s) != NULL)
763 return FALSE;
764 }
765 return TRUE;
766}
767
768/*
769 * Prepare a string for expansion.
770 * When expanding file names: The string will be used with expand_wildcards().
771 * Copy "fname[len]" into allocated memory and add a '*' at the end.
772 * When expanding other names: The string will be used with regcomp(). Copy
773 * the name into allocated memory and prepend "^".
774 */
775 char_u *
776addstar(
777 char_u *fname,
778 int len,
779 int context) // EXPAND_FILES etc.
780{
781 char_u *retval;
782 int i, j;
783 int new_len;
784 char_u *tail;
785 int ends_in_star;
786
787 if (context != EXPAND_FILES
788 && context != EXPAND_FILES_IN_PATH
789 && context != EXPAND_SHELLCMD
790 && context != EXPAND_DIRECTORIES)
791 {
792 // Matching will be done internally (on something other than files).
793 // So we convert the file-matching-type wildcards into our kind for
794 // use with vim_regcomp(). First work out how long it will be:
795
796 // For help tags the translation is done in find_help_tags().
797 // For a tag pattern starting with "/" no translation is needed.
798 if (context == EXPAND_HELP
799 || context == EXPAND_COLORS
800 || context == EXPAND_COMPILER
801 || context == EXPAND_OWNSYNTAX
802 || context == EXPAND_FILETYPE
803 || context == EXPAND_PACKADD
804 || ((context == EXPAND_TAGS_LISTFILES
805 || context == EXPAND_TAGS)
806 && fname[0] == '/'))
807 retval = vim_strnsave(fname, len);
808 else
809 {
810 new_len = len + 2; // +2 for '^' at start, NUL at end
811 for (i = 0; i < len; i++)
812 {
813 if (fname[i] == '*' || fname[i] == '~')
814 new_len++; // '*' needs to be replaced by ".*"
815 // '~' needs to be replaced by "\~"
816
817 // Buffer names are like file names. "." should be literal
818 if (context == EXPAND_BUFFERS && fname[i] == '.')
819 new_len++; // "." becomes "\."
820
821 // Custom expansion takes care of special things, match
822 // backslashes literally (perhaps also for other types?)
823 if ((context == EXPAND_USER_DEFINED
824 || context == EXPAND_USER_LIST) && fname[i] == '\\')
825 new_len++; // '\' becomes "\\"
826 }
827 retval = alloc(new_len);
828 if (retval != NULL)
829 {
830 retval[0] = '^';
831 j = 1;
832 for (i = 0; i < len; i++, j++)
833 {
834 // Skip backslash. But why? At least keep it for custom
835 // expansion.
836 if (context != EXPAND_USER_DEFINED
837 && context != EXPAND_USER_LIST
838 && fname[i] == '\\'
839 && ++i == len)
840 break;
841
842 switch (fname[i])
843 {
844 case '*': retval[j++] = '.';
845 break;
846 case '~': retval[j++] = '\\';
847 break;
848 case '?': retval[j] = '.';
849 continue;
850 case '.': if (context == EXPAND_BUFFERS)
851 retval[j++] = '\\';
852 break;
853 case '\\': if (context == EXPAND_USER_DEFINED
854 || context == EXPAND_USER_LIST)
855 retval[j++] = '\\';
856 break;
857 }
858 retval[j] = fname[i];
859 }
860 retval[j] = NUL;
861 }
862 }
863 }
864 else
865 {
866 retval = alloc(len + 4);
867 if (retval != NULL)
868 {
869 vim_strncpy(retval, fname, len);
870
871 // Don't add a star to *, ~, ~user, $var or `cmd`.
872 // * would become **, which walks the whole tree.
873 // ~ would be at the start of the file name, but not the tail.
874 // $ could be anywhere in the tail.
875 // ` could be anywhere in the file name.
876 // When the name ends in '$' don't add a star, remove the '$'.
877 tail = gettail(retval);
878 ends_in_star = (len > 0 && retval[len - 1] == '*');
879#ifndef BACKSLASH_IN_FILENAME
880 for (i = len - 2; i >= 0; --i)
881 {
882 if (retval[i] != '\\')
883 break;
884 ends_in_star = !ends_in_star;
885 }
886#endif
887 if ((*retval != '~' || tail != retval)
888 && !ends_in_star
889 && vim_strchr(tail, '$') == NULL
890 && vim_strchr(retval, '`') == NULL)
891 retval[len++] = '*';
892 else if (len > 0 && retval[len - 1] == '$')
893 --len;
894 retval[len] = NUL;
895 }
896 }
897 return retval;
898}
899
900/*
901 * Must parse the command line so far to work out what context we are in.
902 * Completion can then be done based on that context.
903 * This routine sets the variables:
904 * xp->xp_pattern The start of the pattern to be expanded within
905 * the command line (ends at the cursor).
906 * xp->xp_context The type of thing to expand. Will be one of:
907 *
908 * EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on
909 * the command line, like an unknown command. Caller
910 * should beep.
911 * EXPAND_NOTHING Unrecognised context for completion, use char like
912 * a normal char, rather than for completion. eg
913 * :s/^I/
914 * EXPAND_COMMANDS Cursor is still touching the command, so complete
915 * it.
916 * EXPAND_BUFFERS Complete file names for :buf and :sbuf commands.
917 * EXPAND_FILES After command with EX_XFILE set, or after setting
918 * with P_EXPAND set. eg :e ^I, :w>>^I
919 * EXPAND_DIRECTORIES In some cases this is used instead of the latter
920 * when we know only directories are of interest. eg
921 * :set dir=^I
922 * EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd".
923 * EXPAND_SETTINGS Complete variable names. eg :set d^I
924 * EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I
925 * EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I
926 * EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect
927 * EXPAND_HELP Complete tags from the file 'helpfile'/tags
928 * EXPAND_EVENTS Complete event names
929 * EXPAND_SYNTAX Complete :syntax command arguments
930 * EXPAND_HIGHLIGHT Complete highlight (syntax) group names
931 * EXPAND_AUGROUP Complete autocommand group names
932 * EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I
933 * EXPAND_MAPPINGS Complete mapping and abbreviation names,
934 * eg :unmap a^I , :cunab x^I
935 * EXPAND_FUNCTIONS Complete internal or user defined function names,
936 * eg :call sub^I
937 * EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I
938 * EXPAND_EXPRESSION Complete internal or user defined function/variable
939 * names in expressions, eg :while s^I
940 * EXPAND_ENV_VARS Complete environment variable names
941 * EXPAND_USER Complete user names
942 */
943 static void
944set_expand_context(expand_T *xp)
945{
946 cmdline_info_T *ccline = get_cmdline_info();
947
948 // only expansion for ':', '>' and '=' command-lines
949 if (ccline->cmdfirstc != ':'
950#ifdef FEAT_EVAL
951 && ccline->cmdfirstc != '>' && ccline->cmdfirstc != '='
952 && !ccline->input_fn
953#endif
954 )
955 {
956 xp->xp_context = EXPAND_NOTHING;
957 return;
958 }
959 set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, TRUE);
960}
961
962 void
963set_cmd_context(
964 expand_T *xp,
965 char_u *str, // start of command line
966 int len, // length of command line (excl. NUL)
967 int col, // position of cursor
968 int use_ccline UNUSED) // use ccline for info
969{
970#ifdef FEAT_EVAL
971 cmdline_info_T *ccline = get_cmdline_info();
972#endif
973 int old_char = NUL;
974 char_u *nextcomm;
975
976 // Avoid a UMR warning from Purify, only save the character if it has been
977 // written before.
978 if (col < len)
979 old_char = str[col];
980 str[col] = NUL;
981 nextcomm = str;
982
983#ifdef FEAT_EVAL
984 if (use_ccline && ccline->cmdfirstc == '=')
985 {
Bram Moolenaar66b51422019-08-18 21:44:12 +0200986 // pass CMD_SIZE because there is no real command
987 set_context_for_expression(xp, str, CMD_SIZE);
Bram Moolenaar66b51422019-08-18 21:44:12 +0200988 }
989 else if (use_ccline && ccline->input_fn)
990 {
991 xp->xp_context = ccline->xp_context;
992 xp->xp_pattern = ccline->cmdbuff;
Bram Moolenaar66b51422019-08-18 21:44:12 +0200993 xp->xp_arg = ccline->xp_arg;
Bram Moolenaar66b51422019-08-18 21:44:12 +0200994 }
995 else
996#endif
997 while (nextcomm != NULL)
998 nextcomm = set_one_cmd_context(xp, nextcomm);
999
1000 // Store the string here so that call_user_expand_func() can get to them
1001 // easily.
1002 xp->xp_line = str;
1003 xp->xp_col = col;
1004
1005 str[col] = old_char;
1006}
1007
1008/*
1009 * Expand the command line "str" from context "xp".
1010 * "xp" must have been set by set_cmd_context().
1011 * xp->xp_pattern points into "str", to where the text that is to be expanded
1012 * starts.
1013 * Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
1014 * cursor.
1015 * Returns EXPAND_NOTHING when there is nothing to expand, might insert the
1016 * key that triggered expansion literally.
1017 * Returns EXPAND_OK otherwise.
1018 */
1019 int
1020expand_cmdline(
1021 expand_T *xp,
1022 char_u *str, // start of command line
1023 int col, // position of cursor
1024 int *matchcount, // return: nr of matches
1025 char_u ***matches) // return: array of pointers to matches
1026{
1027 char_u *file_str = NULL;
1028 int options = WILD_ADD_SLASH|WILD_SILENT;
1029
1030 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
1031 {
1032 beep_flush();
1033 return EXPAND_UNSUCCESSFUL; // Something illegal on command line
1034 }
1035 if (xp->xp_context == EXPAND_NOTHING)
1036 {
1037 // Caller can use the character as a normal char instead
1038 return EXPAND_NOTHING;
1039 }
1040
1041 // add star to file name, or convert to regexp if not exp. files.
1042 xp->xp_pattern_len = (int)(str + col - xp->xp_pattern);
1043 file_str = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
1044 if (file_str == NULL)
1045 return EXPAND_UNSUCCESSFUL;
1046
1047 if (p_wic)
1048 options += WILD_ICASE;
1049
1050 // find all files that match the description
1051 if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL)
1052 {
1053 *matchcount = 0;
1054 *matches = NULL;
1055 }
1056 vim_free(file_str);
1057
1058 return EXPAND_OK;
1059}
1060
1061#ifdef FEAT_MULTI_LANG
1062/*
1063 * Cleanup matches for help tags:
1064 * Remove "@ab" if the top of 'helplang' is "ab" and the language of the first
1065 * tag matches it. Otherwise remove "@en" if "en" is the only language.
1066 */
1067 static void
1068cleanup_help_tags(int num_file, char_u **file)
1069{
1070 int i, j;
1071 int len;
1072 char_u buf[4];
1073 char_u *p = buf;
1074
1075 if (p_hlg[0] != NUL && (p_hlg[0] != 'e' || p_hlg[1] != 'n'))
1076 {
1077 *p++ = '@';
1078 *p++ = p_hlg[0];
1079 *p++ = p_hlg[1];
1080 }
1081 *p = NUL;
1082
1083 for (i = 0; i < num_file; ++i)
1084 {
1085 len = (int)STRLEN(file[i]) - 3;
1086 if (len <= 0)
1087 continue;
1088 if (STRCMP(file[i] + len, "@en") == 0)
1089 {
1090 // Sorting on priority means the same item in another language may
1091 // be anywhere. Search all items for a match up to the "@en".
1092 for (j = 0; j < num_file; ++j)
1093 if (j != i && (int)STRLEN(file[j]) == len + 3
1094 && STRNCMP(file[i], file[j], len + 1) == 0)
1095 break;
1096 if (j == num_file)
1097 // item only exists with @en, remove it
1098 file[i][len] = NUL;
1099 }
1100 }
1101
1102 if (*buf != NUL)
1103 for (i = 0; i < num_file; ++i)
1104 {
1105 len = (int)STRLEN(file[i]) - 3;
1106 if (len <= 0)
1107 continue;
1108 if (STRCMP(file[i] + len, buf) == 0)
1109 {
1110 // remove the default language
1111 file[i][len] = NUL;
1112 }
1113 }
1114}
1115#endif
1116
1117/*
1118 * Do the expansion based on xp->xp_context and "pat".
1119 */
1120 static int
1121ExpandFromContext(
1122 expand_T *xp,
1123 char_u *pat,
1124 int *num_file,
1125 char_u ***file,
1126 int options) // WILD_ flags
1127{
Bram Moolenaar66b51422019-08-18 21:44:12 +02001128 regmatch_T regmatch;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001129 int ret;
1130 int flags;
1131
1132 flags = EW_DIR; // include directories
1133 if (options & WILD_LIST_NOTFOUND)
1134 flags |= EW_NOTFOUND;
1135 if (options & WILD_ADD_SLASH)
1136 flags |= EW_ADDSLASH;
1137 if (options & WILD_KEEP_ALL)
1138 flags |= EW_KEEPALL;
1139 if (options & WILD_SILENT)
1140 flags |= EW_SILENT;
1141 if (options & WILD_ALLLINKS)
1142 flags |= EW_ALLLINKS;
1143
1144 if (xp->xp_context == EXPAND_FILES
1145 || xp->xp_context == EXPAND_DIRECTORIES
1146 || xp->xp_context == EXPAND_FILES_IN_PATH)
1147 {
1148 // Expand file or directory names.
1149 int free_pat = FALSE;
1150 int i;
1151
1152 // for ":set path=" and ":set tags=" halve backslashes for escaped
1153 // space
1154 if (xp->xp_backslash != XP_BS_NONE)
1155 {
1156 free_pat = TRUE;
1157 pat = vim_strsave(pat);
1158 for (i = 0; pat[i]; ++i)
1159 if (pat[i] == '\\')
1160 {
1161 if (xp->xp_backslash == XP_BS_THREE
1162 && pat[i + 1] == '\\'
1163 && pat[i + 2] == '\\'
1164 && pat[i + 3] == ' ')
1165 STRMOVE(pat + i, pat + i + 3);
1166 if (xp->xp_backslash == XP_BS_ONE
1167 && pat[i + 1] == ' ')
1168 STRMOVE(pat + i, pat + i + 1);
1169 }
1170 }
1171
1172 if (xp->xp_context == EXPAND_FILES)
1173 flags |= EW_FILE;
1174 else if (xp->xp_context == EXPAND_FILES_IN_PATH)
1175 flags |= (EW_FILE | EW_PATH);
1176 else
1177 flags = (flags | EW_DIR) & ~EW_FILE;
1178 if (options & WILD_ICASE)
1179 flags |= EW_ICASE;
1180
1181 // Expand wildcards, supporting %:h and the like.
1182 ret = expand_wildcards_eval(&pat, num_file, file, flags);
1183 if (free_pat)
1184 vim_free(pat);
1185#ifdef BACKSLASH_IN_FILENAME
1186 if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0)
1187 {
1188 int i;
1189
1190 for (i = 0; i < *num_file; ++i)
1191 {
1192 char_u *ptr = (*file)[i];
1193
1194 while (*ptr != NUL)
1195 {
1196 if (p_csl[0] == 's' && *ptr == '\\')
1197 *ptr = '/';
1198 else if (p_csl[0] == 'b' && *ptr == '/')
1199 *ptr = '\\';
1200 ptr += (*mb_ptr2len)(ptr);
1201 }
1202 }
1203 }
1204#endif
1205 return ret;
1206 }
1207
1208 *file = (char_u **)"";
1209 *num_file = 0;
1210 if (xp->xp_context == EXPAND_HELP)
1211 {
1212 // With an empty argument we would get all the help tags, which is
1213 // very slow. Get matches for "help" instead.
1214 if (find_help_tags(*pat == NUL ? (char_u *)"help" : pat,
1215 num_file, file, FALSE) == OK)
1216 {
1217#ifdef FEAT_MULTI_LANG
1218 cleanup_help_tags(*num_file, *file);
1219#endif
1220 return OK;
1221 }
1222 return FAIL;
1223 }
1224
Bram Moolenaar66b51422019-08-18 21:44:12 +02001225 if (xp->xp_context == EXPAND_SHELLCMD)
1226 return expand_shellcmd(pat, num_file, file, flags);
1227 if (xp->xp_context == EXPAND_OLD_SETTING)
1228 return ExpandOldSetting(num_file, file);
1229 if (xp->xp_context == EXPAND_BUFFERS)
1230 return ExpandBufnames(pat, num_file, file, options);
1231 if (xp->xp_context == EXPAND_TAGS
1232 || xp->xp_context == EXPAND_TAGS_LISTFILES)
1233 return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
1234 if (xp->xp_context == EXPAND_COLORS)
1235 {
1236 char *directories[] = {"colors", NULL};
1237 return ExpandRTDir(pat, DIP_START + DIP_OPT, num_file, file,
1238 directories);
1239 }
1240 if (xp->xp_context == EXPAND_COMPILER)
1241 {
1242 char *directories[] = {"compiler", NULL};
1243 return ExpandRTDir(pat, 0, num_file, file, directories);
1244 }
1245 if (xp->xp_context == EXPAND_OWNSYNTAX)
1246 {
1247 char *directories[] = {"syntax", NULL};
1248 return ExpandRTDir(pat, 0, num_file, file, directories);
1249 }
1250 if (xp->xp_context == EXPAND_FILETYPE)
1251 {
1252 char *directories[] = {"syntax", "indent", "ftplugin", NULL};
1253 return ExpandRTDir(pat, 0, num_file, file, directories);
1254 }
1255# if defined(FEAT_EVAL)
1256 if (xp->xp_context == EXPAND_USER_LIST)
1257 return ExpandUserList(xp, num_file, file);
1258# endif
1259 if (xp->xp_context == EXPAND_PACKADD)
1260 return ExpandPackAddDir(pat, num_file, file);
1261
1262 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
1263 if (regmatch.regprog == NULL)
1264 return FAIL;
1265
1266 // set ignore-case according to p_ic, p_scs and pat
1267 regmatch.rm_ic = ignorecase(pat);
1268
1269 if (xp->xp_context == EXPAND_SETTINGS
1270 || xp->xp_context == EXPAND_BOOL_SETTINGS)
1271 ret = ExpandSettings(xp, &regmatch, num_file, file);
1272 else if (xp->xp_context == EXPAND_MAPPINGS)
1273 ret = ExpandMappings(&regmatch, num_file, file);
1274# if defined(FEAT_EVAL)
1275 else if (xp->xp_context == EXPAND_USER_DEFINED)
1276 ret = ExpandUserDefined(xp, &regmatch, num_file, file);
1277# endif
1278 else
1279 {
1280 static struct expgen
1281 {
1282 int context;
1283 char_u *((*func)(expand_T *, int));
1284 int ic;
1285 int escaped;
1286 } tab[] =
1287 {
1288 {EXPAND_COMMANDS, get_command_name, FALSE, TRUE},
1289 {EXPAND_BEHAVE, get_behave_arg, TRUE, TRUE},
1290 {EXPAND_MAPCLEAR, get_mapclear_arg, TRUE, TRUE},
1291 {EXPAND_MESSAGES, get_messages_arg, TRUE, TRUE},
1292 {EXPAND_HISTORY, get_history_arg, TRUE, TRUE},
1293 {EXPAND_USER_COMMANDS, get_user_commands, FALSE, TRUE},
1294 {EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, FALSE, TRUE},
1295 {EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE, TRUE},
1296 {EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE, TRUE},
1297 {EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE, TRUE},
1298# ifdef FEAT_EVAL
1299 {EXPAND_USER_VARS, get_user_var_name, FALSE, TRUE},
1300 {EXPAND_FUNCTIONS, get_function_name, FALSE, TRUE},
1301 {EXPAND_USER_FUNC, get_user_func_name, FALSE, TRUE},
1302 {EXPAND_EXPRESSION, get_expr_name, FALSE, TRUE},
1303# endif
1304# ifdef FEAT_MENU
1305 {EXPAND_MENUS, get_menu_name, FALSE, TRUE},
1306 {EXPAND_MENUNAMES, get_menu_names, FALSE, TRUE},
1307# endif
1308# ifdef FEAT_SYN_HL
1309 {EXPAND_SYNTAX, get_syntax_name, TRUE, TRUE},
1310# endif
1311# ifdef FEAT_PROFILE
1312 {EXPAND_SYNTIME, get_syntime_arg, TRUE, TRUE},
1313# endif
1314 {EXPAND_HIGHLIGHT, get_highlight_name, TRUE, TRUE},
1315 {EXPAND_EVENTS, get_event_name, TRUE, TRUE},
1316 {EXPAND_AUGROUP, get_augroup_name, TRUE, TRUE},
1317# ifdef FEAT_CSCOPE
1318 {EXPAND_CSCOPE, get_cscope_name, TRUE, TRUE},
1319# endif
1320# ifdef FEAT_SIGNS
1321 {EXPAND_SIGN, get_sign_name, TRUE, TRUE},
1322# endif
1323# ifdef FEAT_PROFILE
1324 {EXPAND_PROFILE, get_profile_name, TRUE, TRUE},
1325# endif
1326# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1327 {EXPAND_LANGUAGE, get_lang_arg, TRUE, FALSE},
1328 {EXPAND_LOCALES, get_locales, TRUE, FALSE},
1329# endif
1330 {EXPAND_ENV_VARS, get_env_name, TRUE, TRUE},
1331 {EXPAND_USER, get_users, TRUE, FALSE},
1332 {EXPAND_ARGLIST, get_arglist_name, TRUE, FALSE},
1333 };
1334 int i;
1335
1336 // Find a context in the table and call the ExpandGeneric() with the
1337 // right function to do the expansion.
1338 ret = FAIL;
1339 for (i = 0; i < (int)(sizeof(tab) / sizeof(struct expgen)); ++i)
1340 if (xp->xp_context == tab[i].context)
1341 {
1342 if (tab[i].ic)
1343 regmatch.rm_ic = TRUE;
1344 ret = ExpandGeneric(xp, &regmatch, num_file, file,
1345 tab[i].func, tab[i].escaped);
1346 break;
1347 }
1348 }
1349
1350 vim_regfree(regmatch.regprog);
1351
1352 return ret;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001353}
1354
Bram Moolenaar66b51422019-08-18 21:44:12 +02001355/*
1356 * Expand a list of names.
1357 *
1358 * Generic function for command line completion. It calls a function to
1359 * obtain strings, one by one. The strings are matched against a regexp
1360 * program. Matching strings are copied into an array, which is returned.
1361 *
1362 * Returns OK when no problems encountered, FAIL for error (out of memory).
1363 */
1364 int
1365ExpandGeneric(
1366 expand_T *xp,
1367 regmatch_T *regmatch,
1368 int *num_file,
1369 char_u ***file,
1370 char_u *((*func)(expand_T *, int)),
1371 // returns a string from the list
1372 int escaped)
1373{
1374 int i;
1375 int count = 0;
1376 int round;
1377 char_u *str;
1378
1379 // do this loop twice:
1380 // round == 0: count the number of matching names
1381 // round == 1: copy the matching names into allocated memory
1382 for (round = 0; round <= 1; ++round)
1383 {
1384 for (i = 0; ; ++i)
1385 {
1386 str = (*func)(xp, i);
1387 if (str == NULL) // end of list
1388 break;
1389 if (*str == NUL) // skip empty strings
1390 continue;
1391
1392 if (vim_regexec(regmatch, str, (colnr_T)0))
1393 {
1394 if (round)
1395 {
1396 if (escaped)
1397 str = vim_strsave_escaped(str, (char_u *)" \t\\.");
1398 else
1399 str = vim_strsave(str);
1400 (*file)[count] = str;
1401# ifdef FEAT_MENU
1402 if (func == get_menu_names && str != NULL)
1403 {
1404 // test for separator added by get_menu_names()
1405 str += STRLEN(str) - 1;
1406 if (*str == '\001')
1407 *str = '.';
1408 }
1409# endif
1410 }
1411 ++count;
1412 }
1413 }
1414 if (round == 0)
1415 {
1416 if (count == 0)
1417 return OK;
1418 *num_file = count;
1419 *file = ALLOC_MULT(char_u *, count);
1420 if (*file == NULL)
1421 {
1422 *file = (char_u **)"";
1423 return FAIL;
1424 }
1425 count = 0;
1426 }
1427 }
1428
1429 // Sort the results. Keep menu's in the specified order.
1430 if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
1431 {
1432 if (xp->xp_context == EXPAND_EXPRESSION
1433 || xp->xp_context == EXPAND_FUNCTIONS
1434 || xp->xp_context == EXPAND_USER_FUNC)
1435 // <SNR> functions should be sorted to the end.
1436 qsort((void *)*file, (size_t)*num_file, sizeof(char_u *),
1437 sort_func_compare);
1438 else
1439 sort_strings(*file, *num_file);
1440 }
1441
Bram Moolenaar0a52df52019-08-18 22:26:31 +02001442#if defined(FEAT_SYN_HL)
Bram Moolenaar66b51422019-08-18 21:44:12 +02001443 // Reset the variables used for special highlight names expansion, so that
1444 // they don't show up when getting normal highlight names by ID.
1445 reset_expand_highlight();
Bram Moolenaar0a52df52019-08-18 22:26:31 +02001446#endif
Bram Moolenaar66b51422019-08-18 21:44:12 +02001447
1448 return OK;
1449}
1450
1451/*
1452 * Complete a shell command.
1453 * Returns FAIL or OK;
1454 */
1455 static int
1456expand_shellcmd(
1457 char_u *filepat, // pattern to match with command names
1458 int *num_file, // return: number of matches
1459 char_u ***file, // return: array with matches
1460 int flagsarg) // EW_ flags
1461{
1462 char_u *pat;
1463 int i;
1464 char_u *path = NULL;
1465 int mustfree = FALSE;
1466 garray_T ga;
1467 char_u *buf = alloc(MAXPATHL);
1468 size_t l;
1469 char_u *s, *e;
1470 int flags = flagsarg;
1471 int ret;
1472 int did_curdir = FALSE;
1473 hashtab_T found_ht;
1474 hashitem_T *hi;
1475 hash_T hash;
1476
1477 if (buf == NULL)
1478 return FAIL;
1479
1480 // for ":set path=" and ":set tags=" halve backslashes for escaped
1481 // space
1482 pat = vim_strsave(filepat);
1483 for (i = 0; pat[i]; ++i)
1484 if (pat[i] == '\\' && pat[i + 1] == ' ')
1485 STRMOVE(pat + i, pat + i + 1);
1486
1487 flags |= EW_FILE | EW_EXEC | EW_SHELLCMD;
1488
1489 if (pat[0] == '.' && (vim_ispathsep(pat[1])
1490 || (pat[1] == '.' && vim_ispathsep(pat[2]))))
1491 path = (char_u *)".";
1492 else
1493 {
1494 // For an absolute name we don't use $PATH.
1495 if (!mch_isFullName(pat))
1496 path = vim_getenv((char_u *)"PATH", &mustfree);
1497 if (path == NULL)
1498 path = (char_u *)"";
1499 }
1500
1501 // Go over all directories in $PATH. Expand matches in that directory and
1502 // collect them in "ga". When "." is not in $PATH also expand for the
1503 // current directory, to find "subdir/cmd".
1504 ga_init2(&ga, (int)sizeof(char *), 10);
1505 hash_init(&found_ht);
1506 for (s = path; ; s = e)
1507 {
1508# if defined(MSWIN)
1509 e = vim_strchr(s, ';');
1510# else
1511 e = vim_strchr(s, ':');
1512# endif
1513 if (e == NULL)
1514 e = s + STRLEN(s);
1515
1516 if (*s == NUL)
1517 {
1518 if (did_curdir)
1519 break;
1520 // Find directories in the current directory, path is empty.
1521 did_curdir = TRUE;
1522 flags |= EW_DIR;
1523 }
1524 else if (STRNCMP(s, ".", (int)(e - s)) == 0)
1525 {
1526 did_curdir = TRUE;
1527 flags |= EW_DIR;
1528 }
1529 else
1530 // Do not match directories inside a $PATH item.
1531 flags &= ~EW_DIR;
1532
1533 l = e - s;
1534 if (l > MAXPATHL - 5)
1535 break;
1536 vim_strncpy(buf, s, l);
1537 add_pathsep(buf);
1538 l = STRLEN(buf);
1539 vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
1540
1541 // Expand matches in one directory of $PATH.
1542 ret = expand_wildcards(1, &buf, num_file, file, flags);
1543 if (ret == OK)
1544 {
1545 if (ga_grow(&ga, *num_file) == FAIL)
1546 FreeWild(*num_file, *file);
1547 else
1548 {
1549 for (i = 0; i < *num_file; ++i)
1550 {
1551 char_u *name = (*file)[i];
1552
1553 if (STRLEN(name) > l)
1554 {
1555 // Check if this name was already found.
1556 hash = hash_hash(name + l);
1557 hi = hash_lookup(&found_ht, name + l, hash);
1558 if (HASHITEM_EMPTY(hi))
1559 {
1560 // Remove the path that was prepended.
1561 STRMOVE(name, name + l);
1562 ((char_u **)ga.ga_data)[ga.ga_len++] = name;
1563 hash_add_item(&found_ht, hi, name, hash);
1564 name = NULL;
1565 }
1566 }
1567 vim_free(name);
1568 }
1569 vim_free(*file);
1570 }
1571 }
1572 if (*e != NUL)
1573 ++e;
1574 }
1575 *file = ga.ga_data;
1576 *num_file = ga.ga_len;
1577
1578 vim_free(buf);
1579 vim_free(pat);
1580 if (mustfree)
1581 vim_free(path);
1582 hash_clear(&found_ht);
1583 return OK;
1584}
1585
1586# if defined(FEAT_EVAL)
1587/*
1588 * Call "user_expand_func()" to invoke a user defined Vim script function and
1589 * return the result (either a string or a List).
1590 */
1591 static void *
1592call_user_expand_func(
1593 void *(*user_expand_func)(char_u *, int, typval_T *),
1594 expand_T *xp,
1595 int *num_file,
1596 char_u ***file)
1597{
1598 cmdline_info_T *ccline = get_cmdline_info();
1599 int keep = 0;
1600 typval_T args[4];
1601 sctx_T save_current_sctx = current_sctx;
1602 char_u *pat = NULL;
1603 void *ret;
1604
1605 if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL)
1606 return NULL;
1607 *num_file = 0;
1608 *file = NULL;
1609
1610 if (ccline->cmdbuff != NULL)
1611 {
1612 keep = ccline->cmdbuff[ccline->cmdlen];
1613 ccline->cmdbuff[ccline->cmdlen] = 0;
1614 }
1615
1616 pat = vim_strnsave(xp->xp_pattern, xp->xp_pattern_len);
1617
1618 args[0].v_type = VAR_STRING;
1619 args[0].vval.v_string = pat;
1620 args[1].v_type = VAR_STRING;
1621 args[1].vval.v_string = xp->xp_line;
1622 args[2].v_type = VAR_NUMBER;
1623 args[2].vval.v_number = xp->xp_col;
1624 args[3].v_type = VAR_UNKNOWN;
1625
1626 current_sctx = xp->xp_script_ctx;
1627
1628 ret = user_expand_func(xp->xp_arg, 3, args);
1629
1630 current_sctx = save_current_sctx;
1631 if (ccline->cmdbuff != NULL)
1632 ccline->cmdbuff[ccline->cmdlen] = keep;
1633
1634 vim_free(pat);
1635 return ret;
1636}
1637
1638/*
1639 * Expand names with a function defined by the user.
1640 */
1641 static int
1642ExpandUserDefined(
1643 expand_T *xp,
1644 regmatch_T *regmatch,
1645 int *num_file,
1646 char_u ***file)
1647{
1648 char_u *retstr;
1649 char_u *s;
1650 char_u *e;
1651 int keep;
1652 garray_T ga;
1653 int skip;
1654
1655 retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
1656 if (retstr == NULL)
1657 return FAIL;
1658
1659 ga_init2(&ga, (int)sizeof(char *), 3);
1660 for (s = retstr; *s != NUL; s = e)
1661 {
1662 e = vim_strchr(s, '\n');
1663 if (e == NULL)
1664 e = s + STRLEN(s);
1665 keep = *e;
1666 *e = NUL;
1667
1668 skip = xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0;
1669 *e = keep;
1670
1671 if (!skip)
1672 {
1673 if (ga_grow(&ga, 1) == FAIL)
1674 break;
1675 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
1676 ++ga.ga_len;
1677 }
1678
1679 if (*e != NUL)
1680 ++e;
1681 }
1682 vim_free(retstr);
1683 *file = ga.ga_data;
1684 *num_file = ga.ga_len;
1685 return OK;
1686}
1687
1688/*
1689 * Expand names with a list returned by a function defined by the user.
1690 */
1691 static int
1692ExpandUserList(
1693 expand_T *xp,
1694 int *num_file,
1695 char_u ***file)
1696{
1697 list_T *retlist;
1698 listitem_T *li;
1699 garray_T ga;
1700
1701 retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
1702 if (retlist == NULL)
1703 return FAIL;
1704
1705 ga_init2(&ga, (int)sizeof(char *), 3);
1706 // Loop over the items in the list.
1707 for (li = retlist->lv_first; li != NULL; li = li->li_next)
1708 {
1709 if (li->li_tv.v_type != VAR_STRING || li->li_tv.vval.v_string == NULL)
1710 continue; // Skip non-string items and empty strings
1711
1712 if (ga_grow(&ga, 1) == FAIL)
1713 break;
1714
1715 ((char_u **)ga.ga_data)[ga.ga_len] =
1716 vim_strsave(li->li_tv.vval.v_string);
1717 ++ga.ga_len;
1718 }
1719 list_unref(retlist);
1720
1721 *file = ga.ga_data;
1722 *num_file = ga.ga_len;
1723 return OK;
1724}
1725# endif
1726
1727/*
1728 * Expand color scheme, compiler or filetype names.
1729 * Search from 'runtimepath':
1730 * 'runtimepath'/{dirnames}/{pat}.vim
1731 * When "flags" has DIP_START: search also from 'start' of 'packpath':
1732 * 'packpath'/pack/ * /start/ * /{dirnames}/{pat}.vim
1733 * When "flags" has DIP_OPT: search also from 'opt' of 'packpath':
1734 * 'packpath'/pack/ * /opt/ * /{dirnames}/{pat}.vim
1735 * "dirnames" is an array with one or more directory names.
1736 */
1737 static int
1738ExpandRTDir(
1739 char_u *pat,
1740 int flags,
1741 int *num_file,
1742 char_u ***file,
1743 char *dirnames[])
1744{
1745 char_u *s;
1746 char_u *e;
1747 char_u *match;
1748 garray_T ga;
1749 int i;
1750 int pat_len;
1751
1752 *num_file = 0;
1753 *file = NULL;
1754 pat_len = (int)STRLEN(pat);
1755 ga_init2(&ga, (int)sizeof(char *), 10);
1756
1757 for (i = 0; dirnames[i] != NULL; ++i)
1758 {
1759 s = alloc(STRLEN(dirnames[i]) + pat_len + 7);
1760 if (s == NULL)
1761 {
1762 ga_clear_strings(&ga);
1763 return FAIL;
1764 }
1765 sprintf((char *)s, "%s/%s*.vim", dirnames[i], pat);
1766 globpath(p_rtp, s, &ga, 0);
1767 vim_free(s);
1768 }
1769
1770 if (flags & DIP_START) {
1771 for (i = 0; dirnames[i] != NULL; ++i)
1772 {
1773 s = alloc(STRLEN(dirnames[i]) + pat_len + 22);
1774 if (s == NULL)
1775 {
1776 ga_clear_strings(&ga);
1777 return FAIL;
1778 }
1779 sprintf((char *)s, "pack/*/start/*/%s/%s*.vim", dirnames[i], pat);
1780 globpath(p_pp, s, &ga, 0);
1781 vim_free(s);
1782 }
1783 }
1784
1785 if (flags & DIP_OPT) {
1786 for (i = 0; dirnames[i] != NULL; ++i)
1787 {
1788 s = alloc(STRLEN(dirnames[i]) + pat_len + 20);
1789 if (s == NULL)
1790 {
1791 ga_clear_strings(&ga);
1792 return FAIL;
1793 }
1794 sprintf((char *)s, "pack/*/opt/*/%s/%s*.vim", dirnames[i], pat);
1795 globpath(p_pp, s, &ga, 0);
1796 vim_free(s);
1797 }
1798 }
1799
1800 for (i = 0; i < ga.ga_len; ++i)
1801 {
1802 match = ((char_u **)ga.ga_data)[i];
1803 s = match;
1804 e = s + STRLEN(s);
1805 if (e - 4 > s && STRNICMP(e - 4, ".vim", 4) == 0)
1806 {
1807 e -= 4;
1808 for (s = e; s > match; MB_PTR_BACK(match, s))
1809 if (s < match || vim_ispathsep(*s))
1810 break;
1811 ++s;
1812 *e = NUL;
1813 mch_memmove(match, s, e - s + 1);
1814 }
1815 }
1816
1817 if (ga.ga_len == 0)
1818 return FAIL;
1819
1820 // Sort and remove duplicates which can happen when specifying multiple
1821 // directories in dirnames.
1822 remove_duplicates(&ga);
1823
1824 *file = ga.ga_data;
1825 *num_file = ga.ga_len;
1826 return OK;
1827}
1828
1829/*
1830 * Expand loadplugin names:
1831 * 'packpath'/pack/ * /opt/{pat}
1832 */
1833 static int
1834ExpandPackAddDir(
1835 char_u *pat,
1836 int *num_file,
1837 char_u ***file)
1838{
1839 char_u *s;
1840 char_u *e;
1841 char_u *match;
1842 garray_T ga;
1843 int i;
1844 int pat_len;
1845
1846 *num_file = 0;
1847 *file = NULL;
1848 pat_len = (int)STRLEN(pat);
1849 ga_init2(&ga, (int)sizeof(char *), 10);
1850
1851 s = alloc(pat_len + 26);
1852 if (s == NULL)
1853 {
1854 ga_clear_strings(&ga);
1855 return FAIL;
1856 }
1857 sprintf((char *)s, "pack/*/opt/%s*", pat);
1858 globpath(p_pp, s, &ga, 0);
1859 vim_free(s);
1860
1861 for (i = 0; i < ga.ga_len; ++i)
1862 {
1863 match = ((char_u **)ga.ga_data)[i];
1864 s = gettail(match);
1865 e = s + STRLEN(s);
1866 mch_memmove(match, s, e - s + 1);
1867 }
1868
1869 if (ga.ga_len == 0)
1870 return FAIL;
1871
1872 // Sort and remove duplicates which can happen when specifying multiple
1873 // directories in dirnames.
1874 remove_duplicates(&ga);
1875
1876 *file = ga.ga_data;
1877 *num_file = ga.ga_len;
1878 return OK;
1879}
Bram Moolenaar66b51422019-08-18 21:44:12 +02001880
Bram Moolenaar66b51422019-08-18 21:44:12 +02001881/*
1882 * Expand "file" for all comma-separated directories in "path".
1883 * Adds the matches to "ga". Caller must init "ga".
1884 */
1885 void
1886globpath(
1887 char_u *path,
1888 char_u *file,
1889 garray_T *ga,
1890 int expand_options)
1891{
1892 expand_T xpc;
1893 char_u *buf;
1894 int i;
1895 int num_p;
1896 char_u **p;
1897
1898 buf = alloc(MAXPATHL);
1899 if (buf == NULL)
1900 return;
1901
1902 ExpandInit(&xpc);
1903 xpc.xp_context = EXPAND_FILES;
1904
1905 // Loop over all entries in {path}.
1906 while (*path != NUL)
1907 {
1908 // Copy one item of the path to buf[] and concatenate the file name.
1909 copy_option_part(&path, buf, MAXPATHL, ",");
1910 if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
1911 {
1912# if defined(MSWIN)
1913 // Using the platform's path separator (\) makes vim incorrectly
1914 // treat it as an escape character, use '/' instead.
1915 if (*buf != NUL && !after_pathsep(buf, buf + STRLEN(buf)))
1916 STRCAT(buf, "/");
1917# else
1918 add_pathsep(buf);
1919# endif
1920 STRCAT(buf, file);
1921 if (ExpandFromContext(&xpc, buf, &num_p, &p,
1922 WILD_SILENT|expand_options) != FAIL && num_p > 0)
1923 {
1924 ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT|expand_options);
1925
1926 if (ga_grow(ga, num_p) == OK)
1927 {
1928 for (i = 0; i < num_p; ++i)
1929 {
1930 ((char_u **)ga->ga_data)[ga->ga_len] =
1931 vim_strnsave(p[i], (int)STRLEN(p[i]));
1932 ++ga->ga_len;
1933 }
1934 }
1935
1936 FreeWild(num_p, p);
1937 }
1938 }
1939 }
1940
1941 vim_free(buf);
1942}
Bram Moolenaar66b51422019-08-18 21:44:12 +02001943
Bram Moolenaar0a52df52019-08-18 22:26:31 +02001944#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar66b51422019-08-18 21:44:12 +02001945/*
1946 * "getcompletion()" function
1947 */
1948 void
1949f_getcompletion(typval_T *argvars, typval_T *rettv)
1950{
1951 char_u *pat;
1952 expand_T xpc;
1953 int filtered = FALSE;
1954 int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH
1955 | WILD_NO_BEEP;
1956
1957 if (argvars[2].v_type != VAR_UNKNOWN)
1958 filtered = tv_get_number_chk(&argvars[2], NULL);
1959
1960 if (p_wic)
1961 options |= WILD_ICASE;
1962
1963 // For filtered results, 'wildignore' is used
1964 if (!filtered)
1965 options |= WILD_KEEP_ALL;
1966
1967 ExpandInit(&xpc);
1968 xpc.xp_pattern = tv_get_string(&argvars[0]);
1969 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1970 xpc.xp_context = cmdcomplete_str_to_type(tv_get_string(&argvars[1]));
1971 if (xpc.xp_context == EXPAND_NOTHING)
1972 {
1973 if (argvars[1].v_type == VAR_STRING)
1974 semsg(_(e_invarg2), argvars[1].vval.v_string);
1975 else
1976 emsg(_(e_invarg));
1977 return;
1978 }
1979
1980# if defined(FEAT_MENU)
1981 if (xpc.xp_context == EXPAND_MENUS)
1982 {
1983 set_context_in_menu_cmd(&xpc, (char_u *)"menu", xpc.xp_pattern, FALSE);
1984 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1985 }
1986# endif
1987# ifdef FEAT_CSCOPE
1988 if (xpc.xp_context == EXPAND_CSCOPE)
1989 {
1990 set_context_in_cscope_cmd(&xpc, xpc.xp_pattern, CMD_cscope);
1991 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1992 }
1993# endif
1994# ifdef FEAT_SIGNS
1995 if (xpc.xp_context == EXPAND_SIGN)
1996 {
1997 set_context_in_sign_cmd(&xpc, xpc.xp_pattern);
1998 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1999 }
2000# endif
2001
2002 pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
2003 if ((rettv_list_alloc(rettv) != FAIL) && (pat != NULL))
2004 {
2005 int i;
2006
2007 ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP);
2008
2009 for (i = 0; i < xpc.xp_numfiles; i++)
2010 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
2011 }
2012 vim_free(pat);
2013 ExpandCleanup(&xpc);
2014}
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002015#endif // FEAT_EVAL