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