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