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