robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 40URL_SLASH = 1 ,// path_is_url() has found ":/" 41URL_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 ) 57FUNC_ATTR_NONNULL_ALL 58{ 59char expanded_s1 [MAXPATHL ]; 60char full1 [MAXPATHL ]; 61char full2 [MAXPATHL ]; 62FileID file_id1 ,file_id2 ; 63 64assert (!(flags & kPathCmpLiteral )|| flags == kPathCmpLiteral ); 65 66if (flags == kPathCmpLiteral ) { 67const bool is_url = path_with_url (s1 )|| path_with_url (s2 ); 68// URI comparison is scheme-agnostic, so a trailing slash is significant. 69return (!is_url || strlen (s1 )== strlen (s2 )) 70&& path_cmp (p_fic ,s1 ,s2 ,MAXPATHL )== 0 ; 71 } 72 73if (flags & kPathCmpExpand ) { 74expand_env_esc (s1 ,expanded_s1 ,MAXPATHL ,NULL , false,NULL ); 75 }else if (flags ) { 76xstrlcpy (expanded_s1 ,s1 ,MAXPATHL ); 77 } 78 79bool id_ok1 = os_fileid (expanded_s1 ,& file_id1 ); 80bool id_ok2 = os_fileid (s2 ,& file_id2 ); 81if (id_ok1 && id_ok2 && os_fileid_equal (& file_id1 ,& file_id2 )) { 82return true; 83 } 84if (!id_ok1 && !id_ok2 && (flags & kPathCmpFull )) { 85vim_FullName (expanded_s1 ,full1 ,MAXPATHL , false); 86vim_FullName (s2 ,full2 ,MAXPATHL , false); 87return path_cmp (p_fic ,full1 ,full2 ,MAXPATHL )== 0 ; 88 } 89return 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 ) 102FUNC_ATTR_NONNULL_RET 103{ 104if (fname == NULL ) { 105return "" ; 106 } 107 108const char * tail = get_past_head (fname ); 109// Find last part of path. 110for (const char * p = tail ;* p != NUL ;p ++ ) { 111if (vim_ispathsep_nocolon (* p )) { 112tail = p + 1 ; 113 } 114 } 115return (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 ) 128FUNC_ATTR_NONNULL_ALL 129{ 130// Don't remove the '/' from "c:/file". 131char * past_head = get_past_head (fname ); 132char * tail = path_tail (fname ); 133while (tail > past_head && after_pathsep (fname ,tail )) { 134tail -- ; 135 } 136return 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 ) 161FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG (1 ) 162{ 163const char * tail = get_past_head (invocation ); 164const char * tail_end = tail ; 165const char * p = tail ; 166bool inquote = false; 167while (* p != NUL && (inquote || * p != ' ' )) { 168int l = utfc_ptr2len (p ); 169if (vim_ispathsep_nocolon (* p )) { 170tail = p + 1 ;// Now tail points one past the separator. 171tail_end = tail ; 172 }else if (* p == '\\' && inquote ) { 173p ++ ; 174 }else if (* p == '"' ) { 175inquote ^=1 ; 176 }else { 177tail_end = p + l ; 178 } 179p += l ; 180 } 181 182if (len != NULL ) { 183* len = (size_t )(tail_end - tail ); 184 } 185 186return 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 ) 195FUNC_ATTR_NONNULL_ALL 196{ 197while (* fname != NUL && !vim_ispathsep (* fname )) { 198fname ++ ; 199 } 200if (* fname != NUL ) { 201fname ++ ; 202 } 203return 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 ) 212FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_PURE 213{ 214while (colon ?vim_ispathsep (* path ) :vim_ispathsep_nocolon (* path )) { 215path ++ ; 216 } 217return (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 227return 3 ; 228#else 229return 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 ) 240FUNC_ATTR_NONNULL_ALL 241{ 242#ifdef MSWIN 243return isalpha ((uint8_t )path [0 ])&& path [1 ]== ':' ; 244#else 245return 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 ) 253FUNC_ATTR_NONNULL_ALL 254{ 255const char * retval = path ; 256 257#ifdef MSWIN 258// May skip "c:" 259if (is_path_head (path )) { 260retval = path + 2 ; 261 } 262#endif 263 264retval = path_skip_sep (retval , true); 265 266return (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 274return c == '/' ;// Unix has ':' inside file names 275#else 276# ifdef BACKSLASH_IN_FILENAME 277return c == ':' || c == '/' || c == '\\' ; 278# else 279return 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{ 287return 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 298return c == ':' ; 299#else 300return 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 ) 309FUNC_ATTR_NONNULL_ALL 310{ 311char * tail = path_tail (str ); 312char * d = str ; 313bool skip = false; 314int dirchunk_len = 0 ; 315for (char * s = str ;;s ++ ) { 316if (s >=tail ) {// copy the whole tail 317* d ++ = * s ; 318if (* s == NUL ) { 319break ; 320 } 321 }else if (vim_ispathsep (* s )) {// copy '/' and next char 322* d ++ = * s ; 323skip = false; 324dirchunk_len = 0 ; 325 }else if (!skip ) { 326* d ++ = * s ;// copy next char 327if (* s != '~' && * s != '.' ) {// and leading "~" and "." 328dirchunk_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) 331if (dirchunk_len >=trim_len ) { 332skip = true; 333 } 334 } 335int l = utfc_ptr2len (s ); 336while (-- 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 ) 346FUNC_ATTR_NONNULL_ALL 347{ 348shorten_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 ) 355FUNC_ATTR_NONNULL_ALL 356{ 357char * p = path_tail_with_sep (fname ); 358if (p == fname ) { 359return true; 360 } 361char c = * p ; 362* p = NUL ; 363bool retval = os_isdir (fname ); 364* p = c ; 365return 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 , 379const size_t len2 ,const bool sep ,size_t * len ) 380FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 381{ 382if (sep && * fname1 && !after_pathsep (fname1 ,fname1 + len1 )) { 383fname1 [len1 ]= PATHSEP ; 384memmove (fname1 + len1 + 1 ,fname2 ,len2 + 1 ); 385* len = len1 + 1 + len2 ; 386 }else { 387memmove (fname1 + len1 ,fname2 ,len2 + 1 ); 388* len = len1 + len2 ; 389 } 390 391return 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 ) 404FUNC_ATTR_NONNULL_ALL 405{ 406String ret ; 407ret .data = xmalloc (fname1 .size + (sep ?1 :0 )+ fname2 .size + 1 ); 408memmove (ret .data ,fname1 .data ,fname1 .size + 1 ); 409do_concat_fnames (ret .data ,fname1 .size ,fname2 .data ,fname2 .size ,sep ,& ret .size ); 410return 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 ) 425FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 426{ 427const size_t len1 = strlen (fname1 ); 428const size_t len2 = strlen (fname2 ); 429size_t len ; 430return do_concat_fnames (xrealloc (fname1 ,len1 + len2 + 3 ),len1 , 431fname2 ,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 ) 439FUNC_ATTR_NONNULL_ALL 440{ 441if (* p == NUL ) { 442return true; 443 } 444 445const size_t plen = strlen (p ); 446if (!after_pathsep (p ,p + plen )) { 447const size_t pathsep_len = sizeof (PATHSEPSTR ); 448if (plen > MAXPATHL - pathsep_len ) { 449return false; 450 } 451memcpy (p + plen ,PATHSEPSTR ,pathsep_len ); 452 } 453return 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 ) 464FUNC_ATTR_MALLOC 465{ 466if (fname == NULL ) { 467return NULL ; 468 } 469 470char * buf = xmalloc (MAXPATHL ); 471if (vim_FullName (fname ,buf ,MAXPATHL ,force )== FAIL ) { 472xfree (buf ); 473return TO_SLASH_SAVE (fname ); 474 } 475return 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 ) 482FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 483{ 484if (!path_is_absolute (name )) { 485return FullName_save (name , true); 486 } 487return 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 ) 500FUNC_ATTR_NONNULL_ALL 501{ 502char * wildcards = all ?PATH_ALL_WILDCARDS :PATH_ESC_WILDCARDS ; 503for (;* p ;p ++ ) { 504#ifdef UNIX 505if (p [0 ]== '\\' && p [1 ]!= NUL ) { 506p ++ ; 507continue ; 508 } 509#endif 510if (vim_strchr (wildcards , (uint8_t )(* p ))!= NULL 511|| (all && p [0 ]== '~' && p [1 ]!= NUL )) { 512return true; 513 } 514 } 515return false; 516} 517 518static int pstrcmp (const void * a ,const void * b ) 519{ 520return 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 ) 535FUNC_ATTR_NONNULL_ALL 536{ 537return do_path_expand (gap ,path ,0 ,flags , false); 538} 539 540static const char * scandir_next_with_dots (Directory * dir ) 541{ 542static int count = 0 ; 543if (dir == NULL ) {// initialize 544count = 0 ; 545return NULL ; 546 } 547 548count += 1 ; 549if (count == 1 || count == 2 ) { 550return (count == 1 ) ?"." :".." ; 551 } 552return 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 , 559bool didstar ) 560FUNC_ATTR_NONNULL_ALL 561{ 562int start_len = gap -> ga_len ; 563bool starstar = false; 564static int stardepth = 0 ;// depth for "**" expansion 565 566// Expanding "**" may take a long time, check for CTRL-C. 567if (stardepth > 0 && !(flags & EW_NOBREAK )) { 568os_breakcheck (); 569if (got_int ) { 570return 0 ; 571 } 572 } 573 574// Make room for file name (a bit too much to stay on the safe side). 575const size_t buflen = strlen (path )+ MAXPATHL ; 576char * 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. 581char * p = buf ; 582char * s = buf ; 583char * e = NULL ; 584const char * path_end = path ; 585while (* 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. 588if (path_end >=path + wildoff && rem_backslash (path_end )) { 589* p ++ = * path_end ++ ; 590 }else if (vim_ispathsep_nocolon (* path_end )) { 591if (e != NULL ) { 592break ; 593 } 594s = 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 ) { 604e = p ; 605 } 606int charlen = utfc_ptr2len (path_end ); 607memcpy (p ,path_end , (size_t )charlen ); 608p += charlen ; 609path_end += charlen ; 610 } 611e = 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. 617for (p = buf + wildoff ;p < s ;p ++ ) { 618if (rem_backslash (p )) { 619STRMOVE (p ,p + 1 ); 620e -- ; 621s -- ; 622 } 623 } 624 625// Check for "**" between "s" and "e". 626for (p = s ;p < e ;p ++ ) { 627if (p [0 ]== '*' && p [1 ]== '*' ) { 628starstar = true; 629 } 630 } 631 632// convert the file pattern to a regexp pattern 633int starts_with_dot = * s == '.' ; 634char * pat = file_pat_to_reg_pat (s ,e ,NULL , false); 635if (pat == NULL ) { 636xfree (buf ); 637return 0 ; 638 } 639 640// compile the regexp into a program 641regmatch_T regmatch ; 642#ifdef UNIX 643// Ignore case if given 'wildignorecase', else respect 'fileignorecase'. 644regmatch .rm_ic = (flags & EW_ICASE )|| p_fic ; 645#else 646regmatch .rm_ic = true;// Always ignore case on Windows. 647#endif 648if (flags & (EW_NOERROR |EW_NOTWILD )) { 649emsg_silent ++ ; 650 } 651bool nobreak = (flags & EW_NOBREAK ); 652regmatch .regprog = vim_regcomp (pat ,RE_MAGIC | (nobreak ?RE_NOBREAK :0 )); 653if (flags & (EW_NOERROR |EW_NOTWILD )) { 654emsg_silent -- ; 655 } 656xfree (pat ); 657 658if (regmatch .regprog == NULL && (flags & EW_NOTWILD )== 0 ) { 659xfree (buf ); 660return 0 ; 661 } 662 663size_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. 666if (!didstar && stardepth < 100 && starstar && e - s == 2 667&& * path_end == '/' ) { 668vim_snprintf (s ,buflen - len ,"%s" ,path_end + 1 ); 669stardepth ++ ; 670do_path_expand (gap ,buf ,len ,flags , true); 671stardepth -- ; 672 } 673* s = NUL ; 674 675Directory dir ; 676char * dirpath = (* buf == NUL ?"." :buf ); 677if (os_file_is_readable (dirpath )&& os_scandir (& dir ,dirpath )) { 678// Find all matching entries. 679const char * name ; 680scandir_next_with_dots (NULL );// initialize 681while (!got_int && (name = scandir_next_with_dots (& dir ))!= NULL ) { 682len = (size_t )(s - buf ); 683if ((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 ))) { 691len += (size_t )vim_snprintf (s ,buflen - len ,"%s" ,name ); 692if (len + 1 >=buflen ) { 693continue ; 694 } 695 696if (starstar && stardepth < 100 ) { 697// For "**" in the pattern first go deeper in the tree to 698// find matches. 699vim_snprintf (buf + len ,buflen - len ,"/**%s" ,path_end );// NOLINT 700stardepth ++ ; 701do_path_expand (gap ,buf ,len + 1 ,flags , true); 702stardepth -- ; 703 } 704 705vim_snprintf (buf + len ,buflen - len ,"%s" ,path_end ); 706if (path_has_wildcard (path_end , false)) {// handle more wildcards 707if (stardepth < 100 ) { 708stardepth ++ ; 709// need to expand another component of the path 710// remove backslashes for the remaining components only 711do_path_expand (gap ,buf ,len + 1 ,flags , false); 712stardepth -- ; 713 } 714 }else { 715FileInfo file_info ; 716 717// no more wildcards, check if there is a match 718// remove backslashes for the remaining components only 719if (* path_end != NUL ) { 720backslash_halve (buf + len + 1 ); 721 } 722// add existing file or symbolic link 723if ((flags & EW_ALLLINKS ) 724 ?os_fileinfo_link (buf ,& file_info ) 725 :os_path_exists (buf )) { 726addfile (gap ,buf ,flags ); 727 } 728 } 729 } 730 } 731os_closedir (& dir ); 732 } 733 734xfree (buf ); 735vim_regfree (regmatch .regprog ); 736 737// When interrupted the matches probably won't be used and sorting can be 738// slow, thus skip it. 739size_t matches = (size_t )(gap -> ga_len - start_len ); 740if (matches > 0 && !got_int ) { 741qsort (((char ** )gap -> ga_data )+ start_len ,matches , 742sizeof (char * ),pstrcmp ); 743 } 744return 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 ) 750FUNC_ATTR_NONNULL_ALL 751{ 752// skip the current separator 753if (* psep > path && vim_ispathsep (** psep )) { 754 (* psep )-- ; 755 } 756 757// find the previous separator 758while (* psep > path ) { 759if (vim_ispathsep (** psep )) { 760return OK ; 761 } 762MB_PTR_BACK (path ,* psep ); 763 } 764 765return 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 ) 771FUNC_ATTR_NONNULL_ALL 772{ 773size_t candidate_len = strlen (maybe_unique ); 774char ** other_paths = gap -> ga_data ; 775 776for (int j = 0 ;j < gap -> ga_len ;j ++ ) { 777if (j == i ) { 778continue ;// don't compare it with itself 779 } 780size_t other_path_len = strlen (other_paths [j ]); 781if (other_path_len < candidate_len ) { 782continue ;// it's different when it's shorter 783 } 784char * rival = other_paths [j ]+ other_path_len - candidate_len ; 785if (path_equal (maybe_unique ,rival ,kPathCmpLiteral ) 786&& (rival == other_paths [j ]|| vim_ispathsep (* (rival - 1 )))) { 787return false;// match 788 } 789 } 790return 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 ) 803FUNC_ATTR_NONNULL_ALL 804{ 805char * buf = xmalloc (MAXPATHL ); 806size_t curdirlen = 0 ; 807 808while (* path_option != NUL ) { 809size_t buflen = copy_option_part (& path_option ,buf ,MAXPATHL ," ," ); 810 811// do not expand backticks, could have been set via a modeline 812if (vim_strchr (buf ,'`' )!= NULL ) { 813continue ; 814 } 815 816if (buf [0 ]== '.' && (buf [1 ]== NUL || vim_ispathsep (buf [1 ]))) { 817// Relative to current buffer: 818// "/path/file" + "." -> "/path/" 819// "/path/file" + "./subdir" -> "/path/subdir" 820if (curbuf -> b_ffname == NULL ) { 821continue ; 822 } 823char * p = path_tail (curbuf -> b_ffname ); 824size_t plen = (size_t )(p - curbuf -> b_ffname ); 825if (plen + strlen (buf ) >=MAXPATHL ) { 826continue ; 827 } 828if (buf [1 ]== NUL ) { 829buf [plen ]= NUL ; 830 }else { 831memmove (buf + plen ,buf + 2 , (buflen - 2 )+ 1 );// +1 for NUL 832 } 833memmove (buf ,curbuf -> b_ffname ,plen ); 834buflen = simplify_filename (buf ); 835 }else if (buf [0 ]== NUL ) { 836STRCPY (buf ,curdir );// relative to current directory 837if (curdirlen == 0 ) { 838curdirlen = strlen (curdir ); 839 } 840buflen = curdirlen ; 841 }else if (path_with_url (buf )) { 842continue ;// URL can't be used here 843 }else if (!path_is_absolute (buf )) { 844// Expand relative path to their full path equivalent 845if (curdirlen == 0 ) { 846curdirlen = strlen (curdir ); 847 } 848if (curdirlen + buflen + 3 > MAXPATHL ) { 849continue ; 850 } 851memmove (buf + curdirlen + 1 ,buf ,buflen + 1 );// +1 for NUL 852STRCPY (buf ,curdir ); 853buf [curdirlen ]= PATHSEP ; 854buflen = simplify_filename (buf ); 855 } 856 857GA_APPEND (char * ,gap ,xmemdupz (buf ,buflen )); 858 } 859 860xfree (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 ) 870FUNC_ATTR_NONNULL_ALL 871{ 872int maxlen = 0 ; 873char ** path_part = gap -> ga_data ; 874char * cutoff = NULL ; 875 876for (int i = 0 ;i < gap -> ga_len ;i ++ ) { 877int j = 0 ; 878 879while ((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 ) { 885j ++ ; 886 } 887if (j > maxlen ) { 888maxlen = j ; 889cutoff = & fname [j ]; 890 } 891 } 892 893// skip to the file or directory name 894if (cutoff != NULL ) { 895cutoff = path_skip_sep (cutoff , true); 896 } 897 898return 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 ) 907FUNC_ATTR_NONNULL_ALL 908{ 909char ** fnames = gap -> ga_data ; 910bool sort_again = false; 911regmatch_T regmatch ; 912garray_T path_ga ; 913char ** in_curdir = NULL ; 914char * short_name ; 915 916ga_remove_duplicate_strings (gap ); 917ga_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? 922size_t len = strlen (pattern ); 923char * file_pattern = xmalloc (len + 2 ); 924file_pattern [0 ]= '*' ; 925file_pattern [1 ]= NUL ; 926STRCPY (file_pattern + 1 ,pattern ); 927char * pat = file_pat_to_reg_pat (file_pattern ,NULL ,NULL , false); 928xfree (file_pattern ); 929if (pat == NULL ) { 930return ; 931 } 932 933regmatch .rm_ic = true;// always ignore case 934regmatch .regprog = vim_regcomp (pat ,RE_MAGIC + RE_STRING ); 935xfree (pat ); 936if (regmatch .regprog == NULL ) { 937return ; 938 } 939 940char * curdir = xmalloc (MAXPATHL ); 941os_dirname (curdir ,MAXPATHL ); 942expand_path_option (curdir ,path_option ,& path_ga ); 943 944in_curdir = xcalloc ((size_t )gap -> ga_len ,sizeof (char * )); 945 946for (int i = 0 ;i < gap -> ga_len && !got_int ;i ++ ) { 947char * path = fnames [i ]; 948const char * dir_end = gettail_dir (path ); 949 950len = strlen (path ); 951bool is_in_curdir = path_cmp (p_fic ,curdir ,path , (size_t )(dir_end - path ))== 0 952&& curdir [dir_end - path ]== NUL ; 953if (is_in_curdir ) { 954in_curdir [i ]= xmemdupz (path ,len ); 955 } 956 957// Shorten the filename while maintaining its uniqueness 958char * 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. 963if (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 )) { 968sort_again = true; 969memmove (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. 973char * pathsep_p = path + len - 1 ; 974while (find_previous_pathsep (path ,& pathsep_p )) { 975if (vim_regexec (& regmatch ,pathsep_p + 1 ,0 ) 976&& is_unique (pathsep_p + 1 ,gap ,i ) 977&& path_cutoff != NULL && pathsep_p + 1 >=path_cutoff ) { 978sort_again = true; 979memmove (path ,pathsep_p + 1 , 980 (size_t )((path + len )- (pathsep_p + 1 ))+ 1 );// +1 for NUL 981break ; 982 } 983 } 984 } 985 986if (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 997short_name = path_shorten_fname (path ,curdir ); 998if (short_name != NULL && short_name > path + 1 ) { 999vim_snprintf (path ,MAXPATHL ,".%s%s" ,PATHSEPSTR ,short_name ); 1000 } 1001 } 1002os_breakcheck (); 1003 } 1004 1005// Shorten filenames in /in/current/directory/{filename} 1006for (int i = 0 ;i < gap -> ga_len && !got_int ;i ++ ) { 1007char * path = in_curdir [i ]; 1008 1009if (path == NULL ) { 1010continue ; 1011 } 1012 1013// If the {filename} is not unique, change it to ./{filename}. 1014// Else reduce it to {filename} 1015short_name = path_shorten_fname (path ,curdir ); 1016if (short_name == NULL ) { 1017short_name = path ; 1018 } 1019if (is_unique (short_name ,gap ,i )) { 1020STRCPY (fnames [i ],short_name ); 1021continue ; 1022 } 1023 1024size_t rel_pathsize = 1 + STRLEN_LITERAL (PATHSEPSTR )+ strlen (short_name )+ 1 ; 1025char * rel_path = xmalloc (rel_pathsize ); 1026 1027vim_snprintf (rel_path ,rel_pathsize ,".%s%s" ,PATHSEPSTR ,short_name ); 1028 1029xfree (fnames [i ]); 1030fnames [i ]= rel_path ; 1031sort_again = true; 1032os_breakcheck (); 1033 } 1034 1035xfree (curdir ); 1036for (int i = 0 ;i < gap -> ga_len ;i ++ ) { 1037xfree (in_curdir [i ]); 1038 } 1039xfree (in_curdir ); 1040ga_clear_strings (& path_ga ); 1041vim_regfree (regmatch .regprog ); 1042 1043if (sort_again ) { 1044ga_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 ) 1057FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 1058{ 1059const char * dir_end = fname ; 1060const char * next_dir_end = fname ; 1061bool look_for_sep = true; 1062 1063for (const char * p = fname ;* p != NUL ;p ++ ) { 1064if (vim_ispathsep (* p )) { 1065if (look_for_sep ) { 1066next_dir_end = p ; 1067look_for_sep = false; 1068 } 1069 }else { 1070if (!look_for_sep ) { 1071dir_end = next_dir_end ; 1072 } 1073look_for_sep = true; 1074 } 1075 } 1076return 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 ) 1085FUNC_ATTR_NONNULL_ALL 1086{ 1087garray_T path_ga ; 1088char * path_option = * curbuf -> b_p_path == NUL ?p_path :curbuf -> b_p_path ; 1089 1090char * const curdir = xmalloc (MAXPATHL ); 1091os_dirname (curdir ,MAXPATHL ); 1092 1093ga_init (& path_ga , (int )sizeof (char * ),1 ); 1094if (flags & EW_CDPATH ) { 1095expand_path_option (curdir ,p_cdpath ,& path_ga ); 1096 }else { 1097expand_path_option (curdir ,path_option ,& path_ga ); 1098 } 1099xfree (curdir ); 1100if (GA_EMPTY (& path_ga )) { 1101return 0 ; 1102 } 1103 1104char * const paths = ga_concat_strings (& path_ga ,"," ); 1105ga_clear_strings (& path_ga ); 1106 1107int glob_flags = 0 ; 1108if (flags & EW_ICASE ) { 1109glob_flags |=WILD_ICASE ; 1110 } 1111if (flags & EW_ADDSLASH ) { 1112glob_flags |=WILD_ADD_SLASH ; 1113 } 1114globpath (paths ,pattern ,gap ,glob_flags , !!(flags & EW_CDPATH )); 1115xfree (paths ); 1116 1117return 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 ) 1123FUNC_ATTR_NONNULL_ALL 1124{ 1125for (;* p ;p ++ ) { 1126if (* p == '\\' && p [1 ]!= NUL ) { 1127p ++ ; 1128 }else if (vim_strchr ("$" , (uint8_t )(* p ))!= NULL ) { 1129return true; 1130 } 1131 } 1132return 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 ) 1140FUNC_ATTR_NONNULL_ALL 1141{ 1142for (;* p ;p ++ ) { 1143// Disallow line break characters. 1144if (* p == '\r' || * p == '\n' ) { 1145break ; 1146 } 1147// Allow for escaping. 1148if (* p == '\\' && p [1 ]!= NUL && p [1 ]!= '\r' && p [1 ]!= '\n' ) { 1149p ++ ; 1150 }else if (vim_strchr (SPECIAL_WILDCHAR , (uint8_t )(* p ))!= NULL ) { 1151// Need a shell for curly braces only when including non-existing files. 1152if (* p == '{' && !(flags & EW_NOTFOUND )) { 1153continue ; 1154 } 1155// A { must be followed by a matching }. 1156if (* p == '{' && vim_strchr (p ,'}' )== NULL ) { 1157continue ; 1158 } 1159// A quote and backtick must be followed by another one. 1160if ((* p == '`' || * p == '\'' )&& vim_strchr (p , (uint8_t )(* p ))== NULL ) { 1161continue ; 1162 } 1163return true; 1164 } 1165 } 1166return 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{ 1190garray_T ga ; 1191char * p ; 1192static bool recursive = false; 1193int add_pat ; 1194bool did_expand_in_path = false; 1195char * 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. 1200if (recursive ) { 1201#ifdef SPECIAL_WILDCHAR 1202return os_expand_wildcards (num_pat ,pat ,num_file ,file ,flags ); 1203#else 1204return 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. 1213for (int i = 0 ;i < num_pat ;i ++ ) { 1214if (has_special_wildchar (pat [i ],flags ) 1215&& !(vim_backtick (pat [i ])&& pat [i ][1 ]== '=' )) { 1216return os_expand_wildcards (num_pat ,pat ,num_file ,file ,flags ); 1217 } 1218 } 1219#endif 1220 1221recursive = true; 1222 1223// The matching file names are stored in a growarray. Init it empty. 1224ga_init (& ga , (int )sizeof (char * ),30 ); 1225 1226for (int i = 0 ;i < num_pat && !got_int ;i ++ ) { 1227add_pat = -1 ; 1228p = pat [i ]; 1229 1230if (vim_backtick (p )) { 1231add_pat = expand_backtick (& ga ,p ,flags ); 1232if (add_pat == -1 ) { 1233recursive = false; 1234ga_clear_strings (& ga ); 1235* num_file = 0 ; 1236* file = NULL ; 1237return FAIL ; 1238 } 1239 }else { 1240// First expand environment variables, "~/" and "~user/". 1241if ((has_env_var (p )&& !(flags & EW_NOTENV ))|| * p == '~' ) { 1242p = expand_env_save_opt (p , true, (char * )PATH_ESC_WILDCARDS ); 1243if (p == NULL ) { 1244p = 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. 1250if (has_env_var (p )|| * p == '~' ) { 1251xfree (p ); 1252ga_clear_strings (& ga ); 1253i = os_expand_wildcards (num_pat ,pat ,num_file ,file , 1254flags |EW_KEEPDOLLAR ); 1255recursive = false; 1256return 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. 1267if (path_has_wildcard (p , false)|| (flags & EW_ICASE )) { 1268if ((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. 1276recursive = false; 1277add_pat = expand_in_path (& ga ,p ,flags ); 1278recursive = true; 1279did_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. 1283recursive = false; 1284size_t tmp_add_pat = path_expand (& ga ,p ,flags ); 1285recursive = true; 1286assert (tmp_add_pat <=INT_MAX ); 1287add_pat = (int )tmp_add_pat ; 1288 } 1289 } 1290 } 1291 1292if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND ))) { 1293char * t = backslash_halve_save (p ); 1294 1295// When EW_NOTFOUND is used, always add files and dirs. Makes 1296// "vim c:/" work. 1297if (flags & EW_NOTFOUND ) { 1298addfile (& ga ,t ,flags |EW_DIR |EW_FILE ); 1299 }else { 1300addfile (& ga ,t ,flags ); 1301 } 1302 1303if (t != p ) { 1304xfree (t ); 1305 } 1306 } 1307 1308if (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. 1311recursive = false; 1312uniquefy_paths (& ga ,p ,path_option ); 1313recursive = true; 1314 } 1315if (p != pat [i ]) { 1316xfree (p ); 1317 } 1318 } 1319 1320* num_file = ga .ga_len ; 1321* file = (ga .ga_data != NULL ) ?ga .ga_data :NULL ; 1322 1323recursive = false; 1324 1325return ((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{ 1331if (count <=0 || files == NULL ) { 1332return ; 1333 } 1334while (count -- ) { 1335xfree (files [count ]); 1336 } 1337xfree (files ); 1338} 1339 1340/// @return true if we can expand this backtick thing here. 1341static bool vim_backtick (char * p ) 1342FUNC_ATTR_NONNULL_ALL 1343{ 1344return * 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 ) 1353FUNC_ATTR_NONNULL_ALL 1354{ 1355char * p ; 1356char * buffer ; 1357int cnt = 0 ; 1358 1359// Create the command: lop off the backticks. 1360char * cmd = xmemdupz (pat + 1 ,strlen (pat )- 2 ); 1361 1362if (* cmd == '=' ) {// `={expr}`: Expand expression 1363buffer = eval_to_string (cmd + 1 , true, false); 1364 }else { 1365buffer = get_cmd_output (cmd ,NULL , (flags & EW_SILENT ) ?kShellOptSilent :0 ,NULL ); 1366 } 1367xfree (cmd ); 1368if (buffer == NULL ) { 1369return -1 ; 1370 } 1371 1372cmd = buffer ; 1373while (* cmd != NUL ) { 1374cmd = skipwhite (cmd );// skip over white space 1375p = cmd ; 1376while (* p != NUL && * p != '\r' && * p != '\n' ) {// skip over entry 1377p ++ ; 1378 } 1379// add an entry if it is not empty 1380if (p > cmd ) { 1381char i = * p ; 1382* p = NUL ; 1383addfile (gap ,cmd ,flags ); 1384* p = i ; 1385cnt ++ ; 1386 } 1387cmd = p ; 1388while (* cmd != NUL && (* cmd == '\r' || * cmd == '\n' )) { 1389cmd ++ ; 1390 } 1391 } 1392 1393xfree (buffer ); 1394return 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 ) 1407FUNC_ATTR_NONNULL_ALL 1408{ 1409if (path_with_url (p )) { 1410return ; 1411 } 1412 1413if (* p == '`' ) { 1414// don't replace backslash in backtick quoted strings 1415const size_t len = strlen (p ); 1416if (len > 2 && * (p + len - 1 )== '`' ) { 1417return ; 1418 } 1419 } 1420 1421char from = p_ssl ?'\\' :PATHSEP ; 1422char to = p_ssl ?PATHSEP :'\\' ; 1423strchrsub (p ,from ,to ); 1424} 1425#endif 1426 1427/// Convert all slashes to backslashes in-place. 1428char * path_to_backslash (char * p ) 1429{ 1430if (p != NULL ) { 1431strchrsub (p ,PATHSEP ,'\\' ); 1432 } 1433return 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{ 1440if (p != NULL && !path_with_url (p )) { 1441strchrsub (p ,'\\' ,PATHSEP ); 1442 } 1443return p ; 1444} 1445 1446/// Get an allocated copy of path to convert backslashes. 1447char * path_to_slash_save (const char * p ) 1448{ 1449return 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 ) 1462FUNC_ATTR_NONNULL_ALL 1463{ 1464bool isdir ; 1465FileInfo file_info ; 1466 1467// if the file/dir/link doesn't exist, may not add it 1468if (!(flags & EW_NOTFOUND ) 1469&& ((flags & EW_ALLLINKS ) 1470 ? !os_fileinfo_link (f ,& file_info ) 1471 : !os_path_exists (f ))) { 1472return ; 1473 } 1474 1475#ifdef FNAME_ILLEGAL 1476// if the file/dir contains illegal characters, don't add it 1477if (strpbrk (f ,FNAME_ILLEGAL )!= NULL ) { 1478return ; 1479 } 1480#endif 1481 1482isdir = os_isdir (f ); 1483if ((isdir && !(flags & EW_DIR ))|| (!isdir && !(flags & EW_FILE ))) { 1484return ; 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. 1489if (!isdir && (flags & EW_EXEC ) 1490&& !os_can_exe (f ,NULL , !(flags & EW_SHELLCMD ))) { 1491return ; 1492 } 1493 1494char * p = xmalloc (strlen (f )+ 1 + isdir ); 1495 1496STRCPY (p ,f ); 1497TO_SLASH (p ); 1498// Append a slash or backslash after directory names if none is present. 1499if (isdir && (flags & EW_ADDSLASH )) { 1500add_pathsep (p ); 1501 } 1502GA_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 ) 1510FUNC_ATTR_NONNULL_ALL 1511{ 1512int components = 0 ; 1513bool stripping_disabled = false; 1514bool relative = true; 1515 1516char * p = filename ; 1517#ifdef BACKSLASH_IN_FILENAME 1518if (p [0 ]!= NUL && p [1 ]== ':' ) {// skip "x:" 1519p += 2 ; 1520 } 1521#endif 1522 1523if (vim_ispathsep (* p )) { 1524relative = false; 1525p = path_skip_sep (p , true); 1526 } 1527char * start = p ;// remember start after "c:/" or "/" or "///" 1528char * 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". 1531if (start > filename + 2 ) { 1532memmove (filename + 1 ,p , (size_t )(p_end - p )+ 1 );// +1 for NUL 1533p_end -= (size_t )(p - (filename + 1 )); 1534start = p = filename + 1 ; 1535 } 1536#endif 1537 1538do { 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. 1541if (vim_ispathsep (* p )) { 1542memmove (p ,p + 1 , (size_t )(p_end - (p + 1 ))+ 1 );// remove duplicate "/" 1543p_end -- ; 1544 }else if (p [0 ]== '.' 1545&& (vim_ispathsep (p [1 ])|| p [1 ]== NUL )) { 1546if (p == start && relative ) { 1547p += 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. 1553char * tail = p + 1 ; 1554if (p [1 ]!= NUL ) { 1555tail = path_skip_sep (tail , true); 1556 }else if (p > start ) { 1557p -- ;// strip preceding path separator 1558 } 1559memmove (p ,tail , (size_t )(p_end - tail )+ 1 ); 1560p_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 "..///". 1565char * tail = path_skip_sep (p + 2 , true); 1566 1567if (components > 0 ) {// strip one preceding component 1568bool do_strip = false; 1569 1570// Don't strip for an erroneous file name. 1571if (!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. 1575char saved_char = p [-1 ]; 1576p [-1 ]= NUL ; 1577FileInfo file_info ; 1578if (!os_fileinfo_link (filename ,& file_info )) { 1579do_strip = true; 1580 } 1581p [-1 ]= saved_char ; 1582 1583p -- ; 1584// Skip back to after previous '/'. 1585while (p > start && !after_pathsep (start ,p )) { 1586MB_PTR_BACK (start ,p ); 1587 } 1588 1589if (!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. 1600saved_char = * tail ; 1601* tail = NUL ; 1602if (os_fileinfo (filename ,& file_info )) { 1603do_strip = true; 1604 }else { 1605stripping_disabled = true; 1606 } 1607* tail = saved_char ; 1608if (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.) 1616FileInfo new_file_info ; 1617if (p == start && relative ) { 1618os_fileinfo ("." ,& new_file_info ); 1619 }else { 1620saved_char = * p ; 1621* p = NUL ; 1622os_fileinfo (filename ,& new_file_info ); 1623* p = saved_char ; 1624 } 1625 1626if (!os_fileinfo_id_equal (& file_info ,& new_file_info )) { 1627do_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 1636if (!do_strip ) { 1637// Skip the ".." or "../" and reset the counter for the 1638// components that might be stripped later on. 1639p = tail ; 1640components = 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. 1648if (p == start && relative && tail [-1 ]== '.' ) { 1649* p ++ = '.' ; 1650* p = NUL ; 1651 }else { 1652if (p > start && tail [-1 ]== '.' ) { 1653p -- ; 1654 } 1655memmove (p ,tail , (size_t )(p_end - tail )+ 1 );// strip previous component 1656p_end -= (size_t )(tail - p ); 1657 } 1658 1659components -- ; 1660 } 1661 }else if (p == start && !relative ) {// leading "/.." or "/../" 1662memmove (p ,tail , (size_t )(p_end - tail )+ 1 );// strip ".." or "../" 1663p_end -= (size_t )(tail - p ); 1664 }else { 1665if (p == start + 2 && p [-2 ]== '.' ) {// leading "./../" 1666memmove (p - 2 ,p , (size_t )(p_end - p )+ 1 );// strip leading "./" 1667p_end -= 2 ; 1668tail -= 2 ; 1669 } 1670p = tail ;// skip to char after ".." or "../" 1671 } 1672 }else { 1673components ++ ;// Simple path component. 1674p = (char * )path_next_component (p ); 1675 } 1676 }while (* p != NUL ); 1677 1678return (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 ) 1685FUNC_ATTR_NONNULL_ALL 1686{ 1687return 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 ) 1697FUNC_ATTR_NONNULL_ALL 1698{ 1699// In the spec ':' is enough to recognize a scheme 1700// https://url.spec.whatwg.org/#scheme-state 1701if (strncmp (p ,":/" ,2 )== 0 ) { 1702return URL_SLASH ; 1703 }else if (strncmp (p ,":\\\\" ,3 )== 0 ) { 1704return URL_BACKSLASH ; 1705 } 1706return 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 ) 1714FUNC_ATTR_NONNULL_ALL 1715{ 1716const char * p ; 1717 1718// first character must be alpha 1719if (!ASCII_ISALPHA (* fname )) { 1720return 0 ; 1721 } 1722 1723if (path_has_drive_letter (fname ,strlen (fname ))) { 1724return 0 ; 1725 } 1726 1727// check body: (alpha, digit, '+', '-', '.') following RFC3986 1728for (p = fname + 1 ; (ASCII_ISALNUM (* p )|| (* p == '+' )|| (* p == '-' )|| (* p == '.' ));p ++ ) {} 1729 1730// check last char is not '+', '-', or '.' 1731if ((p [-1 ]== '+' )|| (p [-1 ]== '-' )|| (p [-1 ]== '.' )) { 1732return 0 ; 1733 } 1734 1735// ":/" or ":\\" must follow 1736return path_is_url (p ); 1737} 1738 1739bool path_with_extension (const char * path ,const char * extension ) 1740FUNC_ATTR_NONNULL_ALL 1741{ 1742const char * last_dot = strrchr (path ,'.' ); 1743if (!last_dot ) { 1744return false; 1745 } 1746return 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 ) 1751FUNC_ATTR_NONNULL_ALL 1752{ 1753return 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 ) 1767FUNC_ATTR_NONNULL_ARG (2 ) 1768{ 1769* buf = NUL ; 1770if (fname == NULL ) { 1771return FAIL ; 1772 } 1773 1774if (strlen (fname )> (len - 1 )) { 1775xstrlcpy (buf ,fname ,len );// truncate 1776TO_SLASH (buf ); 1777return FAIL ; 1778 } 1779 1780if (path_with_url (fname )) { 1781xstrlcpy (buf ,fname ,len ); 1782return OK ; 1783 } 1784 1785int rv = path_to_absolute (fname ,buf ,len ,force ); 1786if (rv == FAIL ) { 1787xstrlcpy (buf ,fname ,len );// something failed; use the filename 1788 } 1789TO_SLASH (buf ); 1790return 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 1806return FullName_save (fname , true); 1807#else 1808if (!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 ) { 1819return FullName_save (fname , false); 1820 } 1821 1822fname = TO_SLASH_SAVE (fname ); 1823 1824# ifdef CASE_INSENSITIVE_FILENAME 1825path_fix_case ((char * )fname );// set correct case for file name 1826# endif 1827 1828return (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 ) 1838FUNC_ATTR_NONNULL_ALL 1839{ 1840FileInfo file_info ; 1841if (!os_fileinfo_link (name ,& file_info )) { 1842return ; 1843 } 1844 1845// Open the directory where the file is located. 1846char * slash = strrchr (name ,'/' ); 1847char * tail ; 1848Directory dir ; 1849bool ok ; 1850if (slash == NULL ) { 1851ok = os_scandir (& dir ,"." ); 1852tail = name ; 1853 }else { 1854* slash = NUL ; 1855ok = os_scandir (& dir ,name ); 1856* slash = '/' ; 1857tail = slash + 1 ; 1858 } 1859 1860if (!ok ) { 1861return ; 1862 } 1863 1864size_t taillen = strlen (tail ); 1865const char * entry ; 1866while ((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. 1869if (STRICMP (tail ,entry )== 0 && taillen == strlen (entry )) { 1870char newname [MAXPATHL + 1 ]; 1871 1872// Verify the inode is equal. 1873xstrlcpy (newname ,name ,MAXPATHL + 1 ); 1874xstrlcpy (newname + (tail - name ),entry , 1875 (size_t )(MAXPATHL - (tail - name )+ 1 )); 1876FileInfo file_info_new ; 1877if (os_fileinfo_link (newname ,& file_info_new ) 1878&& os_fileinfo_id_equal (& file_info ,& file_info_new )) { 1879STRCPY (tail ,entry ); 1880break ; 1881 } 1882 } 1883 } 1884 1885os_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 ) 1892FUNC_ATTR_NONNULL_ALL 1893{ 1894return 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{ 1902char ffname [MAXPATHL ]; 1903char * t1 ; 1904char * t2 ; 1905 1906// safety check 1907if (f1 == NULL || f2 == NULL ) { 1908return false; 1909 } 1910 1911vim_FullName (f1 ,ffname ,MAXPATHL , false); 1912t1 = path_tail_with_sep (ffname ); 1913t2 = path_tail_with_sep (f2 ); 1914return 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 ) 1919FUNC_ATTR_NONNULL_ALL 1920{ 1921if (vim_ispathsep_nocolon (* p )) { 1922* len = 1 ; 1923return PATHSEP ; 1924 } 1925* len = ic ?utfc_ptr2len (p ) :1 ; 1926return 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{ 1952const char * s = NULL ; 1953int c1 = NUL ; 1954int c2 = NUL ; 1955size_t len = 0 ; 1956 1957#ifdef MSWIN 1958const char ** pp = NULL ; 1959if (vim_ispathsep_nocolon (* p )&& ASCII_ISALPHA (* q )&& q [1 ]== ':' ) { 1960pp = & q ; 1961 }else if (vim_ispathsep_nocolon (* q )&& ASCII_ISALPHA (* p )&& p [1 ]== ':' ) { 1962pp = & p ; 1963 } 1964if (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 1969for (int i = 0 ,j = 0 ;len < maxlen ;len += (size_t )i ) { 1970c1 = path_fold_char (ic ,p ,& i ); 1971c2 = path_fold_char (ic ,q ,& j ); 1972if (c1 == NUL || c2 == NUL || c1 != c2 ) { 1973break ; 1974 } 1975p += i ; 1976q += j ; 1977 } 1978 1979if ((c1 == NUL && c2 == NUL )|| len >=maxlen ) { 1980return 0 ; 1981 } 1982 1983if (c1 != NUL && c2 != NUL ) { 1984if (vim_ispathsep (c1 )) { 1985return -1 ; 1986 } 1987if (vim_ispathsep (c2 )) { 1988return 1 ; 1989 } 1990return c1 - c2 ; 1991 } 1992 1993s = c1 == NUL ?q :p ; 1994// match with a single trailing slash, but not "//" or ":/" 1995if (vim_ispathsep_nocolon (* s ) 1996&& s [1 ]== NUL 1997&& len > 0 1998&& !vim_ispathsep (s [-1 ])) { 1999return 0 ; 2000 } 2001return 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{ 2014char * dirname = xmalloc (MAXPATHL ); 2015char * p = full_path ; 2016 2017if (os_dirname (dirname ,MAXPATHL )== OK ) { 2018p = path_shorten_fname (full_path ,dirname ); 2019if (p == NULL || * p == NUL ) { 2020p = full_path ; 2021 } 2022 } 2023xfree (dirname ); 2024return 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{ 2036if (full_path == NULL ) { 2037return NULL ; 2038 } 2039 2040assert (dir_name != NULL ); 2041size_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. 2045if (path_cmp (p_fic ,dir_name ,full_path ,len )!= 0 ) { 2046return NULL ; 2047 } 2048 2049// If dir_name is a path head, full_path can always be made relative. 2050if (len == (size_t )path_head_length ()&& is_path_head (dir_name )) { 2051return full_path + len ; 2052 } 2053 2054char * 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. 2059if (!vim_ispathsep (* p )) { 2060return NULL ; 2061 } 2062 2063// Skip the matched separator, then any following separators (but not a colon). 2064return 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{ 2083int ret = FAIL ; 2084char * eval_pat = NULL ; 2085char * exp_pat = * pat ; 2086const char * ignored_msg ; 2087size_t usedlen ; 2088const bool is_cur_alt_file = * exp_pat == '%' || * exp_pat == '#' ; 2089bool star_follows = false; 2090 2091if (is_cur_alt_file || * exp_pat == '<' ) { 2092emsg_off ++ ; 2093eval_pat = eval_vars (exp_pat ,exp_pat ,& usedlen ,NULL ,& ignored_msg , 2094NULL , 2095 true); 2096emsg_off -- ; 2097if (eval_pat != NULL ) { 2098star_follows = strcmp (exp_pat + usedlen ,"*" )== 0 ; 2099exp_pat = concat_str (eval_pat ,exp_pat + usedlen ); 2100 } 2101 } 2102 2103if (exp_pat != NULL ) { 2104ret = expand_wildcards (1 ,& exp_pat ,num_file ,file ,flags ); 2105 } 2106 2107if (eval_pat != NULL ) { 2108if (* 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 ; 2114eval_pat = NULL ; 2115* num_file = 1 ; 2116ret = OK ; 2117 } 2118xfree (exp_pat ); 2119xfree (eval_pat ); 2120 } 2121 2122return 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{ 2141int retval = gen_expand_wildcards (num_pat ,pat ,num_files ,files ,flags ); 2142 2143// When keeping all matches, return here 2144if ((flags & EW_KEEPALL )|| retval == FAIL ) { 2145return retval ; 2146 } 2147 2148// Remove names that match 'wildignore'. 2149if (* p_wig ) { 2150// check all files in (*files)[] 2151assert (* num_files == 0 || * files != NULL ); 2152for (int i = 0 ;i < * num_files ;i ++ ) { 2153char * ffname = FullName_save ((* files )[i ], false); 2154assert ((* files )[i ]!= NULL ); 2155assert (ffname != NULL ); 2156if (match_file_list (p_wig , (* files )[i ],ffname )) { 2157// remove this matching file from the list 2158xfree ((* files )[i ]); 2159for (int j = i ;j + 1 < * num_files ;j ++ ) { 2160 (* files )[j ]= (* files )[j + 1 ]; 2161 } 2162 (* num_files )-- ; 2163i -- ; 2164 } 2165xfree (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. 2171assert (* num_files == 0 || * files != NULL ); 2172if (* num_files > 1 && !got_int ) { 2173int non_suf_match = 0 ;// number without matching suffix 2174for (int i = 0 ;i < * num_files ;i ++ ) { 2175if (!match_suffix ((* files )[i ])) { 2176// Move the name without matching suffix to the front of the list. 2177char * p = (* files )[i ]; 2178for (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 2187if (* num_files == 0 ) { 2188XFREE_CLEAR (* files ); 2189return FAIL ; 2190 } 2191 2192return retval ; 2193} 2194 2195/// @return true if "fname" matches with an entry in 'suffixes'. 2196bool match_suffix (char * fname ) 2197FUNC_ATTR_NONNULL_ALL 2198{ 2199#define MAXSUFLEN 30 // maximum length of a file suffix 2200char suf_buf [MAXSUFLEN ]; 2201 2202size_t fnamelen = strlen (fname ); 2203size_t setsuflen = 0 ; 2204for (char * setsuf = p_su ;* setsuf ;) { 2205setsuflen = copy_option_part (& setsuf ,suf_buf ,MAXSUFLEN ,".," ); 2206if (setsuflen == 0 ) { 2207char * tail = path_tail (fname ); 2208 2209// empty entry: match name without a '.' 2210if (vim_strchr (tail ,'.' )== NULL ) { 2211setsuflen = 1 ; 2212break ; 2213 } 2214 }else { 2215if (fnamelen >=setsuflen 2216&& path_cmp (p_fic ,suf_buf ,fname + fnamelen - setsuflen ,setsuflen )== 0 ) { 2217break ; 2218 } 2219setsuflen = 0 ; 2220 } 2221 } 2222return 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 ) 2230FUNC_ATTR_NONNULL_ALL 2231{ 2232if (strlen (directory )== 0 ) { 2233return os_dirname (buffer ,len ); 2234 } 2235 2236if (os_realpath (directory ,buffer ,len )!= NULL ) { 2237return OK ; 2238 } 2239 2240// Path does not exist (yet). For a full path fail, will use the path as-is. 2241if (path_is_absolute (directory )) { 2242return FAIL ; 2243 } 2244// For a relative path use the current directory and append the file name. 2245 2246char old_dir [MAXPATHL ]; 2247 2248// Get current directory name. 2249if (os_dirname (old_dir ,MAXPATHL )== FAIL ) { 2250return FAIL ; 2251 } 2252 2253xstrlcpy (buffer ,old_dir ,len ); 2254if (append_path (buffer ,directory ,len )== FAIL ) { 2255return FAIL ; 2256 } 2257 2258return 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 ) 2263FUNC_ATTR_NONNULL_ALL 2264{ 2265size_t current_length = strlen (path ); 2266size_t to_append_length = strlen (to_append ); 2267 2268// Do not append empty string or a dot. 2269if (to_append_length == 0 || strcmp (to_append ,"." )== 0 ) { 2270return OK ; 2271 } 2272 2273// Combine the path segments, separated by a slash. 2274if (current_length > 0 && !vim_ispathsep_nocolon (path [current_length - 1 ])) { 2275// +1 for the NUL at the end. 2276if (current_length + STRLEN_LITERAL (PATHSEPSTR )+ 1 > max_len ) { 2277return FAIL ;// No space for trailing slash. 2278 } 2279xstrlcpy (path + current_length ,PATHSEPSTR ,max_len - current_length ); 2280current_length += STRLEN_LITERAL (PATHSEPSTR ); 2281 } 2282 2283// +1 for the NUL at the end. 2284if (current_length + to_append_length + 1 > max_len ) { 2285return FAIL ; 2286 } 2287 2288xstrlcpy (path + current_length ,to_append ,max_len - current_length ); 2289return 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 ) 2301FUNC_ATTR_NONNULL_ALL 2302{ 2303const char * p ; 2304* buf = NUL ; 2305 2306char * relative_directory = xmalloc (len ); 2307const char * end_of_path = fname ; 2308 2309// expand it if forced or not an absolute path 2310if (force || !path_is_absolute (fname ) 2311#ifdef MSWIN // enforce drive letter on Windows paths 2312|| fname [0 ]== '/' || fname [0 ]== '\\' 2313#endif 2314 ) { 2315p = strrchr (fname ,'/' ); 2316#ifdef MSWIN 2317if (p == NULL ) { 2318p = strrchr (fname ,'\\' ); 2319 } 2320if (p == NULL && ASCII_ISALPHA (fname [0 ])&& fname [1 ]== ':' ) {// drive letter 2321p = fname + 1 ; 2322 } 2323#endif 2324if (p == NULL && strcmp (fname ,".." )== 0 ) { 2325// Handle ".." without path separators. 2326p = fname + 2 ; 2327 } 2328if (p != NULL ) { 2329if (vim_ispathsep (* p )&& strcmp (p + 1 ,".." )== 0 ) { 2330// For "/path/dir/.." include the "/..". 2331p += 3 ; 2332 } 2333assert (p >=fname ); 2334memcpy (relative_directory ,fname , (size_t )(p - fname + 1 )); 2335relative_directory [p - fname + 1 ]= NUL ; 2336end_of_path = (vim_ispathsep (* p ) ?p + 1 :p ); 2337 }else { 2338relative_directory [0 ]= NUL ; 2339 } 2340 2341if (FAIL == path_full_dir_name (relative_directory ,buf ,len )) { 2342xfree (relative_directory ); 2343return FAIL ; 2344 } 2345 } 2346xfree (relative_directory ); 2347return 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 ) 2354FUNC_ATTR_NONNULL_ALL 2355{ 2356#ifdef MSWIN 2357if (* fname == NUL ) { 2358return 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. 2362return ((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 '~'. 2366return * 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 ) 2378FUNC_ATTR_NONNULL_ALL 2379{ 2380char * path = os_getenv ("PATH" ); 2381 2382if (path == NULL || path_is_absolute (argv0 )) { 2383xstrlcpy (buf ,argv0 ,bufsize ); 2384 }else if (argv0 [0 ]== '.' || strchr (argv0 ,PATHSEP )) { 2385// Relative to CWD. 2386if (os_dirname (buf ,MAXPATHL )!= OK ) { 2387buf [0 ]= NUL ; 2388 } 2389xstrlcat (buf ,PATHSEPSTR ,bufsize ); 2390xstrlcat (buf ,argv0 ,bufsize ); 2391 }else { 2392// Search $PATH for plausible location. 2393const void * iter = NULL ; 2394do { 2395const char * dir ; 2396size_t dir_len ; 2397iter = vim_env_iter (ENV_SEPCHAR ,path ,iter ,& dir ,& dir_len ); 2398if (dir == NULL || dir_len == 0 ) { 2399break ; 2400 } 2401if (dir_len + 1 > sizeof (NameBuff )) { 2402continue ; 2403 } 2404xmemcpyz (NameBuff ,dir ,dir_len ); 2405xstrlcat (NameBuff ,PATHSEPSTR ,sizeof (NameBuff )); 2406xstrlcat (NameBuff ,argv0 ,sizeof (NameBuff )); 2407if (os_can_exe (NameBuff ,NULL , false)) { 2408xstrlcpy (buf ,NameBuff ,bufsize ); 2409TO_SLASH (buf ); 2410return ; 2411 } 2412 }while (iter != NULL ); 2413// Not found in $PATH, fall back to argv0. 2414xstrlcpy (buf ,argv0 ,bufsize ); 2415 } 2416xfree (path ); 2417}