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