robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
70.7 KiB2417 linesraw
1#include <assert.h>
2#include <limits.h>
3#include <stdbool.h>
4#include <stddef.h>
5#include <stdint.h>
6#include <stdlib.h>
7#include <string.h>
8#ifdef MSWIN
9# include <direct.h>
10#endif
11
12#include "auto/config.h"
13#include "nvim/ascii_defs.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/charset.h"
16#include "nvim/cmdexpand.h"
17#include "nvim/eval.h"
18#include "nvim/ex_docmd.h"
19#include "nvim/fileio.h"
20#include "nvim/garray.h"
21#include "nvim/globals.h"
22#include "nvim/macros_defs.h"
23#include "nvim/mbyte.h"
24#include "nvim/memory.h"
25#include "nvim/option.h"
26#include "nvim/option_vars.h"
27#include "nvim/os/fs.h"
28#include "nvim/os/fs_defs.h"
29#include "nvim/os/input.h"
30#include "nvim/os/os.h"
31#include "nvim/os/os_defs.h"
32#include "nvim/os/shell.h"
33#include "nvim/path.h"
34#include "nvim/regexp.h"
35#include "nvim/regexp_defs.h"
36#include "nvim/strings.h"
37#include "nvim/vim_defs.h"
38
39enum {
40  URL_SLASH = 1,      // path_is_url() has found ":/"
41  URL_BACKSLASH = 2,  // path_is_url() has found ":\\"
42};
43
44#ifdef gen_expand_wildcards
45# undef gen_expand_wildcards
46#endif
47
48#include "path.c.generated.h"
49
50/// Checks whether two paths refer to the same file.
51///
52/// @param s1 First path. Environment variables in this path may be expanded.
53/// @param s2 Second path.
54/// @param flags Path comparison Flags.
55/// @return true if the paths are equal.
56bool path_equal(const char *s1, const char *s2, PathCmpFlags flags)
57  FUNC_ATTR_NONNULL_ALL
58{
59  char expanded_s1[MAXPATHL];
60  char full1[MAXPATHL];
61  char full2[MAXPATHL];
62  FileID file_id1, file_id2;
63
64  assert(!(flags & kPathCmpLiteral) || flags == kPathCmpLiteral);
65
66  if (flags == kPathCmpLiteral) {
67    const bool is_url = path_with_url(s1) || path_with_url(s2);
68    // URI comparison is scheme-agnostic, so a trailing slash is significant.
69    return (!is_url || strlen(s1) == strlen(s2))
70           && path_cmp(p_fic, s1, s2, MAXPATHL) == 0;
71  }
72
73  if (flags & kPathCmpExpand) {
74    expand_env_esc(s1, expanded_s1, MAXPATHL, NULL, false, NULL);
75  } else if (flags) {
76    xstrlcpy(expanded_s1, s1, MAXPATHL);
77  }
78
79  bool id_ok1 = os_fileid(expanded_s1, &file_id1);
80  bool id_ok2 = os_fileid(s2, &file_id2);
81  if (id_ok1 && id_ok2 && os_fileid_equal(&file_id1, &file_id2)) {
82    return true;
83  }
84  if (!id_ok1 && !id_ok2 && (flags & kPathCmpFull)) {
85    vim_FullName(expanded_s1, full1, MAXPATHL, false);
86    vim_FullName(s2, full2, MAXPATHL, false);
87    return path_cmp(p_fic, full1, full2, MAXPATHL) == 0;
88  }
89  return false;
90}
91
92/// Gets the tail (filename segment) of path `fname`.
93///
94/// Examples:
95/// - "dir/file.txt" => "file.txt"
96/// - "file.txt" => "file.txt"
97/// - "dir/" => ""
98///
99/// @return pointer just past the last path separator (empty string, if fname
100///         ends in a slash), or empty string if fname is NULL.
101char *path_tail(const char *fname)
102  FUNC_ATTR_NONNULL_RET
103{
104  if (fname == NULL) {
105    return "";
106  }
107
108  const char *tail = get_past_head(fname);
109  // Find last part of path.
110  for (const char *p = tail; *p != NUL; p++) {
111    if (vim_ispathsep_nocolon(*p)) {
112      tail = p + 1;
113    }
114  }
115  return (char *)tail;
116}
117
118/// Get pointer to tail of "fname", including path separators.
119///
120/// Takes care of "c:/" and "//". That means `path_tail_with_sep("dir///file.txt")`
121/// will return a pointer to `"///file.txt"`.
122/// @param fname A file path. (Must be != NULL.)
123/// @return
124///   - Pointer to the last path separator of `fname`, if there is any.
125///   - `fname` if it contains no path separator.
126///   - Never NULL.
127char *path_tail_with_sep(char *fname)
128  FUNC_ATTR_NONNULL_ALL
129{
130  // Don't remove the '/' from "c:/file".
131  char *past_head = get_past_head(fname);
132  char *tail = path_tail(fname);
133  while (tail > past_head && after_pathsep(fname, tail)) {
134    tail--;
135  }
136  return tail;
137}
138
139/// Finds the executable name (path tail) in a program invocation.
140///
141/// The invocation starts with an executable path, optionally followed
142/// by arguments.
143///
144/// Parsing rules:
145/// - A space outside double quotes ends the executable path.
146/// - Within quoted segments, a backslash skips the following character.
147///   Note: on Windows, `\` is treated firstly as a path separator. In
148///   practice, this rule should be rarely needed anyway.
149///
150/// Examples:
151/// - "path/foo/bash --login" => "bash"
152/// - "path/foo bar/bash --login" => "foo"
153/// - "\"path/foo bar/bash\" --login" => "bash"
154/// - "\"path/foo\\\" bar/bash\" --login" => "bash"
155///
156/// @param[in]  invocation Program invocation of the form: "path/to/exe [args]".
157/// @param[out] len Stores the length of the executable name, if not NULL.
158///
159/// @return The position of the last path separator + 1.
160const char *invocation_path_tail(const char *invocation, size_t *len)
161  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1)
162{
163  const char *tail = get_past_head(invocation);
164  const char *tail_end = tail;
165  const char *p = tail;
166  bool inquote = false;
167  while (*p != NUL && (inquote || *p != ' ')) {
168    int l = utfc_ptr2len(p);
169    if (vim_ispathsep_nocolon(*p)) {
170      tail = p + 1;  // Now tail points one past the separator.
171      tail_end = tail;
172    } else if (*p == '\\' && inquote) {
173      p++;
174    } else if (*p == '"') {
175      inquote ^= 1;
176    } else {
177      tail_end = p + l;
178    }
179    p += l;
180  }
181
182  if (len != NULL) {
183    *len = (size_t)(tail_end - tail);
184  }
185
186  return tail;
187}
188
189/// Get the next separator-delimited component of a path name.
190///
191/// @param fname A file path. (Must be != NULL.)
192/// @return Pointer to first found path separator + 1.
193/// An empty string, if `fname` doesn't contain a path separator,
194const char *path_next_component(const char *fname)
195  FUNC_ATTR_NONNULL_ALL
196{
197  while (*fname != NUL && !vim_ispathsep(*fname)) {
198    fname++;
199  }
200  if (*fname != NUL) {
201    fname++;
202  }
203  return fname;
204}
205
206/// Advances past consecutive path separators.
207///
208/// @param path   Position in a path.
209/// @param colon  Whether ':' counts as a separator on MS-Windows (see vim_ispathsep()).
210/// @return  Pointer to the first non-separator byte (or terminating NUL).
211char *path_skip_sep(const char *path, bool colon)
212  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_PURE
213{
214  while (colon ? vim_ispathsep(*path) : vim_ispathsep_nocolon(*path)) {
215    path++;
216  }
217  return (char *)path;
218}
219
220/// Returns the length of the path head on the current platform.
221/// @return
222///   - 3 on windows
223///   - 1 otherwise
224int path_head_length(void)
225{
226#ifdef MSWIN
227  return 3;
228#else
229  return 1;
230#endif
231}
232
233/// Returns true if path begins with characters denoting the head of a path
234/// (e.g. '/' on linux and 'D:' on windows).
235/// @param path The path to be checked.
236/// @return
237///   - True if path begins with a path head
238///   - False otherwise
239bool is_path_head(const char *path)
240  FUNC_ATTR_NONNULL_ALL
241{
242#ifdef MSWIN
243  return isalpha((uint8_t)path[0]) && path[1] == ':';
244#else
245  return vim_ispathsep(*path);
246#endif
247}
248
249/// Get a pointer to one character past the head of a path name.
250/// Unix: after "/"; Win: after "c:\"
251/// If there is no head, path is returned.
252char *get_past_head(const char *path)
253  FUNC_ATTR_NONNULL_ALL
254{
255  const char *retval = path;
256
257#ifdef MSWIN
258  // May skip "c:"
259  if (is_path_head(path)) {
260    retval = path + 2;
261  }
262#endif
263
264  retval = path_skip_sep(retval, true);
265
266  return (char *)retval;
267}
268
269/// @return true if 'c' is a path separator.
270/// Note that for MS-Windows this includes the colon.
271bool vim_ispathsep(int c)
272{
273#ifdef UNIX
274  return c == '/';          // Unix has ':' inside file names
275#else
276# ifdef BACKSLASH_IN_FILENAME
277  return c == ':' || c == '/' || c == '\\';
278# else
279  return c == ':' || c == '/';
280# endif
281#endif
282}
283
284// Like vim_ispathsep(c), but exclude the colon for MS-Windows.
285bool vim_ispathsep_nocolon(int c)
286{
287  return vim_ispathsep(c)
288#ifdef BACKSLASH_IN_FILENAME
289         && c != ':'
290#endif
291  ;
292}
293
294/// @return true if 'c' is a path list separator.
295bool vim_ispathlistsep(int c)
296{
297#ifdef UNIX
298  return c == ':';
299#else
300  return c == ';';      // might not be right for every system...
301#endif
302}
303
304/// Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
305/// "trim_len" specifies how many characters to keep for each directory.
306/// Must be 1 or more.
307/// It's done in-place.
308void shorten_dir_len(char *str, int trim_len)
309  FUNC_ATTR_NONNULL_ALL
310{
311  char *tail = path_tail(str);
312  char *d = str;
313  bool skip = false;
314  int dirchunk_len = 0;
315  for (char *s = str;; s++) {
316    if (s >= tail) {                // copy the whole tail
317      *d++ = *s;
318      if (*s == NUL) {
319        break;
320      }
321    } else if (vim_ispathsep(*s)) {       // copy '/' and next char
322      *d++ = *s;
323      skip = false;
324      dirchunk_len = 0;
325    } else if (!skip) {
326      *d++ = *s;                     // copy next char
327      if (*s != '~' && *s != '.') {  // and leading "~" and "."
328        dirchunk_len++;  // only count word chars for the size
329        // keep copying chars until we have our preferred length (or
330        // until the above if/else branches move us along)
331        if (dirchunk_len >= trim_len) {
332          skip = true;
333        }
334      }
335      int l = utfc_ptr2len(s);
336      while (--l > 0) {
337        *d++ = *++s;
338      }
339    }
340  }
341}
342
343/// Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
344/// It's done in-place.
345void shorten_dir(char *str)
346  FUNC_ATTR_NONNULL_ALL
347{
348  shorten_dir_len(str, 1);
349}
350
351/// Return true if the directory of "fname" exists, false otherwise.
352/// Also returns true if there is no directory name.
353/// "fname" must be writable!.
354bool dir_of_file_exists(char *fname)
355  FUNC_ATTR_NONNULL_ALL
356{
357  char *p = path_tail_with_sep(fname);
358  if (p == fname) {
359    return true;
360  }
361  char c = *p;
362  *p = NUL;
363  bool retval = os_isdir(fname);
364  *p = c;
365  return retval;
366}
367
368/// Append fname2 to fname1
369///
370/// @param[in]  fname1  First fname to append to.
371/// @param[in]  len1    Length of fname1.
372/// @param[in]  fname2  Second part of the file name.
373/// @param[in]  len2    Length of fname2.
374/// @param[in]  sep     If true and fname1 does not end with a path separator,
375///                     add a path separator before fname2.
376///
377/// @return fname1
378static inline char *do_concat_fnames(char *fname1, const size_t len1, const char *fname2,
379                                     const size_t len2, const bool sep, size_t *len)
380  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
381{
382  if (sep && *fname1 && !after_pathsep(fname1, fname1 + len1)) {
383    fname1[len1] = PATHSEP;
384    memmove(fname1 + len1 + 1, fname2, len2 + 1);
385    *len = len1 + 1 + len2;
386  } else {
387    memmove(fname1 + len1, fname2, len2 + 1);
388    *len = len1 + len2;
389  }
390
391  return fname1;
392}
393
394/// Concatenate file names fname1 and fname2 into allocated memory.
395///
396/// Only add a '/' or '\\' when 'sep' is true and it is necessary.
397///
398/// @param fname1 is the first part of the path or filename
399/// @param fname2 is the second half of the path or filename
400/// @param sep    is a flag to indicate a path separator should be added
401///               if necessary
402/// @return [allocated] Concatenation of fname1 and fname2.
403String concat_fnames(String fname1, String fname2, bool sep)
404  FUNC_ATTR_NONNULL_ALL
405{
406  String ret;
407  ret.data = xmalloc(fname1.size + (sep ? 1 : 0) + fname2.size + 1);
408  memmove(ret.data, fname1.data, fname1.size + 1);
409  do_concat_fnames(ret.data, fname1.size, fname2.data, fname2.size, sep, &ret.size);
410  return ret;
411}
412
413/// Concatenate file names fname1 and fname2
414///
415/// Like concat_fnames(), but in place of allocating new memory it reallocates
416/// fname1. For this reason fname1 must be allocated with xmalloc, and can no
417/// longer be used after running concat_fnames_realloc.
418///
419/// @param fname1 is the first part of the path or filename
420/// @param fname2 is the second half of the path or filename
421/// @param sep    is a flag to indicate a path separator should be added
422///               if necessary
423/// @return [allocated] Concatenation of fname1 and fname2.
424char *concat_fnames_realloc(char *fname1, const char *fname2, bool sep)
425  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
426{
427  const size_t len1 = strlen(fname1);
428  const size_t len2 = strlen(fname2);
429  size_t len;
430  return do_concat_fnames(xrealloc(fname1, len1 + len2 + 3), len1,
431                          fname2, len2, sep, &len);
432}
433
434/// Adds a path separator to a filename, unless it already ends in one.
435///
436/// @return `true` if the path separator was added or already existed.
437///         `false` if the filename is too long.
438bool add_pathsep(char *p)
439  FUNC_ATTR_NONNULL_ALL
440{
441  if (*p == NUL) {
442    return true;
443  }
444
445  const size_t plen = strlen(p);
446  if (!after_pathsep(p, p + plen)) {
447    const size_t pathsep_len = sizeof(PATHSEPSTR);
448    if (plen > MAXPATHL - pathsep_len) {
449      return false;
450    }
451    memcpy(p + plen, PATHSEPSTR, pathsep_len);
452  }
453  return true;
454}
455
456/// Get an allocated copy of the full path to a file.
457///
458/// @param fname is the filename to save
459/// @param force is a flag to expand `fname` even if it looks absolute
460///
461/// @return [allocated] Copy of absolute path to `fname` or NULL when
462///                     `fname` is NULL.
463char *FullName_save(const char *fname, bool force)
464  FUNC_ATTR_MALLOC
465{
466  if (fname == NULL) {
467    return NULL;
468  }
469
470  char *buf = xmalloc(MAXPATHL);
471  if (vim_FullName(fname, buf, MAXPATHL, force) == FAIL) {
472    xfree(buf);
473    return TO_SLASH_SAVE(fname);
474  }
475  return buf;
476}
477
478/// Saves the absolute path.
479/// @param name An absolute or relative path.
480/// @return The absolute path of `name`.
481char *save_abs_path(const char *name)
482  FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
483{
484  if (!path_is_absolute(name)) {
485    return FullName_save(name, true);
486  }
487  return TO_SLASH_SAVE(name);
488}
489
490/// Checks if a path has an unescaped wildcard requiring expansion (path_expand).
491/// @param p The path to expand.
492/// @param all Also detect chars requiring special handling:
493///            - "`": backtick expansion
494///            - "'": shell quoting (Only Unix)
495///            - "$": environment variable expansion
496///            - "~": home directory expansion (historically treated as a wildcard
497///                   unless at the end)
498/// @return True if it has an unescaped wildcard
499bool path_has_wildcard(const char *p, bool all)
500  FUNC_ATTR_NONNULL_ALL
501{
502  char *wildcards = all ? PATH_ALL_WILDCARDS : PATH_ESC_WILDCARDS;
503  for (; *p; p++) {
504#ifdef UNIX
505    if (p[0] == '\\' && p[1] != NUL) {
506      p++;
507      continue;
508    }
509#endif
510    if (vim_strchr(wildcards, (uint8_t)(*p)) != NULL
511        || (all && p[0] == '~' && p[1] != NUL)) {
512      return true;
513    }
514  }
515  return false;
516}
517
518static int pstrcmp(const void *a, const void *b)
519{
520  return path_cmp(p_fic, *(char **)a, *(char **)b, MAXPATHL);
521}
522
523/// Recursively expands one path component into all matching files and/or
524/// directories. Handles "*", "?", "[a-z]", "**", etc.
525/// @remark "**" in `path` requests recursive expansion.
526///
527/// @param[out] gap  The matches found.
528/// @param path     The path to search.
529/// @param flags    Flags for regexp expansion.
530///   - EW_ICASE: Ignore case.
531///   - EW_NOERROR: Silence error messages.
532///   - EW_NOTWILD: Add matches literally.
533/// @returns the number of matches found.
534static size_t path_expand(garray_T *gap, const char *path, int flags)
535  FUNC_ATTR_NONNULL_ALL
536{
537  return do_path_expand(gap, path, 0, flags, false);
538}
539
540static const char *scandir_next_with_dots(Directory *dir)
541{
542  static int count = 0;
543  if (dir == NULL) {  // initialize
544    count = 0;
545    return NULL;
546  }
547
548  count += 1;
549  if (count == 1 || count == 2) {
550    return (count == 1) ? "." : "..";
551  }
552  return os_scandir_next(dir);
553}
554
555/// Implementation of path_expand().
556///
557/// Chars before `path + wildoff` do not get expanded.
558static size_t do_path_expand(garray_T *gap, const char *path, size_t wildoff, int flags,
559                             bool didstar)
560  FUNC_ATTR_NONNULL_ALL
561{
562  int start_len = gap->ga_len;
563  bool starstar = false;
564  static int stardepth = 0;  // depth for "**" expansion
565
566  // Expanding "**" may take a long time, check for CTRL-C.
567  if (stardepth > 0 && !(flags & EW_NOBREAK)) {
568    os_breakcheck();
569    if (got_int) {
570      return 0;
571    }
572  }
573
574  // Make room for file name (a bit too much to stay on the safe side).
575  const size_t buflen = strlen(path) + MAXPATHL;
576  char *buf = xmalloc(buflen);
577
578  // Find the first part in the path name that contains a wildcard.
579  // When EW_ICASE is set every letter is considered to be a wildcard.
580  // Copy it into "buf", including the preceding characters.
581  char *p = buf;
582  char *s = buf;
583  char *e = NULL;
584  const char *path_end = path;
585  while (*path_end != NUL) {
586    // May ignore a wildcard that has a backslash before it; it will
587    // be removed by rem_backslash() or file_pat_to_reg_pat() below.
588    if (path_end >= path + wildoff && rem_backslash(path_end)) {
589      *p++ = *path_end++;
590    } else if (vim_ispathsep_nocolon(*path_end)) {
591      if (e != NULL) {
592        break;
593      }
594      s = p + 1;
595    } else if (path_end >= path + wildoff
596               // "~" not included here, we want to treat it as literal.
597               // "~/", "~user/" and env expansion are already handled in `gen_expand_wildcards`.
598               && (vim_strchr(PATH_ESC_WILDCARDS, (uint8_t)(*path_end)) != NULL
599#ifndef MSWIN
600                   || (!p_fic && (flags & EW_ICASE) && mb_isalpha(utf_ptr2char(path_end)))
601#endif
602                   )
603               ) {
604      e = p;
605    }
606    int charlen = utfc_ptr2len(path_end);
607    memcpy(p, path_end, (size_t)charlen);
608    p += charlen;
609    path_end += charlen;
610  }
611  e = p;
612  *e = NUL;
613
614  // Now we have one wildcard component between "s" and "e".
615  // Remove backslashes between "wildoff" and the start of the wildcard
616  // component.
617  for (p = buf + wildoff; p < s; p++) {
618    if (rem_backslash(p)) {
619      STRMOVE(p, p + 1);
620      e--;
621      s--;
622    }
623  }
624
625  // Check for "**" between "s" and "e".
626  for (p = s; p < e; p++) {
627    if (p[0] == '*' && p[1] == '*') {
628      starstar = true;
629    }
630  }
631
632  // convert the file pattern to a regexp pattern
633  int starts_with_dot = *s == '.';
634  char *pat = file_pat_to_reg_pat(s, e, NULL, false);
635  if (pat == NULL) {
636    xfree(buf);
637    return 0;
638  }
639
640  // compile the regexp into a program
641  regmatch_T regmatch;
642#ifdef UNIX
643  // Ignore case if given 'wildignorecase', else respect 'fileignorecase'.
644  regmatch.rm_ic = (flags & EW_ICASE) || p_fic;
645#else
646  regmatch.rm_ic = true;  // Always ignore case on Windows.
647#endif
648  if (flags & (EW_NOERROR | EW_NOTWILD)) {
649    emsg_silent++;
650  }
651  bool nobreak = (flags & EW_NOBREAK);
652  regmatch.regprog = vim_regcomp(pat, RE_MAGIC | (nobreak ? RE_NOBREAK : 0));
653  if (flags & (EW_NOERROR | EW_NOTWILD)) {
654    emsg_silent--;
655  }
656  xfree(pat);
657
658  if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0) {
659    xfree(buf);
660    return 0;
661  }
662
663  size_t len = (size_t)(s - buf);
664  // If "**" is by itself, this is the first time we encounter it and more
665  // is following then find matches without any directory.
666  if (!didstar && stardepth < 100 && starstar && e - s == 2
667      && *path_end == '/') {
668    vim_snprintf(s, buflen - len, "%s", path_end + 1);
669    stardepth++;
670    do_path_expand(gap, buf, len, flags, true);
671    stardepth--;
672  }
673  *s = NUL;
674
675  Directory dir;
676  char *dirpath = (*buf == NUL ? "." : buf);
677  if (os_file_is_readable(dirpath) && os_scandir(&dir, dirpath)) {
678    // Find all matching entries.
679    const char *name;
680    scandir_next_with_dots(NULL);  // initialize
681    while (!got_int && (name = scandir_next_with_dots(&dir)) != NULL) {
682      len = (size_t)(s - buf);
683      if ((name[0] != '.'
684           || starts_with_dot
685           || ((flags & EW_DODOT)
686               && name[1] != NUL
687               && (name[1] != '.' || name[2] != NUL)))
688          && ((regmatch.regprog != NULL && vim_regexec(&regmatch, name, 0))
689              || ((flags & EW_NOTWILD)
690                  && path_cmp(p_fic, path + len, name, (size_t)(e - s)) == 0))) {
691        len += (size_t)vim_snprintf(s, buflen - len, "%s", name);
692        if (len + 1 >= buflen) {
693          continue;
694        }
695
696        if (starstar && stardepth < 100) {
697          // For "**" in the pattern first go deeper in the tree to
698          // find matches.
699          vim_snprintf(buf + len, buflen - len, "/**%s", path_end);  // NOLINT
700          stardepth++;
701          do_path_expand(gap, buf, len + 1, flags, true);
702          stardepth--;
703        }
704
705        vim_snprintf(buf + len, buflen - len, "%s", path_end);
706        if (path_has_wildcard(path_end, false)) {      // handle more wildcards
707          if (stardepth < 100) {
708            stardepth++;
709            // need to expand another component of the path
710            // remove backslashes for the remaining components only
711            do_path_expand(gap, buf, len + 1, flags, false);
712            stardepth--;
713          }
714        } else {
715          FileInfo file_info;
716
717          // no more wildcards, check if there is a match
718          // remove backslashes for the remaining components only
719          if (*path_end != NUL) {
720            backslash_halve(buf + len + 1);
721          }
722          // add existing file or symbolic link
723          if ((flags & EW_ALLLINKS)
724              ? os_fileinfo_link(buf, &file_info)
725              : os_path_exists(buf)) {
726            addfile(gap, buf, flags);
727          }
728        }
729      }
730    }
731    os_closedir(&dir);
732  }
733
734  xfree(buf);
735  vim_regfree(regmatch.regprog);
736
737  // When interrupted the matches probably won't be used and sorting can be
738  // slow, thus skip it.
739  size_t matches = (size_t)(gap->ga_len - start_len);
740  if (matches > 0 && !got_int) {
741    qsort(((char **)gap->ga_data) + start_len, matches,
742          sizeof(char *), pstrcmp);
743  }
744  return matches;
745}
746
747// Moves "*psep" back to the previous path separator in "path".
748// Returns FAIL is "*psep" ends up at the beginning of "path".
749static int find_previous_pathsep(char *path, char **psep)
750  FUNC_ATTR_NONNULL_ALL
751{
752  // skip the current separator
753  if (*psep > path && vim_ispathsep(**psep)) {
754    (*psep)--;
755  }
756
757  // find the previous separator
758  while (*psep > path) {
759    if (vim_ispathsep(**psep)) {
760      return OK;
761    }
762    MB_PTR_BACK(path, *psep);
763  }
764
765  return FAIL;
766}
767
768/// Returns true if "maybe_unique" is unique wrt other_paths in "gap".
769/// "maybe_unique" is the end portion of "((char **)gap->ga_data)[i]".
770static bool is_unique(char *maybe_unique, garray_T *gap, int i)
771  FUNC_ATTR_NONNULL_ALL
772{
773  size_t candidate_len = strlen(maybe_unique);
774  char **other_paths = gap->ga_data;
775
776  for (int j = 0; j < gap->ga_len; j++) {
777    if (j == i) {
778      continue;  // don't compare it with itself
779    }
780    size_t other_path_len = strlen(other_paths[j]);
781    if (other_path_len < candidate_len) {
782      continue;  // it's different when it's shorter
783    }
784    char *rival = other_paths[j] + other_path_len - candidate_len;
785    if (path_equal(maybe_unique, rival, kPathCmpLiteral)
786        && (rival == other_paths[j] || vim_ispathsep(*(rival - 1)))) {
787      return false;  // match
788    }
789  }
790  return true;  // no match found
791}
792
793/// Split the 'path' option into an array of strings in garray_T.  Relative
794/// paths are expanded to their equivalent fullpath.  This includes the "."
795/// (relative to current buffer directory) and empty path (relative to current
796/// directory) notations.
797///
798/// @param path_option  p_path or p_cdpath
799///
800/// TODO(vim): handle upward search (;) and path limiter (**N) notations by
801/// expanding each into their equivalent path(s).
802static void expand_path_option(char *curdir, char *path_option, garray_T *gap)
803  FUNC_ATTR_NONNULL_ALL
804{
805  char *buf = xmalloc(MAXPATHL);
806  size_t curdirlen = 0;
807
808  while (*path_option != NUL) {
809    size_t buflen = copy_option_part(&path_option, buf, MAXPATHL, " ,");
810
811    // do not expand backticks, could have been set via a modeline
812    if (vim_strchr(buf, '`') != NULL) {
813      continue;
814    }
815
816    if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1]))) {
817      // Relative to current buffer:
818      // "/path/file" + "." -> "/path/"
819      // "/path/file"  + "./subdir" -> "/path/subdir"
820      if (curbuf->b_ffname == NULL) {
821        continue;
822      }
823      char *p = path_tail(curbuf->b_ffname);
824      size_t plen = (size_t)(p - curbuf->b_ffname);
825      if (plen + strlen(buf) >= MAXPATHL) {
826        continue;
827      }
828      if (buf[1] == NUL) {
829        buf[plen] = NUL;
830      } else {
831        memmove(buf + plen, buf + 2, (buflen - 2) + 1);  // +1 for NUL
832      }
833      memmove(buf, curbuf->b_ffname, plen);
834      buflen = simplify_filename(buf);
835    } else if (buf[0] == NUL) {
836      STRCPY(buf, curdir);  // relative to current directory
837      if (curdirlen == 0) {
838        curdirlen = strlen(curdir);
839      }
840      buflen = curdirlen;
841    } else if (path_with_url(buf)) {
842      continue;  // URL can't be used here
843    } else if (!path_is_absolute(buf)) {
844      // Expand relative path to their full path equivalent
845      if (curdirlen == 0) {
846        curdirlen = strlen(curdir);
847      }
848      if (curdirlen + buflen + 3 > MAXPATHL) {
849        continue;
850      }
851      memmove(buf + curdirlen + 1, buf, buflen + 1);  // +1 for NUL
852      STRCPY(buf, curdir);
853      buf[curdirlen] = PATHSEP;
854      buflen = simplify_filename(buf);
855    }
856
857    GA_APPEND(char *, gap, xmemdupz(buf, buflen));
858  }
859
860  xfree(buf);
861}
862
863// Returns a pointer to the file or directory name in "fname" that matches the
864// longest path in "ga"p, or NULL if there is no match. For example:
865//
866//    path: /foo/bar/baz
867//   fname: /foo/bar/baz/quux.txt
868// returns:              ^this
869static char *get_path_cutoff(char *fname, garray_T *gap)
870  FUNC_ATTR_NONNULL_ALL
871{
872  int maxlen = 0;
873  char **path_part = gap->ga_data;
874  char *cutoff = NULL;
875
876  for (int i = 0; i < gap->ga_len; i++) {
877    int j = 0;
878
879    while ((fname[j] == path_part[i][j]
880#ifdef MSWIN
881            || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
882#endif
883            )
884           && fname[j] != NUL && path_part[i][j] != NUL) {
885      j++;
886    }
887    if (j > maxlen) {
888      maxlen = j;
889      cutoff = &fname[j];
890    }
891  }
892
893  // skip to the file or directory name
894  if (cutoff != NULL) {
895    cutoff = path_skip_sep(cutoff, true);
896  }
897
898  return cutoff;
899}
900
901/// Sorts, removes duplicates and modifies all the fullpath names in "gap" so
902/// that they are unique with respect to each other while conserving the part
903/// that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
904///
905/// @param path_option  p_path or p_cdpath
906static void uniquefy_paths(garray_T *gap, char *pattern, char *path_option)
907  FUNC_ATTR_NONNULL_ALL
908{
909  char **fnames = gap->ga_data;
910  bool sort_again = false;
911  regmatch_T regmatch;
912  garray_T path_ga;
913  char **in_curdir = NULL;
914  char *short_name;
915
916  ga_remove_duplicate_strings(gap);
917  ga_init(&path_ga, (int)sizeof(char *), 1);
918
919  // We need to prepend a '*' at the beginning of file_pattern so that the
920  // regex matches anywhere in the path. FIXME: is this valid for all
921  // possible patterns?
922  size_t len = strlen(pattern);
923  char *file_pattern = xmalloc(len + 2);
924  file_pattern[0] = '*';
925  file_pattern[1] = NUL;
926  STRCPY(file_pattern + 1, pattern);
927  char *pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, false);
928  xfree(file_pattern);
929  if (pat == NULL) {
930    return;
931  }
932
933  regmatch.rm_ic = true;                // always ignore case
934  regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
935  xfree(pat);
936  if (regmatch.regprog == NULL) {
937    return;
938  }
939
940  char *curdir = xmalloc(MAXPATHL);
941  os_dirname(curdir, MAXPATHL);
942  expand_path_option(curdir, path_option, &path_ga);
943
944  in_curdir = xcalloc((size_t)gap->ga_len, sizeof(char *));
945
946  for (int i = 0; i < gap->ga_len && !got_int; i++) {
947    char *path = fnames[i];
948    const char *dir_end = gettail_dir(path);
949
950    len = strlen(path);
951    bool is_in_curdir = path_cmp(p_fic, curdir, path, (size_t)(dir_end - path)) == 0
952                        && curdir[dir_end - path] == NUL;
953    if (is_in_curdir) {
954      in_curdir[i] = xmemdupz(path, len);
955    }
956
957    // Shorten the filename while maintaining its uniqueness
958    char *path_cutoff = get_path_cutoff(path, &path_ga);
959
960    // Don't assume all files can be reached without path when search
961    // pattern starts with **/, so only remove path_cutoff
962    // when possible.
963    if (pattern[0] == '*' && pattern[1] == '*'
964        && vim_ispathsep_nocolon(pattern[2])
965        && path_cutoff != NULL
966        && vim_regexec(&regmatch, path_cutoff, 0)
967        && is_unique(path_cutoff, gap, i)) {
968      sort_again = true;
969      memmove(path, path_cutoff, strlen(path_cutoff) + 1);
970    } else {
971      // Here all files can be reached without path, so get shortest
972      // unique path.  We start at the end of the path.
973      char *pathsep_p = path + len - 1;
974      while (find_previous_pathsep(path, &pathsep_p)) {
975        if (vim_regexec(&regmatch, pathsep_p + 1, 0)
976            && is_unique(pathsep_p + 1, gap, i)
977            && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff) {
978          sort_again = true;
979          memmove(path, pathsep_p + 1,
980                  (size_t)((path + len) - (pathsep_p + 1)) + 1);  // +1 for NUL
981          break;
982        }
983      }
984    }
985
986    if (path_is_absolute(path)) {
987      // Last resort: shorten relative to curdir if possible.
988      // 'possible' means:
989      // 1. It is under the current directory.
990      // 2. The result is actually shorter than the original.
991      //
992      //     Before                curdir        After
993      //     /foo/bar/file.txt     /foo/bar      ./file.txt
994      //     c:\foo\bar\file.txt   c:\foo\bar    .\file.txt
995      //     /file.txt             /             /file.txt
996      //     c:\file.txt           c:\           .\file.txt
997      short_name = path_shorten_fname(path, curdir);
998      if (short_name != NULL && short_name > path + 1) {
999        vim_snprintf(path, MAXPATHL, ".%s%s", PATHSEPSTR, short_name);
1000      }
1001    }
1002    os_breakcheck();
1003  }
1004
1005  // Shorten filenames in /in/current/directory/{filename}
1006  for (int i = 0; i < gap->ga_len && !got_int; i++) {
1007    char *path = in_curdir[i];
1008
1009    if (path == NULL) {
1010      continue;
1011    }
1012
1013    // If the {filename} is not unique, change it to ./{filename}.
1014    // Else reduce it to {filename}
1015    short_name = path_shorten_fname(path, curdir);
1016    if (short_name == NULL) {
1017      short_name = path;
1018    }
1019    if (is_unique(short_name, gap, i)) {
1020      STRCPY(fnames[i], short_name);
1021      continue;
1022    }
1023
1024    size_t rel_pathsize = 1 + STRLEN_LITERAL(PATHSEPSTR) + strlen(short_name) + 1;
1025    char *rel_path = xmalloc(rel_pathsize);
1026
1027    vim_snprintf(rel_path, rel_pathsize, ".%s%s", PATHSEPSTR, short_name);
1028
1029    xfree(fnames[i]);
1030    fnames[i] = rel_path;
1031    sort_again = true;
1032    os_breakcheck();
1033  }
1034
1035  xfree(curdir);
1036  for (int i = 0; i < gap->ga_len; i++) {
1037    xfree(in_curdir[i]);
1038  }
1039  xfree(in_curdir);
1040  ga_clear_strings(&path_ga);
1041  vim_regfree(regmatch.regprog);
1042
1043  if (sort_again) {
1044    ga_remove_duplicate_strings(gap);
1045  }
1046}
1047
1048/// Find end of the directory name
1049///
1050/// @param[in]  fname  File name to process.
1051///
1052/// @return end of the directory name, on the first path separator:
1053///
1054///            "/path/file", "/path/dir/", "/path//dir", "/file"
1055///                  ^             ^             ^        ^
1056const char *gettail_dir(const char *const fname)
1057  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
1058{
1059  const char *dir_end = fname;
1060  const char *next_dir_end = fname;
1061  bool look_for_sep = true;
1062
1063  for (const char *p = fname; *p != NUL; p++) {
1064    if (vim_ispathsep(*p)) {
1065      if (look_for_sep) {
1066        next_dir_end = p;
1067        look_for_sep = false;
1068      }
1069    } else {
1070      if (!look_for_sep) {
1071        dir_end = next_dir_end;
1072      }
1073      look_for_sep = true;
1074    }
1075  }
1076  return dir_end;
1077}
1078
1079/// Calls globpath() with 'path' values for the given pattern and stores the
1080/// result in "gap".
1081/// Returns the total number of matches.
1082///
1083/// @param flags  EW_* flags
1084static int expand_in_path(garray_T *const gap, char *const pattern, const int flags)
1085  FUNC_ATTR_NONNULL_ALL
1086{
1087  garray_T path_ga;
1088  char *path_option = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
1089
1090  char *const curdir = xmalloc(MAXPATHL);
1091  os_dirname(curdir, MAXPATHL);
1092
1093  ga_init(&path_ga, (int)sizeof(char *), 1);
1094  if (flags & EW_CDPATH) {
1095    expand_path_option(curdir, p_cdpath, &path_ga);
1096  } else {
1097    expand_path_option(curdir, path_option, &path_ga);
1098  }
1099  xfree(curdir);
1100  if (GA_EMPTY(&path_ga)) {
1101    return 0;
1102  }
1103
1104  char *const paths = ga_concat_strings(&path_ga, ",");
1105  ga_clear_strings(&path_ga);
1106
1107  int glob_flags = 0;
1108  if (flags & EW_ICASE) {
1109    glob_flags |= WILD_ICASE;
1110  }
1111  if (flags & EW_ADDSLASH) {
1112    glob_flags |= WILD_ADD_SLASH;
1113  }
1114  globpath(paths, pattern, gap, glob_flags, !!(flags & EW_CDPATH));
1115  xfree(paths);
1116
1117  return gap->ga_len;
1118}
1119
1120/// Return true if "p" contains what looks like an environment variable.
1121/// Allowing for escaping.
1122static bool has_env_var(char *p)
1123  FUNC_ATTR_NONNULL_ALL
1124{
1125  for (; *p; p++) {
1126    if (*p == '\\' && p[1] != NUL) {
1127      p++;
1128    } else if (vim_strchr("$", (uint8_t)(*p)) != NULL) {
1129      return true;
1130    }
1131  }
1132  return false;
1133}
1134
1135#ifdef SPECIAL_WILDCHAR
1136
1137// Return true if "p" contains a special wildcard character, one that Vim
1138// cannot expand, requires using a shell.
1139static bool has_special_wildchar(char *p, int flags)
1140  FUNC_ATTR_NONNULL_ALL
1141{
1142  for (; *p; p++) {
1143    // Disallow line break characters.
1144    if (*p == '\r' || *p == '\n') {
1145      break;
1146    }
1147    // Allow for escaping.
1148    if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n') {
1149      p++;
1150    } else if (vim_strchr(SPECIAL_WILDCHAR, (uint8_t)(*p)) != NULL) {
1151      // Need a shell for curly braces only when including non-existing files.
1152      if (*p == '{' && !(flags & EW_NOTFOUND)) {
1153        continue;
1154      }
1155      // A { must be followed by a matching }.
1156      if (*p == '{' && vim_strchr(p, '}') == NULL) {
1157        continue;
1158      }
1159      // A quote and backtick must be followed by another one.
1160      if ((*p == '`' || *p == '\'') && vim_strchr(p, (uint8_t)(*p)) == NULL) {
1161        continue;
1162      }
1163      return true;
1164    }
1165  }
1166  return false;
1167}
1168#endif
1169
1170/// Generic wildcard expansion code.
1171///
1172/// Characters in pat that should not be expanded must be preceded with a
1173/// backslash. E.g., "/path\ with\ spaces/my\*star*".
1174///
1175/// @param      num_pat  is number of input patterns.
1176/// @param      pat      is an array of pointers to input patterns.
1177/// @param[out] num_file is pointer to number of matched file names.
1178/// @param[out] file     is pointer to array of pointers to matched file names.
1179/// @param      flags    is a combination of EW_* flags used in
1180///                      expand_wildcards().
1181///
1182/// @returns             OK when some files were found. *num_file is set to the
1183///                      number of matches, *file to the allocated array of
1184///                      matches. Call FreeWild() later.
1185///                      If FAIL is returned, *num_file and *file are either
1186///                      unchanged or *num_file is set to 0 and *file is set
1187///                      to NULL or points to "".
1188int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, int flags)
1189{
1190  garray_T ga;
1191  char *p;
1192  static bool recursive = false;
1193  int add_pat;
1194  bool did_expand_in_path = false;
1195  char *path_option = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
1196
1197  // A recursive call can happen when a `=expr` item evaluates an expression
1198  // that starts another expansion.  In this case, always call the machine
1199  // specific expansion function, if possible.  Otherwise, return FAIL.
1200  if (recursive) {
1201#ifdef SPECIAL_WILDCHAR
1202    return os_expand_wildcards(num_pat, pat, num_file, file, flags);
1203#else
1204    return FAIL;
1205#endif
1206  }
1207
1208#ifdef SPECIAL_WILDCHAR
1209  // If there are any special wildcard characters which we cannot handle
1210  // here, call machine specific function for all the expansion.  This
1211  // avoids starting the shell for each argument separately.
1212  // For `=expr` do use the internal function.
1213  for (int i = 0; i < num_pat; i++) {
1214    if (has_special_wildchar(pat[i], flags)
1215        && !(vim_backtick(pat[i]) && pat[i][1] == '=')) {
1216      return os_expand_wildcards(num_pat, pat, num_file, file, flags);
1217    }
1218  }
1219#endif
1220
1221  recursive = true;
1222
1223  // The matching file names are stored in a growarray.  Init it empty.
1224  ga_init(&ga, (int)sizeof(char *), 30);
1225
1226  for (int i = 0; i < num_pat && !got_int; i++) {
1227    add_pat = -1;
1228    p = pat[i];
1229
1230    if (vim_backtick(p)) {
1231      add_pat = expand_backtick(&ga, p, flags);
1232      if (add_pat == -1) {
1233        recursive = false;
1234        ga_clear_strings(&ga);
1235        *num_file = 0;
1236        *file = NULL;
1237        return FAIL;
1238      }
1239    } else {
1240      // First expand environment variables, "~/" and "~user/".
1241      if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~') {
1242        p = expand_env_save_opt(p, true, (char *)PATH_ESC_WILDCARDS);
1243        if (p == NULL) {
1244          p = pat[i];
1245        } else {
1246#ifdef UNIX
1247          // On Unix, if expand_env() can't expand an environment
1248          // variable, use the shell to do that.  Discard previously
1249          // found file names and start all over again.
1250          if (has_env_var(p) || *p == '~') {
1251            xfree(p);
1252            ga_clear_strings(&ga);
1253            i = os_expand_wildcards(num_pat, pat, num_file, file,
1254                                    flags | EW_KEEPDOLLAR);
1255            recursive = false;
1256            return i;
1257          }
1258#endif
1259        }
1260      }
1261
1262      // If there are wildcards or case-insensitive expansion is
1263      // required: Expand file names and add each match to the list.  If
1264      // there is no match, and EW_NOTFOUND is given, add the pattern.
1265      // Otherwise: Add the file name if it exists or when EW_NOTFOUND is
1266      // given.
1267      if (path_has_wildcard(p, false) || (flags & EW_ICASE)) {
1268        if ((flags & (EW_PATH | EW_CDPATH))
1269            && !path_is_absolute(p)
1270            && !(p[0] == '.'
1271                 && (vim_ispathsep(p[1])
1272                     || (p[1] == '.'
1273                         && vim_ispathsep(p[2]))))) {
1274          // :find completion where 'path' is used.
1275          // Recursiveness is OK here.
1276          recursive = false;
1277          add_pat = expand_in_path(&ga, p, flags);
1278          recursive = true;
1279          did_expand_in_path = true;
1280        } else {
1281          // Recursive gen_expand_wildcards() can only happen here when called from an
1282          // event handler in os_breakcheck(), in which case it should be allowed.
1283          recursive = false;
1284          size_t tmp_add_pat = path_expand(&ga, p, flags);
1285          recursive = true;
1286          assert(tmp_add_pat <= INT_MAX);
1287          add_pat = (int)tmp_add_pat;
1288        }
1289      }
1290    }
1291
1292    if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND))) {
1293      char *t = backslash_halve_save(p);
1294
1295      // When EW_NOTFOUND is used, always add files and dirs.  Makes
1296      // "vim c:/" work.
1297      if (flags & EW_NOTFOUND) {
1298        addfile(&ga, t, flags | EW_DIR | EW_FILE);
1299      } else {
1300        addfile(&ga, t, flags);
1301      }
1302
1303      if (t != p) {
1304        xfree(t);
1305      }
1306    }
1307
1308    if (did_expand_in_path && !GA_EMPTY(&ga) && (flags & (EW_PATH | EW_CDPATH))) {
1309      // Recursive gen_expand_wildcards() can only happen here when called from an
1310      // event handler in os_breakcheck(), in which case it should be allowed.
1311      recursive = false;
1312      uniquefy_paths(&ga, p, path_option);
1313      recursive = true;
1314    }
1315    if (p != pat[i]) {
1316      xfree(p);
1317    }
1318  }
1319
1320  *num_file = ga.ga_len;
1321  *file = (ga.ga_data != NULL) ? ga.ga_data : NULL;
1322
1323  recursive = false;
1324
1325  return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? OK : FAIL;
1326}
1327
1328/// Free the list of files returned by expand_wildcards() or other expansion functions.
1329void FreeWild(int count, char **files)
1330{
1331  if (count <= 0 || files == NULL) {
1332    return;
1333  }
1334  while (count--) {
1335    xfree(files[count]);
1336  }
1337  xfree(files);
1338}
1339
1340/// @return  true if we can expand this backtick thing here.
1341static bool vim_backtick(char *p)
1342  FUNC_ATTR_NONNULL_ALL
1343{
1344  return *p == '`' && *(p + 1) != NUL && *(p + strlen(p) - 1) == '`';
1345}
1346
1347/// Expand an item in `backticks` by executing it as a command.
1348/// Currently only works when pat[] starts and ends with a `.
1349/// Returns number of file names found, -1 if an error is encountered.
1350///
1351/// @param flags  EW_* flags
1352static int expand_backtick(garray_T *gap, char *pat, int flags)
1353  FUNC_ATTR_NONNULL_ALL
1354{
1355  char *p;
1356  char *buffer;
1357  int cnt = 0;
1358
1359  // Create the command: lop off the backticks.
1360  char *cmd = xmemdupz(pat + 1, strlen(pat) - 2);
1361
1362  if (*cmd == '=') {          // `={expr}`: Expand expression
1363    buffer = eval_to_string(cmd + 1, true, false);
1364  } else {
1365    buffer = get_cmd_output(cmd, NULL, (flags & EW_SILENT) ? kShellOptSilent : 0, NULL);
1366  }
1367  xfree(cmd);
1368  if (buffer == NULL) {
1369    return -1;
1370  }
1371
1372  cmd = buffer;
1373  while (*cmd != NUL) {
1374    cmd = skipwhite(cmd);               // skip over white space
1375    p = cmd;
1376    while (*p != NUL && *p != '\r' && *p != '\n') {  // skip over entry
1377      p++;
1378    }
1379    // add an entry if it is not empty
1380    if (p > cmd) {
1381      char i = *p;
1382      *p = NUL;
1383      addfile(gap, cmd, flags);
1384      *p = i;
1385      cnt++;
1386    }
1387    cmd = p;
1388    while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n')) {
1389      cmd++;
1390    }
1391  }
1392
1393  xfree(buffer);
1394  return cnt;
1395}
1396
1397#ifdef BACKSLASH_IN_FILENAME
1398/// Replace all slashes by backslashes.
1399/// This used to be the other way around, but MS-DOS sometimes has problems
1400/// with slashes (e.g. in a command name).  We can't have mixed slashes and
1401/// backslashes, because comparing file names will not work correctly.  The
1402/// commands that use a file name should try to avoid the need to type a
1403/// backslash twice.
1404/// When 'shellslash' set do it the other way around.
1405/// When the path looks like a URL leave it unmodified.
1406void slash_adjust(char *p)
1407  FUNC_ATTR_NONNULL_ALL
1408{
1409  if (path_with_url(p)) {
1410    return;
1411  }
1412
1413  if (*p == '`') {
1414    // don't replace backslash in backtick quoted strings
1415    const size_t len = strlen(p);
1416    if (len > 2 && *(p + len - 1) == '`') {
1417      return;
1418    }
1419  }
1420
1421  char from = p_ssl ? '\\' : PATHSEP;
1422  char to = p_ssl ? PATHSEP : '\\';
1423  strchrsub(p, from, to);
1424}
1425#endif
1426
1427/// Convert all slashes to backslashes in-place.
1428char *path_to_backslash(char *p)
1429{
1430  if (p != NULL) {
1431    strchrsub(p, PATHSEP, '\\');
1432  }
1433  return p;
1434}
1435
1436/// Convert all backslashes to forward slashes in-place,
1437/// unless when it looks like a URL (e.g. `term://xxxC:\cmd.exe`).
1438char *path_to_slash(char *p)
1439{
1440  if (p != NULL && !path_with_url(p)) {
1441    strchrsub(p, '\\', PATHSEP);
1442  }
1443  return p;
1444}
1445
1446/// Get an allocated copy of path to convert backslashes.
1447char *path_to_slash_save(const char *p)
1448{
1449  return p == NULL ? NULL : path_to_slash(xstrdup(p));
1450}
1451
1452/// Add a file to a file list.  Accepted flags:
1453/// EW_DIR      add directories
1454/// EW_FILE     add files
1455/// EW_EXEC     add executable files
1456/// EW_NOTFOUND add even when it doesn't exist
1457/// EW_ADDSLASH add slash after directory name
1458/// EW_ALLLINKS add symlink also when the referred file does not exist
1459///
1460/// @param f  filename
1461void addfile(garray_T *gap, char *f, int flags)
1462  FUNC_ATTR_NONNULL_ALL
1463{
1464  bool isdir;
1465  FileInfo file_info;
1466
1467  // if the file/dir/link doesn't exist, may not add it
1468  if (!(flags & EW_NOTFOUND)
1469      && ((flags & EW_ALLLINKS)
1470          ? !os_fileinfo_link(f, &file_info)
1471          : !os_path_exists(f))) {
1472    return;
1473  }
1474
1475#ifdef FNAME_ILLEGAL
1476  // if the file/dir contains illegal characters, don't add it
1477  if (strpbrk(f, FNAME_ILLEGAL) != NULL) {
1478    return;
1479  }
1480#endif
1481
1482  isdir = os_isdir(f);
1483  if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE))) {
1484    return;
1485  }
1486
1487  // If the file isn't executable, may not add it.  Do accept directories.
1488  // When invoked from expand_shellcmd() do not use $PATH.
1489  if (!isdir && (flags & EW_EXEC)
1490      && !os_can_exe(f, NULL, !(flags & EW_SHELLCMD))) {
1491    return;
1492  }
1493
1494  char *p = xmalloc(strlen(f) + 1 + isdir);
1495
1496  STRCPY(p, f);
1497  TO_SLASH(p);
1498  // Append a slash or backslash after directory names if none is present.
1499  if (isdir && (flags & EW_ADDSLASH)) {
1500    add_pathsep(p);
1501  }
1502  GA_APPEND(char *, gap, p);
1503}
1504
1505// Converts a file name into a canonical form. It simplifies a file name into
1506// its simplest form by stripping out unneeded components, if any.  The
1507// resulting file name is simplified in place and will either be the same
1508// length as that supplied, or shorter.
1509size_t simplify_filename(char *filename)
1510  FUNC_ATTR_NONNULL_ALL
1511{
1512  int components = 0;
1513  bool stripping_disabled = false;
1514  bool relative = true;
1515
1516  char *p = filename;
1517#ifdef BACKSLASH_IN_FILENAME
1518  if (p[0] != NUL && p[1] == ':') {        // skip "x:"
1519    p += 2;
1520  }
1521#endif
1522
1523  if (vim_ispathsep(*p)) {
1524    relative = false;
1525    p = path_skip_sep(p, true);
1526  }
1527  char *start = p;        // remember start after "c:/" or "/" or "///"
1528  char *p_end = p + strlen(p);  // point to NUL at end of string "p"
1529#ifdef UNIX
1530  // Posix says that "//path" is unchanged but "///path" is "/path".
1531  if (start > filename + 2) {
1532    memmove(filename + 1, p, (size_t)(p_end - p) + 1);  // +1 for NUL
1533    p_end -= (size_t)(p - (filename + 1));
1534    start = p = filename + 1;
1535  }
1536#endif
1537
1538  do {
1539    // At this point "p" is pointing to the char following a single "/"
1540    // or "p" is at the "start" of the (absolute or relative) path name.
1541    if (vim_ispathsep(*p)) {
1542      memmove(p, p + 1, (size_t)(p_end - (p + 1)) + 1);  // remove duplicate "/"
1543      p_end--;
1544    } else if (p[0] == '.'
1545               && (vim_ispathsep(p[1]) || p[1] == NUL)) {
1546      if (p == start && relative) {
1547        p += 1 + (p[1] != NUL);         // keep single "." or leading "./"
1548      } else {
1549        // Strip "./" or ".///".  If we are at the end of the file name
1550        // and there is no trailing path separator, either strip "/." if
1551        // we are after "start", or strip "." if we are at the beginning
1552        // of an absolute path name.
1553        char *tail = p + 1;
1554        if (p[1] != NUL) {
1555          tail = path_skip_sep(tail, true);
1556        } else if (p > start) {
1557          p--;                          // strip preceding path separator
1558        }
1559        memmove(p, tail, (size_t)(p_end - tail) + 1);
1560        p_end -= (size_t)(tail - p);
1561      }
1562    } else if (p[0] == '.' && p[1] == '.'
1563               && (vim_ispathsep(p[2]) || p[2] == NUL)) {
1564      // Skip to after ".." or "../" or "..///".
1565      char *tail = path_skip_sep(p + 2, true);
1566
1567      if (components > 0) {             // strip one preceding component
1568        bool do_strip = false;
1569
1570        // Don't strip for an erroneous file name.
1571        if (!stripping_disabled) {
1572          // If the preceding component does not exist in the file
1573          // system, we strip it.  On Unix, we don't accept a symbolic
1574          // link that refers to a non-existent file.
1575          char saved_char = p[-1];
1576          p[-1] = NUL;
1577          FileInfo file_info;
1578          if (!os_fileinfo_link(filename, &file_info)) {
1579            do_strip = true;
1580          }
1581          p[-1] = saved_char;
1582
1583          p--;
1584          // Skip back to after previous '/'.
1585          while (p > start && !after_pathsep(start, p)) {
1586            MB_PTR_BACK(start, p);
1587          }
1588
1589          if (!do_strip) {
1590            // If the component exists in the file system, check
1591            // that stripping it won't change the meaning of the
1592            // file name.  First get information about the
1593            // unstripped file name.  This may fail if the component
1594            // to strip is not a searchable directory (but a regular
1595            // file, for instance), since the trailing "/.." cannot
1596            // be applied then.  We don't strip it then since we
1597            // don't want to replace an erroneous file name by
1598            // a valid one, and we disable stripping of later
1599            // components.
1600            saved_char = *tail;
1601            *tail = NUL;
1602            if (os_fileinfo(filename, &file_info)) {
1603              do_strip = true;
1604            } else {
1605              stripping_disabled = true;
1606            }
1607            *tail = saved_char;
1608            if (do_strip) {
1609              // The check for the unstripped file name
1610              // above works also for a symbolic link pointing to
1611              // a searchable directory.  But then the parent of
1612              // the directory pointed to by the link must be the
1613              // same as the stripped file name.  (The latter
1614              // exists in the file system since it is the
1615              // component's parent directory.)
1616              FileInfo new_file_info;
1617              if (p == start && relative) {
1618                os_fileinfo(".", &new_file_info);
1619              } else {
1620                saved_char = *p;
1621                *p = NUL;
1622                os_fileinfo(filename, &new_file_info);
1623                *p = saved_char;
1624              }
1625
1626              if (!os_fileinfo_id_equal(&file_info, &new_file_info)) {
1627                do_strip = false;
1628                // We don't disable stripping of later
1629                // components since the unstripped path name is
1630                // still valid.
1631              }
1632            }
1633          }
1634        }
1635
1636        if (!do_strip) {
1637          // Skip the ".." or "../" and reset the counter for the
1638          // components that might be stripped later on.
1639          p = tail;
1640          components = 0;
1641        } else {
1642          // Strip previous component.  If the result would get empty
1643          // and there is no trailing path separator, leave a single
1644          // "." instead.  If we are at the end of the file name and
1645          // there is no trailing path separator and a preceding
1646          // component is left after stripping, strip its trailing
1647          // path separator as well.
1648          if (p == start && relative && tail[-1] == '.') {
1649            *p++ = '.';
1650            *p = NUL;
1651          } else {
1652            if (p > start && tail[-1] == '.') {
1653              p--;
1654            }
1655            memmove(p, tail, (size_t)(p_end - tail) + 1);  // strip previous component
1656            p_end -= (size_t)(tail - p);
1657          }
1658
1659          components--;
1660        }
1661      } else if (p == start && !relative) {            // leading "/.." or "/../"
1662        memmove(p, tail, (size_t)(p_end - tail) + 1);  // strip ".." or "../"
1663        p_end -= (size_t)(tail - p);
1664      } else {
1665        if (p == start + 2 && p[-2] == '.') {          // leading "./../"
1666          memmove(p - 2, p, (size_t)(p_end - p) + 1);  // strip leading "./"
1667          p_end -= 2;
1668          tail -= 2;
1669        }
1670        p = tail;                       // skip to char after ".." or "../"
1671      }
1672    } else {
1673      components++;  // Simple path component.
1674      p = (char *)path_next_component(p);
1675    }
1676  } while (*p != NUL);
1677
1678  return (size_t)(p_end - filename);
1679}
1680
1681/// Checks for a Windows drive letter ("C:/") at the start of the path.
1682///
1683/// @see https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
1684bool path_has_drive_letter(const char *p, size_t path_len)
1685  FUNC_ATTR_NONNULL_ALL
1686{
1687  return path_len >= 2
1688         && ASCII_ISALPHA(p[0])
1689         && (p[1] == ':' || p[1] == '|')
1690         && (path_len == 2 || ((p[2] == '/') | (p[2] == '\\') | (p[2] == '?') | (p[2] == '#')));
1691}
1692
1693// Check if the ":/" of a URL is at the pointer, return URL_SLASH.
1694// Also check for ":\\", which MS Internet Explorer accepts, return
1695// URL_BACKSLASH.
1696int path_is_url(const char *p)
1697  FUNC_ATTR_NONNULL_ALL
1698{
1699  // In the spec ':' is enough to recognize a scheme
1700  // https://url.spec.whatwg.org/#scheme-state
1701  if (strncmp(p, ":/", 2) == 0) {
1702    return URL_SLASH;
1703  } else if (strncmp(p, ":\\\\", 3) == 0) {
1704    return URL_BACKSLASH;
1705  }
1706  return 0;
1707}
1708
1709/// Check if "fname" starts with "name:/" or "name:\".
1710///
1711/// @param  fname         is the filename to test
1712/// @return URL_SLASH for "name:/", URL_BACKSLASH for "name:\", zero otherwise.
1713int path_with_url(const char *fname)
1714  FUNC_ATTR_NONNULL_ALL
1715{
1716  const char *p;
1717
1718  // first character must be alpha
1719  if (!ASCII_ISALPHA(*fname)) {
1720    return 0;
1721  }
1722
1723  if (path_has_drive_letter(fname, strlen(fname))) {
1724    return 0;
1725  }
1726
1727  // check body: (alpha, digit, '+', '-', '.') following RFC3986
1728  for (p = fname + 1; (ASCII_ISALNUM(*p) || (*p == '+') || (*p == '-') || (*p == '.')); p++) {}
1729
1730  // check last char is not '+', '-', or '.'
1731  if ((p[-1] == '+') || (p[-1] == '-') || (p[-1] == '.')) {
1732    return 0;
1733  }
1734
1735  // ":/" or ":\\" must follow
1736  return path_is_url(p);
1737}
1738
1739bool path_with_extension(const char *path, const char *extension)
1740  FUNC_ATTR_NONNULL_ALL
1741{
1742  const char *last_dot = strrchr(path, '.');
1743  if (!last_dot) {
1744    return false;
1745  }
1746  return mb_strcmp_ic((bool)p_fic, last_dot + 1, extension) == 0;
1747}
1748
1749/// Return true if "name" is a full (absolute) path name or URL.
1750bool vim_isAbsName(const char *name)
1751  FUNC_ATTR_NONNULL_ALL
1752{
1753  return path_with_url(name) != 0 || path_is_absolute(name);
1754}
1755
1756/// Save absolute file name to "buf[len]".
1757///
1758/// @param      fname filename to evaluate
1759/// @param[out] buf   contains `fname` absolute path, or:
1760///                   - truncated `fname` if longer than `len`
1761///                   - unmodified `fname` if absolute path fails or is a URL
1762/// @param      len   length of `buf`
1763/// @param      force flag to force expanding even if the path is absolute
1764///
1765/// @return           FAIL for failure, OK otherwise
1766int vim_FullName(const char *fname, char *buf, size_t len, bool force)
1767  FUNC_ATTR_NONNULL_ARG(2)
1768{
1769  *buf = NUL;
1770  if (fname == NULL) {
1771    return FAIL;
1772  }
1773
1774  if (strlen(fname) > (len - 1)) {
1775    xstrlcpy(buf, fname, len);  // truncate
1776    TO_SLASH(buf);
1777    return FAIL;
1778  }
1779
1780  if (path_with_url(fname)) {
1781    xstrlcpy(buf, fname, len);
1782    return OK;
1783  }
1784
1785  int rv = path_to_absolute(fname, buf, len, force);
1786  if (rv == FAIL) {
1787    xstrlcpy(buf, fname, len);  // something failed; use the filename
1788  }
1789  TO_SLASH(buf);
1790  return rv;
1791}
1792
1793/// Get the full resolved path for `fname`
1794///
1795/// Even filenames that appear to be absolute based on starting from
1796/// the root may have relative paths (like dir/../subdir) or symlinks
1797/// embedded, or even extra separators (//).  This function addresses
1798/// those possibilities, returning a resolved absolute path.
1799/// For MS-Windows, this also provides drive letter for all absolute paths.
1800///
1801/// @param fname is the filename to expand
1802/// @return [allocated] Full path (NULL for failure).
1803char *fix_fname(const char *fname)
1804{
1805#ifdef UNIX
1806  return FullName_save(fname, true);
1807#else
1808  if (!vim_isAbsName(fname)
1809      || strstr(fname, "..") != NULL
1810      || strstr(fname, "//") != NULL
1811# ifdef BACKSLASH_IN_FILENAME
1812      || strstr(fname, "\\\\") != NULL
1813# endif
1814# ifdef MSWIN
1815      || fname[0] == '/'
1816      || fname[0] == '\\'
1817# endif
1818      ) {
1819    return FullName_save(fname, false);
1820  }
1821
1822  fname = TO_SLASH_SAVE(fname);
1823
1824# ifdef CASE_INSENSITIVE_FILENAME
1825  path_fix_case((char *)fname);  // set correct case for file name
1826# endif
1827
1828  return (char *)fname;
1829#endif
1830}
1831
1832/// Set the case of the file name, if it already exists.  This will cause the
1833/// file name to remain exactly the same.
1834/// Only required for file systems where case is ignored and preserved.
1835// TODO(SplinterOfChaos): Could also be used when mounting case-insensitive
1836// file systems.
1837void path_fix_case(char *name)
1838  FUNC_ATTR_NONNULL_ALL
1839{
1840  FileInfo file_info;
1841  if (!os_fileinfo_link(name, &file_info)) {
1842    return;
1843  }
1844
1845  // Open the directory where the file is located.
1846  char *slash = strrchr(name, '/');
1847  char *tail;
1848  Directory dir;
1849  bool ok;
1850  if (slash == NULL) {
1851    ok = os_scandir(&dir, ".");
1852    tail = name;
1853  } else {
1854    *slash = NUL;
1855    ok = os_scandir(&dir, name);
1856    *slash = '/';
1857    tail = slash + 1;
1858  }
1859
1860  if (!ok) {
1861    return;
1862  }
1863
1864  size_t taillen = strlen(tail);
1865  const char *entry;
1866  while ((entry = os_scandir_next(&dir))) {
1867    // Only accept names that differ in case and are the same byte
1868    // length. TODO: accept different length name.
1869    if (STRICMP(tail, entry) == 0 && taillen == strlen(entry)) {
1870      char newname[MAXPATHL + 1];
1871
1872      // Verify the inode is equal.
1873      xstrlcpy(newname, name, MAXPATHL + 1);
1874      xstrlcpy(newname + (tail - name), entry,
1875               (size_t)(MAXPATHL - (tail - name) + 1));
1876      FileInfo file_info_new;
1877      if (os_fileinfo_link(newname, &file_info_new)
1878          && os_fileinfo_id_equal(&file_info, &file_info_new)) {
1879        STRCPY(tail, entry);
1880        break;
1881      }
1882    }
1883  }
1884
1885  os_closedir(&dir);
1886}
1887
1888/// Return true if "p" points to just after a path separator.
1889/// Takes care of multi-byte characters.
1890/// "b" must point to the start of the file name
1891int after_pathsep(const char *b, const char *p)
1892  FUNC_ATTR_NONNULL_ALL
1893{
1894  return p > b && vim_ispathsep(p[-1])
1895         && utf_head_off(b, p - 1) == 0;
1896}
1897
1898/// Return true if file names "f1" and "f2" are in the same directory.
1899/// "f1" may be a short name, "f2" must be a full path.
1900bool same_directory(char *f1, char *f2)
1901{
1902  char ffname[MAXPATHL];
1903  char *t1;
1904  char *t2;
1905
1906  // safety check
1907  if (f1 == NULL || f2 == NULL) {
1908    return false;
1909  }
1910
1911  vim_FullName(f1, ffname, MAXPATHL, false);
1912  t1 = path_tail_with_sep(ffname);
1913  t2 = path_tail_with_sep(f2);
1914  return t1 - ffname == t2 - f2
1915         && path_cmp(p_fic, ffname, f2, (size_t)(t1 - ffname)) == 0;
1916}
1917
1918int path_fold_char(bool ic, const char *p, int *len)
1919  FUNC_ATTR_NONNULL_ALL
1920{
1921  if (vim_ispathsep_nocolon(*p)) {
1922    *len = 1;
1923    return PATHSEP;
1924  }
1925  *len = ic ? utfc_ptr2len(p) : 1;
1926  return ic ? utf_fold(utf_ptr2char(p)) : (uint8_t)*p;
1927}
1928
1929/// Compares filepaths (like `strncmp()`). Unlike `path_equal` this does not make filesystem
1930/// calls: only the names are compared (in a path-aware manner).
1931///
1932/// Extensions:
1933/// - Treats "/" and "\" as equal on Windows.
1934/// - Consults 'fileignorecase': when set, characters are compared with
1935///   `utf_fold()`; otherwise verbatim.
1936/// - Ignores a single trailing path separator, e.g.
1937///   "foo" == "foo/", but "foo/" != "foo//".
1938/// - A path separator sorts before any other character, e.g.
1939///   "foo/bar" < "foobar".
1940/// - On Windows, consults the current drive when comparing an explicit drive
1941///   path with an implicit one, e.g.
1942///   "C:/foo" == "/foo" when the current drive is "C:".
1943///
1944/// @param ic      True if case is to be ignored.
1945/// @param p       First path.
1946/// @param q       Second path.
1947/// @param maxlen  Maximum number of bytes to compare.
1948///
1949/// @return 0 if the paths are equal, non-zero otherwise.
1950int path_cmp(bool ic, const char *p, const char *q, size_t maxlen)
1951{
1952  const char *s = NULL;
1953  int c1 = NUL;
1954  int c2 = NUL;
1955  size_t len = 0;
1956
1957#ifdef MSWIN
1958  const char **pp = NULL;
1959  if (vim_ispathsep_nocolon(*p) && ASCII_ISALPHA(*q) && q[1] == ':') {
1960    pp = &q;
1961  } else if (vim_ispathsep_nocolon(*q) && ASCII_ISALPHA(*p) && p[1] == ':') {
1962    pp = &p;
1963  }
1964  if (pp && TOLOWER_ASC(**pp) == _getdrive() + 'a' - 1) {
1965    *pp += 2;  // advance the pointer of the explicit one, to skip the drive
1966  }
1967#endif
1968
1969  for (int i = 0, j = 0; len < maxlen; len += (size_t)i) {
1970    c1 = path_fold_char(ic, p, &i);
1971    c2 = path_fold_char(ic, q, &j);
1972    if (c1 == NUL || c2 == NUL || c1 != c2) {
1973      break;
1974    }
1975    p += i;
1976    q += j;
1977  }
1978
1979  if ((c1 == NUL && c2 == NUL) || len >= maxlen) {
1980    return 0;
1981  }
1982
1983  if (c1 != NUL && c2 != NUL) {
1984    if (vim_ispathsep(c1)) {
1985      return -1;
1986    }
1987    if (vim_ispathsep(c2)) {
1988      return 1;
1989    }
1990    return c1 - c2;
1991  }
1992
1993  s = c1 == NUL ? q : p;
1994  // match with a single trailing slash, but not "//" or ":/"
1995  if (vim_ispathsep_nocolon(*s)
1996      && s[1] == NUL
1997      && len > 0
1998      && !vim_ispathsep(s[-1])) {
1999    return 0;
2000  }
2001  return s == q ? -1 : 1;
2002}
2003
2004/// Try to find a shortname by comparing the fullname with the current
2005/// directory.
2006///
2007/// @param full_path The full path of the file.
2008/// @return
2009///   - Pointer into `full_path` if shortened.
2010///   - `full_path` unchanged if no shorter name is possible.
2011///   - NULL if `full_path` is NULL.
2012char *path_try_shorten_fname(char *full_path)
2013{
2014  char *dirname = xmalloc(MAXPATHL);
2015  char *p = full_path;
2016
2017  if (os_dirname(dirname, MAXPATHL) == OK) {
2018    p = path_shorten_fname(full_path, dirname);
2019    if (p == NULL || *p == NUL) {
2020      p = full_path;
2021    }
2022  }
2023  xfree(dirname);
2024  return p;
2025}
2026
2027/// Try to find a shortname by comparing the fullname with `dir_name`.
2028///
2029/// @param full_path The full path of the file.
2030/// @param dir_name The directory to shorten relative to.
2031/// @return
2032///   - Pointer into `full_path` if shortened.
2033///   - NULL if no shorter name is possible.
2034char *path_shorten_fname(char *full_path, char *dir_name)
2035{
2036  if (full_path == NULL) {
2037    return NULL;
2038  }
2039
2040  assert(dir_name != NULL);
2041  size_t len = strlen(dir_name);
2042
2043  // If full_path and dir_name do not match, it's impossible to make one
2044  // relative to the other.
2045  if (path_cmp(p_fic, dir_name, full_path, len) != 0) {
2046    return NULL;
2047  }
2048
2049  // If dir_name is a path head, full_path can always be made relative.
2050  if (len == (size_t)path_head_length() && is_path_head(dir_name)) {
2051    return full_path + len;
2052  }
2053
2054  char *p = full_path + len;
2055
2056  // If *p is not pointing to a path separator, this means that full_path's
2057  // last directory name is longer than *dir_name's last directory, so they
2058  // don't actually match.
2059  if (!vim_ispathsep(*p)) {
2060    return NULL;
2061  }
2062
2063  // Skip the matched separator, then any following separators (but not a colon).
2064  return path_skip_sep(p + 1, false);
2065}
2066
2067/// Invoke expand_wildcards() for one pattern
2068///
2069/// One should expand items like "%:h" before the expansion.
2070///
2071/// @param[in]   pat       Pointer to the input pattern.
2072/// @param[out]  num_file  Resulting number of files.
2073/// @param[out]  file      Array of resulting files.
2074/// @param[in]   flags     Flags passed to expand_wildcards().
2075///
2076/// @returns               OK when *file is set to allocated array of matches
2077///                        and *num_file (can be zero) to the number of matches.
2078///                        If FAIL is returned, *num_file and *file are either
2079///                        unchanged or *num_file is set to 0 and *file is set
2080///                        to NULL or points to "".
2081int expand_wildcards_eval(char **pat, int *num_file, char ***file, int flags)
2082{
2083  int ret = FAIL;
2084  char *eval_pat = NULL;
2085  char *exp_pat = *pat;
2086  const char *ignored_msg;
2087  size_t usedlen;
2088  const bool is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
2089  bool star_follows = false;
2090
2091  if (is_cur_alt_file || *exp_pat == '<') {
2092    emsg_off++;
2093    eval_pat = eval_vars(exp_pat, exp_pat, &usedlen, NULL, &ignored_msg,
2094                         NULL,
2095                         true);
2096    emsg_off--;
2097    if (eval_pat != NULL) {
2098      star_follows = strcmp(exp_pat + usedlen, "*") == 0;
2099      exp_pat = concat_str(eval_pat, exp_pat + usedlen);
2100    }
2101  }
2102
2103  if (exp_pat != NULL) {
2104    ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
2105  }
2106
2107  if (eval_pat != NULL) {
2108    if (*num_file == 0 && is_cur_alt_file && star_follows) {
2109      // Expanding "%" or "#" and the file does not exist: Add the
2110      // pattern anyway (without the star) so that this works for remote
2111      // files and non-file buffer names.
2112      *file = xmalloc(sizeof(char *));
2113      **file = eval_pat;
2114      eval_pat = NULL;
2115      *num_file = 1;
2116      ret = OK;
2117    }
2118    xfree(exp_pat);
2119    xfree(eval_pat);
2120  }
2121
2122  return ret;
2123}
2124
2125/// Expand wildcards. Calls gen_expand_wildcards() and removes files matching
2126/// 'wildignore'.
2127///
2128/// @param      num_pat  is number of input patterns.
2129/// @param      pat      is an array of pointers to input patterns.
2130/// @param[out] num_file is pointer to number of matched file names.
2131/// @param[out] file     is pointer to array of pointers to matched file names.
2132/// @param      flags    is a combination of EW_* flags.
2133///
2134/// @returns             OK when *file is set to allocated array of matches
2135///                      and *num_file (can be zero) to the number of matches.
2136///                      If FAIL is returned, *num_file and *file are either
2137///                      unchanged or *num_file is set to 0 and *file is set to
2138///                      NULL or points to "".
2139int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int flags)
2140{
2141  int retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
2142
2143  // When keeping all matches, return here
2144  if ((flags & EW_KEEPALL) || retval == FAIL) {
2145    return retval;
2146  }
2147
2148  // Remove names that match 'wildignore'.
2149  if (*p_wig) {
2150    // check all files in (*files)[]
2151    assert(*num_files == 0 || *files != NULL);
2152    for (int i = 0; i < *num_files; i++) {
2153      char *ffname = FullName_save((*files)[i], false);
2154      assert((*files)[i] != NULL);
2155      assert(ffname != NULL);
2156      if (match_file_list(p_wig, (*files)[i], ffname)) {
2157        // remove this matching file from the list
2158        xfree((*files)[i]);
2159        for (int j = i; j + 1 < *num_files; j++) {
2160          (*files)[j] = (*files)[j + 1];
2161        }
2162        (*num_files)--;
2163        i--;
2164      }
2165      xfree(ffname);
2166    }
2167  }
2168
2169  // Move the names where 'suffixes' match to the end.
2170  // Skip when interrupted, the result probably won't be used.
2171  assert(*num_files == 0 || *files != NULL);
2172  if (*num_files > 1 && !got_int) {
2173    int non_suf_match = 0;            // number without matching suffix
2174    for (int i = 0; i < *num_files; i++) {
2175      if (!match_suffix((*files)[i])) {
2176        // Move the name without matching suffix to the front of the list.
2177        char *p = (*files)[i];
2178        for (int j = i; j > non_suf_match; j--) {
2179          (*files)[j] = (*files)[j - 1];
2180        }
2181        (*files)[non_suf_match++] = p;
2182      }
2183    }
2184  }
2185
2186  // Free empty array of matches
2187  if (*num_files == 0) {
2188    XFREE_CLEAR(*files);
2189    return FAIL;
2190  }
2191
2192  return retval;
2193}
2194
2195/// @return  true if "fname" matches with an entry in 'suffixes'.
2196bool match_suffix(char *fname)
2197  FUNC_ATTR_NONNULL_ALL
2198{
2199#define MAXSUFLEN 30  // maximum length of a file suffix
2200  char suf_buf[MAXSUFLEN];
2201
2202  size_t fnamelen = strlen(fname);
2203  size_t setsuflen = 0;
2204  for (char *setsuf = p_su; *setsuf;) {
2205    setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
2206    if (setsuflen == 0) {
2207      char *tail = path_tail(fname);
2208
2209      // empty entry: match name without a '.'
2210      if (vim_strchr(tail, '.') == NULL) {
2211        setsuflen = 1;
2212        break;
2213      }
2214    } else {
2215      if (fnamelen >= setsuflen
2216          && path_cmp(p_fic, suf_buf, fname + fnamelen - setsuflen, setsuflen) == 0) {
2217        break;
2218      }
2219      setsuflen = 0;
2220    }
2221  }
2222  return setsuflen != 0;
2223}
2224
2225/// Get the absolute name of the given relative directory.
2226///
2227/// @param directory Directory name, relative to current directory.
2228/// @return `FAIL` for failure, `OK` for success.
2229int path_full_dir_name(char *directory, char *buffer, size_t len)
2230  FUNC_ATTR_NONNULL_ALL
2231{
2232  if (strlen(directory) == 0) {
2233    return os_dirname(buffer, len);
2234  }
2235
2236  if (os_realpath(directory, buffer, len) != NULL) {
2237    return OK;
2238  }
2239
2240  // Path does not exist (yet).  For a full path fail, will use the path as-is.
2241  if (path_is_absolute(directory)) {
2242    return FAIL;
2243  }
2244  // For a relative path use the current directory and append the file name.
2245
2246  char old_dir[MAXPATHL];
2247
2248  // Get current directory name.
2249  if (os_dirname(old_dir, MAXPATHL) == FAIL) {
2250    return FAIL;
2251  }
2252
2253  xstrlcpy(buffer, old_dir, len);
2254  if (append_path(buffer, directory, len) == FAIL) {
2255    return FAIL;
2256  }
2257
2258  return OK;
2259}
2260
2261// Append to_append to path with a slash in between.
2262int append_path(char *path, const char *to_append, size_t max_len)
2263  FUNC_ATTR_NONNULL_ALL
2264{
2265  size_t current_length = strlen(path);
2266  size_t to_append_length = strlen(to_append);
2267
2268  // Do not append empty string or a dot.
2269  if (to_append_length == 0 || strcmp(to_append, ".") == 0) {
2270    return OK;
2271  }
2272
2273  // Combine the path segments, separated by a slash.
2274  if (current_length > 0 && !vim_ispathsep_nocolon(path[current_length - 1])) {
2275    // +1 for the NUL at the end.
2276    if (current_length + STRLEN_LITERAL(PATHSEPSTR) + 1 > max_len) {
2277      return FAIL;  // No space for trailing slash.
2278    }
2279    xstrlcpy(path + current_length, PATHSEPSTR, max_len - current_length);
2280    current_length += STRLEN_LITERAL(PATHSEPSTR);
2281  }
2282
2283  // +1 for the NUL at the end.
2284  if (current_length + to_append_length + 1 > max_len) {
2285    return FAIL;
2286  }
2287
2288  xstrlcpy(path + current_length, to_append, max_len - current_length);
2289  return OK;
2290}
2291
2292/// Used by `vim_FullName` and `fix_fname` to expand a filename to its full path.
2293///
2294/// @param  fname  Filename to expand.
2295/// @param  buf    Where to store the absolute path of "fname".
2296/// @param  len    Length of `buf`.
2297/// @param  force  Also expand when `fname` is already absolute.
2298///
2299/// @return FAIL for failure, OK for success.
2300static int path_to_absolute(const char *fname, char *buf, size_t len, int force)
2301  FUNC_ATTR_NONNULL_ALL
2302{
2303  const char *p;
2304  *buf = NUL;
2305
2306  char *relative_directory = xmalloc(len);
2307  const char *end_of_path = fname;
2308
2309  // expand it if forced or not an absolute path
2310  if (force || !path_is_absolute(fname)
2311#ifdef MSWIN  // enforce drive letter on Windows paths
2312      || fname[0] == '/' || fname[0] == '\\'
2313#endif
2314      ) {
2315    p = strrchr(fname, '/');
2316#ifdef MSWIN
2317    if (p == NULL) {
2318      p = strrchr(fname, '\\');
2319    }
2320    if (p == NULL && ASCII_ISALPHA(fname[0]) && fname[1] == ':') {  // drive letter
2321      p = fname + 1;
2322    }
2323#endif
2324    if (p == NULL && strcmp(fname, "..") == 0) {
2325      // Handle ".." without path separators.
2326      p = fname + 2;
2327    }
2328    if (p != NULL) {
2329      if (vim_ispathsep(*p) && strcmp(p + 1, "..") == 0) {
2330        // For "/path/dir/.." include the "/..".
2331        p += 3;
2332      }
2333      assert(p >= fname);
2334      memcpy(relative_directory, fname, (size_t)(p - fname + 1));
2335      relative_directory[p - fname + 1] = NUL;
2336      end_of_path = (vim_ispathsep(*p) ? p + 1 : p);
2337    } else {
2338      relative_directory[0] = NUL;
2339    }
2340
2341    if (FAIL == path_full_dir_name(relative_directory, buf, len)) {
2342      xfree(relative_directory);
2343      return FAIL;
2344    }
2345  }
2346  xfree(relative_directory);
2347  return append_path(buf, end_of_path, len);
2348}
2349
2350/// Check if file `fname` is a full (absolute) path.
2351///
2352/// @return `true` if "fname" is absolute.
2353bool path_is_absolute(const char *fname)
2354  FUNC_ATTR_NONNULL_ALL
2355{
2356#ifdef MSWIN
2357  if (*fname == NUL) {
2358    return false;
2359  }
2360  // A name like "d:/foo" and "//server/share" is absolute
2361  // /foo and \foo are absolute too because Windows keeps a current drive.
2362  return ((ASCII_ISALPHA(fname[0]) && fname[1] == ':' && vim_ispathsep_nocolon(fname[2]))
2363          || vim_ispathsep_nocolon(fname[0]));
2364#else
2365  // UNIX: This just checks if the file name starts with '/' or '~'.
2366  return *fname == '/' || *fname == '~';
2367#endif
2368}
2369
2370/// Builds a full path from an invocation name `argv0`, based on heuristics.
2371///
2372/// @param[in]  argv0     Name by which Nvim was invoked.
2373/// @param[out] buf       Guessed full path to `argv0`.
2374/// @param[in]  bufsize   Size of `buf`.
2375///
2376/// @see os_exepath
2377void path_guess_exepath(const char *argv0, char *buf, size_t bufsize)
2378  FUNC_ATTR_NONNULL_ALL
2379{
2380  char *path = os_getenv("PATH");
2381
2382  if (path == NULL || path_is_absolute(argv0)) {
2383    xstrlcpy(buf, argv0, bufsize);
2384  } else if (argv0[0] == '.' || strchr(argv0, PATHSEP)) {
2385    // Relative to CWD.
2386    if (os_dirname(buf, MAXPATHL) != OK) {
2387      buf[0] = NUL;
2388    }
2389    xstrlcat(buf, PATHSEPSTR, bufsize);
2390    xstrlcat(buf, argv0, bufsize);
2391  } else {
2392    // Search $PATH for plausible location.
2393    const void *iter = NULL;
2394    do {
2395      const char *dir;
2396      size_t dir_len;
2397      iter = vim_env_iter(ENV_SEPCHAR, path, iter, &dir, &dir_len);
2398      if (dir == NULL || dir_len == 0) {
2399        break;
2400      }
2401      if (dir_len + 1 > sizeof(NameBuff)) {
2402        continue;
2403      }
2404      xmemcpyz(NameBuff, dir, dir_len);
2405      xstrlcat(NameBuff, PATHSEPSTR, sizeof(NameBuff));
2406      xstrlcat(NameBuff, argv0, sizeof(NameBuff));
2407      if (os_can_exe(NameBuff, NULL, false)) {
2408        xstrlcpy(buf, NameBuff, bufsize);
2409        TO_SLASH(buf);
2410        return;
2411      }
2412    } while (iter != NULL);
2413    // Not found in $PATH, fall back to argv0.
2414    xstrlcpy(buf, argv0, bufsize);
2415  }
2416  xfree(path);
2417}