blob: 1454fd2f53c96034e13a70f64e4e5edf81530ae4 [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;
649
650 // Expansion was done before and special characters
651 // were escaped, need to halve backslashes. Also
652 // $HOME has been replaced with ~/.
653 exp_path = expand_env_save_opt(files_found[k], TRUE);
654 halved_slash = backslash_halve_save(
655 exp_path != NULL ? exp_path : files_found[k]);
656 j = mch_isdir(halved_slash != NULL ? halved_slash
657 : files_found[k]);
658 vim_free(exp_path);
659 vim_free(halved_slash);
660 }
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
960 void
961set_cmd_context(
962 expand_T *xp,
963 char_u *str, // start of command line
964 int len, // length of command line (excl. NUL)
965 int col, // position of cursor
966 int use_ccline UNUSED) // use ccline for info
967{
968#ifdef FEAT_EVAL
969 cmdline_info_T *ccline = get_cmdline_info();
970#endif
971 int old_char = NUL;
972 char_u *nextcomm;
973
974 // Avoid a UMR warning from Purify, only save the character if it has been
975 // written before.
976 if (col < len)
977 old_char = str[col];
978 str[col] = NUL;
979 nextcomm = str;
980
981#ifdef FEAT_EVAL
982 if (use_ccline && ccline->cmdfirstc == '=')
983 {
Bram Moolenaar66b51422019-08-18 21:44:12 +0200984 // pass CMD_SIZE because there is no real command
985 set_context_for_expression(xp, str, CMD_SIZE);
Bram Moolenaar66b51422019-08-18 21:44:12 +0200986 }
987 else if (use_ccline && ccline->input_fn)
988 {
989 xp->xp_context = ccline->xp_context;
990 xp->xp_pattern = ccline->cmdbuff;
Bram Moolenaar66b51422019-08-18 21:44:12 +0200991 xp->xp_arg = ccline->xp_arg;
Bram Moolenaar66b51422019-08-18 21:44:12 +0200992 }
993 else
994#endif
995 while (nextcomm != NULL)
996 nextcomm = set_one_cmd_context(xp, nextcomm);
997
998 // Store the string here so that call_user_expand_func() can get to them
999 // easily.
1000 xp->xp_line = str;
1001 xp->xp_col = col;
1002
1003 str[col] = old_char;
1004}
1005
1006/*
1007 * Expand the command line "str" from context "xp".
1008 * "xp" must have been set by set_cmd_context().
1009 * xp->xp_pattern points into "str", to where the text that is to be expanded
1010 * starts.
1011 * Returns EXPAND_UNSUCCESSFUL when there is something illegal before the
1012 * cursor.
1013 * Returns EXPAND_NOTHING when there is nothing to expand, might insert the
1014 * key that triggered expansion literally.
1015 * Returns EXPAND_OK otherwise.
1016 */
1017 int
1018expand_cmdline(
1019 expand_T *xp,
1020 char_u *str, // start of command line
1021 int col, // position of cursor
1022 int *matchcount, // return: nr of matches
1023 char_u ***matches) // return: array of pointers to matches
1024{
1025 char_u *file_str = NULL;
1026 int options = WILD_ADD_SLASH|WILD_SILENT;
1027
1028 if (xp->xp_context == EXPAND_UNSUCCESSFUL)
1029 {
1030 beep_flush();
1031 return EXPAND_UNSUCCESSFUL; // Something illegal on command line
1032 }
1033 if (xp->xp_context == EXPAND_NOTHING)
1034 {
1035 // Caller can use the character as a normal char instead
1036 return EXPAND_NOTHING;
1037 }
1038
1039 // add star to file name, or convert to regexp if not exp. files.
1040 xp->xp_pattern_len = (int)(str + col - xp->xp_pattern);
1041 file_str = addstar(xp->xp_pattern, xp->xp_pattern_len, xp->xp_context);
1042 if (file_str == NULL)
1043 return EXPAND_UNSUCCESSFUL;
1044
1045 if (p_wic)
1046 options += WILD_ICASE;
1047
1048 // find all files that match the description
1049 if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL)
1050 {
1051 *matchcount = 0;
1052 *matches = NULL;
1053 }
1054 vim_free(file_str);
1055
1056 return EXPAND_OK;
1057}
1058
1059#ifdef FEAT_MULTI_LANG
1060/*
1061 * Cleanup matches for help tags:
1062 * Remove "@ab" if the top of 'helplang' is "ab" and the language of the first
1063 * tag matches it. Otherwise remove "@en" if "en" is the only language.
1064 */
1065 static void
1066cleanup_help_tags(int num_file, char_u **file)
1067{
1068 int i, j;
1069 int len;
1070 char_u buf[4];
1071 char_u *p = buf;
1072
1073 if (p_hlg[0] != NUL && (p_hlg[0] != 'e' || p_hlg[1] != 'n'))
1074 {
1075 *p++ = '@';
1076 *p++ = p_hlg[0];
1077 *p++ = p_hlg[1];
1078 }
1079 *p = NUL;
1080
1081 for (i = 0; i < num_file; ++i)
1082 {
1083 len = (int)STRLEN(file[i]) - 3;
1084 if (len <= 0)
1085 continue;
1086 if (STRCMP(file[i] + len, "@en") == 0)
1087 {
1088 // Sorting on priority means the same item in another language may
1089 // be anywhere. Search all items for a match up to the "@en".
1090 for (j = 0; j < num_file; ++j)
1091 if (j != i && (int)STRLEN(file[j]) == len + 3
1092 && STRNCMP(file[i], file[j], len + 1) == 0)
1093 break;
1094 if (j == num_file)
1095 // item only exists with @en, remove it
1096 file[i][len] = NUL;
1097 }
1098 }
1099
1100 if (*buf != NUL)
1101 for (i = 0; i < num_file; ++i)
1102 {
1103 len = (int)STRLEN(file[i]) - 3;
1104 if (len <= 0)
1105 continue;
1106 if (STRCMP(file[i] + len, buf) == 0)
1107 {
1108 // remove the default language
1109 file[i][len] = NUL;
1110 }
1111 }
1112}
1113#endif
1114
1115/*
1116 * Do the expansion based on xp->xp_context and "pat".
1117 */
1118 static int
1119ExpandFromContext(
1120 expand_T *xp,
1121 char_u *pat,
1122 int *num_file,
1123 char_u ***file,
1124 int options) // WILD_ flags
1125{
Bram Moolenaar66b51422019-08-18 21:44:12 +02001126 regmatch_T regmatch;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001127 int ret;
1128 int flags;
1129
1130 flags = EW_DIR; // include directories
1131 if (options & WILD_LIST_NOTFOUND)
1132 flags |= EW_NOTFOUND;
1133 if (options & WILD_ADD_SLASH)
1134 flags |= EW_ADDSLASH;
1135 if (options & WILD_KEEP_ALL)
1136 flags |= EW_KEEPALL;
1137 if (options & WILD_SILENT)
1138 flags |= EW_SILENT;
1139 if (options & WILD_ALLLINKS)
1140 flags |= EW_ALLLINKS;
1141
1142 if (xp->xp_context == EXPAND_FILES
1143 || xp->xp_context == EXPAND_DIRECTORIES
1144 || xp->xp_context == EXPAND_FILES_IN_PATH)
1145 {
1146 // Expand file or directory names.
1147 int free_pat = FALSE;
1148 int i;
1149
1150 // for ":set path=" and ":set tags=" halve backslashes for escaped
1151 // space
1152 if (xp->xp_backslash != XP_BS_NONE)
1153 {
1154 free_pat = TRUE;
1155 pat = vim_strsave(pat);
1156 for (i = 0; pat[i]; ++i)
1157 if (pat[i] == '\\')
1158 {
1159 if (xp->xp_backslash == XP_BS_THREE
1160 && pat[i + 1] == '\\'
1161 && pat[i + 2] == '\\'
1162 && pat[i + 3] == ' ')
1163 STRMOVE(pat + i, pat + i + 3);
1164 if (xp->xp_backslash == XP_BS_ONE
1165 && pat[i + 1] == ' ')
1166 STRMOVE(pat + i, pat + i + 1);
1167 }
1168 }
1169
1170 if (xp->xp_context == EXPAND_FILES)
1171 flags |= EW_FILE;
1172 else if (xp->xp_context == EXPAND_FILES_IN_PATH)
1173 flags |= (EW_FILE | EW_PATH);
1174 else
1175 flags = (flags | EW_DIR) & ~EW_FILE;
1176 if (options & WILD_ICASE)
1177 flags |= EW_ICASE;
1178
1179 // Expand wildcards, supporting %:h and the like.
1180 ret = expand_wildcards_eval(&pat, num_file, file, flags);
1181 if (free_pat)
1182 vim_free(pat);
1183#ifdef BACKSLASH_IN_FILENAME
1184 if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0)
1185 {
1186 int i;
1187
1188 for (i = 0; i < *num_file; ++i)
1189 {
1190 char_u *ptr = (*file)[i];
1191
1192 while (*ptr != NUL)
1193 {
1194 if (p_csl[0] == 's' && *ptr == '\\')
1195 *ptr = '/';
1196 else if (p_csl[0] == 'b' && *ptr == '/')
1197 *ptr = '\\';
1198 ptr += (*mb_ptr2len)(ptr);
1199 }
1200 }
1201 }
1202#endif
1203 return ret;
1204 }
1205
1206 *file = (char_u **)"";
1207 *num_file = 0;
1208 if (xp->xp_context == EXPAND_HELP)
1209 {
1210 // With an empty argument we would get all the help tags, which is
1211 // very slow. Get matches for "help" instead.
1212 if (find_help_tags(*pat == NUL ? (char_u *)"help" : pat,
1213 num_file, file, FALSE) == OK)
1214 {
1215#ifdef FEAT_MULTI_LANG
1216 cleanup_help_tags(*num_file, *file);
1217#endif
1218 return OK;
1219 }
1220 return FAIL;
1221 }
1222
Bram Moolenaar66b51422019-08-18 21:44:12 +02001223 if (xp->xp_context == EXPAND_SHELLCMD)
1224 return expand_shellcmd(pat, num_file, file, flags);
1225 if (xp->xp_context == EXPAND_OLD_SETTING)
1226 return ExpandOldSetting(num_file, file);
1227 if (xp->xp_context == EXPAND_BUFFERS)
1228 return ExpandBufnames(pat, num_file, file, options);
1229 if (xp->xp_context == EXPAND_TAGS
1230 || xp->xp_context == EXPAND_TAGS_LISTFILES)
1231 return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file);
1232 if (xp->xp_context == EXPAND_COLORS)
1233 {
1234 char *directories[] = {"colors", NULL};
1235 return ExpandRTDir(pat, DIP_START + DIP_OPT, num_file, file,
1236 directories);
1237 }
1238 if (xp->xp_context == EXPAND_COMPILER)
1239 {
1240 char *directories[] = {"compiler", NULL};
1241 return ExpandRTDir(pat, 0, num_file, file, directories);
1242 }
1243 if (xp->xp_context == EXPAND_OWNSYNTAX)
1244 {
1245 char *directories[] = {"syntax", NULL};
1246 return ExpandRTDir(pat, 0, num_file, file, directories);
1247 }
1248 if (xp->xp_context == EXPAND_FILETYPE)
1249 {
1250 char *directories[] = {"syntax", "indent", "ftplugin", NULL};
1251 return ExpandRTDir(pat, 0, num_file, file, directories);
1252 }
1253# if defined(FEAT_EVAL)
1254 if (xp->xp_context == EXPAND_USER_LIST)
1255 return ExpandUserList(xp, num_file, file);
1256# endif
1257 if (xp->xp_context == EXPAND_PACKADD)
1258 return ExpandPackAddDir(pat, num_file, file);
1259
1260 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
1261 if (regmatch.regprog == NULL)
1262 return FAIL;
1263
1264 // set ignore-case according to p_ic, p_scs and pat
1265 regmatch.rm_ic = ignorecase(pat);
1266
1267 if (xp->xp_context == EXPAND_SETTINGS
1268 || xp->xp_context == EXPAND_BOOL_SETTINGS)
1269 ret = ExpandSettings(xp, &regmatch, num_file, file);
1270 else if (xp->xp_context == EXPAND_MAPPINGS)
1271 ret = ExpandMappings(&regmatch, num_file, file);
1272# if defined(FEAT_EVAL)
1273 else if (xp->xp_context == EXPAND_USER_DEFINED)
1274 ret = ExpandUserDefined(xp, &regmatch, num_file, file);
1275# endif
1276 else
1277 {
1278 static struct expgen
1279 {
1280 int context;
1281 char_u *((*func)(expand_T *, int));
1282 int ic;
1283 int escaped;
1284 } tab[] =
1285 {
1286 {EXPAND_COMMANDS, get_command_name, FALSE, TRUE},
1287 {EXPAND_BEHAVE, get_behave_arg, TRUE, TRUE},
1288 {EXPAND_MAPCLEAR, get_mapclear_arg, TRUE, TRUE},
1289 {EXPAND_MESSAGES, get_messages_arg, TRUE, TRUE},
1290 {EXPAND_HISTORY, get_history_arg, TRUE, TRUE},
1291 {EXPAND_USER_COMMANDS, get_user_commands, FALSE, TRUE},
1292 {EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, FALSE, TRUE},
1293 {EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, FALSE, TRUE},
1294 {EXPAND_USER_NARGS, get_user_cmd_nargs, FALSE, TRUE},
1295 {EXPAND_USER_COMPLETE, get_user_cmd_complete, FALSE, TRUE},
1296# ifdef FEAT_EVAL
1297 {EXPAND_USER_VARS, get_user_var_name, FALSE, TRUE},
1298 {EXPAND_FUNCTIONS, get_function_name, FALSE, TRUE},
1299 {EXPAND_USER_FUNC, get_user_func_name, FALSE, TRUE},
1300 {EXPAND_EXPRESSION, get_expr_name, FALSE, TRUE},
1301# endif
1302# ifdef FEAT_MENU
1303 {EXPAND_MENUS, get_menu_name, FALSE, TRUE},
1304 {EXPAND_MENUNAMES, get_menu_names, FALSE, TRUE},
1305# endif
1306# ifdef FEAT_SYN_HL
1307 {EXPAND_SYNTAX, get_syntax_name, TRUE, TRUE},
1308# endif
1309# ifdef FEAT_PROFILE
1310 {EXPAND_SYNTIME, get_syntime_arg, TRUE, TRUE},
1311# endif
1312 {EXPAND_HIGHLIGHT, get_highlight_name, TRUE, TRUE},
1313 {EXPAND_EVENTS, get_event_name, TRUE, TRUE},
1314 {EXPAND_AUGROUP, get_augroup_name, TRUE, TRUE},
1315# ifdef FEAT_CSCOPE
1316 {EXPAND_CSCOPE, get_cscope_name, TRUE, TRUE},
1317# endif
1318# ifdef FEAT_SIGNS
1319 {EXPAND_SIGN, get_sign_name, TRUE, TRUE},
1320# endif
1321# ifdef FEAT_PROFILE
1322 {EXPAND_PROFILE, get_profile_name, TRUE, TRUE},
1323# endif
1324# if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
1325 {EXPAND_LANGUAGE, get_lang_arg, TRUE, FALSE},
1326 {EXPAND_LOCALES, get_locales, TRUE, FALSE},
1327# endif
1328 {EXPAND_ENV_VARS, get_env_name, TRUE, TRUE},
1329 {EXPAND_USER, get_users, TRUE, FALSE},
1330 {EXPAND_ARGLIST, get_arglist_name, TRUE, FALSE},
1331 };
1332 int i;
1333
1334 // Find a context in the table and call the ExpandGeneric() with the
1335 // right function to do the expansion.
1336 ret = FAIL;
1337 for (i = 0; i < (int)(sizeof(tab) / sizeof(struct expgen)); ++i)
1338 if (xp->xp_context == tab[i].context)
1339 {
1340 if (tab[i].ic)
1341 regmatch.rm_ic = TRUE;
1342 ret = ExpandGeneric(xp, &regmatch, num_file, file,
1343 tab[i].func, tab[i].escaped);
1344 break;
1345 }
1346 }
1347
1348 vim_regfree(regmatch.regprog);
1349
1350 return ret;
Bram Moolenaar66b51422019-08-18 21:44:12 +02001351}
1352
Bram Moolenaar66b51422019-08-18 21:44:12 +02001353/*
1354 * Expand a list of names.
1355 *
1356 * Generic function for command line completion. It calls a function to
1357 * obtain strings, one by one. The strings are matched against a regexp
1358 * program. Matching strings are copied into an array, which is returned.
1359 *
1360 * Returns OK when no problems encountered, FAIL for error (out of memory).
1361 */
1362 int
1363ExpandGeneric(
1364 expand_T *xp,
1365 regmatch_T *regmatch,
1366 int *num_file,
1367 char_u ***file,
1368 char_u *((*func)(expand_T *, int)),
1369 // returns a string from the list
1370 int escaped)
1371{
1372 int i;
1373 int count = 0;
1374 int round;
1375 char_u *str;
1376
1377 // do this loop twice:
1378 // round == 0: count the number of matching names
1379 // round == 1: copy the matching names into allocated memory
1380 for (round = 0; round <= 1; ++round)
1381 {
1382 for (i = 0; ; ++i)
1383 {
1384 str = (*func)(xp, i);
1385 if (str == NULL) // end of list
1386 break;
1387 if (*str == NUL) // skip empty strings
1388 continue;
1389
1390 if (vim_regexec(regmatch, str, (colnr_T)0))
1391 {
1392 if (round)
1393 {
1394 if (escaped)
1395 str = vim_strsave_escaped(str, (char_u *)" \t\\.");
1396 else
1397 str = vim_strsave(str);
1398 (*file)[count] = str;
1399# ifdef FEAT_MENU
1400 if (func == get_menu_names && str != NULL)
1401 {
1402 // test for separator added by get_menu_names()
1403 str += STRLEN(str) - 1;
1404 if (*str == '\001')
1405 *str = '.';
1406 }
1407# endif
1408 }
1409 ++count;
1410 }
1411 }
1412 if (round == 0)
1413 {
1414 if (count == 0)
1415 return OK;
1416 *num_file = count;
1417 *file = ALLOC_MULT(char_u *, count);
1418 if (*file == NULL)
1419 {
1420 *file = (char_u **)"";
1421 return FAIL;
1422 }
1423 count = 0;
1424 }
1425 }
1426
1427 // Sort the results. Keep menu's in the specified order.
1428 if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS)
1429 {
1430 if (xp->xp_context == EXPAND_EXPRESSION
1431 || xp->xp_context == EXPAND_FUNCTIONS
1432 || xp->xp_context == EXPAND_USER_FUNC)
1433 // <SNR> functions should be sorted to the end.
1434 qsort((void *)*file, (size_t)*num_file, sizeof(char_u *),
1435 sort_func_compare);
1436 else
1437 sort_strings(*file, *num_file);
1438 }
1439
Bram Moolenaar0a52df52019-08-18 22:26:31 +02001440#if defined(FEAT_SYN_HL)
Bram Moolenaar66b51422019-08-18 21:44:12 +02001441 // Reset the variables used for special highlight names expansion, so that
1442 // they don't show up when getting normal highlight names by ID.
1443 reset_expand_highlight();
Bram Moolenaar0a52df52019-08-18 22:26:31 +02001444#endif
Bram Moolenaar66b51422019-08-18 21:44:12 +02001445
1446 return OK;
1447}
1448
1449/*
1450 * Complete a shell command.
1451 * Returns FAIL or OK;
1452 */
1453 static int
1454expand_shellcmd(
1455 char_u *filepat, // pattern to match with command names
1456 int *num_file, // return: number of matches
1457 char_u ***file, // return: array with matches
1458 int flagsarg) // EW_ flags
1459{
1460 char_u *pat;
1461 int i;
1462 char_u *path = NULL;
1463 int mustfree = FALSE;
1464 garray_T ga;
1465 char_u *buf = alloc(MAXPATHL);
1466 size_t l;
1467 char_u *s, *e;
1468 int flags = flagsarg;
1469 int ret;
1470 int did_curdir = FALSE;
1471 hashtab_T found_ht;
1472 hashitem_T *hi;
1473 hash_T hash;
1474
1475 if (buf == NULL)
1476 return FAIL;
1477
1478 // for ":set path=" and ":set tags=" halve backslashes for escaped
1479 // space
1480 pat = vim_strsave(filepat);
1481 for (i = 0; pat[i]; ++i)
1482 if (pat[i] == '\\' && pat[i + 1] == ' ')
1483 STRMOVE(pat + i, pat + i + 1);
1484
1485 flags |= EW_FILE | EW_EXEC | EW_SHELLCMD;
1486
1487 if (pat[0] == '.' && (vim_ispathsep(pat[1])
1488 || (pat[1] == '.' && vim_ispathsep(pat[2]))))
1489 path = (char_u *)".";
1490 else
1491 {
1492 // For an absolute name we don't use $PATH.
1493 if (!mch_isFullName(pat))
1494 path = vim_getenv((char_u *)"PATH", &mustfree);
1495 if (path == NULL)
1496 path = (char_u *)"";
1497 }
1498
1499 // Go over all directories in $PATH. Expand matches in that directory and
1500 // collect them in "ga". When "." is not in $PATH also expand for the
1501 // current directory, to find "subdir/cmd".
1502 ga_init2(&ga, (int)sizeof(char *), 10);
1503 hash_init(&found_ht);
1504 for (s = path; ; s = e)
1505 {
1506# if defined(MSWIN)
1507 e = vim_strchr(s, ';');
1508# else
1509 e = vim_strchr(s, ':');
1510# endif
1511 if (e == NULL)
1512 e = s + STRLEN(s);
1513
1514 if (*s == NUL)
1515 {
1516 if (did_curdir)
1517 break;
1518 // Find directories in the current directory, path is empty.
1519 did_curdir = TRUE;
1520 flags |= EW_DIR;
1521 }
1522 else if (STRNCMP(s, ".", (int)(e - s)) == 0)
1523 {
1524 did_curdir = TRUE;
1525 flags |= EW_DIR;
1526 }
1527 else
1528 // Do not match directories inside a $PATH item.
1529 flags &= ~EW_DIR;
1530
1531 l = e - s;
1532 if (l > MAXPATHL - 5)
1533 break;
1534 vim_strncpy(buf, s, l);
1535 add_pathsep(buf);
1536 l = STRLEN(buf);
1537 vim_strncpy(buf + l, pat, MAXPATHL - 1 - l);
1538
1539 // Expand matches in one directory of $PATH.
1540 ret = expand_wildcards(1, &buf, num_file, file, flags);
1541 if (ret == OK)
1542 {
1543 if (ga_grow(&ga, *num_file) == FAIL)
1544 FreeWild(*num_file, *file);
1545 else
1546 {
1547 for (i = 0; i < *num_file; ++i)
1548 {
1549 char_u *name = (*file)[i];
1550
1551 if (STRLEN(name) > l)
1552 {
1553 // Check if this name was already found.
1554 hash = hash_hash(name + l);
1555 hi = hash_lookup(&found_ht, name + l, hash);
1556 if (HASHITEM_EMPTY(hi))
1557 {
1558 // Remove the path that was prepended.
1559 STRMOVE(name, name + l);
1560 ((char_u **)ga.ga_data)[ga.ga_len++] = name;
1561 hash_add_item(&found_ht, hi, name, hash);
1562 name = NULL;
1563 }
1564 }
1565 vim_free(name);
1566 }
1567 vim_free(*file);
1568 }
1569 }
1570 if (*e != NUL)
1571 ++e;
1572 }
1573 *file = ga.ga_data;
1574 *num_file = ga.ga_len;
1575
1576 vim_free(buf);
1577 vim_free(pat);
1578 if (mustfree)
1579 vim_free(path);
1580 hash_clear(&found_ht);
1581 return OK;
1582}
1583
1584# if defined(FEAT_EVAL)
1585/*
1586 * Call "user_expand_func()" to invoke a user defined Vim script function and
1587 * return the result (either a string or a List).
1588 */
1589 static void *
1590call_user_expand_func(
1591 void *(*user_expand_func)(char_u *, int, typval_T *),
1592 expand_T *xp,
1593 int *num_file,
1594 char_u ***file)
1595{
1596 cmdline_info_T *ccline = get_cmdline_info();
1597 int keep = 0;
1598 typval_T args[4];
1599 sctx_T save_current_sctx = current_sctx;
1600 char_u *pat = NULL;
1601 void *ret;
1602
1603 if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL)
1604 return NULL;
1605 *num_file = 0;
1606 *file = NULL;
1607
1608 if (ccline->cmdbuff != NULL)
1609 {
1610 keep = ccline->cmdbuff[ccline->cmdlen];
1611 ccline->cmdbuff[ccline->cmdlen] = 0;
1612 }
1613
1614 pat = vim_strnsave(xp->xp_pattern, xp->xp_pattern_len);
1615
1616 args[0].v_type = VAR_STRING;
1617 args[0].vval.v_string = pat;
1618 args[1].v_type = VAR_STRING;
1619 args[1].vval.v_string = xp->xp_line;
1620 args[2].v_type = VAR_NUMBER;
1621 args[2].vval.v_number = xp->xp_col;
1622 args[3].v_type = VAR_UNKNOWN;
1623
1624 current_sctx = xp->xp_script_ctx;
1625
1626 ret = user_expand_func(xp->xp_arg, 3, args);
1627
1628 current_sctx = save_current_sctx;
1629 if (ccline->cmdbuff != NULL)
1630 ccline->cmdbuff[ccline->cmdlen] = keep;
1631
1632 vim_free(pat);
1633 return ret;
1634}
1635
1636/*
1637 * Expand names with a function defined by the user.
1638 */
1639 static int
1640ExpandUserDefined(
1641 expand_T *xp,
1642 regmatch_T *regmatch,
1643 int *num_file,
1644 char_u ***file)
1645{
1646 char_u *retstr;
1647 char_u *s;
1648 char_u *e;
1649 int keep;
1650 garray_T ga;
1651 int skip;
1652
1653 retstr = call_user_expand_func(call_func_retstr, xp, num_file, file);
1654 if (retstr == NULL)
1655 return FAIL;
1656
1657 ga_init2(&ga, (int)sizeof(char *), 3);
1658 for (s = retstr; *s != NUL; s = e)
1659 {
1660 e = vim_strchr(s, '\n');
1661 if (e == NULL)
1662 e = s + STRLEN(s);
1663 keep = *e;
1664 *e = NUL;
1665
1666 skip = xp->xp_pattern[0] && vim_regexec(regmatch, s, (colnr_T)0) == 0;
1667 *e = keep;
1668
1669 if (!skip)
1670 {
1671 if (ga_grow(&ga, 1) == FAIL)
1672 break;
1673 ((char_u **)ga.ga_data)[ga.ga_len] = vim_strnsave(s, (int)(e - s));
1674 ++ga.ga_len;
1675 }
1676
1677 if (*e != NUL)
1678 ++e;
1679 }
1680 vim_free(retstr);
1681 *file = ga.ga_data;
1682 *num_file = ga.ga_len;
1683 return OK;
1684}
1685
1686/*
1687 * Expand names with a list returned by a function defined by the user.
1688 */
1689 static int
1690ExpandUserList(
1691 expand_T *xp,
1692 int *num_file,
1693 char_u ***file)
1694{
1695 list_T *retlist;
1696 listitem_T *li;
1697 garray_T ga;
1698
1699 retlist = call_user_expand_func(call_func_retlist, xp, num_file, file);
1700 if (retlist == NULL)
1701 return FAIL;
1702
1703 ga_init2(&ga, (int)sizeof(char *), 3);
1704 // Loop over the items in the list.
1705 for (li = retlist->lv_first; li != NULL; li = li->li_next)
1706 {
1707 if (li->li_tv.v_type != VAR_STRING || li->li_tv.vval.v_string == NULL)
1708 continue; // Skip non-string items and empty strings
1709
1710 if (ga_grow(&ga, 1) == FAIL)
1711 break;
1712
1713 ((char_u **)ga.ga_data)[ga.ga_len] =
1714 vim_strsave(li->li_tv.vval.v_string);
1715 ++ga.ga_len;
1716 }
1717 list_unref(retlist);
1718
1719 *file = ga.ga_data;
1720 *num_file = ga.ga_len;
1721 return OK;
1722}
1723# endif
1724
1725/*
1726 * Expand color scheme, compiler or filetype names.
1727 * Search from 'runtimepath':
1728 * 'runtimepath'/{dirnames}/{pat}.vim
1729 * When "flags" has DIP_START: search also from 'start' of 'packpath':
1730 * 'packpath'/pack/ * /start/ * /{dirnames}/{pat}.vim
1731 * When "flags" has DIP_OPT: search also from 'opt' of 'packpath':
1732 * 'packpath'/pack/ * /opt/ * /{dirnames}/{pat}.vim
1733 * "dirnames" is an array with one or more directory names.
1734 */
1735 static int
1736ExpandRTDir(
1737 char_u *pat,
1738 int flags,
1739 int *num_file,
1740 char_u ***file,
1741 char *dirnames[])
1742{
1743 char_u *s;
1744 char_u *e;
1745 char_u *match;
1746 garray_T ga;
1747 int i;
1748 int pat_len;
1749
1750 *num_file = 0;
1751 *file = NULL;
1752 pat_len = (int)STRLEN(pat);
1753 ga_init2(&ga, (int)sizeof(char *), 10);
1754
1755 for (i = 0; dirnames[i] != NULL; ++i)
1756 {
1757 s = alloc(STRLEN(dirnames[i]) + pat_len + 7);
1758 if (s == NULL)
1759 {
1760 ga_clear_strings(&ga);
1761 return FAIL;
1762 }
1763 sprintf((char *)s, "%s/%s*.vim", dirnames[i], pat);
1764 globpath(p_rtp, s, &ga, 0);
1765 vim_free(s);
1766 }
1767
1768 if (flags & DIP_START) {
1769 for (i = 0; dirnames[i] != NULL; ++i)
1770 {
1771 s = alloc(STRLEN(dirnames[i]) + pat_len + 22);
1772 if (s == NULL)
1773 {
1774 ga_clear_strings(&ga);
1775 return FAIL;
1776 }
1777 sprintf((char *)s, "pack/*/start/*/%s/%s*.vim", dirnames[i], pat);
1778 globpath(p_pp, s, &ga, 0);
1779 vim_free(s);
1780 }
1781 }
1782
1783 if (flags & DIP_OPT) {
1784 for (i = 0; dirnames[i] != NULL; ++i)
1785 {
1786 s = alloc(STRLEN(dirnames[i]) + pat_len + 20);
1787 if (s == NULL)
1788 {
1789 ga_clear_strings(&ga);
1790 return FAIL;
1791 }
1792 sprintf((char *)s, "pack/*/opt/*/%s/%s*.vim", dirnames[i], pat);
1793 globpath(p_pp, s, &ga, 0);
1794 vim_free(s);
1795 }
1796 }
1797
1798 for (i = 0; i < ga.ga_len; ++i)
1799 {
1800 match = ((char_u **)ga.ga_data)[i];
1801 s = match;
1802 e = s + STRLEN(s);
1803 if (e - 4 > s && STRNICMP(e - 4, ".vim", 4) == 0)
1804 {
1805 e -= 4;
1806 for (s = e; s > match; MB_PTR_BACK(match, s))
1807 if (s < match || vim_ispathsep(*s))
1808 break;
1809 ++s;
1810 *e = NUL;
1811 mch_memmove(match, s, e - s + 1);
1812 }
1813 }
1814
1815 if (ga.ga_len == 0)
1816 return FAIL;
1817
1818 // Sort and remove duplicates which can happen when specifying multiple
1819 // directories in dirnames.
1820 remove_duplicates(&ga);
1821
1822 *file = ga.ga_data;
1823 *num_file = ga.ga_len;
1824 return OK;
1825}
1826
1827/*
1828 * Expand loadplugin names:
1829 * 'packpath'/pack/ * /opt/{pat}
1830 */
1831 static int
1832ExpandPackAddDir(
1833 char_u *pat,
1834 int *num_file,
1835 char_u ***file)
1836{
1837 char_u *s;
1838 char_u *e;
1839 char_u *match;
1840 garray_T ga;
1841 int i;
1842 int pat_len;
1843
1844 *num_file = 0;
1845 *file = NULL;
1846 pat_len = (int)STRLEN(pat);
1847 ga_init2(&ga, (int)sizeof(char *), 10);
1848
1849 s = alloc(pat_len + 26);
1850 if (s == NULL)
1851 {
1852 ga_clear_strings(&ga);
1853 return FAIL;
1854 }
1855 sprintf((char *)s, "pack/*/opt/%s*", pat);
1856 globpath(p_pp, s, &ga, 0);
1857 vim_free(s);
1858
1859 for (i = 0; i < ga.ga_len; ++i)
1860 {
1861 match = ((char_u **)ga.ga_data)[i];
1862 s = gettail(match);
1863 e = s + STRLEN(s);
1864 mch_memmove(match, s, e - s + 1);
1865 }
1866
1867 if (ga.ga_len == 0)
1868 return FAIL;
1869
1870 // Sort and remove duplicates which can happen when specifying multiple
1871 // directories in dirnames.
1872 remove_duplicates(&ga);
1873
1874 *file = ga.ga_data;
1875 *num_file = ga.ga_len;
1876 return OK;
1877}
Bram Moolenaar66b51422019-08-18 21:44:12 +02001878
Bram Moolenaar66b51422019-08-18 21:44:12 +02001879/*
1880 * Expand "file" for all comma-separated directories in "path".
1881 * Adds the matches to "ga". Caller must init "ga".
1882 */
1883 void
1884globpath(
1885 char_u *path,
1886 char_u *file,
1887 garray_T *ga,
1888 int expand_options)
1889{
1890 expand_T xpc;
1891 char_u *buf;
1892 int i;
1893 int num_p;
1894 char_u **p;
1895
1896 buf = alloc(MAXPATHL);
1897 if (buf == NULL)
1898 return;
1899
1900 ExpandInit(&xpc);
1901 xpc.xp_context = EXPAND_FILES;
1902
1903 // Loop over all entries in {path}.
1904 while (*path != NUL)
1905 {
1906 // Copy one item of the path to buf[] and concatenate the file name.
1907 copy_option_part(&path, buf, MAXPATHL, ",");
1908 if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL)
1909 {
1910# if defined(MSWIN)
1911 // Using the platform's path separator (\) makes vim incorrectly
1912 // treat it as an escape character, use '/' instead.
1913 if (*buf != NUL && !after_pathsep(buf, buf + STRLEN(buf)))
1914 STRCAT(buf, "/");
1915# else
1916 add_pathsep(buf);
1917# endif
1918 STRCAT(buf, file);
1919 if (ExpandFromContext(&xpc, buf, &num_p, &p,
1920 WILD_SILENT|expand_options) != FAIL && num_p > 0)
1921 {
1922 ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT|expand_options);
1923
1924 if (ga_grow(ga, num_p) == OK)
1925 {
1926 for (i = 0; i < num_p; ++i)
1927 {
1928 ((char_u **)ga->ga_data)[ga->ga_len] =
1929 vim_strnsave(p[i], (int)STRLEN(p[i]));
1930 ++ga->ga_len;
1931 }
1932 }
1933
1934 FreeWild(num_p, p);
1935 }
1936 }
1937 }
1938
1939 vim_free(buf);
1940}
Bram Moolenaar66b51422019-08-18 21:44:12 +02001941
Bram Moolenaar0a52df52019-08-18 22:26:31 +02001942#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar66b51422019-08-18 21:44:12 +02001943/*
1944 * "getcompletion()" function
1945 */
1946 void
1947f_getcompletion(typval_T *argvars, typval_T *rettv)
1948{
1949 char_u *pat;
1950 expand_T xpc;
1951 int filtered = FALSE;
1952 int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH
1953 | WILD_NO_BEEP;
1954
1955 if (argvars[2].v_type != VAR_UNKNOWN)
1956 filtered = tv_get_number_chk(&argvars[2], NULL);
1957
1958 if (p_wic)
1959 options |= WILD_ICASE;
1960
1961 // For filtered results, 'wildignore' is used
1962 if (!filtered)
1963 options |= WILD_KEEP_ALL;
1964
1965 ExpandInit(&xpc);
1966 xpc.xp_pattern = tv_get_string(&argvars[0]);
1967 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1968 xpc.xp_context = cmdcomplete_str_to_type(tv_get_string(&argvars[1]));
1969 if (xpc.xp_context == EXPAND_NOTHING)
1970 {
1971 if (argvars[1].v_type == VAR_STRING)
1972 semsg(_(e_invarg2), argvars[1].vval.v_string);
1973 else
1974 emsg(_(e_invarg));
1975 return;
1976 }
1977
1978# if defined(FEAT_MENU)
1979 if (xpc.xp_context == EXPAND_MENUS)
1980 {
1981 set_context_in_menu_cmd(&xpc, (char_u *)"menu", xpc.xp_pattern, FALSE);
1982 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1983 }
1984# endif
1985# ifdef FEAT_CSCOPE
1986 if (xpc.xp_context == EXPAND_CSCOPE)
1987 {
1988 set_context_in_cscope_cmd(&xpc, xpc.xp_pattern, CMD_cscope);
1989 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1990 }
1991# endif
1992# ifdef FEAT_SIGNS
1993 if (xpc.xp_context == EXPAND_SIGN)
1994 {
1995 set_context_in_sign_cmd(&xpc, xpc.xp_pattern);
1996 xpc.xp_pattern_len = (int)STRLEN(xpc.xp_pattern);
1997 }
1998# endif
1999
2000 pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context);
2001 if ((rettv_list_alloc(rettv) != FAIL) && (pat != NULL))
2002 {
2003 int i;
2004
2005 ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP);
2006
2007 for (i = 0; i < xpc.xp_numfiles; i++)
2008 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
2009 }
2010 vim_free(pat);
2011 ExpandCleanup(&xpc);
2012}
Bram Moolenaar0a52df52019-08-18 22:26:31 +02002013#endif // FEAT_EVAL