xref: /vim-8.2.3635/src/filepath.c (revision a0122dcd)
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]) == 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]) == 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]) == 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]) == 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]) == 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]) == FAIL
1027 	    || check_for_string(&argvars[1]) == 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]) == 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]) == 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]) == 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]) == 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     void
1644 f_readfile(typval_T *argvars, typval_T *rettv)
1645 {
1646     int		binary = FALSE;
1647     int		blob = FALSE;
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 			    adjust_prevlen = (int)(buf - dest); // must be 1 or 2
1800 			    dest = buf;
1801 			}
1802 			if (readlen > p - buf + 1)
1803 			    mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1804 			readlen -= 3 - adjust_prevlen;
1805 			prevlen -= adjust_prevlen;
1806 			p = dest - 1;
1807 		    }
1808 		}
1809 	    }
1810 	} // for
1811 
1812 	if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1813 	    break;
1814 	if (start < p)
1815 	{
1816 	    // There's part of a line in buf, store it in "prev".
1817 	    if (p - start + prevlen >= prevsize)
1818 	    {
1819 		// need bigger "prev" buffer
1820 		char_u *newprev;
1821 
1822 		// A common use case is ordinary text files and "prev" gets a
1823 		// fragment of a line, so the first allocation is made
1824 		// small, to avoid repeatedly 'allocing' large and
1825 		// 'reallocing' small.
1826 		if (prevsize == 0)
1827 		    prevsize = (long)(p - start);
1828 		else
1829 		{
1830 		    long grow50pc = (prevsize * 3) / 2;
1831 		    long growmin  = (long)((p - start) * 2 + prevlen);
1832 		    prevsize = grow50pc > growmin ? grow50pc : growmin;
1833 		}
1834 		newprev = vim_realloc(prev, prevsize);
1835 		if (newprev == NULL)
1836 		{
1837 		    do_outofmem_msg((long_u)prevsize);
1838 		    failed = TRUE;
1839 		    break;
1840 		}
1841 		prev = newprev;
1842 	    }
1843 	    // Add the line part to end of "prev".
1844 	    mch_memmove(prev + prevlen, start, p - start);
1845 	    prevlen += (long)(p - start);
1846 	}
1847     } // while
1848 
1849     // For a negative line count use only the lines at the end of the file,
1850     // free the rest.
1851     if (!failed && maxline < 0)
1852 	while (cnt > -maxline)
1853 	{
1854 	    listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1855 	    --cnt;
1856 	}
1857 
1858     if (failed)
1859     {
1860 	// an empty list is returned on error
1861 	list_free(rettv->vval.v_list);
1862 	rettv_list_alloc(rettv);
1863     }
1864 
1865     vim_free(prev);
1866     fclose(fd);
1867 }
1868 
1869 /*
1870  * "resolve()" function
1871  */
1872     void
1873 f_resolve(typval_T *argvars, typval_T *rettv)
1874 {
1875     char_u	*p;
1876 #ifdef HAVE_READLINK
1877     char_u	*buf = NULL;
1878 #endif
1879 
1880     p = tv_get_string(&argvars[0]);
1881 #ifdef FEAT_SHORTCUT
1882     {
1883 	char_u	*v = NULL;
1884 
1885 	v = mch_resolve_path(p, TRUE);
1886 	if (v != NULL)
1887 	    rettv->vval.v_string = v;
1888 	else
1889 	    rettv->vval.v_string = vim_strsave(p);
1890     }
1891 #else
1892 # ifdef HAVE_READLINK
1893     {
1894 	char_u	*cpy;
1895 	int	len;
1896 	char_u	*remain = NULL;
1897 	char_u	*q;
1898 	int	is_relative_to_current = FALSE;
1899 	int	has_trailing_pathsep = FALSE;
1900 	int	limit = 100;
1901 
1902 	p = vim_strsave(p);
1903 	if (p == NULL)
1904 	    goto fail;
1905 	if (p[0] == '.' && (vim_ispathsep(p[1])
1906 				   || (p[1] == '.' && (vim_ispathsep(p[2])))))
1907 	    is_relative_to_current = TRUE;
1908 
1909 	len = STRLEN(p);
1910 	if (len > 1 && after_pathsep(p, p + len))
1911 	{
1912 	    has_trailing_pathsep = TRUE;
1913 	    p[len - 1] = NUL; // the trailing slash breaks readlink()
1914 	}
1915 
1916 	q = getnextcomp(p);
1917 	if (*q != NUL)
1918 	{
1919 	    // Separate the first path component in "p", and keep the
1920 	    // remainder (beginning with the path separator).
1921 	    remain = vim_strsave(q - 1);
1922 	    q[-1] = NUL;
1923 	}
1924 
1925 	buf = alloc(MAXPATHL + 1);
1926 	if (buf == NULL)
1927 	{
1928 	    vim_free(p);
1929 	    goto fail;
1930 	}
1931 
1932 	for (;;)
1933 	{
1934 	    for (;;)
1935 	    {
1936 		len = readlink((char *)p, (char *)buf, MAXPATHL);
1937 		if (len <= 0)
1938 		    break;
1939 		buf[len] = NUL;
1940 
1941 		if (limit-- == 0)
1942 		{
1943 		    vim_free(p);
1944 		    vim_free(remain);
1945 		    emsg(_("E655: Too many symbolic links (cycle?)"));
1946 		    rettv->vval.v_string = NULL;
1947 		    goto fail;
1948 		}
1949 
1950 		// Ensure that the result will have a trailing path separator
1951 		// if the argument has one.
1952 		if (remain == NULL && has_trailing_pathsep)
1953 		    add_pathsep(buf);
1954 
1955 		// Separate the first path component in the link value and
1956 		// concatenate the remainders.
1957 		q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
1958 		if (*q != NUL)
1959 		{
1960 		    if (remain == NULL)
1961 			remain = vim_strsave(q - 1);
1962 		    else
1963 		    {
1964 			cpy = concat_str(q - 1, remain);
1965 			if (cpy != NULL)
1966 			{
1967 			    vim_free(remain);
1968 			    remain = cpy;
1969 			}
1970 		    }
1971 		    q[-1] = NUL;
1972 		}
1973 
1974 		q = gettail(p);
1975 		if (q > p && *q == NUL)
1976 		{
1977 		    // Ignore trailing path separator.
1978 		    q[-1] = NUL;
1979 		    q = gettail(p);
1980 		}
1981 		if (q > p && !mch_isFullName(buf))
1982 		{
1983 		    // symlink is relative to directory of argument
1984 		    cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
1985 		    if (cpy != NULL)
1986 		    {
1987 			STRCPY(cpy, p);
1988 			STRCPY(gettail(cpy), buf);
1989 			vim_free(p);
1990 			p = cpy;
1991 		    }
1992 		}
1993 		else
1994 		{
1995 		    vim_free(p);
1996 		    p = vim_strsave(buf);
1997 		}
1998 	    }
1999 
2000 	    if (remain == NULL)
2001 		break;
2002 
2003 	    // Append the first path component of "remain" to "p".
2004 	    q = getnextcomp(remain + 1);
2005 	    len = q - remain - (*q != NUL);
2006 	    cpy = vim_strnsave(p, STRLEN(p) + len);
2007 	    if (cpy != NULL)
2008 	    {
2009 		STRNCAT(cpy, remain, len);
2010 		vim_free(p);
2011 		p = cpy;
2012 	    }
2013 	    // Shorten "remain".
2014 	    if (*q != NUL)
2015 		STRMOVE(remain, q - 1);
2016 	    else
2017 		VIM_CLEAR(remain);
2018 	}
2019 
2020 	// If the result is a relative path name, make it explicitly relative to
2021 	// the current directory if and only if the argument had this form.
2022 	if (!vim_ispathsep(*p))
2023 	{
2024 	    if (is_relative_to_current
2025 		    && *p != NUL
2026 		    && !(p[0] == '.'
2027 			&& (p[1] == NUL
2028 			    || vim_ispathsep(p[1])
2029 			    || (p[1] == '.'
2030 				&& (p[2] == NUL
2031 				    || vim_ispathsep(p[2]))))))
2032 	    {
2033 		// Prepend "./".
2034 		cpy = concat_str((char_u *)"./", p);
2035 		if (cpy != NULL)
2036 		{
2037 		    vim_free(p);
2038 		    p = cpy;
2039 		}
2040 	    }
2041 	    else if (!is_relative_to_current)
2042 	    {
2043 		// Strip leading "./".
2044 		q = p;
2045 		while (q[0] == '.' && vim_ispathsep(q[1]))
2046 		    q += 2;
2047 		if (q > p)
2048 		    STRMOVE(p, p + 2);
2049 	    }
2050 	}
2051 
2052 	// Ensure that the result will have no trailing path separator
2053 	// if the argument had none.  But keep "/" or "//".
2054 	if (!has_trailing_pathsep)
2055 	{
2056 	    q = p + STRLEN(p);
2057 	    if (after_pathsep(p, q))
2058 		*gettail_sep(p) = NUL;
2059 	}
2060 
2061 	rettv->vval.v_string = p;
2062     }
2063 # else
2064     rettv->vval.v_string = vim_strsave(p);
2065 # endif
2066 #endif
2067 
2068     simplify_filename(rettv->vval.v_string);
2069 
2070 #ifdef HAVE_READLINK
2071 fail:
2072     vim_free(buf);
2073 #endif
2074     rettv->v_type = VAR_STRING;
2075 }
2076 
2077 /*
2078  * "tempname()" function
2079  */
2080     void
2081 f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2082 {
2083     static int	x = 'A';
2084 
2085     rettv->v_type = VAR_STRING;
2086     rettv->vval.v_string = vim_tempname(x, FALSE);
2087 
2088     // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2089     // names.  Skip 'I' and 'O', they are used for shell redirection.
2090     do
2091     {
2092 	if (x == 'Z')
2093 	    x = '0';
2094 	else if (x == '9')
2095 	    x = 'A';
2096 	else
2097 	{
2098 #ifdef EBCDIC
2099 	    if (x == 'I')
2100 		x = 'J';
2101 	    else if (x == 'R')
2102 		x = 'S';
2103 	    else
2104 #endif
2105 		++x;
2106 	}
2107     } while (x == 'I' || x == 'O');
2108 }
2109 
2110 /*
2111  * "writefile()" function
2112  */
2113     void
2114 f_writefile(typval_T *argvars, typval_T *rettv)
2115 {
2116     int		binary = FALSE;
2117     int		append = FALSE;
2118 #ifdef HAVE_FSYNC
2119     int		do_fsync = p_fs;
2120 #endif
2121     char_u	*fname;
2122     FILE	*fd;
2123     int		ret = 0;
2124     listitem_T	*li;
2125     list_T	*list = NULL;
2126     blob_T	*blob = NULL;
2127 
2128     rettv->vval.v_number = -1;
2129     if (check_secure())
2130 	return;
2131 
2132     if (argvars[0].v_type == VAR_LIST)
2133     {
2134 	list = argvars[0].vval.v_list;
2135 	if (list == NULL)
2136 	    return;
2137 	CHECK_LIST_MATERIALIZE(list);
2138 	FOR_ALL_LIST_ITEMS(list, li)
2139 	    if (tv_get_string_chk(&li->li_tv) == NULL)
2140 		return;
2141     }
2142     else if (argvars[0].v_type == VAR_BLOB)
2143     {
2144 	blob = argvars[0].vval.v_blob;
2145 	if (blob == NULL)
2146 	    return;
2147     }
2148     else
2149     {
2150 	semsg(_(e_invarg2),
2151 		_("writefile() first argument must be a List or a Blob"));
2152 	return;
2153     }
2154 
2155     if (argvars[2].v_type != VAR_UNKNOWN)
2156     {
2157 	char_u *arg2 = tv_get_string_chk(&argvars[2]);
2158 
2159 	if (arg2 == NULL)
2160 	    return;
2161 	if (vim_strchr(arg2, 'b') != NULL)
2162 	    binary = TRUE;
2163 	if (vim_strchr(arg2, 'a') != NULL)
2164 	    append = TRUE;
2165 #ifdef HAVE_FSYNC
2166 	if (vim_strchr(arg2, 's') != NULL)
2167 	    do_fsync = TRUE;
2168 	else if (vim_strchr(arg2, 'S') != NULL)
2169 	    do_fsync = FALSE;
2170 #endif
2171     }
2172 
2173     fname = tv_get_string_chk(&argvars[1]);
2174     if (fname == NULL)
2175 	return;
2176 
2177     // Always open the file in binary mode, library functions have a mind of
2178     // their own about CR-LF conversion.
2179     if (*fname == NUL || (fd = mch_fopen((char *)fname,
2180 				      append ? APPENDBIN : WRITEBIN)) == NULL)
2181     {
2182 	semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2183 	ret = -1;
2184     }
2185     else if (blob)
2186     {
2187 	if (write_blob(fd, blob) == FAIL)
2188 	    ret = -1;
2189 #ifdef HAVE_FSYNC
2190 	else if (do_fsync)
2191 	    // Ignore the error, the user wouldn't know what to do about it.
2192 	    // May happen for a device.
2193 	    vim_ignored = vim_fsync(fileno(fd));
2194 #endif
2195 	fclose(fd);
2196     }
2197     else
2198     {
2199 	if (write_list(fd, list, binary) == FAIL)
2200 	    ret = -1;
2201 #ifdef HAVE_FSYNC
2202 	else if (do_fsync)
2203 	    // Ignore the error, the user wouldn't know what to do about it.
2204 	    // May happen for a device.
2205 	    vim_ignored = vim_fsync(fileno(fd));
2206 #endif
2207 	fclose(fd);
2208     }
2209 
2210     rettv->vval.v_number = ret;
2211 }
2212 
2213 #endif // FEAT_EVAL
2214 
2215 #if defined(FEAT_BROWSE) || defined(PROTO)
2216 /*
2217  * Generic browse function.  Calls gui_mch_browse() when possible.
2218  * Later this may pop-up a non-GUI file selector (external command?).
2219  */
2220     char_u *
2221 do_browse(
2222     int		flags,		// BROWSE_SAVE and BROWSE_DIR
2223     char_u	*title,		// title for the window
2224     char_u	*dflt,		// default file name (may include directory)
2225     char_u	*ext,		// extension added
2226     char_u	*initdir,	// initial directory, NULL for current dir or
2227 				// when using path from "dflt"
2228     char_u	*filter,	// file name filter
2229     buf_T	*buf)		// buffer to read/write for
2230 {
2231     char_u		*fname;
2232     static char_u	*last_dir = NULL;    // last used directory
2233     char_u		*tofree = NULL;
2234     int			save_cmod_flags = cmdmod.cmod_flags;
2235 
2236     // Must turn off browse to avoid that autocommands will get the
2237     // flag too!
2238     cmdmod.cmod_flags &= ~CMOD_BROWSE;
2239 
2240     if (title == NULL || *title == NUL)
2241     {
2242 	if (flags & BROWSE_DIR)
2243 	    title = (char_u *)_("Select Directory dialog");
2244 	else if (flags & BROWSE_SAVE)
2245 	    title = (char_u *)_("Save File dialog");
2246 	else
2247 	    title = (char_u *)_("Open File dialog");
2248     }
2249 
2250     // When no directory specified, use default file name, default dir, buffer
2251     // dir, last dir or current dir
2252     if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2253     {
2254 	if (mch_isdir(dflt))		// default file name is a directory
2255 	{
2256 	    initdir = dflt;
2257 	    dflt = NULL;
2258 	}
2259 	else if (gettail(dflt) != dflt)	// default file name includes a path
2260 	{
2261 	    tofree = vim_strsave(dflt);
2262 	    if (tofree != NULL)
2263 	    {
2264 		initdir = tofree;
2265 		*gettail(initdir) = NUL;
2266 		dflt = gettail(dflt);
2267 	    }
2268 	}
2269     }
2270 
2271     if (initdir == NULL || *initdir == NUL)
2272     {
2273 	// When 'browsedir' is a directory, use it
2274 	if (STRCMP(p_bsdir, "last") != 0
2275 		&& STRCMP(p_bsdir, "buffer") != 0
2276 		&& STRCMP(p_bsdir, "current") != 0
2277 		&& mch_isdir(p_bsdir))
2278 	    initdir = p_bsdir;
2279 	// When saving or 'browsedir' is "buffer", use buffer fname
2280 	else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2281 		&& buf != NULL && buf->b_ffname != NULL)
2282 	{
2283 	    if (dflt == NULL || *dflt == NUL)
2284 		dflt = gettail(curbuf->b_ffname);
2285 	    tofree = vim_strsave(curbuf->b_ffname);
2286 	    if (tofree != NULL)
2287 	    {
2288 		initdir = tofree;
2289 		*gettail(initdir) = NUL;
2290 	    }
2291 	}
2292 	// When 'browsedir' is "last", use dir from last browse
2293 	else if (*p_bsdir == 'l')
2294 	    initdir = last_dir;
2295 	// When 'browsedir is "current", use current directory.  This is the
2296 	// default already, leave initdir empty.
2297     }
2298 
2299 # ifdef FEAT_GUI
2300     if (gui.in_use)		// when this changes, also adjust f_has()!
2301     {
2302 	if (filter == NULL
2303 #  ifdef FEAT_EVAL
2304 		&& (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2305 		&& (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2306 #  endif
2307 	)
2308 	    filter = BROWSE_FILTER_DEFAULT;
2309 	if (flags & BROWSE_DIR)
2310 	{
2311 #  if defined(FEAT_GUI_GTK) || defined(MSWIN)
2312 	    // For systems that have a directory dialog.
2313 	    fname = gui_mch_browsedir(title, initdir);
2314 #  else
2315 	    // Generic solution for selecting a directory: select a file and
2316 	    // remove the file name.
2317 	    fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2318 #  endif
2319 #  if !defined(FEAT_GUI_GTK)
2320 	    // Win32 adds a dummy file name, others return an arbitrary file
2321 	    // name.  GTK+ 2 returns only the directory,
2322 	    if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2323 	    {
2324 		// Remove the file name.
2325 		char_u	    *tail = gettail_sep(fname);
2326 
2327 		if (tail == fname)
2328 		    *tail++ = '.';	// use current dir
2329 		*tail = NUL;
2330 	    }
2331 #  endif
2332 	}
2333 	else
2334 	    fname = gui_mch_browse(flags & BROWSE_SAVE,
2335 			       title, dflt, ext, initdir, (char_u *)_(filter));
2336 
2337 	// We hang around in the dialog for a while, the user might do some
2338 	// things to our files.  The Win32 dialog allows deleting or renaming
2339 	// a file, check timestamps.
2340 	need_check_timestamps = TRUE;
2341 	did_check_timestamps = FALSE;
2342     }
2343     else
2344 # endif
2345     {
2346 	// TODO: non-GUI file selector here
2347 	emsg(_("E338: Sorry, no file browser in console mode"));
2348 	fname = NULL;
2349     }
2350 
2351     // keep the directory for next time
2352     if (fname != NULL)
2353     {
2354 	vim_free(last_dir);
2355 	last_dir = vim_strsave(fname);
2356 	if (last_dir != NULL && !(flags & BROWSE_DIR))
2357 	{
2358 	    *gettail(last_dir) = NUL;
2359 	    if (*last_dir == NUL)
2360 	    {
2361 		// filename only returned, must be in current dir
2362 		vim_free(last_dir);
2363 		last_dir = alloc(MAXPATHL);
2364 		if (last_dir != NULL)
2365 		    mch_dirname(last_dir, MAXPATHL);
2366 	    }
2367 	}
2368     }
2369 
2370     vim_free(tofree);
2371     cmdmod.cmod_flags = save_cmod_flags;
2372 
2373     return fname;
2374 }
2375 #endif
2376 
2377 #if defined(FEAT_EVAL) || defined(PROTO)
2378 
2379 /*
2380  * "browse(save, title, initdir, default)" function
2381  */
2382     void
2383 f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2384 {
2385 # ifdef FEAT_BROWSE
2386     int		save;
2387     char_u	*title;
2388     char_u	*initdir;
2389     char_u	*defname;
2390     char_u	buf[NUMBUFLEN];
2391     char_u	buf2[NUMBUFLEN];
2392     int		error = FALSE;
2393 
2394     save = (int)tv_get_number_chk(&argvars[0], &error);
2395     title = tv_get_string_chk(&argvars[1]);
2396     initdir = tv_get_string_buf_chk(&argvars[2], buf);
2397     defname = tv_get_string_buf_chk(&argvars[3], buf2);
2398 
2399     if (error || title == NULL || initdir == NULL || defname == NULL)
2400 	rettv->vval.v_string = NULL;
2401     else
2402 	rettv->vval.v_string =
2403 		 do_browse(save ? BROWSE_SAVE : 0,
2404 				 title, defname, NULL, initdir, NULL, curbuf);
2405 # else
2406     rettv->vval.v_string = NULL;
2407 # endif
2408     rettv->v_type = VAR_STRING;
2409 }
2410 
2411 /*
2412  * "browsedir(title, initdir)" function
2413  */
2414     void
2415 f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2416 {
2417 # ifdef FEAT_BROWSE
2418     char_u	*title;
2419     char_u	*initdir;
2420     char_u	buf[NUMBUFLEN];
2421 
2422     title = tv_get_string_chk(&argvars[0]);
2423     initdir = tv_get_string_buf_chk(&argvars[1], buf);
2424 
2425     if (title == NULL || initdir == NULL)
2426 	rettv->vval.v_string = NULL;
2427     else
2428 	rettv->vval.v_string = do_browse(BROWSE_DIR,
2429 				    title, NULL, NULL, initdir, NULL, curbuf);
2430 # else
2431     rettv->vval.v_string = NULL;
2432 # endif
2433     rettv->v_type = VAR_STRING;
2434 }
2435 
2436 #endif // FEAT_EVAL
2437 
2438 /*
2439  * Replace home directory by "~" in each space or comma separated file name in
2440  * 'src'.
2441  * If anything fails (except when out of space) dst equals src.
2442  */
2443     void
2444 home_replace(
2445     buf_T	*buf,	// when not NULL, check for help files
2446     char_u	*src,	// input file name
2447     char_u	*dst,	// where to put the result
2448     int		dstlen,	// maximum length of the result
2449     int		one)	// if TRUE, only replace one file name, include
2450 			// spaces and commas in the file name.
2451 {
2452     size_t	dirlen = 0, envlen = 0;
2453     size_t	len;
2454     char_u	*homedir_env, *homedir_env_orig;
2455     char_u	*p;
2456 
2457     if (src == NULL)
2458     {
2459 	*dst = NUL;
2460 	return;
2461     }
2462 
2463     /*
2464      * If the file is a help file, remove the path completely.
2465      */
2466     if (buf != NULL && buf->b_help)
2467     {
2468 	vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2469 	return;
2470     }
2471 
2472     /*
2473      * We check both the value of the $HOME environment variable and the
2474      * "real" home directory.
2475      */
2476     if (homedir != NULL)
2477 	dirlen = STRLEN(homedir);
2478 
2479 #ifdef VMS
2480     homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2481 #else
2482     homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2483 #endif
2484 #ifdef MSWIN
2485     if (homedir_env == NULL)
2486 	homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2487 #endif
2488     // Empty is the same as not set.
2489     if (homedir_env != NULL && *homedir_env == NUL)
2490 	homedir_env = NULL;
2491 
2492     if (homedir_env != NULL && *homedir_env == '~')
2493     {
2494 	int	usedlen = 0;
2495 	int	flen;
2496 	char_u	*fbuf = NULL;
2497 
2498 	flen = (int)STRLEN(homedir_env);
2499 	(void)modify_fname((char_u *)":p", FALSE, &usedlen,
2500 						  &homedir_env, &fbuf, &flen);
2501 	flen = (int)STRLEN(homedir_env);
2502 	if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2503 	    // Remove the trailing / that is added to a directory.
2504 	    homedir_env[flen - 1] = NUL;
2505     }
2506 
2507     if (homedir_env != NULL)
2508 	envlen = STRLEN(homedir_env);
2509 
2510     if (!one)
2511 	src = skipwhite(src);
2512     while (*src && dstlen > 0)
2513     {
2514 	/*
2515 	 * Here we are at the beginning of a file name.
2516 	 * First, check to see if the beginning of the file name matches
2517 	 * $HOME or the "real" home directory. Check that there is a '/'
2518 	 * after the match (so that if e.g. the file is "/home/pieter/bla",
2519 	 * and the home directory is "/home/piet", the file does not end up
2520 	 * as "~er/bla" (which would seem to indicate the file "bla" in user
2521 	 * er's home directory)).
2522 	 */
2523 	p = homedir;
2524 	len = dirlen;
2525 	for (;;)
2526 	{
2527 	    if (   len
2528 		&& fnamencmp(src, p, len) == 0
2529 		&& (vim_ispathsep(src[len])
2530 		    || (!one && (src[len] == ',' || src[len] == ' '))
2531 		    || src[len] == NUL))
2532 	    {
2533 		src += len;
2534 		if (--dstlen > 0)
2535 		    *dst++ = '~';
2536 
2537 		// Do not add directory separator into dst, because dst is
2538 		// expected to just return the directory name without the
2539 		// directory separator '/'.
2540 		break;
2541 	    }
2542 	    if (p == homedir_env)
2543 		break;
2544 	    p = homedir_env;
2545 	    len = envlen;
2546 	}
2547 
2548 	// if (!one) skip to separator: space or comma
2549 	while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2550 	    *dst++ = *src++;
2551 	// skip separator
2552 	while ((*src == ' ' || *src == ',') && --dstlen > 0)
2553 	    *dst++ = *src++;
2554     }
2555     // if (dstlen == 0) out of space, what to do???
2556 
2557     *dst = NUL;
2558 
2559     if (homedir_env != homedir_env_orig)
2560 	vim_free(homedir_env);
2561 }
2562 
2563 /*
2564  * Like home_replace, store the replaced string in allocated memory.
2565  * When something fails, NULL is returned.
2566  */
2567     char_u  *
2568 home_replace_save(
2569     buf_T	*buf,	// when not NULL, check for help files
2570     char_u	*src)	// input file name
2571 {
2572     char_u	*dst;
2573     unsigned	len;
2574 
2575     len = 3;			// space for "~/" and trailing NUL
2576     if (src != NULL)		// just in case
2577 	len += (unsigned)STRLEN(src);
2578     dst = alloc(len);
2579     if (dst != NULL)
2580 	home_replace(buf, src, dst, len, TRUE);
2581     return dst;
2582 }
2583 
2584 /*
2585  * Compare two file names and return:
2586  * FPC_SAME   if they both exist and are the same file.
2587  * FPC_SAMEX  if they both don't exist and have the same file name.
2588  * FPC_DIFF   if they both exist and are different files.
2589  * FPC_NOTX   if they both don't exist.
2590  * FPC_DIFFX  if one of them doesn't exist.
2591  * For the first name environment variables are expanded if "expandenv" is
2592  * TRUE.
2593  */
2594     int
2595 fullpathcmp(
2596     char_u *s1,
2597     char_u *s2,
2598     int	    checkname,		// when both don't exist, check file names
2599     int	    expandenv)
2600 {
2601 #ifdef UNIX
2602     char_u	    exp1[MAXPATHL];
2603     char_u	    full1[MAXPATHL];
2604     char_u	    full2[MAXPATHL];
2605     stat_T	    st1, st2;
2606     int		    r1, r2;
2607 
2608     if (expandenv)
2609 	expand_env(s1, exp1, MAXPATHL);
2610     else
2611 	vim_strncpy(exp1, s1, MAXPATHL - 1);
2612     r1 = mch_stat((char *)exp1, &st1);
2613     r2 = mch_stat((char *)s2, &st2);
2614     if (r1 != 0 && r2 != 0)
2615     {
2616 	// if mch_stat() doesn't work, may compare the names
2617 	if (checkname)
2618 	{
2619 	    if (fnamecmp(exp1, s2) == 0)
2620 		return FPC_SAMEX;
2621 	    r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2622 	    r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2623 	    if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2624 		return FPC_SAMEX;
2625 	}
2626 	return FPC_NOTX;
2627     }
2628     if (r1 != 0 || r2 != 0)
2629 	return FPC_DIFFX;
2630     if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2631 	return FPC_SAME;
2632     return FPC_DIFF;
2633 #else
2634     char_u  *exp1;		// expanded s1
2635     char_u  *full1;		// full path of s1
2636     char_u  *full2;		// full path of s2
2637     int	    retval = FPC_DIFF;
2638     int	    r1, r2;
2639 
2640     // allocate one buffer to store three paths (alloc()/free() is slow!)
2641     if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2642     {
2643 	full1 = exp1 + MAXPATHL;
2644 	full2 = full1 + MAXPATHL;
2645 
2646 	if (expandenv)
2647 	    expand_env(s1, exp1, MAXPATHL);
2648 	else
2649 	    vim_strncpy(exp1, s1, MAXPATHL - 1);
2650 	r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2651 	r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2652 
2653 	// If vim_FullName() fails, the file probably doesn't exist.
2654 	if (r1 != OK && r2 != OK)
2655 	{
2656 	    if (checkname && fnamecmp(exp1, s2) == 0)
2657 		retval = FPC_SAMEX;
2658 	    else
2659 		retval = FPC_NOTX;
2660 	}
2661 	else if (r1 != OK || r2 != OK)
2662 	    retval = FPC_DIFFX;
2663 	else if (fnamecmp(full1, full2))
2664 	    retval = FPC_DIFF;
2665 	else
2666 	    retval = FPC_SAME;
2667 	vim_free(exp1);
2668     }
2669     return retval;
2670 #endif
2671 }
2672 
2673 /*
2674  * Get the tail of a path: the file name.
2675  * When the path ends in a path separator the tail is the NUL after it.
2676  * Fail safe: never returns NULL.
2677  */
2678     char_u *
2679 gettail(char_u *fname)
2680 {
2681     char_u  *p1, *p2;
2682 
2683     if (fname == NULL)
2684 	return (char_u *)"";
2685     for (p1 = p2 = get_past_head(fname); *p2; )	// find last part of path
2686     {
2687 	if (vim_ispathsep_nocolon(*p2))
2688 	    p1 = p2 + 1;
2689 	MB_PTR_ADV(p2);
2690     }
2691     return p1;
2692 }
2693 
2694 /*
2695  * Get pointer to tail of "fname", including path separators.  Putting a NUL
2696  * here leaves the directory name.  Takes care of "c:/" and "//".
2697  * Always returns a valid pointer.
2698  */
2699     char_u *
2700 gettail_sep(char_u *fname)
2701 {
2702     char_u	*p;
2703     char_u	*t;
2704 
2705     p = get_past_head(fname);	// don't remove the '/' from "c:/file"
2706     t = gettail(fname);
2707     while (t > p && after_pathsep(fname, t))
2708 	--t;
2709 #ifdef VMS
2710     // path separator is part of the path
2711     ++t;
2712 #endif
2713     return t;
2714 }
2715 
2716 /*
2717  * get the next path component (just after the next path separator).
2718  */
2719     char_u *
2720 getnextcomp(char_u *fname)
2721 {
2722     while (*fname && !vim_ispathsep(*fname))
2723 	MB_PTR_ADV(fname);
2724     if (*fname)
2725 	++fname;
2726     return fname;
2727 }
2728 
2729 /*
2730  * Get a pointer to one character past the head of a path name.
2731  * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2732  * If there is no head, path is returned.
2733  */
2734     char_u *
2735 get_past_head(char_u *path)
2736 {
2737     char_u  *retval;
2738 
2739 #if defined(MSWIN)
2740     // may skip "c:"
2741     if (isalpha(path[0]) && path[1] == ':')
2742 	retval = path + 2;
2743     else
2744 	retval = path;
2745 #else
2746 # if defined(AMIGA)
2747     // may skip "label:"
2748     retval = vim_strchr(path, ':');
2749     if (retval == NULL)
2750 	retval = path;
2751 # else	// Unix
2752     retval = path;
2753 # endif
2754 #endif
2755 
2756     while (vim_ispathsep(*retval))
2757 	++retval;
2758 
2759     return retval;
2760 }
2761 
2762 /*
2763  * Return TRUE if 'c' is a path separator.
2764  * Note that for MS-Windows this includes the colon.
2765  */
2766     int
2767 vim_ispathsep(int c)
2768 {
2769 #ifdef UNIX
2770     return (c == '/');	    // UNIX has ':' inside file names
2771 #else
2772 # ifdef BACKSLASH_IN_FILENAME
2773     return (c == ':' || c == '/' || c == '\\');
2774 # else
2775 #  ifdef VMS
2776     // server"user passwd"::device:[full.path.name]fname.extension;version"
2777     return (c == ':' || c == '[' || c == ']' || c == '/'
2778 	    || c == '<' || c == '>' || c == '"' );
2779 #  else
2780     return (c == ':' || c == '/');
2781 #  endif // VMS
2782 # endif
2783 #endif
2784 }
2785 
2786 /*
2787  * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2788  */
2789     int
2790 vim_ispathsep_nocolon(int c)
2791 {
2792     return vim_ispathsep(c)
2793 #ifdef BACKSLASH_IN_FILENAME
2794 	&& c != ':'
2795 #endif
2796 	;
2797 }
2798 
2799 /*
2800  * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2801  * Also returns TRUE if there is no directory name.
2802  * "fname" must be writable!.
2803  */
2804     int
2805 dir_of_file_exists(char_u *fname)
2806 {
2807     char_u	*p;
2808     int		c;
2809     int		retval;
2810 
2811     p = gettail_sep(fname);
2812     if (p == fname)
2813 	return TRUE;
2814     c = *p;
2815     *p = NUL;
2816     retval = mch_isdir(fname);
2817     *p = c;
2818     return retval;
2819 }
2820 
2821 /*
2822  * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2823  * and deal with 'fileignorecase'.
2824  */
2825     int
2826 vim_fnamecmp(char_u *x, char_u *y)
2827 {
2828 #ifdef BACKSLASH_IN_FILENAME
2829     return vim_fnamencmp(x, y, MAXPATHL);
2830 #else
2831     if (p_fic)
2832 	return MB_STRICMP(x, y);
2833     return STRCMP(x, y);
2834 #endif
2835 }
2836 
2837     int
2838 vim_fnamencmp(char_u *x, char_u *y, size_t len)
2839 {
2840 #ifdef BACKSLASH_IN_FILENAME
2841     char_u	*px = x;
2842     char_u	*py = y;
2843     int		cx = NUL;
2844     int		cy = NUL;
2845 
2846     while (len > 0)
2847     {
2848 	cx = PTR2CHAR(px);
2849 	cy = PTR2CHAR(py);
2850 	if (cx == NUL || cy == NUL
2851 	    || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2852 		&& !(cx == '/' && cy == '\\')
2853 		&& !(cx == '\\' && cy == '/')))
2854 	    break;
2855 	len -= mb_ptr2len(px);
2856 	px += mb_ptr2len(px);
2857 	py += mb_ptr2len(py);
2858     }
2859     if (len == 0)
2860 	return 0;
2861     return (cx - cy);
2862 #else
2863     if (p_fic)
2864 	return MB_STRNICMP(x, y, len);
2865     return STRNCMP(x, y, len);
2866 #endif
2867 }
2868 
2869 /*
2870  * Concatenate file names fname1 and fname2 into allocated memory.
2871  * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
2872  */
2873     char_u  *
2874 concat_fnames(char_u *fname1, char_u *fname2, int sep)
2875 {
2876     char_u  *dest;
2877 
2878     dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
2879     if (dest != NULL)
2880     {
2881 	STRCPY(dest, fname1);
2882 	if (sep)
2883 	    add_pathsep(dest);
2884 	STRCAT(dest, fname2);
2885     }
2886     return dest;
2887 }
2888 
2889 /*
2890  * Add a path separator to a file name, unless it already ends in a path
2891  * separator.
2892  */
2893     void
2894 add_pathsep(char_u *p)
2895 {
2896     if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
2897 	STRCAT(p, PATHSEPSTR);
2898 }
2899 
2900 /*
2901  * FullName_save - Make an allocated copy of a full file name.
2902  * Returns NULL when out of memory.
2903  */
2904     char_u  *
2905 FullName_save(
2906     char_u	*fname,
2907     int		force)		// force expansion, even when it already looks
2908 				// like a full path name
2909 {
2910     char_u	*buf;
2911     char_u	*new_fname = NULL;
2912 
2913     if (fname == NULL)
2914 	return NULL;
2915 
2916     buf = alloc(MAXPATHL);
2917     if (buf != NULL)
2918     {
2919 	if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
2920 	    new_fname = vim_strsave(buf);
2921 	else
2922 	    new_fname = vim_strsave(fname);
2923 	vim_free(buf);
2924     }
2925     return new_fname;
2926 }
2927 
2928 /*
2929  * return TRUE if "fname" exists.
2930  */
2931     int
2932 vim_fexists(char_u *fname)
2933 {
2934     stat_T st;
2935 
2936     if (mch_stat((char *)fname, &st))
2937 	return FALSE;
2938     return TRUE;
2939 }
2940 
2941 /*
2942  * Invoke expand_wildcards() for one pattern.
2943  * Expand items like "%:h" before the expansion.
2944  * Returns OK or FAIL.
2945  */
2946     int
2947 expand_wildcards_eval(
2948     char_u	 **pat,		// pointer to input pattern
2949     int		  *num_file,	// resulting number of files
2950     char_u	***file,	// array of resulting files
2951     int		   flags)	// EW_DIR, etc.
2952 {
2953     int		ret = FAIL;
2954     char_u	*eval_pat = NULL;
2955     char_u	*exp_pat = *pat;
2956     char      *ignored_msg;
2957     int		usedlen;
2958 
2959     if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
2960     {
2961 	++emsg_off;
2962 	eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
2963 						    NULL, &ignored_msg, NULL);
2964 	--emsg_off;
2965 	if (eval_pat != NULL)
2966 	    exp_pat = concat_str(eval_pat, exp_pat + usedlen);
2967     }
2968 
2969     if (exp_pat != NULL)
2970 	ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
2971 
2972     if (eval_pat != NULL)
2973     {
2974 	vim_free(exp_pat);
2975 	vim_free(eval_pat);
2976     }
2977 
2978     return ret;
2979 }
2980 
2981 /*
2982  * Expand wildcards.  Calls gen_expand_wildcards() and removes files matching
2983  * 'wildignore'.
2984  * Returns OK or FAIL.  When FAIL then "num_files" won't be set.
2985  */
2986     int
2987 expand_wildcards(
2988     int		   num_pat,	// number of input patterns
2989     char_u	 **pat,		// array of input patterns
2990     int		  *num_files,	// resulting number of files
2991     char_u	***files,	// array of resulting files
2992     int		   flags)	// EW_DIR, etc.
2993 {
2994     int		retval;
2995     int		i, j;
2996     char_u	*p;
2997     int		non_suf_match;	// number without matching suffix
2998 
2999     retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3000 
3001     // When keeping all matches, return here
3002     if ((flags & EW_KEEPALL) || retval == FAIL)
3003 	return retval;
3004 
3005 #ifdef FEAT_WILDIGN
3006     /*
3007      * Remove names that match 'wildignore'.
3008      */
3009     if (*p_wig)
3010     {
3011 	char_u	*ffname;
3012 
3013 	// check all files in (*files)[]
3014 	for (i = 0; i < *num_files; ++i)
3015 	{
3016 	    ffname = FullName_save((*files)[i], FALSE);
3017 	    if (ffname == NULL)		// out of memory
3018 		break;
3019 # ifdef VMS
3020 	    vms_remove_version(ffname);
3021 # endif
3022 	    if (match_file_list(p_wig, (*files)[i], ffname))
3023 	    {
3024 		// remove this matching file from the list
3025 		vim_free((*files)[i]);
3026 		for (j = i; j + 1 < *num_files; ++j)
3027 		    (*files)[j] = (*files)[j + 1];
3028 		--*num_files;
3029 		--i;
3030 	    }
3031 	    vim_free(ffname);
3032 	}
3033 
3034 	// If the number of matches is now zero, we fail.
3035 	if (*num_files == 0)
3036 	{
3037 	    VIM_CLEAR(*files);
3038 	    return FAIL;
3039 	}
3040     }
3041 #endif
3042 
3043     /*
3044      * Move the names where 'suffixes' match to the end.
3045      */
3046     if (*num_files > 1)
3047     {
3048 	non_suf_match = 0;
3049 	for (i = 0; i < *num_files; ++i)
3050 	{
3051 	    if (!match_suffix((*files)[i]))
3052 	    {
3053 		/*
3054 		 * Move the name without matching suffix to the front
3055 		 * of the list.
3056 		 */
3057 		p = (*files)[i];
3058 		for (j = i; j > non_suf_match; --j)
3059 		    (*files)[j] = (*files)[j - 1];
3060 		(*files)[non_suf_match++] = p;
3061 	    }
3062 	}
3063     }
3064 
3065     return retval;
3066 }
3067 
3068 /*
3069  * Return TRUE if "fname" matches with an entry in 'suffixes'.
3070  */
3071     int
3072 match_suffix(char_u *fname)
3073 {
3074     int		fnamelen, setsuflen;
3075     char_u	*setsuf;
3076 #define MAXSUFLEN 30	    // maximum length of a file suffix
3077     char_u	suf_buf[MAXSUFLEN];
3078 
3079     fnamelen = (int)STRLEN(fname);
3080     setsuflen = 0;
3081     for (setsuf = p_su; *setsuf; )
3082     {
3083 	setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3084 	if (setsuflen == 0)
3085 	{
3086 	    char_u *tail = gettail(fname);
3087 
3088 	    // empty entry: match name without a '.'
3089 	    if (vim_strchr(tail, '.') == NULL)
3090 	    {
3091 		setsuflen = 1;
3092 		break;
3093 	    }
3094 	}
3095 	else
3096 	{
3097 	    if (fnamelen >= setsuflen
3098 		    && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3099 						  (size_t)setsuflen) == 0)
3100 		break;
3101 	    setsuflen = 0;
3102 	}
3103     }
3104     return (setsuflen != 0);
3105 }
3106 
3107 #ifdef VIM_BACKTICK
3108 
3109 /*
3110  * Return TRUE if we can expand this backtick thing here.
3111  */
3112     static int
3113 vim_backtick(char_u *p)
3114 {
3115     return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3116 }
3117 
3118 /*
3119  * Expand an item in `backticks` by executing it as a command.
3120  * Currently only works when pat[] starts and ends with a `.
3121  * Returns number of file names found, -1 if an error is encountered.
3122  */
3123     static int
3124 expand_backtick(
3125     garray_T	*gap,
3126     char_u	*pat,
3127     int		flags)	// EW_* flags
3128 {
3129     char_u	*p;
3130     char_u	*cmd;
3131     char_u	*buffer;
3132     int		cnt = 0;
3133     int		i;
3134 
3135     // Create the command: lop off the backticks.
3136     cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
3137     if (cmd == NULL)
3138 	return -1;
3139 
3140 #ifdef FEAT_EVAL
3141     if (*cmd == '=')	    // `={expr}`: Expand expression
3142 	buffer = eval_to_string(cmd + 1, TRUE);
3143     else
3144 #endif
3145 	buffer = get_cmd_output(cmd, NULL,
3146 				(flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3147     vim_free(cmd);
3148     if (buffer == NULL)
3149 	return -1;
3150 
3151     cmd = buffer;
3152     while (*cmd != NUL)
3153     {
3154 	cmd = skipwhite(cmd);		// skip over white space
3155 	p = cmd;
3156 	while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3157 	    ++p;
3158 	// add an entry if it is not empty
3159 	if (p > cmd)
3160 	{
3161 	    i = *p;
3162 	    *p = NUL;
3163 	    addfile(gap, cmd, flags);
3164 	    *p = i;
3165 	    ++cnt;
3166 	}
3167 	cmd = p;
3168 	while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3169 	    ++cmd;
3170     }
3171 
3172     vim_free(buffer);
3173     return cnt;
3174 }
3175 #endif // VIM_BACKTICK
3176 
3177 #if defined(MSWIN)
3178 /*
3179  * File name expansion code for MS-DOS, Win16 and Win32.  It's here because
3180  * it's shared between these systems.
3181  */
3182 
3183 /*
3184  * comparison function for qsort in dos_expandpath()
3185  */
3186     static int
3187 pstrcmp(const void *a, const void *b)
3188 {
3189     return (pathcmp(*(char **)a, *(char **)b, -1));
3190 }
3191 
3192 /*
3193  * Recursively expand one path component into all matching files and/or
3194  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
3195  * Return the number of matches found.
3196  * "path" has backslashes before chars that are not to be expanded, starting
3197  * at "path[wildoff]".
3198  * Return the number of matches found.
3199  * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3200  */
3201     static int
3202 dos_expandpath(
3203     garray_T	*gap,
3204     char_u	*path,
3205     int		wildoff,
3206     int		flags,		// EW_* flags
3207     int		didstar)	// expanded "**" once already
3208 {
3209     char_u	*buf;
3210     char_u	*path_end;
3211     char_u	*p, *s, *e;
3212     int		start_len = gap->ga_len;
3213     char_u	*pat;
3214     regmatch_T	regmatch;
3215     int		starts_with_dot;
3216     int		matches;
3217     int		len;
3218     int		starstar = FALSE;
3219     static int	stardepth = 0;	    // depth for "**" expansion
3220     HANDLE		hFind = INVALID_HANDLE_VALUE;
3221     WIN32_FIND_DATAW    wfb;
3222     WCHAR		*wn = NULL;	// UCS-2 name, NULL when not used.
3223     char_u		*matchname;
3224     int			ok;
3225     char_u		*p_alt;
3226 
3227     // Expanding "**" may take a long time, check for CTRL-C.
3228     if (stardepth > 0)
3229     {
3230 	ui_breakcheck();
3231 	if (got_int)
3232 	    return 0;
3233     }
3234 
3235     // Make room for file name.  When doing encoding conversion the actual
3236     // length may be quite a bit longer, thus use the maximum possible length.
3237     buf = alloc(MAXPATHL);
3238     if (buf == NULL)
3239 	return 0;
3240 
3241     /*
3242      * Find the first part in the path name that contains a wildcard or a ~1.
3243      * Copy it into buf, including the preceding characters.
3244      */
3245     p = buf;
3246     s = buf;
3247     e = NULL;
3248     path_end = path;
3249     while (*path_end != NUL)
3250     {
3251 	// May ignore a wildcard that has a backslash before it; it will
3252 	// be removed by rem_backslash() or file_pat_to_reg_pat() below.
3253 	if (path_end >= path + wildoff && rem_backslash(path_end))
3254 	    *p++ = *path_end++;
3255 	else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3256 	{
3257 	    if (e != NULL)
3258 		break;
3259 	    s = p + 1;
3260 	}
3261 	else if (path_end >= path + wildoff
3262 			 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3263 	    e = p;
3264 	if (has_mbyte)
3265 	{
3266 	    len = (*mb_ptr2len)(path_end);
3267 	    STRNCPY(p, path_end, len);
3268 	    p += len;
3269 	    path_end += len;
3270 	}
3271 	else
3272 	    *p++ = *path_end++;
3273     }
3274     e = p;
3275     *e = NUL;
3276 
3277     // now we have one wildcard component between s and e
3278     // Remove backslashes between "wildoff" and the start of the wildcard
3279     // component.
3280     for (p = buf + wildoff; p < s; ++p)
3281 	if (rem_backslash(p))
3282 	{
3283 	    STRMOVE(p, p + 1);
3284 	    --e;
3285 	    --s;
3286 	}
3287 
3288     // Check for "**" between "s" and "e".
3289     for (p = s; p < e; ++p)
3290 	if (p[0] == '*' && p[1] == '*')
3291 	    starstar = TRUE;
3292 
3293     starts_with_dot = *s == '.';
3294     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3295     if (pat == NULL)
3296     {
3297 	vim_free(buf);
3298 	return 0;
3299     }
3300 
3301     // compile the regexp into a program
3302     if (flags & (EW_NOERROR | EW_NOTWILD))
3303 	++emsg_silent;
3304     regmatch.rm_ic = TRUE;		// Always ignore case
3305     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3306     if (flags & (EW_NOERROR | EW_NOTWILD))
3307 	--emsg_silent;
3308     vim_free(pat);
3309 
3310     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3311     {
3312 	vim_free(buf);
3313 	return 0;
3314     }
3315 
3316     // remember the pattern or file name being looked for
3317     matchname = vim_strsave(s);
3318 
3319     // If "**" is by itself, this is the first time we encounter it and more
3320     // is following then find matches without any directory.
3321     if (!didstar && stardepth < 100 && starstar && e - s == 2
3322 							  && *path_end == '/')
3323     {
3324 	STRCPY(s, path_end + 1);
3325 	++stardepth;
3326 	(void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3327 	--stardepth;
3328     }
3329 
3330     // Scan all files in the directory with "dir/ *.*"
3331     STRCPY(s, "*.*");
3332     wn = enc_to_utf16(buf, NULL);
3333     if (wn != NULL)
3334 	hFind = FindFirstFileW(wn, &wfb);
3335     ok = (hFind != INVALID_HANDLE_VALUE);
3336 
3337     while (ok)
3338     {
3339 	p = utf16_to_enc(wfb.cFileName, NULL);   // p is allocated here
3340 
3341 	if (p == NULL)
3342 	    break;  // out of memory
3343 
3344 	if (*wfb.cAlternateFileName == NUL)
3345 	    p_alt = NULL;
3346 	else
3347 	    p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3348 
3349 	// Ignore entries starting with a dot, unless when asked for.  Accept
3350 	// all entries found with "matchname".
3351 	if ((p[0] != '.' || starts_with_dot
3352 			 || ((flags & EW_DODOT)
3353 			     && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3354 		&& (matchname == NULL
3355 		  || (regmatch.regprog != NULL
3356 		      && (vim_regexec(&regmatch, p, (colnr_T)0)
3357 			 || (p_alt != NULL
3358 				&& vim_regexec(&regmatch, p_alt, (colnr_T)0))))
3359 		  || ((flags & EW_NOTWILD)
3360 		     && fnamencmp(path + (s - buf), p, e - s) == 0)))
3361 	{
3362 	    STRCPY(s, p);
3363 	    len = (int)STRLEN(buf);
3364 
3365 	    if (starstar && stardepth < 100
3366 			  && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
3367 	    {
3368 		// For "**" in the pattern first go deeper in the tree to
3369 		// find matches.
3370 		STRCPY(buf + len, "/**");
3371 		STRCPY(buf + len + 3, path_end);
3372 		++stardepth;
3373 		(void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3374 		--stardepth;
3375 	    }
3376 
3377 	    STRCPY(buf + len, path_end);
3378 	    if (mch_has_exp_wildcard(path_end))
3379 	    {
3380 		// need to expand another component of the path
3381 		// remove backslashes for the remaining components only
3382 		(void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3383 	    }
3384 	    else
3385 	    {
3386 		// no more wildcards, check if there is a match
3387 		// remove backslashes for the remaining components only
3388 		if (*path_end != 0)
3389 		    backslash_halve(buf + len + 1);
3390 		if (mch_getperm(buf) >= 0)	// add existing file
3391 		    addfile(gap, buf, flags);
3392 	    }
3393 	}
3394 
3395 	vim_free(p_alt);
3396 	vim_free(p);
3397 	ok = FindNextFileW(hFind, &wfb);
3398     }
3399 
3400     FindClose(hFind);
3401     vim_free(wn);
3402     vim_free(buf);
3403     vim_regfree(regmatch.regprog);
3404     vim_free(matchname);
3405 
3406     matches = gap->ga_len - start_len;
3407     if (matches > 0)
3408 	qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3409 						   sizeof(char_u *), pstrcmp);
3410     return matches;
3411 }
3412 
3413     int
3414 mch_expandpath(
3415     garray_T	*gap,
3416     char_u	*path,
3417     int		flags)		// EW_* flags
3418 {
3419     return dos_expandpath(gap, path, 0, flags, FALSE);
3420 }
3421 #endif // MSWIN
3422 
3423 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3424 	|| defined(PROTO)
3425 /*
3426  * Unix style wildcard expansion code.
3427  * It's here because it's used both for Unix and Mac.
3428  */
3429     static int
3430 pstrcmp(const void *a, const void *b)
3431 {
3432     return (pathcmp(*(char **)a, *(char **)b, -1));
3433 }
3434 
3435 /*
3436  * Recursively expand one path component into all matching files and/or
3437  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
3438  * "path" has backslashes before chars that are not to be expanded, starting
3439  * at "path + wildoff".
3440  * Return the number of matches found.
3441  * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3442  */
3443     int
3444 unix_expandpath(
3445     garray_T	*gap,
3446     char_u	*path,
3447     int		wildoff,
3448     int		flags,		// EW_* flags
3449     int		didstar)	// expanded "**" once already
3450 {
3451     char_u	*buf;
3452     char_u	*path_end;
3453     char_u	*p, *s, *e;
3454     int		start_len = gap->ga_len;
3455     char_u	*pat;
3456     regmatch_T	regmatch;
3457     int		starts_with_dot;
3458     int		matches;
3459     int		len;
3460     int		starstar = FALSE;
3461     static int	stardepth = 0;	    // depth for "**" expansion
3462 
3463     DIR		*dirp;
3464     struct dirent *dp;
3465 
3466     // Expanding "**" may take a long time, check for CTRL-C.
3467     if (stardepth > 0)
3468     {
3469 	ui_breakcheck();
3470 	if (got_int)
3471 	    return 0;
3472     }
3473 
3474     // make room for file name
3475     buf = alloc(STRLEN(path) + BASENAMELEN + 5);
3476     if (buf == NULL)
3477 	return 0;
3478 
3479     /*
3480      * Find the first part in the path name that contains a wildcard.
3481      * When EW_ICASE is set every letter is considered to be a wildcard.
3482      * Copy it into "buf", including the preceding characters.
3483      */
3484     p = buf;
3485     s = buf;
3486     e = NULL;
3487     path_end = path;
3488     while (*path_end != NUL)
3489     {
3490 	// May ignore a wildcard that has a backslash before it; it will
3491 	// be removed by rem_backslash() or file_pat_to_reg_pat() below.
3492 	if (path_end >= path + wildoff && rem_backslash(path_end))
3493 	    *p++ = *path_end++;
3494 	else if (*path_end == '/')
3495 	{
3496 	    if (e != NULL)
3497 		break;
3498 	    s = p + 1;
3499 	}
3500 	else if (path_end >= path + wildoff
3501 			 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3502 			     || (!p_fic && (flags & EW_ICASE)
3503 					     && isalpha(PTR2CHAR(path_end)))))
3504 	    e = p;
3505 	if (has_mbyte)
3506 	{
3507 	    len = (*mb_ptr2len)(path_end);
3508 	    STRNCPY(p, path_end, len);
3509 	    p += len;
3510 	    path_end += len;
3511 	}
3512 	else
3513 	    *p++ = *path_end++;
3514     }
3515     e = p;
3516     *e = NUL;
3517 
3518     // Now we have one wildcard component between "s" and "e".
3519     // Remove backslashes between "wildoff" and the start of the wildcard
3520     // component.
3521     for (p = buf + wildoff; p < s; ++p)
3522 	if (rem_backslash(p))
3523 	{
3524 	    STRMOVE(p, p + 1);
3525 	    --e;
3526 	    --s;
3527 	}
3528 
3529     // Check for "**" between "s" and "e".
3530     for (p = s; p < e; ++p)
3531 	if (p[0] == '*' && p[1] == '*')
3532 	    starstar = TRUE;
3533 
3534     // convert the file pattern to a regexp pattern
3535     starts_with_dot = *s == '.';
3536     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3537     if (pat == NULL)
3538     {
3539 	vim_free(buf);
3540 	return 0;
3541     }
3542 
3543     // compile the regexp into a program
3544     if (flags & EW_ICASE)
3545 	regmatch.rm_ic = TRUE;		// 'wildignorecase' set
3546     else
3547 	regmatch.rm_ic = p_fic;	// ignore case when 'fileignorecase' is set
3548     if (flags & (EW_NOERROR | EW_NOTWILD))
3549 	++emsg_silent;
3550     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3551     if (flags & (EW_NOERROR | EW_NOTWILD))
3552 	--emsg_silent;
3553     vim_free(pat);
3554 
3555     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3556     {
3557 	vim_free(buf);
3558 	return 0;
3559     }
3560 
3561     // If "**" is by itself, this is the first time we encounter it and more
3562     // is following then find matches without any directory.
3563     if (!didstar && stardepth < 100 && starstar && e - s == 2
3564 							  && *path_end == '/')
3565     {
3566 	STRCPY(s, path_end + 1);
3567 	++stardepth;
3568 	(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3569 	--stardepth;
3570     }
3571 
3572     // open the directory for scanning
3573     *s = NUL;
3574     dirp = opendir(*buf == NUL ? "." : (char *)buf);
3575 
3576     // Find all matching entries
3577     if (dirp != NULL)
3578     {
3579 	for (;;)
3580 	{
3581 	    dp = readdir(dirp);
3582 	    if (dp == NULL)
3583 		break;
3584 	    if ((dp->d_name[0] != '.' || starts_with_dot
3585 			|| ((flags & EW_DODOT)
3586 			    && dp->d_name[1] != NUL
3587 			    && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3588 		 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3589 					     (char_u *)dp->d_name, (colnr_T)0))
3590 		   || ((flags & EW_NOTWILD)
3591 		     && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3592 	    {
3593 		STRCPY(s, dp->d_name);
3594 		len = STRLEN(buf);
3595 
3596 		if (starstar && stardepth < 100)
3597 		{
3598 		    // For "**" in the pattern first go deeper in the tree to
3599 		    // find matches.
3600 		    STRCPY(buf + len, "/**");
3601 		    STRCPY(buf + len + 3, path_end);
3602 		    ++stardepth;
3603 		    (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3604 		    --stardepth;
3605 		}
3606 
3607 		STRCPY(buf + len, path_end);
3608 		if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3609 		{
3610 		    // need to expand another component of the path
3611 		    // remove backslashes for the remaining components only
3612 		    (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3613 		}
3614 		else
3615 		{
3616 		    stat_T  sb;
3617 
3618 		    // no more wildcards, check if there is a match
3619 		    // remove backslashes for the remaining components only
3620 		    if (*path_end != NUL)
3621 			backslash_halve(buf + len + 1);
3622 		    // add existing file or symbolic link
3623 		    if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3624 						      : mch_getperm(buf) >= 0)
3625 		    {
3626 #ifdef MACOS_CONVERT
3627 			size_t precomp_len = STRLEN(buf)+1;
3628 			char_u *precomp_buf =
3629 			    mac_precompose_path(buf, precomp_len, &precomp_len);
3630 
3631 			if (precomp_buf)
3632 			{
3633 			    mch_memmove(buf, precomp_buf, precomp_len);
3634 			    vim_free(precomp_buf);
3635 			}
3636 #endif
3637 			addfile(gap, buf, flags);
3638 		    }
3639 		}
3640 	    }
3641 	}
3642 
3643 	closedir(dirp);
3644     }
3645 
3646     vim_free(buf);
3647     vim_regfree(regmatch.regprog);
3648 
3649     matches = gap->ga_len - start_len;
3650     if (matches > 0)
3651 	qsort(((char_u **)gap->ga_data) + start_len, matches,
3652 						   sizeof(char_u *), pstrcmp);
3653     return matches;
3654 }
3655 #endif
3656 
3657 /*
3658  * Return TRUE if "p" contains what looks like an environment variable.
3659  * Allowing for escaping.
3660  */
3661     static int
3662 has_env_var(char_u *p)
3663 {
3664     for ( ; *p; MB_PTR_ADV(p))
3665     {
3666 	if (*p == '\\' && p[1] != NUL)
3667 	    ++p;
3668 	else if (vim_strchr((char_u *)
3669 #if defined(MSWIN)
3670 				    "$%"
3671 #else
3672 				    "$"
3673 #endif
3674 					, *p) != NULL)
3675 	    return TRUE;
3676     }
3677     return FALSE;
3678 }
3679 
3680 #ifdef SPECIAL_WILDCHAR
3681 /*
3682  * Return TRUE if "p" contains a special wildcard character, one that Vim
3683  * cannot expand, requires using a shell.
3684  */
3685     static int
3686 has_special_wildchar(char_u *p)
3687 {
3688     for ( ; *p; MB_PTR_ADV(p))
3689     {
3690 	// Disallow line break characters.
3691 	if (*p == '\r' || *p == '\n')
3692 	    break;
3693 	// Allow for escaping.
3694 	if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3695 	    ++p;
3696 	else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3697 	{
3698 	    // A { must be followed by a matching }.
3699 	    if (*p == '{' && vim_strchr(p, '}') == NULL)
3700 		continue;
3701 	    // A quote and backtick must be followed by another one.
3702 	    if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3703 		continue;
3704 	    return TRUE;
3705 	}
3706     }
3707     return FALSE;
3708 }
3709 #endif
3710 
3711 /*
3712  * Generic wildcard expansion code.
3713  *
3714  * Characters in "pat" that should not be expanded must be preceded with a
3715  * backslash. E.g., "/path\ with\ spaces/my\*star*"
3716  *
3717  * Return FAIL when no single file was found.  In this case "num_file" is not
3718  * set, and "file" may contain an error message.
3719  * Return OK when some files found.  "num_file" is set to the number of
3720  * matches, "file" to the array of matches.  Call FreeWild() later.
3721  */
3722     int
3723 gen_expand_wildcards(
3724     int		num_pat,	// number of input patterns
3725     char_u	**pat,		// array of input patterns
3726     int		*num_file,	// resulting number of files
3727     char_u	***file,	// array of resulting files
3728     int		flags)		// EW_* flags
3729 {
3730     int			i;
3731     garray_T		ga;
3732     char_u		*p;
3733     static int		recursive = FALSE;
3734     int			add_pat;
3735     int			retval = OK;
3736 #if defined(FEAT_SEARCHPATH)
3737     int			did_expand_in_path = FALSE;
3738 #endif
3739 
3740     /*
3741      * expand_env() is called to expand things like "~user".  If this fails,
3742      * it calls ExpandOne(), which brings us back here.  In this case, always
3743      * call the machine specific expansion function, if possible.  Otherwise,
3744      * return FAIL.
3745      */
3746     if (recursive)
3747 #ifdef SPECIAL_WILDCHAR
3748 	return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3749 #else
3750 	return FAIL;
3751 #endif
3752 
3753 #ifdef SPECIAL_WILDCHAR
3754     /*
3755      * If there are any special wildcard characters which we cannot handle
3756      * here, call machine specific function for all the expansion.  This
3757      * avoids starting the shell for each argument separately.
3758      * For `=expr` do use the internal function.
3759      */
3760     for (i = 0; i < num_pat; i++)
3761     {
3762 	if (has_special_wildchar(pat[i])
3763 # ifdef VIM_BACKTICK
3764 		&& !(vim_backtick(pat[i]) && pat[i][1] == '=')
3765 # endif
3766 	   )
3767 	    return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3768     }
3769 #endif
3770 
3771     recursive = TRUE;
3772 
3773     /*
3774      * The matching file names are stored in a growarray.  Init it empty.
3775      */
3776     ga_init2(&ga, (int)sizeof(char_u *), 30);
3777 
3778     for (i = 0; i < num_pat; ++i)
3779     {
3780 	add_pat = -1;
3781 	p = pat[i];
3782 
3783 #ifdef VIM_BACKTICK
3784 	if (vim_backtick(p))
3785 	{
3786 	    add_pat = expand_backtick(&ga, p, flags);
3787 	    if (add_pat == -1)
3788 		retval = FAIL;
3789 	}
3790 	else
3791 #endif
3792 	{
3793 	    /*
3794 	     * First expand environment variables, "~/" and "~user/".
3795 	     */
3796 	    if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3797 	    {
3798 		p = expand_env_save_opt(p, TRUE);
3799 		if (p == NULL)
3800 		    p = pat[i];
3801 #ifdef UNIX
3802 		/*
3803 		 * On Unix, if expand_env() can't expand an environment
3804 		 * variable, use the shell to do that.  Discard previously
3805 		 * found file names and start all over again.
3806 		 */
3807 		else if (has_env_var(p) || *p == '~')
3808 		{
3809 		    vim_free(p);
3810 		    ga_clear_strings(&ga);
3811 		    i = mch_expand_wildcards(num_pat, pat, num_file, file,
3812 							 flags|EW_KEEPDOLLAR);
3813 		    recursive = FALSE;
3814 		    return i;
3815 		}
3816 #endif
3817 	    }
3818 
3819 	    /*
3820 	     * If there are wildcards: Expand file names and add each match to
3821 	     * the list.  If there is no match, and EW_NOTFOUND is given, add
3822 	     * the pattern.
3823 	     * If there are no wildcards: Add the file name if it exists or
3824 	     * when EW_NOTFOUND is given.
3825 	     */
3826 	    if (mch_has_exp_wildcard(p))
3827 	    {
3828 #if defined(FEAT_SEARCHPATH)
3829 		if ((flags & EW_PATH)
3830 			&& !mch_isFullName(p)
3831 			&& !(p[0] == '.'
3832 			    && (vim_ispathsep(p[1])
3833 				|| (p[1] == '.' && vim_ispathsep(p[2]))))
3834 		   )
3835 		{
3836 		    // :find completion where 'path' is used.
3837 		    // Recursiveness is OK here.
3838 		    recursive = FALSE;
3839 		    add_pat = expand_in_path(&ga, p, flags);
3840 		    recursive = TRUE;
3841 		    did_expand_in_path = TRUE;
3842 		}
3843 		else
3844 #endif
3845 		    add_pat = mch_expandpath(&ga, p, flags);
3846 	    }
3847 	}
3848 
3849 	if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3850 	{
3851 	    char_u	*t = backslash_halve_save(p);
3852 
3853 	    // When EW_NOTFOUND is used, always add files and dirs.  Makes
3854 	    // "vim c:/" work.
3855 	    if (flags & EW_NOTFOUND)
3856 		addfile(&ga, t, flags | EW_DIR | EW_FILE);
3857 	    else
3858 		addfile(&ga, t, flags);
3859 
3860 	    if (t != p)
3861 		vim_free(t);
3862 	}
3863 
3864 #if defined(FEAT_SEARCHPATH)
3865 	if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
3866 	    uniquefy_paths(&ga, p);
3867 #endif
3868 	if (p != pat[i])
3869 	    vim_free(p);
3870     }
3871 
3872     // When returning FAIL the array must be freed here.
3873     if (retval == FAIL)
3874 	ga_clear(&ga);
3875 
3876     *num_file = ga.ga_len;
3877     *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
3878 						  : (char_u **)_("no matches");
3879 
3880     recursive = FALSE;
3881 
3882     return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
3883 }
3884 
3885 /*
3886  * Add a file to a file list.  Accepted flags:
3887  * EW_DIR	add directories
3888  * EW_FILE	add files
3889  * EW_EXEC	add executable files
3890  * EW_NOTFOUND	add even when it doesn't exist
3891  * EW_ADDSLASH	add slash after directory name
3892  * EW_ALLLINKS	add symlink also when the referred file does not exist
3893  */
3894     void
3895 addfile(
3896     garray_T	*gap,
3897     char_u	*f,	// filename
3898     int		flags)
3899 {
3900     char_u	*p;
3901     int		isdir;
3902     stat_T	sb;
3903 
3904     // if the file/dir/link doesn't exist, may not add it
3905     if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
3906 			? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
3907 	return;
3908 
3909 #ifdef FNAME_ILLEGAL
3910     // if the file/dir contains illegal characters, don't add it
3911     if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
3912 	return;
3913 #endif
3914 
3915     isdir = mch_isdir(f);
3916     if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
3917 	return;
3918 
3919     // If the file isn't executable, may not add it.  Do accept directories.
3920     // When invoked from expand_shellcmd() do not use $PATH.
3921     if (!isdir && (flags & EW_EXEC)
3922 			     && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
3923 	return;
3924 
3925     // Make room for another item in the file list.
3926     if (ga_grow(gap, 1) == FAIL)
3927 	return;
3928 
3929     p = alloc(STRLEN(f) + 1 + isdir);
3930     if (p == NULL)
3931 	return;
3932 
3933     STRCPY(p, f);
3934 #ifdef BACKSLASH_IN_FILENAME
3935     slash_adjust(p);
3936 #endif
3937     /*
3938      * Append a slash or backslash after directory names if none is present.
3939      */
3940 #ifndef DONT_ADD_PATHSEP_TO_DIR
3941     if (isdir && (flags & EW_ADDSLASH))
3942 	add_pathsep(p);
3943 #endif
3944     ((char_u **)gap->ga_data)[gap->ga_len++] = p;
3945 }
3946 
3947 /*
3948  * Free the list of files returned by expand_wildcards() or other expansion
3949  * functions.
3950  */
3951     void
3952 FreeWild(int count, char_u **files)
3953 {
3954     if (count <= 0 || files == NULL)
3955 	return;
3956     while (count--)
3957 	vim_free(files[count]);
3958     vim_free(files);
3959 }
3960 
3961 /*
3962  * Compare path "p[]" to "q[]".
3963  * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
3964  * Return value like strcmp(p, q), but consider path separators.
3965  */
3966     int
3967 pathcmp(const char *p, const char *q, int maxlen)
3968 {
3969     int		i, j;
3970     int		c1, c2;
3971     const char	*s = NULL;
3972 
3973     for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
3974     {
3975 	c1 = PTR2CHAR((char_u *)p + i);
3976 	c2 = PTR2CHAR((char_u *)q + j);
3977 
3978 	// End of "p": check if "q" also ends or just has a slash.
3979 	if (c1 == NUL)
3980 	{
3981 	    if (c2 == NUL)  // full match
3982 		return 0;
3983 	    s = q;
3984 	    i = j;
3985 	    break;
3986 	}
3987 
3988 	// End of "q": check if "p" just has a slash.
3989 	if (c2 == NUL)
3990 	{
3991 	    s = p;
3992 	    break;
3993 	}
3994 
3995 	if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
3996 #ifdef BACKSLASH_IN_FILENAME
3997 		// consider '/' and '\\' to be equal
3998 		&& !((c1 == '/' && c2 == '\\')
3999 		    || (c1 == '\\' && c2 == '/'))
4000 #endif
4001 		)
4002 	{
4003 	    if (vim_ispathsep(c1))
4004 		return -1;
4005 	    if (vim_ispathsep(c2))
4006 		return 1;
4007 	    return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4008 		    : c1 - c2;  // no match
4009 	}
4010 
4011 	i += mb_ptr2len((char_u *)p + i);
4012 	j += mb_ptr2len((char_u *)q + j);
4013     }
4014     if (s == NULL)	// "i" or "j" ran into "maxlen"
4015 	return 0;
4016 
4017     c1 = PTR2CHAR((char_u *)s + i);
4018     c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
4019     // ignore a trailing slash, but not "//" or ":/"
4020     if (c2 == NUL
4021 	    && i > 0
4022 	    && !after_pathsep((char_u *)s, (char_u *)s + i)
4023 #ifdef BACKSLASH_IN_FILENAME
4024 	    && (c1 == '/' || c1 == '\\')
4025 #else
4026 	    && c1 == '/'
4027 #endif
4028        )
4029 	return 0;   // match with trailing slash
4030     if (s == q)
4031 	return -1;	    // no match
4032     return 1;
4033 }
4034 
4035 /*
4036  * Return TRUE if "name" is a full (absolute) path name or URL.
4037  */
4038     int
4039 vim_isAbsName(char_u *name)
4040 {
4041     return (path_with_url(name) != 0 || mch_isFullName(name));
4042 }
4043 
4044 /*
4045  * Get absolute file name into buffer "buf[len]".
4046  *
4047  * return FAIL for failure, OK otherwise
4048  */
4049     int
4050 vim_FullName(
4051     char_u	*fname,
4052     char_u	*buf,
4053     int		len,
4054     int		force)	    // force expansion even when already absolute
4055 {
4056     int		retval = OK;
4057     int		url;
4058 
4059     *buf = NUL;
4060     if (fname == NULL)
4061 	return FAIL;
4062 
4063     url = path_with_url(fname);
4064     if (!url)
4065 	retval = mch_FullName(fname, buf, len, force);
4066     if (url || retval == FAIL)
4067     {
4068 	// something failed; use the file name (truncate when too long)
4069 	vim_strncpy(buf, fname, len - 1);
4070     }
4071 #if defined(MSWIN)
4072     slash_adjust(buf);
4073 #endif
4074     return retval;
4075 }
4076