1 /* vi:set ts=8 sts=4 sw=4 noet: 2 * 3 * VIM - Vi IMproved by Bram Moolenaar 4 * 5 * Do ":help uganda" in Vim to read copying and usage conditions. 6 * Do ":help credits" in Vim to see a list of people who contributed. 7 * See README.txt for an overview of the Vim source code. 8 */ 9 10 /* 11 * filepath.c: dealing with file names and paths. 12 */ 13 14 #include "vim.h" 15 16 #ifdef MSWIN 17 /* 18 * Functions for ":8" filename modifier: get 8.3 version of a filename. 19 */ 20 21 /* 22 * Get the short path (8.3) for the filename in "fnamep". 23 * Only works for a valid file name. 24 * When the path gets longer "fnamep" is changed and the allocated buffer 25 * is put in "bufp". 26 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path. 27 * Returns OK on success, FAIL on failure. 28 */ 29 static int 30 get_short_pathname(char_u **fnamep, char_u **bufp, int *fnamelen) 31 { 32 int l, len; 33 WCHAR *newbuf; 34 WCHAR *wfname; 35 36 len = MAXPATHL; 37 newbuf = malloc(len * sizeof(*newbuf)); 38 if (newbuf == NULL) 39 return FAIL; 40 41 wfname = enc_to_utf16(*fnamep, NULL); 42 if (wfname == NULL) 43 { 44 vim_free(newbuf); 45 return FAIL; 46 } 47 48 l = GetShortPathNameW(wfname, newbuf, len); 49 if (l > len - 1) 50 { 51 // If that doesn't work (not enough space), then save the string 52 // and try again with a new buffer big enough. 53 WCHAR *newbuf_t = newbuf; 54 newbuf = vim_realloc(newbuf, (l + 1) * sizeof(*newbuf)); 55 if (newbuf == NULL) 56 { 57 vim_free(wfname); 58 vim_free(newbuf_t); 59 return FAIL; 60 } 61 // Really should always succeed, as the buffer is big enough. 62 l = GetShortPathNameW(wfname, newbuf, l+1); 63 } 64 if (l != 0) 65 { 66 char_u *p = utf16_to_enc(newbuf, NULL); 67 68 if (p != NULL) 69 { 70 vim_free(*bufp); 71 *fnamep = *bufp = p; 72 } 73 else 74 { 75 vim_free(wfname); 76 vim_free(newbuf); 77 return FAIL; 78 } 79 } 80 vim_free(wfname); 81 vim_free(newbuf); 82 83 *fnamelen = l == 0 ? l : (int)STRLEN(*bufp); 84 return OK; 85 } 86 87 /* 88 * Get the short path (8.3) for the filename in "fname". The converted 89 * path is returned in "bufp". 90 * 91 * Some of the directories specified in "fname" may not exist. This function 92 * will shorten the existing directories at the beginning of the path and then 93 * append the remaining non-existing path. 94 * 95 * fname - Pointer to the filename to shorten. On return, contains the 96 * pointer to the shortened pathname 97 * bufp - Pointer to an allocated buffer for the filename. 98 * fnamelen - Length of the filename pointed to by fname 99 * 100 * Returns OK on success (or nothing done) and FAIL on failure (out of memory). 101 */ 102 static int 103 shortpath_for_invalid_fname( 104 char_u **fname, 105 char_u **bufp, 106 int *fnamelen) 107 { 108 char_u *short_fname, *save_fname, *pbuf_unused; 109 char_u *endp, *save_endp; 110 char_u ch; 111 int old_len, len; 112 int new_len, sfx_len; 113 int retval = OK; 114 115 // Make a copy 116 old_len = *fnamelen; 117 save_fname = vim_strnsave(*fname, old_len); 118 pbuf_unused = NULL; 119 short_fname = NULL; 120 121 endp = save_fname + old_len - 1; // Find the end of the copy 122 save_endp = endp; 123 124 /* 125 * Try shortening the supplied path till it succeeds by removing one 126 * directory at a time from the tail of the path. 127 */ 128 len = 0; 129 for (;;) 130 { 131 // go back one path-separator 132 while (endp > save_fname && !after_pathsep(save_fname, endp + 1)) 133 --endp; 134 if (endp <= save_fname) 135 break; // processed the complete path 136 137 /* 138 * Replace the path separator with a NUL and try to shorten the 139 * resulting path. 140 */ 141 ch = *endp; 142 *endp = 0; 143 short_fname = save_fname; 144 len = (int)STRLEN(short_fname) + 1; 145 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL) 146 { 147 retval = FAIL; 148 goto theend; 149 } 150 *endp = ch; // preserve the string 151 152 if (len > 0) 153 break; // successfully shortened the path 154 155 // failed to shorten the path. Skip the path separator 156 --endp; 157 } 158 159 if (len > 0) 160 { 161 /* 162 * Succeeded in shortening the path. Now concatenate the shortened 163 * path with the remaining path at the tail. 164 */ 165 166 // Compute the length of the new path. 167 sfx_len = (int)(save_endp - endp) + 1; 168 new_len = len + sfx_len; 169 170 *fnamelen = new_len; 171 vim_free(*bufp); 172 if (new_len > old_len) 173 { 174 // There is not enough space in the currently allocated string, 175 // copy it to a buffer big enough. 176 *fname = *bufp = vim_strnsave(short_fname, new_len); 177 if (*fname == NULL) 178 { 179 retval = FAIL; 180 goto theend; 181 } 182 } 183 else 184 { 185 // Transfer short_fname to the main buffer (it's big enough), 186 // unless get_short_pathname() did its work in-place. 187 *fname = *bufp = save_fname; 188 if (short_fname != save_fname) 189 vim_strncpy(save_fname, short_fname, len); 190 save_fname = NULL; 191 } 192 193 // concat the not-shortened part of the path 194 vim_strncpy(*fname + len, endp, sfx_len); 195 (*fname)[new_len] = NUL; 196 } 197 198 theend: 199 vim_free(pbuf_unused); 200 vim_free(save_fname); 201 202 return retval; 203 } 204 205 /* 206 * Get a pathname for a partial path. 207 * Returns OK for success, FAIL for failure. 208 */ 209 static int 210 shortpath_for_partial( 211 char_u **fnamep, 212 char_u **bufp, 213 int *fnamelen) 214 { 215 int sepcount, len, tflen; 216 char_u *p; 217 char_u *pbuf, *tfname; 218 int hasTilde; 219 220 // Count up the path separators from the RHS.. so we know which part 221 // of the path to return. 222 sepcount = 0; 223 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p)) 224 if (vim_ispathsep(*p)) 225 ++sepcount; 226 227 // Need full path first (use expand_env() to remove a "~/") 228 hasTilde = (**fnamep == '~'); 229 if (hasTilde) 230 pbuf = tfname = expand_env_save(*fnamep); 231 else 232 pbuf = tfname = FullName_save(*fnamep, FALSE); 233 234 len = tflen = (int)STRLEN(tfname); 235 236 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL) 237 return FAIL; 238 239 if (len == 0) 240 { 241 // Don't have a valid filename, so shorten the rest of the 242 // path if we can. This CAN give us invalid 8.3 filenames, but 243 // there's not a lot of point in guessing what it might be. 244 len = tflen; 245 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL) 246 return FAIL; 247 } 248 249 // Count the paths backward to find the beginning of the desired string. 250 for (p = tfname + len - 1; p >= tfname; --p) 251 { 252 if (has_mbyte) 253 p -= mb_head_off(tfname, p); 254 if (vim_ispathsep(*p)) 255 { 256 if (sepcount == 0 || (hasTilde && sepcount == 1)) 257 break; 258 else 259 sepcount --; 260 } 261 } 262 if (hasTilde) 263 { 264 --p; 265 if (p >= tfname) 266 *p = '~'; 267 else 268 return FAIL; 269 } 270 else 271 ++p; 272 273 // Copy in the string - p indexes into tfname - allocated at pbuf 274 vim_free(*bufp); 275 *fnamelen = (int)STRLEN(p); 276 *bufp = pbuf; 277 *fnamep = p; 278 279 return OK; 280 } 281 #endif // MSWIN 282 283 /* 284 * Adjust a filename, according to a string of modifiers. 285 * *fnamep must be NUL terminated when called. When returning, the length is 286 * determined by *fnamelen. 287 * Returns VALID_ flags or -1 for failure. 288 * When there is an error, *fnamep is set to NULL. 289 */ 290 int 291 modify_fname( 292 char_u *src, // string with modifiers 293 int tilde_file, // "~" is a file name, not $HOME 294 int *usedlen, // characters after src that are used 295 char_u **fnamep, // file name so far 296 char_u **bufp, // buffer for allocated file name or NULL 297 int *fnamelen) // length of fnamep 298 { 299 int valid = 0; 300 char_u *tail; 301 char_u *s, *p, *pbuf; 302 char_u dirname[MAXPATHL]; 303 int c; 304 int has_fullname = 0; 305 int has_homerelative = 0; 306 #ifdef MSWIN 307 char_u *fname_start = *fnamep; 308 int has_shortname = 0; 309 #endif 310 311 repeat: 312 // ":p" - full path/file_name 313 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p') 314 { 315 has_fullname = 1; 316 317 valid |= VALID_PATH; 318 *usedlen += 2; 319 320 // Expand "~/path" for all systems and "~user/path" for Unix and VMS 321 if ((*fnamep)[0] == '~' 322 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME)) 323 && ((*fnamep)[1] == '/' 324 # ifdef BACKSLASH_IN_FILENAME 325 || (*fnamep)[1] == '\\' 326 # endif 327 || (*fnamep)[1] == NUL) 328 #endif 329 && !(tilde_file && (*fnamep)[1] == NUL) 330 ) 331 { 332 *fnamep = expand_env_save(*fnamep); 333 vim_free(*bufp); // free any allocated file name 334 *bufp = *fnamep; 335 if (*fnamep == NULL) 336 return -1; 337 } 338 339 // When "/." or "/.." is used: force expansion to get rid of it. 340 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p)) 341 { 342 if (vim_ispathsep(*p) 343 && p[1] == '.' 344 && (p[2] == NUL 345 || vim_ispathsep(p[2]) 346 || (p[2] == '.' 347 && (p[3] == NUL || vim_ispathsep(p[3]))))) 348 break; 349 } 350 351 // FullName_save() is slow, don't use it when not needed. 352 if (*p != NUL || !vim_isAbsName(*fnamep)) 353 { 354 *fnamep = FullName_save(*fnamep, *p != NUL); 355 vim_free(*bufp); // free any allocated file name 356 *bufp = *fnamep; 357 if (*fnamep == NULL) 358 return -1; 359 } 360 361 #ifdef MSWIN 362 # if _WIN32_WINNT >= 0x0500 363 if (vim_strchr(*fnamep, '~') != NULL) 364 { 365 // Expand 8.3 filename to full path. Needed to make sure the same 366 // file does not have two different names. 367 // Note: problem does not occur if _WIN32_WINNT < 0x0500. 368 WCHAR *wfname = enc_to_utf16(*fnamep, NULL); 369 WCHAR buf[_MAX_PATH]; 370 371 if (wfname != NULL) 372 { 373 if (GetLongPathNameW(wfname, buf, _MAX_PATH)) 374 { 375 char_u *p = utf16_to_enc(buf, NULL); 376 377 if (p != NULL) 378 { 379 vim_free(*bufp); // free any allocated file name 380 *bufp = *fnamep = p; 381 } 382 } 383 vim_free(wfname); 384 } 385 } 386 # endif 387 #endif 388 // Append a path separator to a directory. 389 if (mch_isdir(*fnamep)) 390 { 391 // Make room for one or two extra characters. 392 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2); 393 vim_free(*bufp); // free any allocated file name 394 *bufp = *fnamep; 395 if (*fnamep == NULL) 396 return -1; 397 add_pathsep(*fnamep); 398 } 399 } 400 401 // ":." - path relative to the current directory 402 // ":~" - path relative to the home directory 403 // ":8" - shortname path - postponed till after 404 while (src[*usedlen] == ':' 405 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8')) 406 { 407 *usedlen += 2; 408 if (c == '8') 409 { 410 #ifdef MSWIN 411 has_shortname = 1; // Postpone this. 412 #endif 413 continue; 414 } 415 pbuf = NULL; 416 // Need full path first (use expand_env() to remove a "~/") 417 if (!has_fullname && !has_homerelative) 418 { 419 if ((c == '.' || c == '~') && **fnamep == '~') 420 p = pbuf = expand_env_save(*fnamep); 421 else 422 p = pbuf = FullName_save(*fnamep, FALSE); 423 } 424 else 425 p = *fnamep; 426 427 has_fullname = 0; 428 429 if (p != NULL) 430 { 431 if (c == '.') 432 { 433 size_t namelen; 434 435 mch_dirname(dirname, MAXPATHL); 436 if (has_homerelative) 437 { 438 s = vim_strsave(dirname); 439 if (s != NULL) 440 { 441 home_replace(NULL, s, dirname, MAXPATHL, TRUE); 442 vim_free(s); 443 } 444 } 445 namelen = STRLEN(dirname); 446 447 // Do not call shorten_fname() here since it removes the prefix 448 // even though the path does not have a prefix. 449 if (fnamencmp(p, dirname, namelen) == 0) 450 { 451 p += namelen; 452 if (vim_ispathsep(*p)) 453 { 454 while (*p && vim_ispathsep(*p)) 455 ++p; 456 *fnamep = p; 457 if (pbuf != NULL) 458 { 459 // free any allocated file name 460 vim_free(*bufp); 461 *bufp = pbuf; 462 pbuf = NULL; 463 } 464 } 465 } 466 } 467 else 468 { 469 home_replace(NULL, p, dirname, MAXPATHL, TRUE); 470 // Only replace it when it starts with '~' 471 if (*dirname == '~') 472 { 473 s = vim_strsave(dirname); 474 if (s != NULL) 475 { 476 *fnamep = s; 477 vim_free(*bufp); 478 *bufp = s; 479 has_homerelative = TRUE; 480 } 481 } 482 } 483 vim_free(pbuf); 484 } 485 } 486 487 tail = gettail(*fnamep); 488 *fnamelen = (int)STRLEN(*fnamep); 489 490 // ":h" - head, remove "/file_name", can be repeated 491 // Don't remove the first "/" or "c:\" 492 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h') 493 { 494 valid |= VALID_HEAD; 495 *usedlen += 2; 496 s = get_past_head(*fnamep); 497 while (tail > s && after_pathsep(s, tail)) 498 MB_PTR_BACK(*fnamep, tail); 499 *fnamelen = (int)(tail - *fnamep); 500 #ifdef VMS 501 if (*fnamelen > 0) 502 *fnamelen += 1; // the path separator is part of the path 503 #endif 504 if (*fnamelen == 0) 505 { 506 // Result is empty. Turn it into "." to make ":cd %:h" work. 507 p = vim_strsave((char_u *)"."); 508 if (p == NULL) 509 return -1; 510 vim_free(*bufp); 511 *bufp = *fnamep = tail = p; 512 *fnamelen = 1; 513 } 514 else 515 { 516 while (tail > s && !after_pathsep(s, tail)) 517 MB_PTR_BACK(*fnamep, tail); 518 } 519 } 520 521 // ":8" - shortname 522 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8') 523 { 524 *usedlen += 2; 525 #ifdef MSWIN 526 has_shortname = 1; 527 #endif 528 } 529 530 #ifdef MSWIN 531 /* 532 * Handle ":8" after we have done 'heads' and before we do 'tails'. 533 */ 534 if (has_shortname) 535 { 536 // Copy the string if it is shortened by :h and when it wasn't copied 537 // yet, because we are going to change it in place. Avoids changing 538 // the buffer name for "%:8". 539 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start) 540 { 541 p = vim_strnsave(*fnamep, *fnamelen); 542 if (p == NULL) 543 return -1; 544 vim_free(*bufp); 545 *bufp = *fnamep = p; 546 } 547 548 // Split into two implementations - makes it easier. First is where 549 // there isn't a full name already, second is where there is. 550 if (!has_fullname && !vim_isAbsName(*fnamep)) 551 { 552 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL) 553 return -1; 554 } 555 else 556 { 557 int l = *fnamelen; 558 559 // Simple case, already have the full-name. 560 // Nearly always shorter, so try first time. 561 if (get_short_pathname(fnamep, bufp, &l) == FAIL) 562 return -1; 563 564 if (l == 0) 565 { 566 // Couldn't find the filename, search the paths. 567 l = *fnamelen; 568 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL) 569 return -1; 570 } 571 *fnamelen = l; 572 } 573 } 574 #endif // MSWIN 575 576 // ":t" - tail, just the basename 577 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't') 578 { 579 *usedlen += 2; 580 *fnamelen -= (int)(tail - *fnamep); 581 *fnamep = tail; 582 } 583 584 // ":e" - extension, can be repeated 585 // ":r" - root, without extension, can be repeated 586 while (src[*usedlen] == ':' 587 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r')) 588 { 589 // find a '.' in the tail: 590 // - for second :e: before the current fname 591 // - otherwise: The last '.' 592 if (src[*usedlen + 1] == 'e' && *fnamep > tail) 593 s = *fnamep - 2; 594 else 595 s = *fnamep + *fnamelen - 1; 596 for ( ; s > tail; --s) 597 if (s[0] == '.') 598 break; 599 if (src[*usedlen + 1] == 'e') // :e 600 { 601 if (s > tail) 602 { 603 *fnamelen += (int)(*fnamep - (s + 1)); 604 *fnamep = s + 1; 605 #ifdef VMS 606 // cut version from the extension 607 s = *fnamep + *fnamelen - 1; 608 for ( ; s > *fnamep; --s) 609 if (s[0] == ';') 610 break; 611 if (s > *fnamep) 612 *fnamelen = s - *fnamep; 613 #endif 614 } 615 else if (*fnamep <= tail) 616 *fnamelen = 0; 617 } 618 else // :r 619 { 620 char_u *limit = *fnamep; 621 622 if (limit < tail) 623 limit = tail; 624 if (s > limit) // remove one extension 625 *fnamelen = (int)(s - *fnamep); 626 } 627 *usedlen += 2; 628 } 629 630 // ":s?pat?foo?" - substitute 631 // ":gs?pat?foo?" - global substitute 632 if (src[*usedlen] == ':' 633 && (src[*usedlen + 1] == 's' 634 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's'))) 635 { 636 char_u *str; 637 char_u *pat; 638 char_u *sub; 639 int sep; 640 char_u *flags; 641 int didit = FALSE; 642 643 flags = (char_u *)""; 644 s = src + *usedlen + 2; 645 if (src[*usedlen + 1] == 'g') 646 { 647 flags = (char_u *)"g"; 648 ++s; 649 } 650 651 sep = *s++; 652 if (sep) 653 { 654 // find end of pattern 655 p = vim_strchr(s, sep); 656 if (p != NULL) 657 { 658 pat = vim_strnsave(s, p - s); 659 if (pat != NULL) 660 { 661 s = p + 1; 662 // find end of substitution 663 p = vim_strchr(s, sep); 664 if (p != NULL) 665 { 666 sub = vim_strnsave(s, p - s); 667 str = vim_strnsave(*fnamep, *fnamelen); 668 if (sub != NULL && str != NULL) 669 { 670 *usedlen = (int)(p + 1 - src); 671 s = do_string_sub(str, pat, sub, NULL, flags); 672 if (s != NULL) 673 { 674 *fnamep = s; 675 *fnamelen = (int)STRLEN(s); 676 vim_free(*bufp); 677 *bufp = s; 678 didit = TRUE; 679 } 680 } 681 vim_free(sub); 682 vim_free(str); 683 } 684 vim_free(pat); 685 } 686 } 687 // after using ":s", repeat all the modifiers 688 if (didit) 689 goto repeat; 690 } 691 } 692 693 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S') 694 { 695 // vim_strsave_shellescape() needs a NUL terminated string. 696 c = (*fnamep)[*fnamelen]; 697 if (c != NUL) 698 (*fnamep)[*fnamelen] = NUL; 699 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE); 700 if (c != NUL) 701 (*fnamep)[*fnamelen] = c; 702 if (p == NULL) 703 return -1; 704 vim_free(*bufp); 705 *bufp = *fnamep = p; 706 *fnamelen = (int)STRLEN(p); 707 *usedlen += 2; 708 } 709 710 return valid; 711 } 712 713 /* 714 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname" 715 * "trim_len" specifies how many characters to keep for each directory. 716 * Must be 1 or more. 717 * It's done in-place. 718 */ 719 static void 720 shorten_dir_len(char_u *str, int trim_len) 721 { 722 char_u *tail, *s, *d; 723 int skip = FALSE; 724 int dirchunk_len = 0; 725 726 tail = gettail(str); 727 d = str; 728 for (s = str; ; ++s) 729 { 730 if (s >= tail) // copy the whole tail 731 { 732 *d++ = *s; 733 if (*s == NUL) 734 break; 735 } 736 else if (vim_ispathsep(*s)) // copy '/' and next char 737 { 738 *d++ = *s; 739 skip = FALSE; 740 dirchunk_len = 0; 741 } 742 else if (!skip) 743 { 744 *d++ = *s; // copy next char 745 if (*s != '~' && *s != '.') // and leading "~" and "." 746 { 747 ++dirchunk_len; // only count word chars for the size 748 749 // keep copying chars until we have our preferred length (or 750 // until the above if/else branches move us along) 751 if (dirchunk_len >= trim_len) 752 skip = TRUE; 753 } 754 755 if (has_mbyte) 756 { 757 int l = mb_ptr2len(s); 758 759 while (--l > 0) 760 *d++ = *++s; 761 } 762 } 763 } 764 } 765 766 /* 767 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname" 768 * It's done in-place. 769 */ 770 void 771 shorten_dir(char_u *str) 772 { 773 shorten_dir_len(str, 1); 774 } 775 776 #if defined(FEAT_EVAL) || defined(PROTO) 777 778 /* 779 * "chdir(dir)" function 780 */ 781 void 782 f_chdir(typval_T *argvars, typval_T *rettv) 783 { 784 char_u *cwd; 785 cdscope_T scope = CDSCOPE_GLOBAL; 786 787 rettv->v_type = VAR_STRING; 788 rettv->vval.v_string = NULL; 789 790 if (argvars[0].v_type != VAR_STRING) 791 { 792 // Returning an empty string means it failed. 793 // No error message, for historic reasons. 794 if (in_vim9script()) 795 (void) check_for_string_arg(argvars, 0); 796 return; 797 } 798 799 // Return the current directory 800 cwd = alloc(MAXPATHL); 801 if (cwd != NULL) 802 { 803 if (mch_dirname(cwd, MAXPATHL) != FAIL) 804 { 805 #ifdef BACKSLASH_IN_FILENAME 806 slash_adjust(cwd); 807 #endif 808 rettv->vval.v_string = vim_strsave(cwd); 809 } 810 vim_free(cwd); 811 } 812 813 if (curwin->w_localdir != NULL) 814 scope = CDSCOPE_WINDOW; 815 else if (curtab->tp_localdir != NULL) 816 scope = CDSCOPE_TABPAGE; 817 818 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope)) 819 // Directory change failed 820 VIM_CLEAR(rettv->vval.v_string); 821 } 822 823 /* 824 * "delete()" function 825 */ 826 void 827 f_delete(typval_T *argvars, typval_T *rettv) 828 { 829 char_u nbuf[NUMBUFLEN]; 830 char_u *name; 831 char_u *flags; 832 833 rettv->vval.v_number = -1; 834 if (check_restricted() || check_secure()) 835 return; 836 837 name = tv_get_string(&argvars[0]); 838 if (name == NULL || *name == NUL) 839 { 840 emsg(_(e_invarg)); 841 return; 842 } 843 844 if (argvars[1].v_type != VAR_UNKNOWN) 845 flags = tv_get_string_buf(&argvars[1], nbuf); 846 else 847 flags = (char_u *)""; 848 849 if (*flags == NUL) 850 // delete a file 851 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1; 852 else if (STRCMP(flags, "d") == 0) 853 // delete an empty directory 854 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1; 855 else if (STRCMP(flags, "rf") == 0) 856 // delete a directory recursively 857 rettv->vval.v_number = delete_recursive(name); 858 else 859 semsg(_(e_invexpr2), flags); 860 } 861 862 /* 863 * "executable()" function 864 */ 865 void 866 f_executable(typval_T *argvars, typval_T *rettv) 867 { 868 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 869 return; 870 871 // Check in $PATH and also check directly if there is a directory name. 872 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE); 873 } 874 875 /* 876 * "exepath()" function 877 */ 878 void 879 f_exepath(typval_T *argvars, typval_T *rettv) 880 { 881 char_u *p = NULL; 882 883 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL) 884 return; 885 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE); 886 rettv->v_type = VAR_STRING; 887 rettv->vval.v_string = p; 888 } 889 890 /* 891 * "filereadable()" function 892 */ 893 void 894 f_filereadable(typval_T *argvars, typval_T *rettv) 895 { 896 int fd; 897 char_u *p; 898 int n; 899 900 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 901 return; 902 #ifndef O_NONBLOCK 903 # define O_NONBLOCK 0 904 #endif 905 p = tv_get_string(&argvars[0]); 906 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p, 907 O_RDONLY | O_NONBLOCK, 0)) >= 0) 908 { 909 n = TRUE; 910 close(fd); 911 } 912 else 913 n = FALSE; 914 915 rettv->vval.v_number = n; 916 } 917 918 /* 919 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have 920 * rights to write into. 921 */ 922 void 923 f_filewritable(typval_T *argvars, typval_T *rettv) 924 { 925 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 926 return; 927 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0])); 928 } 929 930 static void 931 findfilendir( 932 typval_T *argvars UNUSED, 933 typval_T *rettv, 934 int find_what UNUSED) 935 { 936 #ifdef FEAT_SEARCHPATH 937 char_u *fname; 938 char_u *fresult = NULL; 939 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path; 940 char_u *p; 941 char_u pathbuf[NUMBUFLEN]; 942 int count = 1; 943 int first = TRUE; 944 int error = FALSE; 945 #endif 946 947 rettv->vval.v_string = NULL; 948 rettv->v_type = VAR_STRING; 949 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL) 950 return; 951 952 #ifdef FEAT_SEARCHPATH 953 fname = tv_get_string(&argvars[0]); 954 955 if (argvars[1].v_type != VAR_UNKNOWN) 956 { 957 p = tv_get_string_buf_chk(&argvars[1], pathbuf); 958 if (p == NULL) 959 error = TRUE; 960 else 961 { 962 if (*p != NUL) 963 path = p; 964 965 if (argvars[2].v_type != VAR_UNKNOWN) 966 count = (int)tv_get_number_chk(&argvars[2], &error); 967 } 968 } 969 970 if (count < 0 && rettv_list_alloc(rettv) == FAIL) 971 error = TRUE; 972 973 if (*fname != NUL && !error) 974 { 975 do 976 { 977 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST) 978 vim_free(fresult); 979 fresult = find_file_in_path_option(first ? fname : NULL, 980 first ? (int)STRLEN(fname) : 0, 981 0, first, path, 982 find_what, 983 curbuf->b_ffname, 984 find_what == FINDFILE_DIR 985 ? (char_u *)"" : curbuf->b_p_sua); 986 first = FALSE; 987 988 if (fresult != NULL && rettv->v_type == VAR_LIST) 989 list_append_string(rettv->vval.v_list, fresult, -1); 990 991 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL); 992 } 993 994 if (rettv->v_type == VAR_STRING) 995 rettv->vval.v_string = fresult; 996 #endif 997 } 998 999 /* 1000 * "finddir({fname}[, {path}[, {count}]])" function 1001 */ 1002 void 1003 f_finddir(typval_T *argvars, typval_T *rettv) 1004 { 1005 findfilendir(argvars, rettv, FINDFILE_DIR); 1006 } 1007 1008 /* 1009 * "findfile({fname}[, {path}[, {count}]])" function 1010 */ 1011 void 1012 f_findfile(typval_T *argvars, typval_T *rettv) 1013 { 1014 findfilendir(argvars, rettv, FINDFILE_FILE); 1015 } 1016 1017 /* 1018 * "fnamemodify({fname}, {mods})" function 1019 */ 1020 void 1021 f_fnamemodify(typval_T *argvars, typval_T *rettv) 1022 { 1023 char_u *fname; 1024 char_u *mods; 1025 int usedlen = 0; 1026 int len = 0; 1027 char_u *fbuf = NULL; 1028 char_u buf[NUMBUFLEN]; 1029 1030 if (in_vim9script() && (check_for_string_arg(argvars, 0) == FAIL 1031 || check_for_string_arg(argvars, 1) == FAIL)) 1032 return; 1033 fname = tv_get_string_chk(&argvars[0]); 1034 mods = tv_get_string_buf_chk(&argvars[1], buf); 1035 if (mods == NULL || fname == NULL) 1036 fname = NULL; 1037 else 1038 { 1039 len = (int)STRLEN(fname); 1040 if (mods != NULL && *mods != NUL) 1041 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len); 1042 } 1043 1044 rettv->v_type = VAR_STRING; 1045 if (fname == NULL) 1046 rettv->vval.v_string = NULL; 1047 else 1048 rettv->vval.v_string = vim_strnsave(fname, len); 1049 vim_free(fbuf); 1050 } 1051 1052 /* 1053 * "getcwd()" function 1054 * 1055 * Return the current working directory of a window in a tab page. 1056 * First optional argument 'winnr' is the window number or -1 and the second 1057 * optional argument 'tabnr' is the tab page number. 1058 * 1059 * If no arguments are supplied, then return the directory of the current 1060 * window. 1061 * If only 'winnr' is specified and is not -1 or 0 then return the directory of 1062 * the specified window. 1063 * If 'winnr' is 0 then return the directory of the current window. 1064 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the 1065 * directory of the specified tab page. Otherwise return the directory of the 1066 * specified window in the specified tab page. 1067 * If the window or the tab page doesn't exist then return NULL. 1068 */ 1069 void 1070 f_getcwd(typval_T *argvars, typval_T *rettv) 1071 { 1072 win_T *wp = NULL; 1073 tabpage_T *tp = NULL; 1074 char_u *cwd; 1075 int global = FALSE; 1076 1077 rettv->v_type = VAR_STRING; 1078 rettv->vval.v_string = NULL; 1079 1080 if (argvars[0].v_type == VAR_NUMBER 1081 && argvars[0].vval.v_number == -1 1082 && argvars[1].v_type == VAR_UNKNOWN) 1083 global = TRUE; 1084 else 1085 wp = find_tabwin(&argvars[0], &argvars[1], &tp); 1086 1087 if (wp != NULL && wp->w_localdir != NULL) 1088 rettv->vval.v_string = vim_strsave(wp->w_localdir); 1089 else if (tp != NULL && tp->tp_localdir != NULL) 1090 rettv->vval.v_string = vim_strsave(tp->tp_localdir); 1091 else if (wp != NULL || tp != NULL || global) 1092 { 1093 if (globaldir != NULL) 1094 rettv->vval.v_string = vim_strsave(globaldir); 1095 else 1096 { 1097 cwd = alloc(MAXPATHL); 1098 if (cwd != NULL) 1099 { 1100 if (mch_dirname(cwd, MAXPATHL) != FAIL) 1101 rettv->vval.v_string = vim_strsave(cwd); 1102 vim_free(cwd); 1103 } 1104 } 1105 } 1106 #ifdef BACKSLASH_IN_FILENAME 1107 if (rettv->vval.v_string != NULL) 1108 slash_adjust(rettv->vval.v_string); 1109 #endif 1110 } 1111 1112 /* 1113 * Convert "st" to file permission string. 1114 */ 1115 char_u * 1116 getfpermst(stat_T *st, char_u *perm) 1117 { 1118 char_u flags[] = "rwx"; 1119 int i; 1120 1121 for (i = 0; i < 9; i++) 1122 { 1123 if (st->st_mode & (1 << (8 - i))) 1124 perm[i] = flags[i % 3]; 1125 else 1126 perm[i] = '-'; 1127 } 1128 return perm; 1129 } 1130 1131 /* 1132 * "getfperm({fname})" function 1133 */ 1134 void 1135 f_getfperm(typval_T *argvars, typval_T *rettv) 1136 { 1137 char_u *fname; 1138 stat_T st; 1139 char_u *perm = NULL; 1140 char_u permbuf[] = "---------"; 1141 1142 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 1143 return; 1144 fname = tv_get_string(&argvars[0]); 1145 1146 rettv->v_type = VAR_STRING; 1147 if (mch_stat((char *)fname, &st) >= 0) 1148 perm = vim_strsave(getfpermst(&st, permbuf)); 1149 rettv->vval.v_string = perm; 1150 } 1151 1152 /* 1153 * "getfsize({fname})" function 1154 */ 1155 void 1156 f_getfsize(typval_T *argvars, typval_T *rettv) 1157 { 1158 char_u *fname; 1159 stat_T st; 1160 1161 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 1162 return; 1163 1164 fname = tv_get_string(&argvars[0]); 1165 if (mch_stat((char *)fname, &st) >= 0) 1166 { 1167 if (mch_isdir(fname)) 1168 rettv->vval.v_number = 0; 1169 else 1170 { 1171 rettv->vval.v_number = (varnumber_T)st.st_size; 1172 1173 // non-perfect check for overflow 1174 if ((off_T)rettv->vval.v_number != (off_T)st.st_size) 1175 rettv->vval.v_number = -2; 1176 } 1177 } 1178 else 1179 rettv->vval.v_number = -1; 1180 } 1181 1182 /* 1183 * "getftime({fname})" function 1184 */ 1185 void 1186 f_getftime(typval_T *argvars, typval_T *rettv) 1187 { 1188 char_u *fname; 1189 stat_T st; 1190 1191 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 1192 return; 1193 fname = tv_get_string(&argvars[0]); 1194 if (mch_stat((char *)fname, &st) >= 0) 1195 rettv->vval.v_number = (varnumber_T)st.st_mtime; 1196 else 1197 rettv->vval.v_number = -1; 1198 } 1199 1200 /* 1201 * Convert "st" to file type string. 1202 */ 1203 char_u * 1204 getftypest(stat_T *st) 1205 { 1206 char *t; 1207 1208 if (S_ISREG(st->st_mode)) 1209 t = "file"; 1210 else if (S_ISDIR(st->st_mode)) 1211 t = "dir"; 1212 else if (S_ISLNK(st->st_mode)) 1213 t = "link"; 1214 else if (S_ISBLK(st->st_mode)) 1215 t = "bdev"; 1216 else if (S_ISCHR(st->st_mode)) 1217 t = "cdev"; 1218 else if (S_ISFIFO(st->st_mode)) 1219 t = "fifo"; 1220 else if (S_ISSOCK(st->st_mode)) 1221 t = "socket"; 1222 else 1223 t = "other"; 1224 return (char_u*)t; 1225 } 1226 1227 /* 1228 * "getftype({fname})" function 1229 */ 1230 void 1231 f_getftype(typval_T *argvars, typval_T *rettv) 1232 { 1233 char_u *fname; 1234 stat_T st; 1235 char_u *type = NULL; 1236 1237 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL) 1238 return; 1239 fname = tv_get_string(&argvars[0]); 1240 1241 rettv->v_type = VAR_STRING; 1242 if (mch_lstat((char *)fname, &st) >= 0) 1243 type = vim_strsave(getftypest(&st)); 1244 rettv->vval.v_string = type; 1245 } 1246 1247 /* 1248 * "glob()" function 1249 */ 1250 void 1251 f_glob(typval_T *argvars, typval_T *rettv) 1252 { 1253 int options = WILD_SILENT|WILD_USE_NL; 1254 expand_T xpc; 1255 int error = FALSE; 1256 1257 // When the optional second argument is non-zero, don't remove matches 1258 // for 'wildignore' and don't put matches for 'suffixes' at the end. 1259 rettv->v_type = VAR_STRING; 1260 if (argvars[1].v_type != VAR_UNKNOWN) 1261 { 1262 if (tv_get_bool_chk(&argvars[1], &error)) 1263 options |= WILD_KEEP_ALL; 1264 if (argvars[2].v_type != VAR_UNKNOWN) 1265 { 1266 if (tv_get_bool_chk(&argvars[2], &error)) 1267 rettv_list_set(rettv, NULL); 1268 if (argvars[3].v_type != VAR_UNKNOWN 1269 && tv_get_bool_chk(&argvars[3], &error)) 1270 options |= WILD_ALLLINKS; 1271 } 1272 } 1273 if (!error) 1274 { 1275 ExpandInit(&xpc); 1276 xpc.xp_context = EXPAND_FILES; 1277 if (p_wic) 1278 options += WILD_ICASE; 1279 if (rettv->v_type == VAR_STRING) 1280 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]), 1281 NULL, options, WILD_ALL); 1282 else if (rettv_list_alloc(rettv) != FAIL) 1283 { 1284 int i; 1285 1286 ExpandOne(&xpc, tv_get_string(&argvars[0]), 1287 NULL, options, WILD_ALL_KEEP); 1288 for (i = 0; i < xpc.xp_numfiles; i++) 1289 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1); 1290 1291 ExpandCleanup(&xpc); 1292 } 1293 } 1294 else 1295 rettv->vval.v_string = NULL; 1296 } 1297 1298 /* 1299 * "glob2regpat()" function 1300 */ 1301 void 1302 f_glob2regpat(typval_T *argvars, typval_T *rettv) 1303 { 1304 char_u *pat = tv_get_string_chk(&argvars[0]); 1305 1306 rettv->v_type = VAR_STRING; 1307 rettv->vval.v_string = (pat == NULL) 1308 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE); 1309 } 1310 1311 /* 1312 * "globpath()" function 1313 */ 1314 void 1315 f_globpath(typval_T *argvars, typval_T *rettv) 1316 { 1317 int flags = WILD_IGNORE_COMPLETESLASH; 1318 char_u buf1[NUMBUFLEN]; 1319 char_u *file = tv_get_string_buf_chk(&argvars[1], buf1); 1320 int error = FALSE; 1321 garray_T ga; 1322 int i; 1323 1324 // When the optional second argument is non-zero, don't remove matches 1325 // for 'wildignore' and don't put matches for 'suffixes' at the end. 1326 rettv->v_type = VAR_STRING; 1327 if (argvars[2].v_type != VAR_UNKNOWN) 1328 { 1329 if (tv_get_bool_chk(&argvars[2], &error)) 1330 flags |= WILD_KEEP_ALL; 1331 if (argvars[3].v_type != VAR_UNKNOWN) 1332 { 1333 if (tv_get_bool_chk(&argvars[3], &error)) 1334 rettv_list_set(rettv, NULL); 1335 if (argvars[4].v_type != VAR_UNKNOWN 1336 && tv_get_bool_chk(&argvars[4], &error)) 1337 flags |= WILD_ALLLINKS; 1338 } 1339 } 1340 if (file != NULL && !error) 1341 { 1342 ga_init2(&ga, (int)sizeof(char_u *), 10); 1343 globpath(tv_get_string(&argvars[0]), file, &ga, flags); 1344 if (rettv->v_type == VAR_STRING) 1345 rettv->vval.v_string = ga_concat_strings(&ga, "\n"); 1346 else if (rettv_list_alloc(rettv) != FAIL) 1347 for (i = 0; i < ga.ga_len; ++i) 1348 list_append_string(rettv->vval.v_list, 1349 ((char_u **)(ga.ga_data))[i], -1); 1350 ga_clear_strings(&ga); 1351 } 1352 else 1353 rettv->vval.v_string = NULL; 1354 } 1355 1356 /* 1357 * "isdirectory()" function 1358 */ 1359 void 1360 f_isdirectory(typval_T *argvars, typval_T *rettv) 1361 { 1362 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0])); 1363 } 1364 1365 /* 1366 * Create the directory in which "dir" is located, and higher levels when 1367 * needed. 1368 * Return OK or FAIL. 1369 */ 1370 static int 1371 mkdir_recurse(char_u *dir, int prot) 1372 { 1373 char_u *p; 1374 char_u *updir; 1375 int r = FAIL; 1376 1377 // Get end of directory name in "dir". 1378 // We're done when it's "/" or "c:/". 1379 p = gettail_sep(dir); 1380 if (p <= get_past_head(dir)) 1381 return OK; 1382 1383 // If the directory exists we're done. Otherwise: create it. 1384 updir = vim_strnsave(dir, p - dir); 1385 if (updir == NULL) 1386 return FAIL; 1387 if (mch_isdir(updir)) 1388 r = OK; 1389 else if (mkdir_recurse(updir, prot) == OK) 1390 r = vim_mkdir_emsg(updir, prot); 1391 vim_free(updir); 1392 return r; 1393 } 1394 1395 /* 1396 * "mkdir()" function 1397 */ 1398 void 1399 f_mkdir(typval_T *argvars, typval_T *rettv) 1400 { 1401 char_u *dir; 1402 char_u buf[NUMBUFLEN]; 1403 int prot = 0755; 1404 1405 rettv->vval.v_number = FAIL; 1406 if (check_restricted() || check_secure()) 1407 return; 1408 1409 dir = tv_get_string_buf(&argvars[0], buf); 1410 if (*dir == NUL) 1411 return; 1412 1413 if (*gettail(dir) == NUL) 1414 // remove trailing slashes 1415 *gettail_sep(dir) = NUL; 1416 1417 if (argvars[1].v_type != VAR_UNKNOWN) 1418 { 1419 if (argvars[2].v_type != VAR_UNKNOWN) 1420 { 1421 prot = (int)tv_get_number_chk(&argvars[2], NULL); 1422 if (prot == -1) 1423 return; 1424 } 1425 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0) 1426 { 1427 if (mch_isdir(dir)) 1428 { 1429 // With the "p" flag it's OK if the dir already exists. 1430 rettv->vval.v_number = OK; 1431 return; 1432 } 1433 mkdir_recurse(dir, prot); 1434 } 1435 } 1436 rettv->vval.v_number = vim_mkdir_emsg(dir, prot); 1437 } 1438 1439 /* 1440 * "pathshorten()" function 1441 */ 1442 void 1443 f_pathshorten(typval_T *argvars, typval_T *rettv) 1444 { 1445 char_u *p; 1446 int trim_len = 1; 1447 1448 if (argvars[1].v_type != VAR_UNKNOWN) 1449 { 1450 trim_len = (int)tv_get_number(&argvars[1]); 1451 if (trim_len < 1) 1452 trim_len = 1; 1453 } 1454 1455 rettv->v_type = VAR_STRING; 1456 p = tv_get_string_chk(&argvars[0]); 1457 1458 if (p == NULL) 1459 rettv->vval.v_string = NULL; 1460 else 1461 { 1462 p = vim_strsave(p); 1463 rettv->vval.v_string = p; 1464 if (p != NULL) 1465 shorten_dir_len(p, trim_len); 1466 } 1467 } 1468 1469 /* 1470 * Common code for readdir_checkitem() and readdirex_checkitem(). 1471 * Either "name" or "dict" is NULL. 1472 */ 1473 static int 1474 checkitem_common(void *context, char_u *name, dict_T *dict) 1475 { 1476 typval_T *expr = (typval_T *)context; 1477 typval_T save_val; 1478 typval_T rettv; 1479 typval_T argv[2]; 1480 int retval = 0; 1481 int error = FALSE; 1482 1483 prepare_vimvar(VV_VAL, &save_val); 1484 if (name != NULL) 1485 { 1486 set_vim_var_string(VV_VAL, name, -1); 1487 argv[0].v_type = VAR_STRING; 1488 argv[0].vval.v_string = name; 1489 } 1490 else 1491 { 1492 set_vim_var_dict(VV_VAL, dict); 1493 argv[0].v_type = VAR_DICT; 1494 argv[0].vval.v_dict = dict; 1495 } 1496 1497 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL) 1498 goto theend; 1499 1500 // We want to use -1, but also true/false should be allowed. 1501 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL) 1502 { 1503 rettv.v_type = VAR_NUMBER; 1504 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE; 1505 } 1506 retval = tv_get_number_chk(&rettv, &error); 1507 if (error) 1508 retval = -1; 1509 clear_tv(&rettv); 1510 1511 theend: 1512 if (name != NULL) 1513 set_vim_var_string(VV_VAL, NULL, 0); 1514 else 1515 set_vim_var_dict(VV_VAL, NULL); 1516 restore_vimvar(VV_VAL, &save_val); 1517 return retval; 1518 } 1519 1520 /* 1521 * Evaluate "expr" (= "context") for readdir(). 1522 */ 1523 static int 1524 readdir_checkitem(void *context, void *item) 1525 { 1526 char_u *name = (char_u *)item; 1527 1528 return checkitem_common(context, name, NULL); 1529 } 1530 1531 static int 1532 readdirex_dict_arg(typval_T *tv, int *cmp) 1533 { 1534 char_u *compare; 1535 1536 if (tv->v_type != VAR_DICT) 1537 { 1538 emsg(_(e_dictreq)); 1539 return FAIL; 1540 } 1541 1542 if (dict_find(tv->vval.v_dict, (char_u *)"sort", -1) != NULL) 1543 compare = dict_get_string(tv->vval.v_dict, (char_u *)"sort", FALSE); 1544 else 1545 { 1546 semsg(_(e_no_dict_key), "sort"); 1547 return FAIL; 1548 } 1549 1550 if (STRCMP(compare, (char_u *) "none") == 0) 1551 *cmp = READDIR_SORT_NONE; 1552 else if (STRCMP(compare, (char_u *) "case") == 0) 1553 *cmp = READDIR_SORT_BYTE; 1554 else if (STRCMP(compare, (char_u *) "icase") == 0) 1555 *cmp = READDIR_SORT_IC; 1556 else if (STRCMP(compare, (char_u *) "collate") == 0) 1557 *cmp = READDIR_SORT_COLLATE; 1558 return OK; 1559 } 1560 1561 /* 1562 * "readdir()" function 1563 */ 1564 void 1565 f_readdir(typval_T *argvars, typval_T *rettv) 1566 { 1567 typval_T *expr; 1568 int ret; 1569 char_u *path; 1570 char_u *p; 1571 garray_T ga; 1572 int i; 1573 int sort = READDIR_SORT_BYTE; 1574 1575 if (rettv_list_alloc(rettv) == FAIL) 1576 return; 1577 path = tv_get_string(&argvars[0]); 1578 expr = &argvars[1]; 1579 1580 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN && 1581 readdirex_dict_arg(&argvars[2], &sort) == FAIL) 1582 return; 1583 1584 ret = readdir_core(&ga, path, FALSE, (void *)expr, 1585 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort); 1586 if (ret == OK) 1587 { 1588 for (i = 0; i < ga.ga_len; i++) 1589 { 1590 p = ((char_u **)ga.ga_data)[i]; 1591 list_append_string(rettv->vval.v_list, p, -1); 1592 } 1593 } 1594 ga_clear_strings(&ga); 1595 } 1596 1597 /* 1598 * Evaluate "expr" (= "context") for readdirex(). 1599 */ 1600 static int 1601 readdirex_checkitem(void *context, void *item) 1602 { 1603 dict_T *dict = (dict_T*)item; 1604 1605 return checkitem_common(context, NULL, dict); 1606 } 1607 1608 /* 1609 * "readdirex()" function 1610 */ 1611 void 1612 f_readdirex(typval_T *argvars, typval_T *rettv) 1613 { 1614 typval_T *expr; 1615 int ret; 1616 char_u *path; 1617 garray_T ga; 1618 int i; 1619 int sort = READDIR_SORT_BYTE; 1620 1621 if (rettv_list_alloc(rettv) == FAIL) 1622 return; 1623 path = tv_get_string(&argvars[0]); 1624 expr = &argvars[1]; 1625 1626 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN && 1627 readdirex_dict_arg(&argvars[2], &sort) == FAIL) 1628 return; 1629 1630 ret = readdir_core(&ga, path, TRUE, (void *)expr, 1631 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort); 1632 if (ret == OK) 1633 { 1634 for (i = 0; i < ga.ga_len; i++) 1635 { 1636 dict_T *dict = ((dict_T**)ga.ga_data)[i]; 1637 list_append_dict(rettv->vval.v_list, dict); 1638 dict_unref(dict); 1639 } 1640 } 1641 ga_clear(&ga); 1642 } 1643 1644 /* 1645 * "readfile()" function 1646 */ 1647 static void 1648 read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob) 1649 { 1650 int binary = FALSE; 1651 int blob = always_blob; 1652 int failed = FALSE; 1653 char_u *fname; 1654 FILE *fd; 1655 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1 1656 int io_size = sizeof(buf); 1657 int readlen; // size of last fread() 1658 char_u *prev = NULL; // previously read bytes, if any 1659 long prevlen = 0; // length of data in prev 1660 long prevsize = 0; // size of prev buffer 1661 long maxline = MAXLNUM; 1662 long cnt = 0; 1663 char_u *p; // position in buf 1664 char_u *start; // start of current line 1665 1666 if (argvars[1].v_type != VAR_UNKNOWN) 1667 { 1668 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0) 1669 binary = TRUE; 1670 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0) 1671 blob = TRUE; 1672 1673 if (argvars[2].v_type != VAR_UNKNOWN) 1674 maxline = (long)tv_get_number(&argvars[2]); 1675 } 1676 1677 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL) 1678 return; 1679 1680 // Always open the file in binary mode, library functions have a mind of 1681 // their own about CR-LF conversion. 1682 fname = tv_get_string(&argvars[0]); 1683 1684 if (mch_isdir(fname)) 1685 { 1686 semsg(_(e_isadir2), fname); 1687 return; 1688 } 1689 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL) 1690 { 1691 semsg(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname); 1692 return; 1693 } 1694 1695 if (blob) 1696 { 1697 if (read_blob(fd, rettv->vval.v_blob) == FAIL) 1698 { 1699 semsg(_(e_notread), fname); 1700 // An empty blob is returned on error. 1701 blob_free(rettv->vval.v_blob); 1702 rettv->vval.v_blob = NULL; 1703 } 1704 fclose(fd); 1705 return; 1706 } 1707 1708 while (cnt < maxline || maxline < 0) 1709 { 1710 readlen = (int)fread(buf, 1, io_size, fd); 1711 1712 // This for loop processes what was read, but is also entered at end 1713 // of file so that either: 1714 // - an incomplete line gets written 1715 // - a "binary" file gets an empty line at the end if it ends in a 1716 // newline. 1717 for (p = buf, start = buf; 1718 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary)); 1719 ++p) 1720 { 1721 if (*p == '\n' || readlen <= 0) 1722 { 1723 listitem_T *li; 1724 char_u *s = NULL; 1725 long_u len = p - start; 1726 1727 // Finished a line. Remove CRs before NL. 1728 if (readlen > 0 && !binary) 1729 { 1730 while (len > 0 && start[len - 1] == '\r') 1731 --len; 1732 // removal may cross back to the "prev" string 1733 if (len == 0) 1734 while (prevlen > 0 && prev[prevlen - 1] == '\r') 1735 --prevlen; 1736 } 1737 if (prevlen == 0) 1738 s = vim_strnsave(start, len); 1739 else 1740 { 1741 // Change "prev" buffer to be the right size. This way 1742 // the bytes are only copied once, and very long lines are 1743 // allocated only once. 1744 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL) 1745 { 1746 mch_memmove(s + prevlen, start, len); 1747 s[prevlen + len] = NUL; 1748 prev = NULL; // the list will own the string 1749 prevlen = prevsize = 0; 1750 } 1751 } 1752 if (s == NULL) 1753 { 1754 do_outofmem_msg((long_u) prevlen + len + 1); 1755 failed = TRUE; 1756 break; 1757 } 1758 1759 if ((li = listitem_alloc()) == NULL) 1760 { 1761 vim_free(s); 1762 failed = TRUE; 1763 break; 1764 } 1765 li->li_tv.v_type = VAR_STRING; 1766 li->li_tv.v_lock = 0; 1767 li->li_tv.vval.v_string = s; 1768 list_append(rettv->vval.v_list, li); 1769 1770 start = p + 1; // step over newline 1771 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0) 1772 break; 1773 } 1774 else if (*p == NUL) 1775 *p = '\n'; 1776 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this 1777 // when finding the BF and check the previous two bytes. 1778 else if (*p == 0xbf && enc_utf8 && !binary) 1779 { 1780 // Find the two bytes before the 0xbf. If p is at buf, or buf 1781 // + 1, these may be in the "prev" string. 1782 char_u back1 = p >= buf + 1 ? p[-1] 1783 : prevlen >= 1 ? prev[prevlen - 1] : NUL; 1784 char_u back2 = p >= buf + 2 ? p[-2] 1785 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1] 1786 : prevlen >= 2 ? prev[prevlen - 2] : NUL; 1787 1788 if (back2 == 0xef && back1 == 0xbb) 1789 { 1790 char_u *dest = p - 2; 1791 1792 // Usually a BOM is at the beginning of a file, and so at 1793 // the beginning of a line; then we can just step over it. 1794 if (start == dest) 1795 start = p + 1; 1796 else 1797 { 1798 // have to shuffle buf to close gap 1799 int adjust_prevlen = 0; 1800 1801 if (dest < buf) 1802 { 1803 // must be 1 or 2 1804 adjust_prevlen = (int)(buf - dest); 1805 dest = buf; 1806 } 1807 if (readlen > p - buf + 1) 1808 mch_memmove(dest, p + 1, readlen - (p - buf) - 1); 1809 readlen -= 3 - adjust_prevlen; 1810 prevlen -= adjust_prevlen; 1811 p = dest - 1; 1812 } 1813 } 1814 } 1815 } // for 1816 1817 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0) 1818 break; 1819 if (start < p) 1820 { 1821 // There's part of a line in buf, store it in "prev". 1822 if (p - start + prevlen >= prevsize) 1823 { 1824 // need bigger "prev" buffer 1825 char_u *newprev; 1826 1827 // A common use case is ordinary text files and "prev" gets a 1828 // fragment of a line, so the first allocation is made 1829 // small, to avoid repeatedly 'allocing' large and 1830 // 'reallocing' small. 1831 if (prevsize == 0) 1832 prevsize = (long)(p - start); 1833 else 1834 { 1835 long grow50pc = (prevsize * 3) / 2; 1836 long growmin = (long)((p - start) * 2 + prevlen); 1837 prevsize = grow50pc > growmin ? grow50pc : growmin; 1838 } 1839 newprev = vim_realloc(prev, prevsize); 1840 if (newprev == NULL) 1841 { 1842 do_outofmem_msg((long_u)prevsize); 1843 failed = TRUE; 1844 break; 1845 } 1846 prev = newprev; 1847 } 1848 // Add the line part to end of "prev". 1849 mch_memmove(prev + prevlen, start, p - start); 1850 prevlen += (long)(p - start); 1851 } 1852 } // while 1853 1854 // For a negative line count use only the lines at the end of the file, 1855 // free the rest. 1856 if (!failed && maxline < 0) 1857 while (cnt > -maxline) 1858 { 1859 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first); 1860 --cnt; 1861 } 1862 1863 if (failed) 1864 { 1865 // an empty list is returned on error 1866 list_free(rettv->vval.v_list); 1867 rettv_list_alloc(rettv); 1868 } 1869 1870 vim_free(prev); 1871 fclose(fd); 1872 } 1873 1874 /* 1875 * "readblob()" function 1876 */ 1877 void 1878 f_readblob(typval_T *argvars, typval_T *rettv) 1879 { 1880 read_file_or_blob(argvars, rettv, TRUE); 1881 } 1882 1883 /* 1884 * "readfile()" function 1885 */ 1886 void 1887 f_readfile(typval_T *argvars, typval_T *rettv) 1888 { 1889 read_file_or_blob(argvars, rettv, FALSE); 1890 } 1891 1892 /* 1893 * "resolve()" function 1894 */ 1895 void 1896 f_resolve(typval_T *argvars, typval_T *rettv) 1897 { 1898 char_u *p; 1899 #ifdef HAVE_READLINK 1900 char_u *buf = NULL; 1901 #endif 1902 1903 p = tv_get_string(&argvars[0]); 1904 #ifdef FEAT_SHORTCUT 1905 { 1906 char_u *v = NULL; 1907 1908 v = mch_resolve_path(p, TRUE); 1909 if (v != NULL) 1910 rettv->vval.v_string = v; 1911 else 1912 rettv->vval.v_string = vim_strsave(p); 1913 } 1914 #else 1915 # ifdef HAVE_READLINK 1916 { 1917 char_u *cpy; 1918 int len; 1919 char_u *remain = NULL; 1920 char_u *q; 1921 int is_relative_to_current = FALSE; 1922 int has_trailing_pathsep = FALSE; 1923 int limit = 100; 1924 1925 p = vim_strsave(p); 1926 if (p == NULL) 1927 goto fail; 1928 if (p[0] == '.' && (vim_ispathsep(p[1]) 1929 || (p[1] == '.' && (vim_ispathsep(p[2]))))) 1930 is_relative_to_current = TRUE; 1931 1932 len = STRLEN(p); 1933 if (len > 1 && after_pathsep(p, p + len)) 1934 { 1935 has_trailing_pathsep = TRUE; 1936 p[len - 1] = NUL; // the trailing slash breaks readlink() 1937 } 1938 1939 q = getnextcomp(p); 1940 if (*q != NUL) 1941 { 1942 // Separate the first path component in "p", and keep the 1943 // remainder (beginning with the path separator). 1944 remain = vim_strsave(q - 1); 1945 q[-1] = NUL; 1946 } 1947 1948 buf = alloc(MAXPATHL + 1); 1949 if (buf == NULL) 1950 { 1951 vim_free(p); 1952 goto fail; 1953 } 1954 1955 for (;;) 1956 { 1957 for (;;) 1958 { 1959 len = readlink((char *)p, (char *)buf, MAXPATHL); 1960 if (len <= 0) 1961 break; 1962 buf[len] = NUL; 1963 1964 if (limit-- == 0) 1965 { 1966 vim_free(p); 1967 vim_free(remain); 1968 emsg(_("E655: Too many symbolic links (cycle?)")); 1969 rettv->vval.v_string = NULL; 1970 goto fail; 1971 } 1972 1973 // Ensure that the result will have a trailing path separator 1974 // if the argument has one. 1975 if (remain == NULL && has_trailing_pathsep) 1976 add_pathsep(buf); 1977 1978 // Separate the first path component in the link value and 1979 // concatenate the remainders. 1980 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf); 1981 if (*q != NUL) 1982 { 1983 if (remain == NULL) 1984 remain = vim_strsave(q - 1); 1985 else 1986 { 1987 cpy = concat_str(q - 1, remain); 1988 if (cpy != NULL) 1989 { 1990 vim_free(remain); 1991 remain = cpy; 1992 } 1993 } 1994 q[-1] = NUL; 1995 } 1996 1997 q = gettail(p); 1998 if (q > p && *q == NUL) 1999 { 2000 // Ignore trailing path separator. 2001 q[-1] = NUL; 2002 q = gettail(p); 2003 } 2004 if (q > p && !mch_isFullName(buf)) 2005 { 2006 // symlink is relative to directory of argument 2007 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1); 2008 if (cpy != NULL) 2009 { 2010 STRCPY(cpy, p); 2011 STRCPY(gettail(cpy), buf); 2012 vim_free(p); 2013 p = cpy; 2014 } 2015 } 2016 else 2017 { 2018 vim_free(p); 2019 p = vim_strsave(buf); 2020 } 2021 } 2022 2023 if (remain == NULL) 2024 break; 2025 2026 // Append the first path component of "remain" to "p". 2027 q = getnextcomp(remain + 1); 2028 len = q - remain - (*q != NUL); 2029 cpy = vim_strnsave(p, STRLEN(p) + len); 2030 if (cpy != NULL) 2031 { 2032 STRNCAT(cpy, remain, len); 2033 vim_free(p); 2034 p = cpy; 2035 } 2036 // Shorten "remain". 2037 if (*q != NUL) 2038 STRMOVE(remain, q - 1); 2039 else 2040 VIM_CLEAR(remain); 2041 } 2042 2043 // If the result is a relative path name, make it explicitly relative to 2044 // the current directory if and only if the argument had this form. 2045 if (!vim_ispathsep(*p)) 2046 { 2047 if (is_relative_to_current 2048 && *p != NUL 2049 && !(p[0] == '.' 2050 && (p[1] == NUL 2051 || vim_ispathsep(p[1]) 2052 || (p[1] == '.' 2053 && (p[2] == NUL 2054 || vim_ispathsep(p[2])))))) 2055 { 2056 // Prepend "./". 2057 cpy = concat_str((char_u *)"./", p); 2058 if (cpy != NULL) 2059 { 2060 vim_free(p); 2061 p = cpy; 2062 } 2063 } 2064 else if (!is_relative_to_current) 2065 { 2066 // Strip leading "./". 2067 q = p; 2068 while (q[0] == '.' && vim_ispathsep(q[1])) 2069 q += 2; 2070 if (q > p) 2071 STRMOVE(p, p + 2); 2072 } 2073 } 2074 2075 // Ensure that the result will have no trailing path separator 2076 // if the argument had none. But keep "/" or "//". 2077 if (!has_trailing_pathsep) 2078 { 2079 q = p + STRLEN(p); 2080 if (after_pathsep(p, q)) 2081 *gettail_sep(p) = NUL; 2082 } 2083 2084 rettv->vval.v_string = p; 2085 } 2086 # else 2087 rettv->vval.v_string = vim_strsave(p); 2088 # endif 2089 #endif 2090 2091 simplify_filename(rettv->vval.v_string); 2092 2093 #ifdef HAVE_READLINK 2094 fail: 2095 vim_free(buf); 2096 #endif 2097 rettv->v_type = VAR_STRING; 2098 } 2099 2100 /* 2101 * "tempname()" function 2102 */ 2103 void 2104 f_tempname(typval_T *argvars UNUSED, typval_T *rettv) 2105 { 2106 static int x = 'A'; 2107 2108 rettv->v_type = VAR_STRING; 2109 rettv->vval.v_string = vim_tempname(x, FALSE); 2110 2111 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different 2112 // names. Skip 'I' and 'O', they are used for shell redirection. 2113 do 2114 { 2115 if (x == 'Z') 2116 x = '0'; 2117 else if (x == '9') 2118 x = 'A'; 2119 else 2120 { 2121 #ifdef EBCDIC 2122 if (x == 'I') 2123 x = 'J'; 2124 else if (x == 'R') 2125 x = 'S'; 2126 else 2127 #endif 2128 ++x; 2129 } 2130 } while (x == 'I' || x == 'O'); 2131 } 2132 2133 /* 2134 * "writefile()" function 2135 */ 2136 void 2137 f_writefile(typval_T *argvars, typval_T *rettv) 2138 { 2139 int binary = FALSE; 2140 int append = FALSE; 2141 #ifdef HAVE_FSYNC 2142 int do_fsync = p_fs; 2143 #endif 2144 char_u *fname; 2145 FILE *fd; 2146 int ret = 0; 2147 listitem_T *li; 2148 list_T *list = NULL; 2149 blob_T *blob = NULL; 2150 2151 rettv->vval.v_number = -1; 2152 if (check_secure()) 2153 return; 2154 2155 if (argvars[0].v_type == VAR_LIST) 2156 { 2157 list = argvars[0].vval.v_list; 2158 if (list == NULL) 2159 return; 2160 CHECK_LIST_MATERIALIZE(list); 2161 FOR_ALL_LIST_ITEMS(list, li) 2162 if (tv_get_string_chk(&li->li_tv) == NULL) 2163 return; 2164 } 2165 else if (argvars[0].v_type == VAR_BLOB) 2166 { 2167 blob = argvars[0].vval.v_blob; 2168 if (blob == NULL) 2169 return; 2170 } 2171 else 2172 { 2173 semsg(_(e_invarg2), 2174 _("writefile() first argument must be a List or a Blob")); 2175 return; 2176 } 2177 2178 if (argvars[2].v_type != VAR_UNKNOWN) 2179 { 2180 char_u *arg2 = tv_get_string_chk(&argvars[2]); 2181 2182 if (arg2 == NULL) 2183 return; 2184 if (vim_strchr(arg2, 'b') != NULL) 2185 binary = TRUE; 2186 if (vim_strchr(arg2, 'a') != NULL) 2187 append = TRUE; 2188 #ifdef HAVE_FSYNC 2189 if (vim_strchr(arg2, 's') != NULL) 2190 do_fsync = TRUE; 2191 else if (vim_strchr(arg2, 'S') != NULL) 2192 do_fsync = FALSE; 2193 #endif 2194 } 2195 2196 fname = tv_get_string_chk(&argvars[1]); 2197 if (fname == NULL) 2198 return; 2199 2200 // Always open the file in binary mode, library functions have a mind of 2201 // their own about CR-LF conversion. 2202 if (*fname == NUL || (fd = mch_fopen((char *)fname, 2203 append ? APPENDBIN : WRITEBIN)) == NULL) 2204 { 2205 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname); 2206 ret = -1; 2207 } 2208 else if (blob) 2209 { 2210 if (write_blob(fd, blob) == FAIL) 2211 ret = -1; 2212 #ifdef HAVE_FSYNC 2213 else if (do_fsync) 2214 // Ignore the error, the user wouldn't know what to do about it. 2215 // May happen for a device. 2216 vim_ignored = vim_fsync(fileno(fd)); 2217 #endif 2218 fclose(fd); 2219 } 2220 else 2221 { 2222 if (write_list(fd, list, binary) == FAIL) 2223 ret = -1; 2224 #ifdef HAVE_FSYNC 2225 else if (do_fsync) 2226 // Ignore the error, the user wouldn't know what to do about it. 2227 // May happen for a device. 2228 vim_ignored = vim_fsync(fileno(fd)); 2229 #endif 2230 fclose(fd); 2231 } 2232 2233 rettv->vval.v_number = ret; 2234 } 2235 2236 #endif // FEAT_EVAL 2237 2238 #if defined(FEAT_BROWSE) || defined(PROTO) 2239 /* 2240 * Generic browse function. Calls gui_mch_browse() when possible. 2241 * Later this may pop-up a non-GUI file selector (external command?). 2242 */ 2243 char_u * 2244 do_browse( 2245 int flags, // BROWSE_SAVE and BROWSE_DIR 2246 char_u *title, // title for the window 2247 char_u *dflt, // default file name (may include directory) 2248 char_u *ext, // extension added 2249 char_u *initdir, // initial directory, NULL for current dir or 2250 // when using path from "dflt" 2251 char_u *filter, // file name filter 2252 buf_T *buf) // buffer to read/write for 2253 { 2254 char_u *fname; 2255 static char_u *last_dir = NULL; // last used directory 2256 char_u *tofree = NULL; 2257 int save_cmod_flags = cmdmod.cmod_flags; 2258 2259 // Must turn off browse to avoid that autocommands will get the 2260 // flag too! 2261 cmdmod.cmod_flags &= ~CMOD_BROWSE; 2262 2263 if (title == NULL || *title == NUL) 2264 { 2265 if (flags & BROWSE_DIR) 2266 title = (char_u *)_("Select Directory dialog"); 2267 else if (flags & BROWSE_SAVE) 2268 title = (char_u *)_("Save File dialog"); 2269 else 2270 title = (char_u *)_("Open File dialog"); 2271 } 2272 2273 // When no directory specified, use default file name, default dir, buffer 2274 // dir, last dir or current dir 2275 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL) 2276 { 2277 if (mch_isdir(dflt)) // default file name is a directory 2278 { 2279 initdir = dflt; 2280 dflt = NULL; 2281 } 2282 else if (gettail(dflt) != dflt) // default file name includes a path 2283 { 2284 tofree = vim_strsave(dflt); 2285 if (tofree != NULL) 2286 { 2287 initdir = tofree; 2288 *gettail(initdir) = NUL; 2289 dflt = gettail(dflt); 2290 } 2291 } 2292 } 2293 2294 if (initdir == NULL || *initdir == NUL) 2295 { 2296 // When 'browsedir' is a directory, use it 2297 if (STRCMP(p_bsdir, "last") != 0 2298 && STRCMP(p_bsdir, "buffer") != 0 2299 && STRCMP(p_bsdir, "current") != 0 2300 && mch_isdir(p_bsdir)) 2301 initdir = p_bsdir; 2302 // When saving or 'browsedir' is "buffer", use buffer fname 2303 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b') 2304 && buf != NULL && buf->b_ffname != NULL) 2305 { 2306 if (dflt == NULL || *dflt == NUL) 2307 dflt = gettail(curbuf->b_ffname); 2308 tofree = vim_strsave(curbuf->b_ffname); 2309 if (tofree != NULL) 2310 { 2311 initdir = tofree; 2312 *gettail(initdir) = NUL; 2313 } 2314 } 2315 // When 'browsedir' is "last", use dir from last browse 2316 else if (*p_bsdir == 'l') 2317 initdir = last_dir; 2318 // When 'browsedir is "current", use current directory. This is the 2319 // default already, leave initdir empty. 2320 } 2321 2322 # ifdef FEAT_GUI 2323 if (gui.in_use) // when this changes, also adjust f_has()! 2324 { 2325 if (filter == NULL 2326 # ifdef FEAT_EVAL 2327 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL 2328 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL 2329 # endif 2330 ) 2331 filter = BROWSE_FILTER_DEFAULT; 2332 if (flags & BROWSE_DIR) 2333 { 2334 # if defined(FEAT_GUI_GTK) || defined(MSWIN) 2335 // For systems that have a directory dialog. 2336 fname = gui_mch_browsedir(title, initdir); 2337 # else 2338 // Generic solution for selecting a directory: select a file and 2339 // remove the file name. 2340 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)""); 2341 # endif 2342 # if !defined(FEAT_GUI_GTK) 2343 // Win32 adds a dummy file name, others return an arbitrary file 2344 // name. GTK+ 2 returns only the directory, 2345 if (fname != NULL && *fname != NUL && !mch_isdir(fname)) 2346 { 2347 // Remove the file name. 2348 char_u *tail = gettail_sep(fname); 2349 2350 if (tail == fname) 2351 *tail++ = '.'; // use current dir 2352 *tail = NUL; 2353 } 2354 # endif 2355 } 2356 else 2357 fname = gui_mch_browse(flags & BROWSE_SAVE, 2358 title, dflt, ext, initdir, (char_u *)_(filter)); 2359 2360 // We hang around in the dialog for a while, the user might do some 2361 // things to our files. The Win32 dialog allows deleting or renaming 2362 // a file, check timestamps. 2363 need_check_timestamps = TRUE; 2364 did_check_timestamps = FALSE; 2365 } 2366 else 2367 # endif 2368 { 2369 // TODO: non-GUI file selector here 2370 emsg(_("E338: Sorry, no file browser in console mode")); 2371 fname = NULL; 2372 } 2373 2374 // keep the directory for next time 2375 if (fname != NULL) 2376 { 2377 vim_free(last_dir); 2378 last_dir = vim_strsave(fname); 2379 if (last_dir != NULL && !(flags & BROWSE_DIR)) 2380 { 2381 *gettail(last_dir) = NUL; 2382 if (*last_dir == NUL) 2383 { 2384 // filename only returned, must be in current dir 2385 vim_free(last_dir); 2386 last_dir = alloc(MAXPATHL); 2387 if (last_dir != NULL) 2388 mch_dirname(last_dir, MAXPATHL); 2389 } 2390 } 2391 } 2392 2393 vim_free(tofree); 2394 cmdmod.cmod_flags = save_cmod_flags; 2395 2396 return fname; 2397 } 2398 #endif 2399 2400 #if defined(FEAT_EVAL) || defined(PROTO) 2401 2402 /* 2403 * "browse(save, title, initdir, default)" function 2404 */ 2405 void 2406 f_browse(typval_T *argvars UNUSED, typval_T *rettv) 2407 { 2408 # ifdef FEAT_BROWSE 2409 int save; 2410 char_u *title; 2411 char_u *initdir; 2412 char_u *defname; 2413 char_u buf[NUMBUFLEN]; 2414 char_u buf2[NUMBUFLEN]; 2415 int error = FALSE; 2416 2417 if (in_vim9script() 2418 && (check_for_string_arg(argvars, 1) == FAIL 2419 || check_for_string_arg(argvars, 2) == FAIL 2420 || check_for_string_arg(argvars, 3) == FAIL)) 2421 return; 2422 save = (int)tv_get_number_chk(&argvars[0], &error); 2423 title = tv_get_string_chk(&argvars[1]); 2424 initdir = tv_get_string_buf_chk(&argvars[2], buf); 2425 defname = tv_get_string_buf_chk(&argvars[3], buf2); 2426 2427 if (error || title == NULL || initdir == NULL || defname == NULL) 2428 rettv->vval.v_string = NULL; 2429 else 2430 rettv->vval.v_string = 2431 do_browse(save ? BROWSE_SAVE : 0, 2432 title, defname, NULL, initdir, NULL, curbuf); 2433 # else 2434 rettv->vval.v_string = NULL; 2435 # endif 2436 rettv->v_type = VAR_STRING; 2437 } 2438 2439 /* 2440 * "browsedir(title, initdir)" function 2441 */ 2442 void 2443 f_browsedir(typval_T *argvars UNUSED, typval_T *rettv) 2444 { 2445 # ifdef FEAT_BROWSE 2446 char_u *title; 2447 char_u *initdir; 2448 char_u buf[NUMBUFLEN]; 2449 2450 title = tv_get_string_chk(&argvars[0]); 2451 initdir = tv_get_string_buf_chk(&argvars[1], buf); 2452 2453 if (title == NULL || initdir == NULL) 2454 rettv->vval.v_string = NULL; 2455 else 2456 rettv->vval.v_string = do_browse(BROWSE_DIR, 2457 title, NULL, NULL, initdir, NULL, curbuf); 2458 # else 2459 rettv->vval.v_string = NULL; 2460 # endif 2461 rettv->v_type = VAR_STRING; 2462 } 2463 2464 #endif // FEAT_EVAL 2465 2466 /* 2467 * Replace home directory by "~" in each space or comma separated file name in 2468 * 'src'. 2469 * If anything fails (except when out of space) dst equals src. 2470 */ 2471 void 2472 home_replace( 2473 buf_T *buf, // when not NULL, check for help files 2474 char_u *src, // input file name 2475 char_u *dst, // where to put the result 2476 int dstlen, // maximum length of the result 2477 int one) // if TRUE, only replace one file name, include 2478 // spaces and commas in the file name. 2479 { 2480 size_t dirlen = 0, envlen = 0; 2481 size_t len; 2482 char_u *homedir_env, *homedir_env_orig; 2483 char_u *p; 2484 2485 if (src == NULL) 2486 { 2487 *dst = NUL; 2488 return; 2489 } 2490 2491 /* 2492 * If the file is a help file, remove the path completely. 2493 */ 2494 if (buf != NULL && buf->b_help) 2495 { 2496 vim_snprintf((char *)dst, dstlen, "%s", gettail(src)); 2497 return; 2498 } 2499 2500 /* 2501 * We check both the value of the $HOME environment variable and the 2502 * "real" home directory. 2503 */ 2504 if (homedir != NULL) 2505 dirlen = STRLEN(homedir); 2506 2507 #ifdef VMS 2508 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN"); 2509 #else 2510 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME"); 2511 #endif 2512 #ifdef MSWIN 2513 if (homedir_env == NULL) 2514 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE"); 2515 #endif 2516 // Empty is the same as not set. 2517 if (homedir_env != NULL && *homedir_env == NUL) 2518 homedir_env = NULL; 2519 2520 if (homedir_env != NULL && *homedir_env == '~') 2521 { 2522 int usedlen = 0; 2523 int flen; 2524 char_u *fbuf = NULL; 2525 2526 flen = (int)STRLEN(homedir_env); 2527 (void)modify_fname((char_u *)":p", FALSE, &usedlen, 2528 &homedir_env, &fbuf, &flen); 2529 flen = (int)STRLEN(homedir_env); 2530 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1])) 2531 // Remove the trailing / that is added to a directory. 2532 homedir_env[flen - 1] = NUL; 2533 } 2534 2535 if (homedir_env != NULL) 2536 envlen = STRLEN(homedir_env); 2537 2538 if (!one) 2539 src = skipwhite(src); 2540 while (*src && dstlen > 0) 2541 { 2542 /* 2543 * Here we are at the beginning of a file name. 2544 * First, check to see if the beginning of the file name matches 2545 * $HOME or the "real" home directory. Check that there is a '/' 2546 * after the match (so that if e.g. the file is "/home/pieter/bla", 2547 * and the home directory is "/home/piet", the file does not end up 2548 * as "~er/bla" (which would seem to indicate the file "bla" in user 2549 * er's home directory)). 2550 */ 2551 p = homedir; 2552 len = dirlen; 2553 for (;;) 2554 { 2555 if ( len 2556 && fnamencmp(src, p, len) == 0 2557 && (vim_ispathsep(src[len]) 2558 || (!one && (src[len] == ',' || src[len] == ' ')) 2559 || src[len] == NUL)) 2560 { 2561 src += len; 2562 if (--dstlen > 0) 2563 *dst++ = '~'; 2564 2565 // Do not add directory separator into dst, because dst is 2566 // expected to just return the directory name without the 2567 // directory separator '/'. 2568 break; 2569 } 2570 if (p == homedir_env) 2571 break; 2572 p = homedir_env; 2573 len = envlen; 2574 } 2575 2576 // if (!one) skip to separator: space or comma 2577 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0) 2578 *dst++ = *src++; 2579 // skip separator 2580 while ((*src == ' ' || *src == ',') && --dstlen > 0) 2581 *dst++ = *src++; 2582 } 2583 // if (dstlen == 0) out of space, what to do??? 2584 2585 *dst = NUL; 2586 2587 if (homedir_env != homedir_env_orig) 2588 vim_free(homedir_env); 2589 } 2590 2591 /* 2592 * Like home_replace, store the replaced string in allocated memory. 2593 * When something fails, NULL is returned. 2594 */ 2595 char_u * 2596 home_replace_save( 2597 buf_T *buf, // when not NULL, check for help files 2598 char_u *src) // input file name 2599 { 2600 char_u *dst; 2601 unsigned len; 2602 2603 len = 3; // space for "~/" and trailing NUL 2604 if (src != NULL) // just in case 2605 len += (unsigned)STRLEN(src); 2606 dst = alloc(len); 2607 if (dst != NULL) 2608 home_replace(buf, src, dst, len, TRUE); 2609 return dst; 2610 } 2611 2612 /* 2613 * Compare two file names and return: 2614 * FPC_SAME if they both exist and are the same file. 2615 * FPC_SAMEX if they both don't exist and have the same file name. 2616 * FPC_DIFF if they both exist and are different files. 2617 * FPC_NOTX if they both don't exist. 2618 * FPC_DIFFX if one of them doesn't exist. 2619 * For the first name environment variables are expanded if "expandenv" is 2620 * TRUE. 2621 */ 2622 int 2623 fullpathcmp( 2624 char_u *s1, 2625 char_u *s2, 2626 int checkname, // when both don't exist, check file names 2627 int expandenv) 2628 { 2629 #ifdef UNIX 2630 char_u exp1[MAXPATHL]; 2631 char_u full1[MAXPATHL]; 2632 char_u full2[MAXPATHL]; 2633 stat_T st1, st2; 2634 int r1, r2; 2635 2636 if (expandenv) 2637 expand_env(s1, exp1, MAXPATHL); 2638 else 2639 vim_strncpy(exp1, s1, MAXPATHL - 1); 2640 r1 = mch_stat((char *)exp1, &st1); 2641 r2 = mch_stat((char *)s2, &st2); 2642 if (r1 != 0 && r2 != 0) 2643 { 2644 // if mch_stat() doesn't work, may compare the names 2645 if (checkname) 2646 { 2647 if (fnamecmp(exp1, s2) == 0) 2648 return FPC_SAMEX; 2649 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE); 2650 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE); 2651 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0) 2652 return FPC_SAMEX; 2653 } 2654 return FPC_NOTX; 2655 } 2656 if (r1 != 0 || r2 != 0) 2657 return FPC_DIFFX; 2658 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) 2659 return FPC_SAME; 2660 return FPC_DIFF; 2661 #else 2662 char_u *exp1; // expanded s1 2663 char_u *full1; // full path of s1 2664 char_u *full2; // full path of s2 2665 int retval = FPC_DIFF; 2666 int r1, r2; 2667 2668 // allocate one buffer to store three paths (alloc()/free() is slow!) 2669 if ((exp1 = alloc(MAXPATHL * 3)) != NULL) 2670 { 2671 full1 = exp1 + MAXPATHL; 2672 full2 = full1 + MAXPATHL; 2673 2674 if (expandenv) 2675 expand_env(s1, exp1, MAXPATHL); 2676 else 2677 vim_strncpy(exp1, s1, MAXPATHL - 1); 2678 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE); 2679 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE); 2680 2681 // If vim_FullName() fails, the file probably doesn't exist. 2682 if (r1 != OK && r2 != OK) 2683 { 2684 if (checkname && fnamecmp(exp1, s2) == 0) 2685 retval = FPC_SAMEX; 2686 else 2687 retval = FPC_NOTX; 2688 } 2689 else if (r1 != OK || r2 != OK) 2690 retval = FPC_DIFFX; 2691 else if (fnamecmp(full1, full2)) 2692 retval = FPC_DIFF; 2693 else 2694 retval = FPC_SAME; 2695 vim_free(exp1); 2696 } 2697 return retval; 2698 #endif 2699 } 2700 2701 /* 2702 * Get the tail of a path: the file name. 2703 * When the path ends in a path separator the tail is the NUL after it. 2704 * Fail safe: never returns NULL. 2705 */ 2706 char_u * 2707 gettail(char_u *fname) 2708 { 2709 char_u *p1, *p2; 2710 2711 if (fname == NULL) 2712 return (char_u *)""; 2713 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path 2714 { 2715 if (vim_ispathsep_nocolon(*p2)) 2716 p1 = p2 + 1; 2717 MB_PTR_ADV(p2); 2718 } 2719 return p1; 2720 } 2721 2722 /* 2723 * Get pointer to tail of "fname", including path separators. Putting a NUL 2724 * here leaves the directory name. Takes care of "c:/" and "//". 2725 * Always returns a valid pointer. 2726 */ 2727 char_u * 2728 gettail_sep(char_u *fname) 2729 { 2730 char_u *p; 2731 char_u *t; 2732 2733 p = get_past_head(fname); // don't remove the '/' from "c:/file" 2734 t = gettail(fname); 2735 while (t > p && after_pathsep(fname, t)) 2736 --t; 2737 #ifdef VMS 2738 // path separator is part of the path 2739 ++t; 2740 #endif 2741 return t; 2742 } 2743 2744 /* 2745 * get the next path component (just after the next path separator). 2746 */ 2747 char_u * 2748 getnextcomp(char_u *fname) 2749 { 2750 while (*fname && !vim_ispathsep(*fname)) 2751 MB_PTR_ADV(fname); 2752 if (*fname) 2753 ++fname; 2754 return fname; 2755 } 2756 2757 /* 2758 * Get a pointer to one character past the head of a path name. 2759 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head. 2760 * If there is no head, path is returned. 2761 */ 2762 char_u * 2763 get_past_head(char_u *path) 2764 { 2765 char_u *retval; 2766 2767 #if defined(MSWIN) 2768 // may skip "c:" 2769 if (isalpha(path[0]) && path[1] == ':') 2770 retval = path + 2; 2771 else 2772 retval = path; 2773 #else 2774 # if defined(AMIGA) 2775 // may skip "label:" 2776 retval = vim_strchr(path, ':'); 2777 if (retval == NULL) 2778 retval = path; 2779 # else // Unix 2780 retval = path; 2781 # endif 2782 #endif 2783 2784 while (vim_ispathsep(*retval)) 2785 ++retval; 2786 2787 return retval; 2788 } 2789 2790 /* 2791 * Return TRUE if 'c' is a path separator. 2792 * Note that for MS-Windows this includes the colon. 2793 */ 2794 int 2795 vim_ispathsep(int c) 2796 { 2797 #ifdef UNIX 2798 return (c == '/'); // UNIX has ':' inside file names 2799 #else 2800 # ifdef BACKSLASH_IN_FILENAME 2801 return (c == ':' || c == '/' || c == '\\'); 2802 # else 2803 # ifdef VMS 2804 // server"user passwd"::device:[full.path.name]fname.extension;version" 2805 return (c == ':' || c == '[' || c == ']' || c == '/' 2806 || c == '<' || c == '>' || c == '"' ); 2807 # else 2808 return (c == ':' || c == '/'); 2809 # endif // VMS 2810 # endif 2811 #endif 2812 } 2813 2814 /* 2815 * Like vim_ispathsep(c), but exclude the colon for MS-Windows. 2816 */ 2817 int 2818 vim_ispathsep_nocolon(int c) 2819 { 2820 return vim_ispathsep(c) 2821 #ifdef BACKSLASH_IN_FILENAME 2822 && c != ':' 2823 #endif 2824 ; 2825 } 2826 2827 /* 2828 * Return TRUE if the directory of "fname" exists, FALSE otherwise. 2829 * Also returns TRUE if there is no directory name. 2830 * "fname" must be writable!. 2831 */ 2832 int 2833 dir_of_file_exists(char_u *fname) 2834 { 2835 char_u *p; 2836 int c; 2837 int retval; 2838 2839 p = gettail_sep(fname); 2840 if (p == fname) 2841 return TRUE; 2842 c = *p; 2843 *p = NUL; 2844 retval = mch_isdir(fname); 2845 *p = c; 2846 return retval; 2847 } 2848 2849 /* 2850 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally 2851 * and deal with 'fileignorecase'. 2852 */ 2853 int 2854 vim_fnamecmp(char_u *x, char_u *y) 2855 { 2856 #ifdef BACKSLASH_IN_FILENAME 2857 return vim_fnamencmp(x, y, MAXPATHL); 2858 #else 2859 if (p_fic) 2860 return MB_STRICMP(x, y); 2861 return STRCMP(x, y); 2862 #endif 2863 } 2864 2865 int 2866 vim_fnamencmp(char_u *x, char_u *y, size_t len) 2867 { 2868 #ifdef BACKSLASH_IN_FILENAME 2869 char_u *px = x; 2870 char_u *py = y; 2871 int cx = NUL; 2872 int cy = NUL; 2873 2874 while (len > 0) 2875 { 2876 cx = PTR2CHAR(px); 2877 cy = PTR2CHAR(py); 2878 if (cx == NUL || cy == NUL 2879 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy) 2880 && !(cx == '/' && cy == '\\') 2881 && !(cx == '\\' && cy == '/'))) 2882 break; 2883 len -= mb_ptr2len(px); 2884 px += mb_ptr2len(px); 2885 py += mb_ptr2len(py); 2886 } 2887 if (len == 0) 2888 return 0; 2889 return (cx - cy); 2890 #else 2891 if (p_fic) 2892 return MB_STRNICMP(x, y, len); 2893 return STRNCMP(x, y, len); 2894 #endif 2895 } 2896 2897 /* 2898 * Concatenate file names fname1 and fname2 into allocated memory. 2899 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary. 2900 */ 2901 char_u * 2902 concat_fnames(char_u *fname1, char_u *fname2, int sep) 2903 { 2904 char_u *dest; 2905 2906 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3); 2907 if (dest != NULL) 2908 { 2909 STRCPY(dest, fname1); 2910 if (sep) 2911 add_pathsep(dest); 2912 STRCAT(dest, fname2); 2913 } 2914 return dest; 2915 } 2916 2917 /* 2918 * Add a path separator to a file name, unless it already ends in a path 2919 * separator. 2920 */ 2921 void 2922 add_pathsep(char_u *p) 2923 { 2924 if (*p != NUL && !after_pathsep(p, p + STRLEN(p))) 2925 STRCAT(p, PATHSEPSTR); 2926 } 2927 2928 /* 2929 * FullName_save - Make an allocated copy of a full file name. 2930 * Returns NULL when out of memory. 2931 */ 2932 char_u * 2933 FullName_save( 2934 char_u *fname, 2935 int force) // force expansion, even when it already looks 2936 // like a full path name 2937 { 2938 char_u *buf; 2939 char_u *new_fname = NULL; 2940 2941 if (fname == NULL) 2942 return NULL; 2943 2944 buf = alloc(MAXPATHL); 2945 if (buf != NULL) 2946 { 2947 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL) 2948 new_fname = vim_strsave(buf); 2949 else 2950 new_fname = vim_strsave(fname); 2951 vim_free(buf); 2952 } 2953 return new_fname; 2954 } 2955 2956 /* 2957 * return TRUE if "fname" exists. 2958 */ 2959 int 2960 vim_fexists(char_u *fname) 2961 { 2962 stat_T st; 2963 2964 if (mch_stat((char *)fname, &st)) 2965 return FALSE; 2966 return TRUE; 2967 } 2968 2969 /* 2970 * Invoke expand_wildcards() for one pattern. 2971 * Expand items like "%:h" before the expansion. 2972 * Returns OK or FAIL. 2973 */ 2974 int 2975 expand_wildcards_eval( 2976 char_u **pat, // pointer to input pattern 2977 int *num_file, // resulting number of files 2978 char_u ***file, // array of resulting files 2979 int flags) // EW_DIR, etc. 2980 { 2981 int ret = FAIL; 2982 char_u *eval_pat = NULL; 2983 char_u *exp_pat = *pat; 2984 char *ignored_msg; 2985 int usedlen; 2986 2987 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<') 2988 { 2989 ++emsg_off; 2990 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen, 2991 NULL, &ignored_msg, NULL); 2992 --emsg_off; 2993 if (eval_pat != NULL) 2994 exp_pat = concat_str(eval_pat, exp_pat + usedlen); 2995 } 2996 2997 if (exp_pat != NULL) 2998 ret = expand_wildcards(1, &exp_pat, num_file, file, flags); 2999 3000 if (eval_pat != NULL) 3001 { 3002 vim_free(exp_pat); 3003 vim_free(eval_pat); 3004 } 3005 3006 return ret; 3007 } 3008 3009 /* 3010 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching 3011 * 'wildignore'. 3012 * Returns OK or FAIL. When FAIL then "num_files" won't be set. 3013 */ 3014 int 3015 expand_wildcards( 3016 int num_pat, // number of input patterns 3017 char_u **pat, // array of input patterns 3018 int *num_files, // resulting number of files 3019 char_u ***files, // array of resulting files 3020 int flags) // EW_DIR, etc. 3021 { 3022 int retval; 3023 int i, j; 3024 char_u *p; 3025 int non_suf_match; // number without matching suffix 3026 3027 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags); 3028 3029 // When keeping all matches, return here 3030 if ((flags & EW_KEEPALL) || retval == FAIL) 3031 return retval; 3032 3033 #ifdef FEAT_WILDIGN 3034 /* 3035 * Remove names that match 'wildignore'. 3036 */ 3037 if (*p_wig) 3038 { 3039 char_u *ffname; 3040 3041 // check all files in (*files)[] 3042 for (i = 0; i < *num_files; ++i) 3043 { 3044 ffname = FullName_save((*files)[i], FALSE); 3045 if (ffname == NULL) // out of memory 3046 break; 3047 # ifdef VMS 3048 vms_remove_version(ffname); 3049 # endif 3050 if (match_file_list(p_wig, (*files)[i], ffname)) 3051 { 3052 // remove this matching file from the list 3053 vim_free((*files)[i]); 3054 for (j = i; j + 1 < *num_files; ++j) 3055 (*files)[j] = (*files)[j + 1]; 3056 --*num_files; 3057 --i; 3058 } 3059 vim_free(ffname); 3060 } 3061 3062 // If the number of matches is now zero, we fail. 3063 if (*num_files == 0) 3064 { 3065 VIM_CLEAR(*files); 3066 return FAIL; 3067 } 3068 } 3069 #endif 3070 3071 /* 3072 * Move the names where 'suffixes' match to the end. 3073 */ 3074 if (*num_files > 1) 3075 { 3076 non_suf_match = 0; 3077 for (i = 0; i < *num_files; ++i) 3078 { 3079 if (!match_suffix((*files)[i])) 3080 { 3081 /* 3082 * Move the name without matching suffix to the front 3083 * of the list. 3084 */ 3085 p = (*files)[i]; 3086 for (j = i; j > non_suf_match; --j) 3087 (*files)[j] = (*files)[j - 1]; 3088 (*files)[non_suf_match++] = p; 3089 } 3090 } 3091 } 3092 3093 return retval; 3094 } 3095 3096 /* 3097 * Return TRUE if "fname" matches with an entry in 'suffixes'. 3098 */ 3099 int 3100 match_suffix(char_u *fname) 3101 { 3102 int fnamelen, setsuflen; 3103 char_u *setsuf; 3104 #define MAXSUFLEN 30 // maximum length of a file suffix 3105 char_u suf_buf[MAXSUFLEN]; 3106 3107 fnamelen = (int)STRLEN(fname); 3108 setsuflen = 0; 3109 for (setsuf = p_su; *setsuf; ) 3110 { 3111 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,"); 3112 if (setsuflen == 0) 3113 { 3114 char_u *tail = gettail(fname); 3115 3116 // empty entry: match name without a '.' 3117 if (vim_strchr(tail, '.') == NULL) 3118 { 3119 setsuflen = 1; 3120 break; 3121 } 3122 } 3123 else 3124 { 3125 if (fnamelen >= setsuflen 3126 && fnamencmp(suf_buf, fname + fnamelen - setsuflen, 3127 (size_t)setsuflen) == 0) 3128 break; 3129 setsuflen = 0; 3130 } 3131 } 3132 return (setsuflen != 0); 3133 } 3134 3135 #ifdef VIM_BACKTICK 3136 3137 /* 3138 * Return TRUE if we can expand this backtick thing here. 3139 */ 3140 static int 3141 vim_backtick(char_u *p) 3142 { 3143 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`'); 3144 } 3145 3146 /* 3147 * Expand an item in `backticks` by executing it as a command. 3148 * Currently only works when pat[] starts and ends with a `. 3149 * Returns number of file names found, -1 if an error is encountered. 3150 */ 3151 static int 3152 expand_backtick( 3153 garray_T *gap, 3154 char_u *pat, 3155 int flags) // EW_* flags 3156 { 3157 char_u *p; 3158 char_u *cmd; 3159 char_u *buffer; 3160 int cnt = 0; 3161 int i; 3162 3163 // Create the command: lop off the backticks. 3164 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2); 3165 if (cmd == NULL) 3166 return -1; 3167 3168 #ifdef FEAT_EVAL 3169 if (*cmd == '=') // `={expr}`: Expand expression 3170 buffer = eval_to_string(cmd + 1, TRUE); 3171 else 3172 #endif 3173 buffer = get_cmd_output(cmd, NULL, 3174 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL); 3175 vim_free(cmd); 3176 if (buffer == NULL) 3177 return -1; 3178 3179 cmd = buffer; 3180 while (*cmd != NUL) 3181 { 3182 cmd = skipwhite(cmd); // skip over white space 3183 p = cmd; 3184 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry 3185 ++p; 3186 // add an entry if it is not empty 3187 if (p > cmd) 3188 { 3189 i = *p; 3190 *p = NUL; 3191 addfile(gap, cmd, flags); 3192 *p = i; 3193 ++cnt; 3194 } 3195 cmd = p; 3196 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n')) 3197 ++cmd; 3198 } 3199 3200 vim_free(buffer); 3201 return cnt; 3202 } 3203 #endif // VIM_BACKTICK 3204 3205 #if defined(MSWIN) 3206 /* 3207 * File name expansion code for MS-DOS, Win16 and Win32. It's here because 3208 * it's shared between these systems. 3209 */ 3210 3211 /* 3212 * comparison function for qsort in dos_expandpath() 3213 */ 3214 static int 3215 pstrcmp(const void *a, const void *b) 3216 { 3217 return (pathcmp(*(char **)a, *(char **)b, -1)); 3218 } 3219 3220 /* 3221 * Recursively expand one path component into all matching files and/or 3222 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc. 3223 * Return the number of matches found. 3224 * "path" has backslashes before chars that are not to be expanded, starting 3225 * at "path[wildoff]". 3226 * Return the number of matches found. 3227 * NOTE: much of this is identical to unix_expandpath(), keep in sync! 3228 */ 3229 static int 3230 dos_expandpath( 3231 garray_T *gap, 3232 char_u *path, 3233 int wildoff, 3234 int flags, // EW_* flags 3235 int didstar) // expanded "**" once already 3236 { 3237 char_u *buf; 3238 char_u *path_end; 3239 char_u *p, *s, *e; 3240 int start_len = gap->ga_len; 3241 char_u *pat; 3242 regmatch_T regmatch; 3243 int starts_with_dot; 3244 int matches; 3245 int len; 3246 int starstar = FALSE; 3247 static int stardepth = 0; // depth for "**" expansion 3248 HANDLE hFind = INVALID_HANDLE_VALUE; 3249 WIN32_FIND_DATAW wfb; 3250 WCHAR *wn = NULL; // UCS-2 name, NULL when not used. 3251 char_u *matchname; 3252 int ok; 3253 char_u *p_alt; 3254 3255 // Expanding "**" may take a long time, check for CTRL-C. 3256 if (stardepth > 0) 3257 { 3258 ui_breakcheck(); 3259 if (got_int) 3260 return 0; 3261 } 3262 3263 // Make room for file name. When doing encoding conversion the actual 3264 // length may be quite a bit longer, thus use the maximum possible length. 3265 buf = alloc(MAXPATHL); 3266 if (buf == NULL) 3267 return 0; 3268 3269 /* 3270 * Find the first part in the path name that contains a wildcard or a ~1. 3271 * Copy it into buf, including the preceding characters. 3272 */ 3273 p = buf; 3274 s = buf; 3275 e = NULL; 3276 path_end = path; 3277 while (*path_end != NUL) 3278 { 3279 // May ignore a wildcard that has a backslash before it; it will 3280 // be removed by rem_backslash() or file_pat_to_reg_pat() below. 3281 if (path_end >= path + wildoff && rem_backslash(path_end)) 3282 *p++ = *path_end++; 3283 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/') 3284 { 3285 if (e != NULL) 3286 break; 3287 s = p + 1; 3288 } 3289 else if (path_end >= path + wildoff 3290 && vim_strchr((char_u *)"*?[~", *path_end) != NULL) 3291 e = p; 3292 if (has_mbyte) 3293 { 3294 len = (*mb_ptr2len)(path_end); 3295 STRNCPY(p, path_end, len); 3296 p += len; 3297 path_end += len; 3298 } 3299 else 3300 *p++ = *path_end++; 3301 } 3302 e = p; 3303 *e = NUL; 3304 3305 // now we have one wildcard component between s and e 3306 // Remove backslashes between "wildoff" and the start of the wildcard 3307 // component. 3308 for (p = buf + wildoff; p < s; ++p) 3309 if (rem_backslash(p)) 3310 { 3311 STRMOVE(p, p + 1); 3312 --e; 3313 --s; 3314 } 3315 3316 // Check for "**" between "s" and "e". 3317 for (p = s; p < e; ++p) 3318 if (p[0] == '*' && p[1] == '*') 3319 starstar = TRUE; 3320 3321 starts_with_dot = *s == '.'; 3322 pat = file_pat_to_reg_pat(s, e, NULL, FALSE); 3323 if (pat == NULL) 3324 { 3325 vim_free(buf); 3326 return 0; 3327 } 3328 3329 // compile the regexp into a program 3330 if (flags & (EW_NOERROR | EW_NOTWILD)) 3331 ++emsg_silent; 3332 regmatch.rm_ic = TRUE; // Always ignore case 3333 regmatch.regprog = vim_regcomp(pat, RE_MAGIC); 3334 if (flags & (EW_NOERROR | EW_NOTWILD)) 3335 --emsg_silent; 3336 vim_free(pat); 3337 3338 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0) 3339 { 3340 vim_free(buf); 3341 return 0; 3342 } 3343 3344 // remember the pattern or file name being looked for 3345 matchname = vim_strsave(s); 3346 3347 // If "**" is by itself, this is the first time we encounter it and more 3348 // is following then find matches without any directory. 3349 if (!didstar && stardepth < 100 && starstar && e - s == 2 3350 && *path_end == '/') 3351 { 3352 STRCPY(s, path_end + 1); 3353 ++stardepth; 3354 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE); 3355 --stardepth; 3356 } 3357 3358 // Scan all files in the directory with "dir/ *.*" 3359 STRCPY(s, "*.*"); 3360 wn = enc_to_utf16(buf, NULL); 3361 if (wn != NULL) 3362 hFind = FindFirstFileW(wn, &wfb); 3363 ok = (hFind != INVALID_HANDLE_VALUE); 3364 3365 while (ok) 3366 { 3367 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here 3368 3369 if (p == NULL) 3370 break; // out of memory 3371 3372 // Do not use the alternate filename when the file name ends in '~', 3373 // because it picks up backup files: short name for "foo.vim~" is 3374 // "foo~1.vim", which matches "*.vim". 3375 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~') 3376 p_alt = NULL; 3377 else 3378 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL); 3379 3380 // Ignore entries starting with a dot, unless when asked for. Accept 3381 // all entries found with "matchname". 3382 if ((p[0] != '.' || starts_with_dot 3383 || ((flags & EW_DODOT) 3384 && p[1] != NUL && (p[1] != '.' || p[2] != NUL))) 3385 && (matchname == NULL 3386 || (regmatch.regprog != NULL 3387 && (vim_regexec(®match, p, (colnr_T)0) 3388 || (p_alt != NULL 3389 && vim_regexec(®match, p_alt, (colnr_T)0)))) 3390 || ((flags & EW_NOTWILD) 3391 && fnamencmp(path + (s - buf), p, e - s) == 0))) 3392 { 3393 STRCPY(s, p); 3394 len = (int)STRLEN(buf); 3395 3396 if (starstar && stardepth < 100 3397 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 3398 { 3399 // For "**" in the pattern first go deeper in the tree to 3400 // find matches. 3401 STRCPY(buf + len, "/**"); 3402 STRCPY(buf + len + 3, path_end); 3403 ++stardepth; 3404 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE); 3405 --stardepth; 3406 } 3407 3408 STRCPY(buf + len, path_end); 3409 if (mch_has_exp_wildcard(path_end)) 3410 { 3411 // need to expand another component of the path 3412 // remove backslashes for the remaining components only 3413 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE); 3414 } 3415 else 3416 { 3417 // no more wildcards, check if there is a match 3418 // remove backslashes for the remaining components only 3419 if (*path_end != 0) 3420 backslash_halve(buf + len + 1); 3421 if (mch_getperm(buf) >= 0) // add existing file 3422 addfile(gap, buf, flags); 3423 } 3424 } 3425 3426 vim_free(p_alt); 3427 vim_free(p); 3428 ok = FindNextFileW(hFind, &wfb); 3429 } 3430 3431 FindClose(hFind); 3432 vim_free(wn); 3433 vim_free(buf); 3434 vim_regfree(regmatch.regprog); 3435 vim_free(matchname); 3436 3437 matches = gap->ga_len - start_len; 3438 if (matches > 0) 3439 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches, 3440 sizeof(char_u *), pstrcmp); 3441 return matches; 3442 } 3443 3444 int 3445 mch_expandpath( 3446 garray_T *gap, 3447 char_u *path, 3448 int flags) // EW_* flags 3449 { 3450 return dos_expandpath(gap, path, 0, flags, FALSE); 3451 } 3452 #endif // MSWIN 3453 3454 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \ 3455 || defined(PROTO) 3456 /* 3457 * Unix style wildcard expansion code. 3458 * It's here because it's used both for Unix and Mac. 3459 */ 3460 static int 3461 pstrcmp(const void *a, const void *b) 3462 { 3463 return (pathcmp(*(char **)a, *(char **)b, -1)); 3464 } 3465 3466 /* 3467 * Recursively expand one path component into all matching files and/or 3468 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc. 3469 * "path" has backslashes before chars that are not to be expanded, starting 3470 * at "path + wildoff". 3471 * Return the number of matches found. 3472 * NOTE: much of this is identical to dos_expandpath(), keep in sync! 3473 */ 3474 int 3475 unix_expandpath( 3476 garray_T *gap, 3477 char_u *path, 3478 int wildoff, 3479 int flags, // EW_* flags 3480 int didstar) // expanded "**" once already 3481 { 3482 char_u *buf; 3483 char_u *path_end; 3484 char_u *p, *s, *e; 3485 int start_len = gap->ga_len; 3486 char_u *pat; 3487 regmatch_T regmatch; 3488 int starts_with_dot; 3489 int matches; 3490 int len; 3491 int starstar = FALSE; 3492 static int stardepth = 0; // depth for "**" expansion 3493 3494 DIR *dirp; 3495 struct dirent *dp; 3496 3497 // Expanding "**" may take a long time, check for CTRL-C. 3498 if (stardepth > 0) 3499 { 3500 ui_breakcheck(); 3501 if (got_int) 3502 return 0; 3503 } 3504 3505 // make room for file name 3506 buf = alloc(STRLEN(path) + BASENAMELEN + 5); 3507 if (buf == NULL) 3508 return 0; 3509 3510 /* 3511 * Find the first part in the path name that contains a wildcard. 3512 * When EW_ICASE is set every letter is considered to be a wildcard. 3513 * Copy it into "buf", including the preceding characters. 3514 */ 3515 p = buf; 3516 s = buf; 3517 e = NULL; 3518 path_end = path; 3519 while (*path_end != NUL) 3520 { 3521 // May ignore a wildcard that has a backslash before it; it will 3522 // be removed by rem_backslash() or file_pat_to_reg_pat() below. 3523 if (path_end >= path + wildoff && rem_backslash(path_end)) 3524 *p++ = *path_end++; 3525 else if (*path_end == '/') 3526 { 3527 if (e != NULL) 3528 break; 3529 s = p + 1; 3530 } 3531 else if (path_end >= path + wildoff 3532 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL 3533 || (!p_fic && (flags & EW_ICASE) 3534 && isalpha(PTR2CHAR(path_end))))) 3535 e = p; 3536 if (has_mbyte) 3537 { 3538 len = (*mb_ptr2len)(path_end); 3539 STRNCPY(p, path_end, len); 3540 p += len; 3541 path_end += len; 3542 } 3543 else 3544 *p++ = *path_end++; 3545 } 3546 e = p; 3547 *e = NUL; 3548 3549 // Now we have one wildcard component between "s" and "e". 3550 // Remove backslashes between "wildoff" and the start of the wildcard 3551 // component. 3552 for (p = buf + wildoff; p < s; ++p) 3553 if (rem_backslash(p)) 3554 { 3555 STRMOVE(p, p + 1); 3556 --e; 3557 --s; 3558 } 3559 3560 // Check for "**" between "s" and "e". 3561 for (p = s; p < e; ++p) 3562 if (p[0] == '*' && p[1] == '*') 3563 starstar = TRUE; 3564 3565 // convert the file pattern to a regexp pattern 3566 starts_with_dot = *s == '.'; 3567 pat = file_pat_to_reg_pat(s, e, NULL, FALSE); 3568 if (pat == NULL) 3569 { 3570 vim_free(buf); 3571 return 0; 3572 } 3573 3574 // compile the regexp into a program 3575 if (flags & EW_ICASE) 3576 regmatch.rm_ic = TRUE; // 'wildignorecase' set 3577 else 3578 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set 3579 if (flags & (EW_NOERROR | EW_NOTWILD)) 3580 ++emsg_silent; 3581 regmatch.regprog = vim_regcomp(pat, RE_MAGIC); 3582 if (flags & (EW_NOERROR | EW_NOTWILD)) 3583 --emsg_silent; 3584 vim_free(pat); 3585 3586 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0) 3587 { 3588 vim_free(buf); 3589 return 0; 3590 } 3591 3592 // If "**" is by itself, this is the first time we encounter it and more 3593 // is following then find matches without any directory. 3594 if (!didstar && stardepth < 100 && starstar && e - s == 2 3595 && *path_end == '/') 3596 { 3597 STRCPY(s, path_end + 1); 3598 ++stardepth; 3599 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE); 3600 --stardepth; 3601 } 3602 3603 // open the directory for scanning 3604 *s = NUL; 3605 dirp = opendir(*buf == NUL ? "." : (char *)buf); 3606 3607 // Find all matching entries 3608 if (dirp != NULL) 3609 { 3610 for (;;) 3611 { 3612 dp = readdir(dirp); 3613 if (dp == NULL) 3614 break; 3615 if ((dp->d_name[0] != '.' || starts_with_dot 3616 || ((flags & EW_DODOT) 3617 && dp->d_name[1] != NUL 3618 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL))) 3619 && ((regmatch.regprog != NULL && vim_regexec(®match, 3620 (char_u *)dp->d_name, (colnr_T)0)) 3621 || ((flags & EW_NOTWILD) 3622 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0))) 3623 { 3624 STRCPY(s, dp->d_name); 3625 len = STRLEN(buf); 3626 3627 if (starstar && stardepth < 100) 3628 { 3629 // For "**" in the pattern first go deeper in the tree to 3630 // find matches. 3631 STRCPY(buf + len, "/**"); 3632 STRCPY(buf + len + 3, path_end); 3633 ++stardepth; 3634 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE); 3635 --stardepth; 3636 } 3637 3638 STRCPY(buf + len, path_end); 3639 if (mch_has_exp_wildcard(path_end)) // handle more wildcards 3640 { 3641 // need to expand another component of the path 3642 // remove backslashes for the remaining components only 3643 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE); 3644 } 3645 else 3646 { 3647 stat_T sb; 3648 3649 // no more wildcards, check if there is a match 3650 // remove backslashes for the remaining components only 3651 if (*path_end != NUL) 3652 backslash_halve(buf + len + 1); 3653 // add existing file or symbolic link 3654 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0 3655 : mch_getperm(buf) >= 0) 3656 { 3657 #ifdef MACOS_CONVERT 3658 size_t precomp_len = STRLEN(buf)+1; 3659 char_u *precomp_buf = 3660 mac_precompose_path(buf, precomp_len, &precomp_len); 3661 3662 if (precomp_buf) 3663 { 3664 mch_memmove(buf, precomp_buf, precomp_len); 3665 vim_free(precomp_buf); 3666 } 3667 #endif 3668 addfile(gap, buf, flags); 3669 } 3670 } 3671 } 3672 } 3673 3674 closedir(dirp); 3675 } 3676 3677 vim_free(buf); 3678 vim_regfree(regmatch.regprog); 3679 3680 matches = gap->ga_len - start_len; 3681 if (matches > 0) 3682 qsort(((char_u **)gap->ga_data) + start_len, matches, 3683 sizeof(char_u *), pstrcmp); 3684 return matches; 3685 } 3686 #endif 3687 3688 /* 3689 * Return TRUE if "p" contains what looks like an environment variable. 3690 * Allowing for escaping. 3691 */ 3692 static int 3693 has_env_var(char_u *p) 3694 { 3695 for ( ; *p; MB_PTR_ADV(p)) 3696 { 3697 if (*p == '\\' && p[1] != NUL) 3698 ++p; 3699 else if (vim_strchr((char_u *) 3700 #if defined(MSWIN) 3701 "$%" 3702 #else 3703 "$" 3704 #endif 3705 , *p) != NULL) 3706 return TRUE; 3707 } 3708 return FALSE; 3709 } 3710 3711 #ifdef SPECIAL_WILDCHAR 3712 /* 3713 * Return TRUE if "p" contains a special wildcard character, one that Vim 3714 * cannot expand, requires using a shell. 3715 */ 3716 static int 3717 has_special_wildchar(char_u *p) 3718 { 3719 for ( ; *p; MB_PTR_ADV(p)) 3720 { 3721 // Disallow line break characters. 3722 if (*p == '\r' || *p == '\n') 3723 break; 3724 // Allow for escaping. 3725 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n') 3726 ++p; 3727 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL) 3728 { 3729 // A { must be followed by a matching }. 3730 if (*p == '{' && vim_strchr(p, '}') == NULL) 3731 continue; 3732 // A quote and backtick must be followed by another one. 3733 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL) 3734 continue; 3735 return TRUE; 3736 } 3737 } 3738 return FALSE; 3739 } 3740 #endif 3741 3742 /* 3743 * Generic wildcard expansion code. 3744 * 3745 * Characters in "pat" that should not be expanded must be preceded with a 3746 * backslash. E.g., "/path\ with\ spaces/my\*star*" 3747 * 3748 * Return FAIL when no single file was found. In this case "num_file" is not 3749 * set, and "file" may contain an error message. 3750 * Return OK when some files found. "num_file" is set to the number of 3751 * matches, "file" to the array of matches. Call FreeWild() later. 3752 */ 3753 int 3754 gen_expand_wildcards( 3755 int num_pat, // number of input patterns 3756 char_u **pat, // array of input patterns 3757 int *num_file, // resulting number of files 3758 char_u ***file, // array of resulting files 3759 int flags) // EW_* flags 3760 { 3761 int i; 3762 garray_T ga; 3763 char_u *p; 3764 static int recursive = FALSE; 3765 int add_pat; 3766 int retval = OK; 3767 #if defined(FEAT_SEARCHPATH) 3768 int did_expand_in_path = FALSE; 3769 #endif 3770 3771 /* 3772 * expand_env() is called to expand things like "~user". If this fails, 3773 * it calls ExpandOne(), which brings us back here. In this case, always 3774 * call the machine specific expansion function, if possible. Otherwise, 3775 * return FAIL. 3776 */ 3777 if (recursive) 3778 #ifdef SPECIAL_WILDCHAR 3779 return mch_expand_wildcards(num_pat, pat, num_file, file, flags); 3780 #else 3781 return FAIL; 3782 #endif 3783 3784 #ifdef SPECIAL_WILDCHAR 3785 /* 3786 * If there are any special wildcard characters which we cannot handle 3787 * here, call machine specific function for all the expansion. This 3788 * avoids starting the shell for each argument separately. 3789 * For `=expr` do use the internal function. 3790 */ 3791 for (i = 0; i < num_pat; i++) 3792 { 3793 if (has_special_wildchar(pat[i]) 3794 # ifdef VIM_BACKTICK 3795 && !(vim_backtick(pat[i]) && pat[i][1] == '=') 3796 # endif 3797 ) 3798 return mch_expand_wildcards(num_pat, pat, num_file, file, flags); 3799 } 3800 #endif 3801 3802 recursive = TRUE; 3803 3804 /* 3805 * The matching file names are stored in a growarray. Init it empty. 3806 */ 3807 ga_init2(&ga, (int)sizeof(char_u *), 30); 3808 3809 for (i = 0; i < num_pat; ++i) 3810 { 3811 add_pat = -1; 3812 p = pat[i]; 3813 3814 #ifdef VIM_BACKTICK 3815 if (vim_backtick(p)) 3816 { 3817 add_pat = expand_backtick(&ga, p, flags); 3818 if (add_pat == -1) 3819 retval = FAIL; 3820 } 3821 else 3822 #endif 3823 { 3824 /* 3825 * First expand environment variables, "~/" and "~user/". 3826 */ 3827 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~') 3828 { 3829 p = expand_env_save_opt(p, TRUE); 3830 if (p == NULL) 3831 p = pat[i]; 3832 #ifdef UNIX 3833 /* 3834 * On Unix, if expand_env() can't expand an environment 3835 * variable, use the shell to do that. Discard previously 3836 * found file names and start all over again. 3837 */ 3838 else if (has_env_var(p) || *p == '~') 3839 { 3840 vim_free(p); 3841 ga_clear_strings(&ga); 3842 i = mch_expand_wildcards(num_pat, pat, num_file, file, 3843 flags|EW_KEEPDOLLAR); 3844 recursive = FALSE; 3845 return i; 3846 } 3847 #endif 3848 } 3849 3850 /* 3851 * If there are wildcards: Expand file names and add each match to 3852 * the list. If there is no match, and EW_NOTFOUND is given, add 3853 * the pattern. 3854 * If there are no wildcards: Add the file name if it exists or 3855 * when EW_NOTFOUND is given. 3856 */ 3857 if (mch_has_exp_wildcard(p)) 3858 { 3859 #if defined(FEAT_SEARCHPATH) 3860 if ((flags & EW_PATH) 3861 && !mch_isFullName(p) 3862 && !(p[0] == '.' 3863 && (vim_ispathsep(p[1]) 3864 || (p[1] == '.' && vim_ispathsep(p[2])))) 3865 ) 3866 { 3867 // :find completion where 'path' is used. 3868 // Recursiveness is OK here. 3869 recursive = FALSE; 3870 add_pat = expand_in_path(&ga, p, flags); 3871 recursive = TRUE; 3872 did_expand_in_path = TRUE; 3873 } 3874 else 3875 #endif 3876 add_pat = mch_expandpath(&ga, p, flags); 3877 } 3878 } 3879 3880 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND))) 3881 { 3882 char_u *t = backslash_halve_save(p); 3883 3884 // When EW_NOTFOUND is used, always add files and dirs. Makes 3885 // "vim c:/" work. 3886 if (flags & EW_NOTFOUND) 3887 addfile(&ga, t, flags | EW_DIR | EW_FILE); 3888 else 3889 addfile(&ga, t, flags); 3890 3891 if (t != p) 3892 vim_free(t); 3893 } 3894 3895 #if defined(FEAT_SEARCHPATH) 3896 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH)) 3897 uniquefy_paths(&ga, p); 3898 #endif 3899 if (p != pat[i]) 3900 vim_free(p); 3901 } 3902 3903 // When returning FAIL the array must be freed here. 3904 if (retval == FAIL) 3905 ga_clear(&ga); 3906 3907 *num_file = ga.ga_len; 3908 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data 3909 : (char_u **)_("no matches"); 3910 3911 recursive = FALSE; 3912 3913 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL; 3914 } 3915 3916 /* 3917 * Add a file to a file list. Accepted flags: 3918 * EW_DIR add directories 3919 * EW_FILE add files 3920 * EW_EXEC add executable files 3921 * EW_NOTFOUND add even when it doesn't exist 3922 * EW_ADDSLASH add slash after directory name 3923 * EW_ALLLINKS add symlink also when the referred file does not exist 3924 */ 3925 void 3926 addfile( 3927 garray_T *gap, 3928 char_u *f, // filename 3929 int flags) 3930 { 3931 char_u *p; 3932 int isdir; 3933 stat_T sb; 3934 3935 // if the file/dir/link doesn't exist, may not add it 3936 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS) 3937 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0)) 3938 return; 3939 3940 #ifdef FNAME_ILLEGAL 3941 // if the file/dir contains illegal characters, don't add it 3942 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL) 3943 return; 3944 #endif 3945 3946 isdir = mch_isdir(f); 3947 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE))) 3948 return; 3949 3950 // If the file isn't executable, may not add it. Do accept directories. 3951 // When invoked from expand_shellcmd() do not use $PATH. 3952 if (!isdir && (flags & EW_EXEC) 3953 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD))) 3954 return; 3955 3956 // Make room for another item in the file list. 3957 if (ga_grow(gap, 1) == FAIL) 3958 return; 3959 3960 p = alloc(STRLEN(f) + 1 + isdir); 3961 if (p == NULL) 3962 return; 3963 3964 STRCPY(p, f); 3965 #ifdef BACKSLASH_IN_FILENAME 3966 slash_adjust(p); 3967 #endif 3968 /* 3969 * Append a slash or backslash after directory names if none is present. 3970 */ 3971 #ifndef DONT_ADD_PATHSEP_TO_DIR 3972 if (isdir && (flags & EW_ADDSLASH)) 3973 add_pathsep(p); 3974 #endif 3975 ((char_u **)gap->ga_data)[gap->ga_len++] = p; 3976 } 3977 3978 /* 3979 * Free the list of files returned by expand_wildcards() or other expansion 3980 * functions. 3981 */ 3982 void 3983 FreeWild(int count, char_u **files) 3984 { 3985 if (count <= 0 || files == NULL) 3986 return; 3987 while (count--) 3988 vim_free(files[count]); 3989 vim_free(files); 3990 } 3991 3992 /* 3993 * Compare path "p[]" to "q[]". 3994 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]" 3995 * Return value like strcmp(p, q), but consider path separators. 3996 */ 3997 int 3998 pathcmp(const char *p, const char *q, int maxlen) 3999 { 4000 int i, j; 4001 int c1, c2; 4002 const char *s = NULL; 4003 4004 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);) 4005 { 4006 c1 = PTR2CHAR((char_u *)p + i); 4007 c2 = PTR2CHAR((char_u *)q + j); 4008 4009 // End of "p": check if "q" also ends or just has a slash. 4010 if (c1 == NUL) 4011 { 4012 if (c2 == NUL) // full match 4013 return 0; 4014 s = q; 4015 i = j; 4016 break; 4017 } 4018 4019 // End of "q": check if "p" just has a slash. 4020 if (c2 == NUL) 4021 { 4022 s = p; 4023 break; 4024 } 4025 4026 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2) 4027 #ifdef BACKSLASH_IN_FILENAME 4028 // consider '/' and '\\' to be equal 4029 && !((c1 == '/' && c2 == '\\') 4030 || (c1 == '\\' && c2 == '/')) 4031 #endif 4032 ) 4033 { 4034 if (vim_ispathsep(c1)) 4035 return -1; 4036 if (vim_ispathsep(c2)) 4037 return 1; 4038 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2) 4039 : c1 - c2; // no match 4040 } 4041 4042 i += mb_ptr2len((char_u *)p + i); 4043 j += mb_ptr2len((char_u *)q + j); 4044 } 4045 if (s == NULL) // "i" or "j" ran into "maxlen" 4046 return 0; 4047 4048 c1 = PTR2CHAR((char_u *)s + i); 4049 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i)); 4050 // ignore a trailing slash, but not "//" or ":/" 4051 if (c2 == NUL 4052 && i > 0 4053 && !after_pathsep((char_u *)s, (char_u *)s + i) 4054 #ifdef BACKSLASH_IN_FILENAME 4055 && (c1 == '/' || c1 == '\\') 4056 #else 4057 && c1 == '/' 4058 #endif 4059 ) 4060 return 0; // match with trailing slash 4061 if (s == q) 4062 return -1; // no match 4063 return 1; 4064 } 4065 4066 /* 4067 * Return TRUE if "name" is a full (absolute) path name or URL. 4068 */ 4069 int 4070 vim_isAbsName(char_u *name) 4071 { 4072 return (path_with_url(name) != 0 || mch_isFullName(name)); 4073 } 4074 4075 /* 4076 * Get absolute file name into buffer "buf[len]". 4077 * 4078 * return FAIL for failure, OK otherwise 4079 */ 4080 int 4081 vim_FullName( 4082 char_u *fname, 4083 char_u *buf, 4084 int len, 4085 int force) // force expansion even when already absolute 4086 { 4087 int retval = OK; 4088 int url; 4089 4090 *buf = NUL; 4091 if (fname == NULL) 4092 return FAIL; 4093 4094 url = path_with_url(fname); 4095 if (!url) 4096 retval = mch_FullName(fname, buf, len, force); 4097 if (url || retval == FAIL) 4098 { 4099 // something failed; use the file name (truncate when too long) 4100 vim_strncpy(buf, fname, len - 1); 4101 } 4102 #if defined(MSWIN) 4103 slash_adjust(buf); 4104 #endif 4105 return retval; 4106 } 4107