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