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