blob: c448edb0495fe65bfd2491ef4932039f412e32b4 [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)
Christian Brabandt81da16b2022-03-10 12:24:02 +0000189 STRNCPY(save_fname, short_fname, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200190 save_fname = NULL;
191 }
192
Bram Moolenaar26262f82019-09-04 20:59:15 +0200193 // concat the not-shortened part of the path
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +0100194 if ((*fname + len) != endp)
195 vim_strncpy(*fname + len, endp, sfx_len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200196 (*fname)[new_len] = NUL;
197 }
198
199theend:
200 vim_free(pbuf_unused);
201 vim_free(save_fname);
202
203 return retval;
204}
205
206/*
207 * Get a pathname for a partial path.
208 * Returns OK for success, FAIL for failure.
209 */
210 static int
211shortpath_for_partial(
212 char_u **fnamep,
213 char_u **bufp,
214 int *fnamelen)
215{
216 int sepcount, len, tflen;
217 char_u *p;
218 char_u *pbuf, *tfname;
219 int hasTilde;
220
Bram Moolenaar26262f82019-09-04 20:59:15 +0200221 // Count up the path separators from the RHS.. so we know which part
222 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200223 sepcount = 0;
224 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
225 if (vim_ispathsep(*p))
226 ++sepcount;
227
Bram Moolenaar26262f82019-09-04 20:59:15 +0200228 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200229 hasTilde = (**fnamep == '~');
230 if (hasTilde)
231 pbuf = tfname = expand_env_save(*fnamep);
232 else
233 pbuf = tfname = FullName_save(*fnamep, FALSE);
234
235 len = tflen = (int)STRLEN(tfname);
236
237 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
238 return FAIL;
239
240 if (len == 0)
241 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200242 // Don't have a valid filename, so shorten the rest of the
243 // path if we can. This CAN give us invalid 8.3 filenames, but
244 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200245 len = tflen;
246 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
247 return FAIL;
248 }
249
Bram Moolenaar26262f82019-09-04 20:59:15 +0200250 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200251 for (p = tfname + len - 1; p >= tfname; --p)
252 {
253 if (has_mbyte)
254 p -= mb_head_off(tfname, p);
255 if (vim_ispathsep(*p))
256 {
257 if (sepcount == 0 || (hasTilde && sepcount == 1))
258 break;
259 else
260 sepcount --;
261 }
262 }
263 if (hasTilde)
264 {
265 --p;
266 if (p >= tfname)
267 *p = '~';
268 else
269 return FAIL;
270 }
271 else
272 ++p;
273
Bram Moolenaar26262f82019-09-04 20:59:15 +0200274 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200275 vim_free(*bufp);
276 *fnamelen = (int)STRLEN(p);
277 *bufp = pbuf;
278 *fnamep = p;
279
280 return OK;
281}
282#endif // MSWIN
283
284/*
285 * Adjust a filename, according to a string of modifiers.
286 * *fnamep must be NUL terminated when called. When returning, the length is
287 * determined by *fnamelen.
288 * Returns VALID_ flags or -1 for failure.
289 * When there is an error, *fnamep is set to NULL.
290 */
291 int
292modify_fname(
293 char_u *src, // string with modifiers
294 int tilde_file, // "~" is a file name, not $HOME
295 int *usedlen, // characters after src that are used
296 char_u **fnamep, // file name so far
297 char_u **bufp, // buffer for allocated file name or NULL
298 int *fnamelen) // length of fnamep
299{
300 int valid = 0;
301 char_u *tail;
302 char_u *s, *p, *pbuf;
303 char_u dirname[MAXPATHL];
304 int c;
305 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100306 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200307#ifdef MSWIN
308 char_u *fname_start = *fnamep;
309 int has_shortname = 0;
310#endif
311
312repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200313 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200314 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
315 {
316 has_fullname = 1;
317
318 valid |= VALID_PATH;
319 *usedlen += 2;
320
Bram Moolenaar26262f82019-09-04 20:59:15 +0200321 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200322 if ((*fnamep)[0] == '~'
323#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
324 && ((*fnamep)[1] == '/'
325# ifdef BACKSLASH_IN_FILENAME
326 || (*fnamep)[1] == '\\'
327# endif
328 || (*fnamep)[1] == NUL)
329#endif
330 && !(tilde_file && (*fnamep)[1] == NUL)
331 )
332 {
333 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200334 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200335 *bufp = *fnamep;
336 if (*fnamep == NULL)
337 return -1;
338 }
339
Bram Moolenaar26262f82019-09-04 20:59:15 +0200340 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200341 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
342 {
343 if (vim_ispathsep(*p)
344 && p[1] == '.'
345 && (p[2] == NUL
346 || vim_ispathsep(p[2])
347 || (p[2] == '.'
348 && (p[3] == NUL || vim_ispathsep(p[3])))))
349 break;
350 }
351
Bram Moolenaar26262f82019-09-04 20:59:15 +0200352 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200353 if (*p != NUL || !vim_isAbsName(*fnamep))
354 {
355 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200356 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200357 *bufp = *fnamep;
358 if (*fnamep == NULL)
359 return -1;
360 }
361
362#ifdef MSWIN
363# if _WIN32_WINNT >= 0x0500
364 if (vim_strchr(*fnamep, '~') != NULL)
365 {
366 // Expand 8.3 filename to full path. Needed to make sure the same
367 // file does not have two different names.
368 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
369 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
370 WCHAR buf[_MAX_PATH];
371
372 if (wfname != NULL)
373 {
374 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
375 {
K.Takata54119102022-02-03 13:33:03 +0000376 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200377
K.Takata54119102022-02-03 13:33:03 +0000378 if (q != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200379 {
380 vim_free(*bufp); // free any allocated file name
K.Takata54119102022-02-03 13:33:03 +0000381 *bufp = *fnamep = q;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200382 }
383 }
384 vim_free(wfname);
385 }
386 }
387# endif
388#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200389 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200390 if (mch_isdir(*fnamep))
391 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200392 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200393 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200394 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200395 *bufp = *fnamep;
396 if (*fnamep == NULL)
397 return -1;
398 add_pathsep(*fnamep);
399 }
400 }
401
Bram Moolenaar26262f82019-09-04 20:59:15 +0200402 // ":." - path relative to the current directory
403 // ":~" - path relative to the home directory
404 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200405 while (src[*usedlen] == ':'
406 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
407 {
408 *usedlen += 2;
409 if (c == '8')
410 {
411#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200412 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200413#endif
414 continue;
415 }
416 pbuf = NULL;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200417 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaard816cd92020-02-04 22:23:09 +0100418 if (!has_fullname && !has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200419 {
=?UTF-8?q?Dundar=20G=C3=B6c?=78a84042022-02-09 15:20:39 +0000420 if (**fnamep == '~')
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200421 p = pbuf = expand_env_save(*fnamep);
422 else
423 p = pbuf = FullName_save(*fnamep, FALSE);
424 }
425 else
426 p = *fnamep;
427
428 has_fullname = 0;
429
430 if (p != NULL)
431 {
432 if (c == '.')
433 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100434 size_t namelen;
435
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200436 mch_dirname(dirname, MAXPATHL);
Bram Moolenaard816cd92020-02-04 22:23:09 +0100437 if (has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200438 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100439 s = vim_strsave(dirname);
440 if (s != NULL)
441 {
442 home_replace(NULL, s, dirname, MAXPATHL, TRUE);
443 vim_free(s);
444 }
445 }
446 namelen = STRLEN(dirname);
447
448 // Do not call shorten_fname() here since it removes the prefix
449 // even though the path does not have a prefix.
450 if (fnamencmp(p, dirname, namelen) == 0)
451 {
452 p += namelen;
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100453 if (vim_ispathsep(*p))
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200454 {
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100455 while (*p && vim_ispathsep(*p))
456 ++p;
457 *fnamep = p;
458 if (pbuf != NULL)
459 {
460 // free any allocated file name
461 vim_free(*bufp);
462 *bufp = pbuf;
463 pbuf = NULL;
464 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200465 }
466 }
467 }
468 else
469 {
470 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200471 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200472 if (*dirname == '~')
473 {
474 s = vim_strsave(dirname);
475 if (s != NULL)
476 {
477 *fnamep = s;
478 vim_free(*bufp);
479 *bufp = s;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100480 has_homerelative = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200481 }
482 }
483 }
484 vim_free(pbuf);
485 }
486 }
487
488 tail = gettail(*fnamep);
489 *fnamelen = (int)STRLEN(*fnamep);
490
Bram Moolenaar26262f82019-09-04 20:59:15 +0200491 // ":h" - head, remove "/file_name", can be repeated
492 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200493 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
494 {
495 valid |= VALID_HEAD;
496 *usedlen += 2;
497 s = get_past_head(*fnamep);
498 while (tail > s && after_pathsep(s, tail))
499 MB_PTR_BACK(*fnamep, tail);
500 *fnamelen = (int)(tail - *fnamep);
501#ifdef VMS
502 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200503 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200504#endif
505 if (*fnamelen == 0)
506 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200507 // Result is empty. Turn it into "." to make ":cd %:h" work.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200508 p = vim_strsave((char_u *)".");
509 if (p == NULL)
510 return -1;
511 vim_free(*bufp);
512 *bufp = *fnamep = tail = p;
513 *fnamelen = 1;
514 }
515 else
516 {
517 while (tail > s && !after_pathsep(s, tail))
518 MB_PTR_BACK(*fnamep, tail);
519 }
520 }
521
Bram Moolenaar26262f82019-09-04 20:59:15 +0200522 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200523 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
524 {
525 *usedlen += 2;
526#ifdef MSWIN
527 has_shortname = 1;
528#endif
529 }
530
531#ifdef MSWIN
532 /*
533 * Handle ":8" after we have done 'heads' and before we do 'tails'.
534 */
535 if (has_shortname)
536 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200537 // Copy the string if it is shortened by :h and when it wasn't copied
538 // yet, because we are going to change it in place. Avoids changing
539 // the buffer name for "%:8".
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200540 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
541 {
542 p = vim_strnsave(*fnamep, *fnamelen);
543 if (p == NULL)
544 return -1;
545 vim_free(*bufp);
546 *bufp = *fnamep = p;
547 }
548
Bram Moolenaar26262f82019-09-04 20:59:15 +0200549 // Split into two implementations - makes it easier. First is where
550 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200551 if (!has_fullname && !vim_isAbsName(*fnamep))
552 {
553 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
554 return -1;
555 }
556 else
557 {
558 int l = *fnamelen;
559
Bram Moolenaar26262f82019-09-04 20:59:15 +0200560 // Simple case, already have the full-name.
561 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200562 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
563 return -1;
564
565 if (l == 0)
566 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200567 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200568 l = *fnamelen;
569 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
570 return -1;
571 }
572 *fnamelen = l;
573 }
574 }
575#endif // MSWIN
576
Bram Moolenaar26262f82019-09-04 20:59:15 +0200577 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200578 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
579 {
580 *usedlen += 2;
581 *fnamelen -= (int)(tail - *fnamep);
582 *fnamep = tail;
583 }
584
Bram Moolenaar26262f82019-09-04 20:59:15 +0200585 // ":e" - extension, can be repeated
586 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200587 while (src[*usedlen] == ':'
588 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
589 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200590 // find a '.' in the tail:
591 // - for second :e: before the current fname
592 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200593 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
594 s = *fnamep - 2;
595 else
596 s = *fnamep + *fnamelen - 1;
597 for ( ; s > tail; --s)
598 if (s[0] == '.')
599 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200600 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200601 {
602 if (s > tail)
603 {
604 *fnamelen += (int)(*fnamep - (s + 1));
605 *fnamep = s + 1;
606#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200607 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200608 s = *fnamep + *fnamelen - 1;
609 for ( ; s > *fnamep; --s)
610 if (s[0] == ';')
611 break;
612 if (s > *fnamep)
613 *fnamelen = s - *fnamep;
614#endif
615 }
616 else if (*fnamep <= tail)
617 *fnamelen = 0;
618 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200619 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200620 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200621 char_u *limit = *fnamep;
622
623 if (limit < tail)
624 limit = tail;
625 if (s > limit) // remove one extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200626 *fnamelen = (int)(s - *fnamep);
627 }
628 *usedlen += 2;
629 }
630
Bram Moolenaar26262f82019-09-04 20:59:15 +0200631 // ":s?pat?foo?" - substitute
632 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200633 if (src[*usedlen] == ':'
634 && (src[*usedlen + 1] == 's'
635 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
636 {
637 char_u *str;
638 char_u *pat;
639 char_u *sub;
640 int sep;
641 char_u *flags;
642 int didit = FALSE;
643
644 flags = (char_u *)"";
645 s = src + *usedlen + 2;
646 if (src[*usedlen + 1] == 'g')
647 {
648 flags = (char_u *)"g";
649 ++s;
650 }
651
652 sep = *s++;
653 if (sep)
654 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200655 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200656 p = vim_strchr(s, sep);
657 if (p != NULL)
658 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200659 pat = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200660 if (pat != NULL)
661 {
662 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200663 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200664 p = vim_strchr(s, sep);
665 if (p != NULL)
666 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200667 sub = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200668 str = vim_strnsave(*fnamep, *fnamelen);
669 if (sub != NULL && str != NULL)
670 {
671 *usedlen = (int)(p + 1 - src);
672 s = do_string_sub(str, pat, sub, NULL, flags);
673 if (s != NULL)
674 {
675 *fnamep = s;
676 *fnamelen = (int)STRLEN(s);
677 vim_free(*bufp);
678 *bufp = s;
679 didit = TRUE;
680 }
681 }
682 vim_free(sub);
683 vim_free(str);
684 }
685 vim_free(pat);
686 }
687 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200688 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200689 if (didit)
690 goto repeat;
691 }
692 }
693
694 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
695 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200696 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200697 c = (*fnamep)[*fnamelen];
698 if (c != NUL)
699 (*fnamep)[*fnamelen] = NUL;
700 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
701 if (c != NUL)
702 (*fnamep)[*fnamelen] = c;
703 if (p == NULL)
704 return -1;
705 vim_free(*bufp);
706 *bufp = *fnamep = p;
707 *fnamelen = (int)STRLEN(p);
708 *usedlen += 2;
709 }
710
711 return valid;
712}
713
Bram Moolenaar273af492020-09-25 23:49:01 +0200714/*
715 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
716 * "trim_len" specifies how many characters to keep for each directory.
717 * Must be 1 or more.
718 * It's done in-place.
719 */
720 static void
721shorten_dir_len(char_u *str, int trim_len)
722{
723 char_u *tail, *s, *d;
724 int skip = FALSE;
725 int dirchunk_len = 0;
726
727 tail = gettail(str);
728 d = str;
729 for (s = str; ; ++s)
730 {
731 if (s >= tail) // copy the whole tail
732 {
733 *d++ = *s;
734 if (*s == NUL)
735 break;
736 }
737 else if (vim_ispathsep(*s)) // copy '/' and next char
738 {
739 *d++ = *s;
740 skip = FALSE;
741 dirchunk_len = 0;
742 }
743 else if (!skip)
744 {
745 *d++ = *s; // copy next char
746 if (*s != '~' && *s != '.') // and leading "~" and "."
747 {
748 ++dirchunk_len; // only count word chars for the size
749
750 // keep copying chars until we have our preferred length (or
751 // until the above if/else branches move us along)
752 if (dirchunk_len >= trim_len)
753 skip = TRUE;
754 }
755
756 if (has_mbyte)
757 {
758 int l = mb_ptr2len(s);
759
760 while (--l > 0)
761 *d++ = *++s;
762 }
763 }
764 }
765}
766
767/*
768 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
769 * It's done in-place.
770 */
771 void
772shorten_dir(char_u *str)
773{
774 shorten_dir_len(str, 1);
775}
776
Bram Moolenaar022f9ef2022-07-02 17:36:31 +0100777/*
778 * Return TRUE if "fname" is a readable file.
779 */
780 int
781file_is_readable(char_u *fname)
782{
783 int fd;
784
785#ifndef O_NONBLOCK
786# define O_NONBLOCK 0
787#endif
788 if (*fname && !mch_isdir(fname)
789 && (fd = mch_open((char *)fname, O_RDONLY | O_NONBLOCK, 0)) >= 0)
790 {
791 close(fd);
792 return TRUE;
793 }
794 return FALSE;
795}
796
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200797#if defined(FEAT_EVAL) || defined(PROTO)
798
799/*
800 * "chdir(dir)" function
801 */
802 void
803f_chdir(typval_T *argvars, typval_T *rettv)
804{
805 char_u *cwd;
806 cdscope_T scope = CDSCOPE_GLOBAL;
807
808 rettv->v_type = VAR_STRING;
809 rettv->vval.v_string = NULL;
810
811 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100812 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100813 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200814 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100815 if (in_vim9script())
816 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200817 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100818 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200819
820 // Return the current directory
821 cwd = alloc(MAXPATHL);
822 if (cwd != NULL)
823 {
824 if (mch_dirname(cwd, MAXPATHL) != FAIL)
825 {
826#ifdef BACKSLASH_IN_FILENAME
827 slash_adjust(cwd);
828#endif
829 rettv->vval.v_string = vim_strsave(cwd);
830 }
831 vim_free(cwd);
832 }
833
834 if (curwin->w_localdir != NULL)
835 scope = CDSCOPE_WINDOW;
836 else if (curtab->tp_localdir != NULL)
837 scope = CDSCOPE_TABPAGE;
838
839 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
840 // Directory change failed
841 VIM_CLEAR(rettv->vval.v_string);
842}
843
844/*
845 * "delete()" function
846 */
847 void
848f_delete(typval_T *argvars, typval_T *rettv)
849{
850 char_u nbuf[NUMBUFLEN];
851 char_u *name;
852 char_u *flags;
853
854 rettv->vval.v_number = -1;
855 if (check_restricted() || check_secure())
856 return;
857
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200858 if (in_vim9script()
859 && (check_for_string_arg(argvars, 0) == FAIL
860 || check_for_opt_string_arg(argvars, 1) == FAIL))
861 return;
862
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200863 name = tv_get_string(&argvars[0]);
864 if (name == NULL || *name == NUL)
865 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000866 emsg(_(e_invalid_argument));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200867 return;
868 }
869
870 if (argvars[1].v_type != VAR_UNKNOWN)
871 flags = tv_get_string_buf(&argvars[1], nbuf);
872 else
873 flags = (char_u *)"";
874
875 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200876 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200877 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
878 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200879 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200880 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
881 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200882 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200883 rettv->vval.v_number = delete_recursive(name);
884 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200885 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200886}
887
888/*
889 * "executable()" function
890 */
891 void
892f_executable(typval_T *argvars, typval_T *rettv)
893{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100894 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100895 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200896
Bram Moolenaar26262f82019-09-04 20:59:15 +0200897 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100898 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200899}
900
901/*
902 * "exepath()" function
903 */
904 void
905f_exepath(typval_T *argvars, typval_T *rettv)
906{
907 char_u *p = NULL;
908
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100909 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100910 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200911 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
912 rettv->v_type = VAR_STRING;
913 rettv->vval.v_string = p;
914}
915
916/*
917 * "filereadable()" function
918 */
919 void
920f_filereadable(typval_T *argvars, typval_T *rettv)
921{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100922 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100923 return;
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100924 rettv->vval.v_number = file_is_readable(tv_get_string(&argvars[0]));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200925}
926
927/*
928 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
929 * rights to write into.
930 */
931 void
932f_filewritable(typval_T *argvars, typval_T *rettv)
933{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100934 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100935 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200936 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
937}
938
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200939 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200940findfilendir(
941 typval_T *argvars UNUSED,
942 typval_T *rettv,
943 int find_what UNUSED)
944{
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200945 char_u *fname;
946 char_u *fresult = NULL;
947 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
948 char_u *p;
949 char_u pathbuf[NUMBUFLEN];
950 int count = 1;
951 int first = TRUE;
952 int error = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200953
954 rettv->vval.v_string = NULL;
955 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200956 if (in_vim9script()
957 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
958 || check_for_opt_string_arg(argvars, 1) == FAIL
959 || (argvars[1].v_type != VAR_UNKNOWN
960 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100961 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200962
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200963 fname = tv_get_string(&argvars[0]);
964
965 if (argvars[1].v_type != VAR_UNKNOWN)
966 {
967 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
968 if (p == NULL)
969 error = TRUE;
970 else
971 {
972 if (*p != NUL)
973 path = p;
974
975 if (argvars[2].v_type != VAR_UNKNOWN)
976 count = (int)tv_get_number_chk(&argvars[2], &error);
977 }
978 }
979
980 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
981 error = TRUE;
982
983 if (*fname != NUL && !error)
984 {
985 do
986 {
987 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
988 vim_free(fresult);
989 fresult = find_file_in_path_option(first ? fname : NULL,
990 first ? (int)STRLEN(fname) : 0,
991 0, first, path,
992 find_what,
993 curbuf->b_ffname,
994 find_what == FINDFILE_DIR
995 ? (char_u *)"" : curbuf->b_p_sua);
996 first = FALSE;
997
998 if (fresult != NULL && rettv->v_type == VAR_LIST)
999 list_append_string(rettv->vval.v_list, fresult, -1);
1000
1001 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
1002 }
1003
1004 if (rettv->v_type == VAR_STRING)
1005 rettv->vval.v_string = fresult;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001006}
1007
1008/*
1009 * "finddir({fname}[, {path}[, {count}]])" function
1010 */
1011 void
1012f_finddir(typval_T *argvars, typval_T *rettv)
1013{
1014 findfilendir(argvars, rettv, FINDFILE_DIR);
1015}
1016
1017/*
1018 * "findfile({fname}[, {path}[, {count}]])" function
1019 */
1020 void
1021f_findfile(typval_T *argvars, typval_T *rettv)
1022{
1023 findfilendir(argvars, rettv, FINDFILE_FILE);
1024}
1025
1026/*
1027 * "fnamemodify({fname}, {mods})" function
1028 */
1029 void
1030f_fnamemodify(typval_T *argvars, typval_T *rettv)
1031{
1032 char_u *fname;
1033 char_u *mods;
1034 int usedlen = 0;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001035 int len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001036 char_u *fbuf = NULL;
1037 char_u buf[NUMBUFLEN];
1038
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001039 if (in_vim9script()
1040 && (check_for_string_arg(argvars, 0) == FAIL
1041 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001042 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001043
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001044 fname = tv_get_string_chk(&argvars[0]);
1045 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001046 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001047 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001048 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001049 {
1050 len = (int)STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001051 if (mods != NULL && *mods != NUL)
1052 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001053 }
1054
1055 rettv->v_type = VAR_STRING;
1056 if (fname == NULL)
1057 rettv->vval.v_string = NULL;
1058 else
1059 rettv->vval.v_string = vim_strnsave(fname, len);
1060 vim_free(fbuf);
1061}
1062
1063/*
1064 * "getcwd()" function
1065 *
1066 * Return the current working directory of a window in a tab page.
1067 * First optional argument 'winnr' is the window number or -1 and the second
1068 * optional argument 'tabnr' is the tab page number.
1069 *
1070 * If no arguments are supplied, then return the directory of the current
1071 * window.
1072 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1073 * the specified window.
1074 * If 'winnr' is 0 then return the directory of the current window.
1075 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1076 * directory of the specified tab page. Otherwise return the directory of the
1077 * specified window in the specified tab page.
1078 * If the window or the tab page doesn't exist then return NULL.
1079 */
1080 void
1081f_getcwd(typval_T *argvars, typval_T *rettv)
1082{
1083 win_T *wp = NULL;
1084 tabpage_T *tp = NULL;
1085 char_u *cwd;
1086 int global = FALSE;
1087
1088 rettv->v_type = VAR_STRING;
1089 rettv->vval.v_string = NULL;
1090
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001091 if (in_vim9script()
1092 && (check_for_opt_number_arg(argvars, 0) == FAIL
1093 || (argvars[0].v_type != VAR_UNKNOWN
1094 && check_for_opt_number_arg(argvars, 1) == FAIL)))
1095 return;
1096
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001097 if (argvars[0].v_type == VAR_NUMBER
1098 && argvars[0].vval.v_number == -1
1099 && argvars[1].v_type == VAR_UNKNOWN)
1100 global = TRUE;
1101 else
1102 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1103
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001104 if (wp != NULL && wp->w_localdir != NULL
1105 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001106 rettv->vval.v_string = vim_strsave(wp->w_localdir);
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001107 else if (tp != NULL && tp->tp_localdir != NULL
1108 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001109 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1110 else if (wp != NULL || tp != NULL || global)
1111 {
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001112 if (globaldir != NULL && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001113 rettv->vval.v_string = vim_strsave(globaldir);
1114 else
1115 {
1116 cwd = alloc(MAXPATHL);
1117 if (cwd != NULL)
1118 {
1119 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1120 rettv->vval.v_string = vim_strsave(cwd);
1121 vim_free(cwd);
1122 }
1123 }
1124 }
1125#ifdef BACKSLASH_IN_FILENAME
1126 if (rettv->vval.v_string != NULL)
1127 slash_adjust(rettv->vval.v_string);
1128#endif
1129}
1130
1131/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001132 * Convert "st" to file permission string.
1133 */
1134 char_u *
1135getfpermst(stat_T *st, char_u *perm)
1136{
1137 char_u flags[] = "rwx";
1138 int i;
1139
1140 for (i = 0; i < 9; i++)
1141 {
1142 if (st->st_mode & (1 << (8 - i)))
1143 perm[i] = flags[i % 3];
1144 else
1145 perm[i] = '-';
1146 }
1147 return perm;
1148}
1149
1150/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001151 * "getfperm({fname})" function
1152 */
1153 void
1154f_getfperm(typval_T *argvars, typval_T *rettv)
1155{
1156 char_u *fname;
1157 stat_T st;
1158 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001159 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001160
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001161 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001162 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001163
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001164 fname = tv_get_string(&argvars[0]);
1165
1166 rettv->v_type = VAR_STRING;
1167 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001168 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001169 rettv->vval.v_string = perm;
1170}
1171
1172/*
1173 * "getfsize({fname})" function
1174 */
1175 void
1176f_getfsize(typval_T *argvars, typval_T *rettv)
1177{
1178 char_u *fname;
1179 stat_T st;
1180
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001181 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001182 return;
1183
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001184 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001185 if (mch_stat((char *)fname, &st) >= 0)
1186 {
1187 if (mch_isdir(fname))
1188 rettv->vval.v_number = 0;
1189 else
1190 {
1191 rettv->vval.v_number = (varnumber_T)st.st_size;
1192
Bram Moolenaar26262f82019-09-04 20:59:15 +02001193 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001194 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1195 rettv->vval.v_number = -2;
1196 }
1197 }
1198 else
1199 rettv->vval.v_number = -1;
1200}
1201
1202/*
1203 * "getftime({fname})" function
1204 */
1205 void
1206f_getftime(typval_T *argvars, typval_T *rettv)
1207{
1208 char_u *fname;
1209 stat_T st;
1210
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001211 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001212 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001213
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001214 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001215 if (mch_stat((char *)fname, &st) >= 0)
1216 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1217 else
1218 rettv->vval.v_number = -1;
1219}
1220
1221/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001222 * Convert "st" to file type string.
1223 */
1224 char_u *
1225getftypest(stat_T *st)
1226{
1227 char *t;
1228
1229 if (S_ISREG(st->st_mode))
1230 t = "file";
1231 else if (S_ISDIR(st->st_mode))
1232 t = "dir";
1233 else if (S_ISLNK(st->st_mode))
1234 t = "link";
1235 else if (S_ISBLK(st->st_mode))
1236 t = "bdev";
1237 else if (S_ISCHR(st->st_mode))
1238 t = "cdev";
1239 else if (S_ISFIFO(st->st_mode))
1240 t = "fifo";
1241 else if (S_ISSOCK(st->st_mode))
1242 t = "socket";
1243 else
1244 t = "other";
1245 return (char_u*)t;
1246}
1247
1248/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001249 * "getftype({fname})" function
1250 */
1251 void
1252f_getftype(typval_T *argvars, typval_T *rettv)
1253{
1254 char_u *fname;
1255 stat_T st;
1256 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001257
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001258 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001259 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001260
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001261 fname = tv_get_string(&argvars[0]);
1262
1263 rettv->v_type = VAR_STRING;
1264 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001265 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001266 rettv->vval.v_string = type;
1267}
1268
1269/*
1270 * "glob()" function
1271 */
1272 void
1273f_glob(typval_T *argvars, typval_T *rettv)
1274{
1275 int options = WILD_SILENT|WILD_USE_NL;
1276 expand_T xpc;
1277 int error = FALSE;
1278
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001279 if (in_vim9script()
1280 && (check_for_string_arg(argvars, 0) == FAIL
1281 || check_for_opt_bool_arg(argvars, 1) == FAIL
1282 || (argvars[1].v_type != VAR_UNKNOWN
1283 && (check_for_opt_bool_arg(argvars, 2) == FAIL
1284 || (argvars[2].v_type != VAR_UNKNOWN
1285 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
1286 return;
1287
Bram Moolenaar26262f82019-09-04 20:59:15 +02001288 // When the optional second argument is non-zero, don't remove matches
1289 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001290 rettv->v_type = VAR_STRING;
1291 if (argvars[1].v_type != VAR_UNKNOWN)
1292 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001293 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001294 options |= WILD_KEEP_ALL;
1295 if (argvars[2].v_type != VAR_UNKNOWN)
1296 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001297 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001298 rettv_list_set(rettv, NULL);
1299 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001300 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001301 options |= WILD_ALLLINKS;
1302 }
1303 }
1304 if (!error)
1305 {
1306 ExpandInit(&xpc);
1307 xpc.xp_context = EXPAND_FILES;
1308 if (p_wic)
1309 options += WILD_ICASE;
1310 if (rettv->v_type == VAR_STRING)
1311 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1312 NULL, options, WILD_ALL);
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001313 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001314 {
1315 int i;
1316
1317 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1318 NULL, options, WILD_ALL_KEEP);
1319 for (i = 0; i < xpc.xp_numfiles; i++)
1320 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1321
1322 ExpandCleanup(&xpc);
1323 }
1324 }
1325 else
1326 rettv->vval.v_string = NULL;
1327}
1328
1329/*
1330 * "glob2regpat()" function
1331 */
1332 void
1333f_glob2regpat(typval_T *argvars, typval_T *rettv)
1334{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001335 char_u buf[NUMBUFLEN];
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001336 char_u *pat;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001337
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001338 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1339 return;
1340
1341 pat = tv_get_string_buf_chk_strict(&argvars[0], buf, in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001342 rettv->v_type = VAR_STRING;
1343 rettv->vval.v_string = (pat == NULL)
1344 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1345}
1346
1347/*
1348 * "globpath()" function
1349 */
1350 void
1351f_globpath(typval_T *argvars, typval_T *rettv)
1352{
1353 int flags = WILD_IGNORE_COMPLETESLASH;
1354 char_u buf1[NUMBUFLEN];
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001355 char_u *file;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001356 int error = FALSE;
1357 garray_T ga;
1358 int i;
1359
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001360 if (in_vim9script()
1361 && (check_for_string_arg(argvars, 0) == FAIL
1362 || check_for_string_arg(argvars, 1) == FAIL
1363 || check_for_opt_bool_arg(argvars, 2) == FAIL
1364 || (argvars[2].v_type != VAR_UNKNOWN
1365 && (check_for_opt_bool_arg(argvars, 3) == FAIL
1366 || (argvars[3].v_type != VAR_UNKNOWN
1367 && check_for_opt_bool_arg(argvars, 4) == FAIL)))))
1368 return;
1369
1370 file = tv_get_string_buf_chk(&argvars[1], buf1);
1371
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001372 // When the optional second argument is non-zero, don't remove matches
1373 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1374 rettv->v_type = VAR_STRING;
1375 if (argvars[2].v_type != VAR_UNKNOWN)
1376 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001377 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001378 flags |= WILD_KEEP_ALL;
1379 if (argvars[3].v_type != VAR_UNKNOWN)
1380 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001381 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001382 rettv_list_set(rettv, NULL);
1383 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001384 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001385 flags |= WILD_ALLLINKS;
1386 }
1387 }
1388 if (file != NULL && !error)
1389 {
Bram Moolenaar04935fb2022-01-08 16:19:22 +00001390 ga_init2(&ga, sizeof(char_u *), 10);
zeertzjq3770f4c2023-01-22 18:38:51 +00001391 globpath(tv_get_string(&argvars[0]), file, &ga, flags, FALSE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001392 if (rettv->v_type == VAR_STRING)
1393 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001394 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001395 for (i = 0; i < ga.ga_len; ++i)
1396 list_append_string(rettv->vval.v_list,
1397 ((char_u **)(ga.ga_data))[i], -1);
1398 ga_clear_strings(&ga);
1399 }
1400 else
1401 rettv->vval.v_string = NULL;
1402}
1403
1404/*
1405 * "isdirectory()" function
1406 */
1407 void
1408f_isdirectory(typval_T *argvars, typval_T *rettv)
1409{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001410 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1411 return;
1412
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001413 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1414}
1415
1416/*
LemonBoydca1d402022-04-28 15:26:33 +01001417 * "isabsolutepath()" function
1418 */
1419 void
1420f_isabsolutepath(typval_T *argvars, typval_T *rettv)
1421{
1422 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1423 return;
1424
1425 rettv->vval.v_number = mch_isFullName(tv_get_string_strict(&argvars[0]));
1426}
1427
1428/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001429 * Create the directory in which "dir" is located, and higher levels when
1430 * needed.
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001431 * Set "created" to the full name of the first created directory. It will be
1432 * NULL until that happens.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001433 * Return OK or FAIL.
1434 */
1435 static int
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001436mkdir_recurse(char_u *dir, int prot, char_u **created)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001437{
1438 char_u *p;
1439 char_u *updir;
1440 int r = FAIL;
1441
Bram Moolenaar26262f82019-09-04 20:59:15 +02001442 // Get end of directory name in "dir".
1443 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001444 p = gettail_sep(dir);
1445 if (p <= get_past_head(dir))
1446 return OK;
1447
Bram Moolenaar26262f82019-09-04 20:59:15 +02001448 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001449 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001450 if (updir == NULL)
1451 return FAIL;
1452 if (mch_isdir(updir))
1453 r = OK;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001454 else if (mkdir_recurse(updir, prot, created) == OK)
1455 {
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001456 r = vim_mkdir_emsg(updir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001457 if (r == OK && created != NULL && *created == NULL)
1458 *created = FullName_save(updir, FALSE);
1459 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001460 vim_free(updir);
1461 return r;
1462}
1463
1464/*
1465 * "mkdir()" function
1466 */
1467 void
1468f_mkdir(typval_T *argvars, typval_T *rettv)
1469{
1470 char_u *dir;
1471 char_u buf[NUMBUFLEN];
1472 int prot = 0755;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001473 int defer = FALSE;
1474 int defer_recurse = FALSE;
1475 char_u *created = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001476
1477 rettv->vval.v_number = FAIL;
1478 if (check_restricted() || check_secure())
1479 return;
1480
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001481 if (in_vim9script()
1482 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1483 || check_for_opt_string_arg(argvars, 1) == FAIL
1484 || (argvars[1].v_type != VAR_UNKNOWN
1485 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1486 return;
1487
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001488 dir = tv_get_string_buf(&argvars[0], buf);
1489 if (*dir == NUL)
1490 return;
1491
1492 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001493 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001494 *gettail_sep(dir) = NUL;
1495
1496 if (argvars[1].v_type != VAR_UNKNOWN)
1497 {
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001498 char_u *arg2;
1499
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001500 if (argvars[2].v_type != VAR_UNKNOWN)
1501 {
1502 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1503 if (prot == -1)
1504 return;
1505 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001506 arg2 = tv_get_string(&argvars[1]);
1507 defer = vim_strchr(arg2, 'D') != NULL;
1508 defer_recurse = vim_strchr(arg2, 'R') != NULL;
1509 if ((defer || defer_recurse) && !can_add_defer())
1510 return;
1511
1512 if (vim_strchr(arg2, 'p') != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001513 {
1514 if (mch_isdir(dir))
1515 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001516 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001517 rettv->vval.v_number = OK;
1518 return;
1519 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001520 mkdir_recurse(dir, prot, defer || defer_recurse ? &created : NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001521 }
1522 }
1523 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001524
1525 // Handle "D" and "R": deferred deletion of the created directory.
1526 if (rettv->vval.v_number == OK
1527 && created == NULL && (defer || defer_recurse))
1528 created = FullName_save(dir, FALSE);
1529 if (created != NULL)
1530 {
1531 typval_T tv[2];
1532
1533 tv[0].v_type = VAR_STRING;
1534 tv[0].v_lock = 0;
1535 tv[0].vval.v_string = created;
1536 tv[1].v_type = VAR_STRING;
1537 tv[1].v_lock = 0;
1538 tv[1].vval.v_string = vim_strsave(
1539 (char_u *)(defer_recurse ? "rf" : "d"));
1540 if (tv[0].vval.v_string == NULL || tv[1].vval.v_string == NULL
1541 || add_defer((char_u *)"delete", 2, tv) == FAIL)
1542 {
1543 vim_free(tv[0].vval.v_string);
1544 vim_free(tv[1].vval.v_string);
1545 }
1546 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001547}
1548
1549/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001550 * "pathshorten()" function
1551 */
1552 void
1553f_pathshorten(typval_T *argvars, typval_T *rettv)
1554{
1555 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001556 int trim_len = 1;
1557
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001558 if (in_vim9script()
1559 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001560 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001561 return;
1562
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001563 if (argvars[1].v_type != VAR_UNKNOWN)
1564 {
1565 trim_len = (int)tv_get_number(&argvars[1]);
1566 if (trim_len < 1)
1567 trim_len = 1;
1568 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001569
1570 rettv->v_type = VAR_STRING;
1571 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001572
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001573 if (p == NULL)
1574 rettv->vval.v_string = NULL;
1575 else
1576 {
1577 p = vim_strsave(p);
1578 rettv->vval.v_string = p;
1579 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001580 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001581 }
1582}
1583
1584/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001585 * Common code for readdir_checkitem() and readdirex_checkitem().
1586 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001587 */
1588 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001589checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001590{
1591 typval_T *expr = (typval_T *)context;
1592 typval_T save_val;
1593 typval_T rettv;
1594 typval_T argv[2];
1595 int retval = 0;
1596 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001597
1598 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001599 if (name != NULL)
1600 {
1601 set_vim_var_string(VV_VAL, name, -1);
1602 argv[0].v_type = VAR_STRING;
1603 argv[0].vval.v_string = name;
1604 }
1605 else
1606 {
1607 set_vim_var_dict(VV_VAL, dict);
1608 argv[0].v_type = VAR_DICT;
1609 argv[0].vval.v_dict = dict;
1610 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001611
Bram Moolenaar82418262022-09-28 16:16:15 +01001612 if (eval_expr_typval(expr, argv, 1, NULL, &rettv) == FAIL)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001613 goto theend;
1614
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001615 // We want to use -1, but also true/false should be allowed.
1616 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1617 {
1618 rettv.v_type = VAR_NUMBER;
1619 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1620 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001621 retval = tv_get_number_chk(&rettv, &error);
1622 if (error)
1623 retval = -1;
1624 clear_tv(&rettv);
1625
1626theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001627 if (name != NULL)
1628 set_vim_var_string(VV_VAL, NULL, 0);
1629 else
1630 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001631 restore_vimvar(VV_VAL, &save_val);
1632 return retval;
1633}
1634
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001635/*
1636 * Evaluate "expr" (= "context") for readdir().
1637 */
1638 static int
1639readdir_checkitem(void *context, void *item)
1640{
1641 char_u *name = (char_u *)item;
1642
1643 return checkitem_common(context, name, NULL);
1644}
1645
Bram Moolenaard83392a2022-09-01 12:22:46 +01001646/*
1647 * Process the keys in the Dict argument to the readdir() and readdirex()
1648 * functions. Assumes the Dict argument is the 3rd argument.
1649 */
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001650 static int
Bram Moolenaard83392a2022-09-01 12:22:46 +01001651readdirex_dict_arg(typval_T *argvars, int *cmp)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001652{
1653 char_u *compare;
1654
Bram Moolenaard83392a2022-09-01 12:22:46 +01001655 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001656 return FAIL;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001657
Bram Moolenaard83392a2022-09-01 12:22:46 +01001658 if (dict_has_key(argvars[2].vval.v_dict, "sort"))
1659 compare = dict_get_string(argvars[2].vval.v_dict, "sort", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001660 else
1661 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001662 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001663 return FAIL;
1664 }
1665
1666 if (STRCMP(compare, (char_u *) "none") == 0)
1667 *cmp = READDIR_SORT_NONE;
1668 else if (STRCMP(compare, (char_u *) "case") == 0)
1669 *cmp = READDIR_SORT_BYTE;
1670 else if (STRCMP(compare, (char_u *) "icase") == 0)
1671 *cmp = READDIR_SORT_IC;
1672 else if (STRCMP(compare, (char_u *) "collate") == 0)
1673 *cmp = READDIR_SORT_COLLATE;
1674 return OK;
1675}
1676
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001677/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001678 * "readdir()" function
1679 */
1680 void
1681f_readdir(typval_T *argvars, typval_T *rettv)
1682{
1683 typval_T *expr;
1684 int ret;
1685 char_u *path;
1686 char_u *p;
1687 garray_T ga;
1688 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001689 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001690
1691 if (rettv_list_alloc(rettv) == FAIL)
1692 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001693
1694 if (in_vim9script()
1695 && (check_for_string_arg(argvars, 0) == FAIL
1696 || (argvars[1].v_type != VAR_UNKNOWN
1697 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1698 return;
1699
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001700 path = tv_get_string(&argvars[0]);
1701 expr = &argvars[1];
1702
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001703 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001704 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001705 return;
1706
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001707 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001708 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001709 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001710 {
1711 for (i = 0; i < ga.ga_len; i++)
1712 {
1713 p = ((char_u **)ga.ga_data)[i];
1714 list_append_string(rettv->vval.v_list, p, -1);
1715 }
1716 }
1717 ga_clear_strings(&ga);
1718}
1719
1720/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001721 * Evaluate "expr" (= "context") for readdirex().
1722 */
1723 static int
1724readdirex_checkitem(void *context, void *item)
1725{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001726 dict_T *dict = (dict_T*)item;
1727
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001728 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001729}
1730
1731/*
1732 * "readdirex()" function
1733 */
1734 void
1735f_readdirex(typval_T *argvars, typval_T *rettv)
1736{
1737 typval_T *expr;
1738 int ret;
1739 char_u *path;
1740 garray_T ga;
1741 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001742 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001743
1744 if (rettv_list_alloc(rettv) == FAIL)
1745 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001746
1747 if (in_vim9script()
1748 && (check_for_string_arg(argvars, 0) == FAIL
1749 || (argvars[1].v_type != VAR_UNKNOWN
1750 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1751 return;
1752
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001753 path = tv_get_string(&argvars[0]);
1754 expr = &argvars[1];
1755
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001756 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001757 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001758 return;
1759
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001760 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001761 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001762 if (ret == OK)
1763 {
1764 for (i = 0; i < ga.ga_len; i++)
1765 {
1766 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1767 list_append_dict(rettv->vval.v_list, dict);
1768 dict_unref(dict);
1769 }
1770 }
1771 ga_clear(&ga);
1772}
1773
1774/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001775 * "readfile()" function
1776 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001777 static void
1778read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001779{
1780 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001781 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001782 int failed = FALSE;
1783 char_u *fname;
1784 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001785 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001786 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001787 int readlen; // size of last fread()
1788 char_u *prev = NULL; // previously read bytes, if any
1789 long prevlen = 0; // length of data in prev
1790 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001791 long maxline = MAXLNUM;
1792 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001793 char_u *p; // position in buf
1794 char_u *start; // start of current line
K.Takata11df3ae2022-10-19 14:02:40 +01001795 off_T offset = 0;
1796 off_T size = -1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001797
1798 if (argvars[1].v_type != VAR_UNKNOWN)
1799 {
K.Takata11df3ae2022-10-19 14:02:40 +01001800 if (always_blob)
1801 {
1802 offset = (off_T)tv_get_number(&argvars[1]);
1803 if (argvars[2].v_type != VAR_UNKNOWN)
1804 size = (off_T)tv_get_number(&argvars[2]);
1805 }
1806 else
1807 {
1808 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1809 binary = TRUE;
1810 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1811 blob = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001812
K.Takata11df3ae2022-10-19 14:02:40 +01001813 if (argvars[2].v_type != VAR_UNKNOWN)
1814 maxline = (long)tv_get_number(&argvars[2]);
1815 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001816 }
1817
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001818 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1819 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001820
Bram Moolenaar26262f82019-09-04 20:59:15 +02001821 // Always open the file in binary mode, library functions have a mind of
1822 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001823 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001824
1825 if (mch_isdir(fname))
1826 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001827 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001828 return;
1829 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001830 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1831 {
K.Takata11df3ae2022-10-19 14:02:40 +01001832 semsg(_(e_cant_open_file_str),
1833 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001834 return;
1835 }
1836
1837 if (blob)
1838 {
K.Takata11df3ae2022-10-19 14:02:40 +01001839 if (read_blob(fd, rettv, offset, size) == FAIL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001840 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001841 fclose(fd);
1842 return;
1843 }
1844
1845 while (cnt < maxline || maxline < 0)
1846 {
1847 readlen = (int)fread(buf, 1, io_size, fd);
1848
Bram Moolenaar26262f82019-09-04 20:59:15 +02001849 // This for loop processes what was read, but is also entered at end
1850 // of file so that either:
1851 // - an incomplete line gets written
1852 // - a "binary" file gets an empty line at the end if it ends in a
1853 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001854 for (p = buf, start = buf;
1855 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1856 ++p)
1857 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001858 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001859 {
1860 listitem_T *li;
1861 char_u *s = NULL;
1862 long_u len = p - start;
1863
Bram Moolenaar26262f82019-09-04 20:59:15 +02001864 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001865 if (readlen > 0 && !binary)
1866 {
1867 while (len > 0 && start[len - 1] == '\r')
1868 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001869 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001870 if (len == 0)
1871 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1872 --prevlen;
1873 }
1874 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001875 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001876 else
1877 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001878 // Change "prev" buffer to be the right size. This way
1879 // the bytes are only copied once, and very long lines are
1880 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001881 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1882 {
1883 mch_memmove(s + prevlen, start, len);
1884 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001885 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001886 prevlen = prevsize = 0;
1887 }
1888 }
1889 if (s == NULL)
1890 {
1891 do_outofmem_msg((long_u) prevlen + len + 1);
1892 failed = TRUE;
1893 break;
1894 }
1895
1896 if ((li = listitem_alloc()) == NULL)
1897 {
1898 vim_free(s);
1899 failed = TRUE;
1900 break;
1901 }
1902 li->li_tv.v_type = VAR_STRING;
1903 li->li_tv.v_lock = 0;
1904 li->li_tv.vval.v_string = s;
1905 list_append(rettv->vval.v_list, li);
1906
Bram Moolenaar26262f82019-09-04 20:59:15 +02001907 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001908 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1909 break;
1910 }
1911 else if (*p == NUL)
1912 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001913 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1914 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001915 else if (*p == 0xbf && enc_utf8 && !binary)
1916 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001917 // Find the two bytes before the 0xbf. If p is at buf, or buf
1918 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001919 char_u back1 = p >= buf + 1 ? p[-1]
1920 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1921 char_u back2 = p >= buf + 2 ? p[-2]
1922 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1923 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1924
1925 if (back2 == 0xef && back1 == 0xbb)
1926 {
1927 char_u *dest = p - 2;
1928
Bram Moolenaar26262f82019-09-04 20:59:15 +02001929 // Usually a BOM is at the beginning of a file, and so at
1930 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001931 if (start == dest)
1932 start = p + 1;
1933 else
1934 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001935 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001936 int adjust_prevlen = 0;
1937
1938 if (dest < buf)
1939 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001940 // must be 1 or 2
1941 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001942 dest = buf;
1943 }
1944 if (readlen > p - buf + 1)
1945 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1946 readlen -= 3 - adjust_prevlen;
1947 prevlen -= adjust_prevlen;
1948 p = dest - 1;
1949 }
1950 }
1951 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001952 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001953
1954 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1955 break;
1956 if (start < p)
1957 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001958 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001959 if (p - start + prevlen >= prevsize)
1960 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001961 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001962 char_u *newprev;
1963
Bram Moolenaar26262f82019-09-04 20:59:15 +02001964 // A common use case is ordinary text files and "prev" gets a
1965 // fragment of a line, so the first allocation is made
1966 // small, to avoid repeatedly 'allocing' large and
1967 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001968 if (prevsize == 0)
1969 prevsize = (long)(p - start);
1970 else
1971 {
1972 long grow50pc = (prevsize * 3) / 2;
1973 long growmin = (long)((p - start) * 2 + prevlen);
1974 prevsize = grow50pc > growmin ? grow50pc : growmin;
1975 }
1976 newprev = vim_realloc(prev, prevsize);
1977 if (newprev == NULL)
1978 {
1979 do_outofmem_msg((long_u)prevsize);
1980 failed = TRUE;
1981 break;
1982 }
1983 prev = newprev;
1984 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001985 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001986 mch_memmove(prev + prevlen, start, p - start);
1987 prevlen += (long)(p - start);
1988 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001989 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001990
Bram Moolenaar26262f82019-09-04 20:59:15 +02001991 // For a negative line count use only the lines at the end of the file,
1992 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001993 if (!failed && maxline < 0)
1994 while (cnt > -maxline)
1995 {
1996 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1997 --cnt;
1998 }
1999
2000 if (failed)
2001 {
2002 // an empty list is returned on error
2003 list_free(rettv->vval.v_list);
2004 rettv_list_alloc(rettv);
2005 }
2006
2007 vim_free(prev);
2008 fclose(fd);
2009}
2010
2011/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002012 * "readblob()" function
2013 */
2014 void
2015f_readblob(typval_T *argvars, typval_T *rettv)
2016{
K.Takata11df3ae2022-10-19 14:02:40 +01002017 if (in_vim9script()
2018 && (check_for_string_arg(argvars, 0) == FAIL
2019 || check_for_opt_number_arg(argvars, 1) == FAIL
2020 || (argvars[1].v_type != VAR_UNKNOWN
2021 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002022 return;
2023
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002024 read_file_or_blob(argvars, rettv, TRUE);
2025}
2026
2027/*
2028 * "readfile()" function
2029 */
2030 void
2031f_readfile(typval_T *argvars, typval_T *rettv)
2032{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002033 if (in_vim9script()
2034 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
2035 || check_for_opt_string_arg(argvars, 1) == FAIL
2036 || (argvars[1].v_type != VAR_UNKNOWN
2037 && check_for_opt_number_arg(argvars, 2) == FAIL)))
2038 return;
2039
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002040 read_file_or_blob(argvars, rettv, FALSE);
2041}
2042
2043/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002044 * "resolve()" function
2045 */
2046 void
2047f_resolve(typval_T *argvars, typval_T *rettv)
2048{
2049 char_u *p;
2050#ifdef HAVE_READLINK
2051 char_u *buf = NULL;
2052#endif
2053
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002054 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2055 return;
2056
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002057 p = tv_get_string(&argvars[0]);
2058#ifdef FEAT_SHORTCUT
2059 {
2060 char_u *v = NULL;
2061
2062 v = mch_resolve_path(p, TRUE);
2063 if (v != NULL)
2064 rettv->vval.v_string = v;
2065 else
2066 rettv->vval.v_string = vim_strsave(p);
2067 }
2068#else
2069# ifdef HAVE_READLINK
2070 {
2071 char_u *cpy;
2072 int len;
2073 char_u *remain = NULL;
2074 char_u *q;
2075 int is_relative_to_current = FALSE;
2076 int has_trailing_pathsep = FALSE;
2077 int limit = 100;
2078
2079 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002080 if (p == NULL)
2081 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002082 if (p[0] == '.' && (vim_ispathsep(p[1])
2083 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2084 is_relative_to_current = TRUE;
2085
2086 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02002087 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002088 {
2089 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002090 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002091 }
2092
2093 q = getnextcomp(p);
2094 if (*q != NUL)
2095 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002096 // Separate the first path component in "p", and keep the
2097 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002098 remain = vim_strsave(q - 1);
2099 q[-1] = NUL;
2100 }
2101
2102 buf = alloc(MAXPATHL + 1);
2103 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01002104 {
2105 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002106 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01002107 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002108
2109 for (;;)
2110 {
2111 for (;;)
2112 {
2113 len = readlink((char *)p, (char *)buf, MAXPATHL);
2114 if (len <= 0)
2115 break;
2116 buf[len] = NUL;
2117
2118 if (limit-- == 0)
2119 {
2120 vim_free(p);
2121 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002122 emsg(_(e_too_many_symbolic_links_cycle));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002123 rettv->vval.v_string = NULL;
2124 goto fail;
2125 }
2126
Bram Moolenaar26262f82019-09-04 20:59:15 +02002127 // Ensure that the result will have a trailing path separator
2128 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002129 if (remain == NULL && has_trailing_pathsep)
2130 add_pathsep(buf);
2131
Bram Moolenaar26262f82019-09-04 20:59:15 +02002132 // Separate the first path component in the link value and
2133 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002134 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2135 if (*q != NUL)
2136 {
2137 if (remain == NULL)
2138 remain = vim_strsave(q - 1);
2139 else
2140 {
2141 cpy = concat_str(q - 1, remain);
2142 if (cpy != NULL)
2143 {
2144 vim_free(remain);
2145 remain = cpy;
2146 }
2147 }
2148 q[-1] = NUL;
2149 }
2150
2151 q = gettail(p);
2152 if (q > p && *q == NUL)
2153 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002154 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002155 q[-1] = NUL;
2156 q = gettail(p);
2157 }
2158 if (q > p && !mch_isFullName(buf))
2159 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002160 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002161 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2162 if (cpy != NULL)
2163 {
2164 STRCPY(cpy, p);
2165 STRCPY(gettail(cpy), buf);
2166 vim_free(p);
2167 p = cpy;
2168 }
2169 }
2170 else
2171 {
2172 vim_free(p);
2173 p = vim_strsave(buf);
2174 }
2175 }
2176
2177 if (remain == NULL)
2178 break;
2179
Bram Moolenaar26262f82019-09-04 20:59:15 +02002180 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002181 q = getnextcomp(remain + 1);
2182 len = q - remain - (*q != NUL);
2183 cpy = vim_strnsave(p, STRLEN(p) + len);
2184 if (cpy != NULL)
2185 {
2186 STRNCAT(cpy, remain, len);
2187 vim_free(p);
2188 p = cpy;
2189 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002190 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002191 if (*q != NUL)
2192 STRMOVE(remain, q - 1);
2193 else
2194 VIM_CLEAR(remain);
2195 }
2196
Bram Moolenaar26262f82019-09-04 20:59:15 +02002197 // If the result is a relative path name, make it explicitly relative to
2198 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002199 if (!vim_ispathsep(*p))
2200 {
2201 if (is_relative_to_current
2202 && *p != NUL
2203 && !(p[0] == '.'
2204 && (p[1] == NUL
2205 || vim_ispathsep(p[1])
2206 || (p[1] == '.'
2207 && (p[2] == NUL
2208 || vim_ispathsep(p[2]))))))
2209 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002210 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002211 cpy = concat_str((char_u *)"./", p);
2212 if (cpy != NULL)
2213 {
2214 vim_free(p);
2215 p = cpy;
2216 }
2217 }
2218 else if (!is_relative_to_current)
2219 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002220 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002221 q = p;
2222 while (q[0] == '.' && vim_ispathsep(q[1]))
2223 q += 2;
2224 if (q > p)
2225 STRMOVE(p, p + 2);
2226 }
2227 }
2228
Bram Moolenaar26262f82019-09-04 20:59:15 +02002229 // Ensure that the result will have no trailing path separator
2230 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002231 if (!has_trailing_pathsep)
2232 {
2233 q = p + STRLEN(p);
2234 if (after_pathsep(p, q))
2235 *gettail_sep(p) = NUL;
2236 }
2237
2238 rettv->vval.v_string = p;
2239 }
2240# else
2241 rettv->vval.v_string = vim_strsave(p);
2242# endif
2243#endif
2244
2245 simplify_filename(rettv->vval.v_string);
2246
2247#ifdef HAVE_READLINK
2248fail:
2249 vim_free(buf);
2250#endif
2251 rettv->v_type = VAR_STRING;
2252}
2253
2254/*
2255 * "tempname()" function
2256 */
2257 void
2258f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2259{
2260 static int x = 'A';
2261
2262 rettv->v_type = VAR_STRING;
2263 rettv->vval.v_string = vim_tempname(x, FALSE);
2264
Bram Moolenaar26262f82019-09-04 20:59:15 +02002265 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2266 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002267 do
2268 {
2269 if (x == 'Z')
2270 x = '0';
2271 else if (x == '9')
2272 x = 'A';
2273 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002274 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002275 } while (x == 'I' || x == 'O');
2276}
2277
2278/*
2279 * "writefile()" function
2280 */
2281 void
2282f_writefile(typval_T *argvars, typval_T *rettv)
2283{
2284 int binary = FALSE;
2285 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002286 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002287#ifdef HAVE_FSYNC
2288 int do_fsync = p_fs;
2289#endif
2290 char_u *fname;
2291 FILE *fd;
2292 int ret = 0;
2293 listitem_T *li;
2294 list_T *list = NULL;
2295 blob_T *blob = NULL;
2296
2297 rettv->vval.v_number = -1;
2298 if (check_secure())
2299 return;
2300
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002301 if (in_vim9script()
2302 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2303 || check_for_string_arg(argvars, 1) == FAIL
2304 || check_for_opt_string_arg(argvars, 2) == FAIL))
2305 return;
2306
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002307 if (argvars[0].v_type == VAR_LIST)
2308 {
2309 list = argvars[0].vval.v_list;
2310 if (list == NULL)
2311 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002312 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002313 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002314 if (tv_get_string_chk(&li->li_tv) == NULL)
2315 return;
2316 }
2317 else if (argvars[0].v_type == VAR_BLOB)
2318 {
2319 blob = argvars[0].vval.v_blob;
2320 if (blob == NULL)
2321 return;
2322 }
2323 else
2324 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002325 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002326 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002327 return;
2328 }
2329
2330 if (argvars[2].v_type != VAR_UNKNOWN)
2331 {
2332 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2333
2334 if (arg2 == NULL)
2335 return;
2336 if (vim_strchr(arg2, 'b') != NULL)
2337 binary = TRUE;
2338 if (vim_strchr(arg2, 'a') != NULL)
2339 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002340 if (vim_strchr(arg2, 'D') != NULL)
2341 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002342#ifdef HAVE_FSYNC
2343 if (vim_strchr(arg2, 's') != NULL)
2344 do_fsync = TRUE;
2345 else if (vim_strchr(arg2, 'S') != NULL)
2346 do_fsync = FALSE;
2347#endif
2348 }
2349
2350 fname = tv_get_string_chk(&argvars[1]);
2351 if (fname == NULL)
2352 return;
2353
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002354 if (defer && !can_add_defer())
Bram Moolenaar806a2732022-09-04 15:40:36 +01002355 return;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002356
Bram Moolenaar26262f82019-09-04 20:59:15 +02002357 // Always open the file in binary mode, library functions have a mind of
2358 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002359 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2360 append ? APPENDBIN : WRITEBIN)) == NULL)
2361 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002362 semsg(_(e_cant_create_file_str),
2363 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002364 ret = -1;
2365 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002366 else
2367 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002368 if (defer)
2369 {
2370 typval_T tv;
2371
2372 tv.v_type = VAR_STRING;
2373 tv.v_lock = 0;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002374 tv.vval.v_string = FullName_save(fname, FALSE);
Bram Moolenaar806a2732022-09-04 15:40:36 +01002375 if (tv.vval.v_string == NULL
2376 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2377 {
2378 ret = -1;
2379 fclose(fd);
2380 (void)mch_remove(fname);
2381 }
2382 }
2383
2384 if (ret == 0)
2385 {
2386 if (blob)
2387 {
2388 if (write_blob(fd, blob) == FAIL)
2389 ret = -1;
2390 }
2391 else
2392 {
2393 if (write_list(fd, list, binary) == FAIL)
2394 ret = -1;
2395 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002396#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002397 if (ret == 0 && do_fsync)
2398 // Ignore the error, the user wouldn't know what to do about
2399 // it. May happen for a device.
2400 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002401#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002402 fclose(fd);
2403 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002404 }
2405
2406 rettv->vval.v_number = ret;
2407}
2408
2409#endif // FEAT_EVAL
2410
2411#if defined(FEAT_BROWSE) || defined(PROTO)
2412/*
2413 * Generic browse function. Calls gui_mch_browse() when possible.
2414 * Later this may pop-up a non-GUI file selector (external command?).
2415 */
2416 char_u *
2417do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002418 int flags, // BROWSE_SAVE and BROWSE_DIR
2419 char_u *title, // title for the window
2420 char_u *dflt, // default file name (may include directory)
2421 char_u *ext, // extension added
2422 char_u *initdir, // initial directory, NULL for current dir or
2423 // when using path from "dflt"
2424 char_u *filter, // file name filter
2425 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002426{
2427 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002428 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002429 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002430 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002431
Bram Moolenaar26262f82019-09-04 20:59:15 +02002432 // Must turn off browse to avoid that autocommands will get the
2433 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002434 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002435
2436 if (title == NULL || *title == NUL)
2437 {
2438 if (flags & BROWSE_DIR)
2439 title = (char_u *)_("Select Directory dialog");
2440 else if (flags & BROWSE_SAVE)
2441 title = (char_u *)_("Save File dialog");
2442 else
2443 title = (char_u *)_("Open File dialog");
2444 }
2445
Bram Moolenaar26262f82019-09-04 20:59:15 +02002446 // When no directory specified, use default file name, default dir, buffer
2447 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002448 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2449 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002450 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002451 {
2452 initdir = dflt;
2453 dflt = NULL;
2454 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002455 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002456 {
2457 tofree = vim_strsave(dflt);
2458 if (tofree != NULL)
2459 {
2460 initdir = tofree;
2461 *gettail(initdir) = NUL;
2462 dflt = gettail(dflt);
2463 }
2464 }
2465 }
2466
2467 if (initdir == NULL || *initdir == NUL)
2468 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002469 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002470 if (STRCMP(p_bsdir, "last") != 0
2471 && STRCMP(p_bsdir, "buffer") != 0
2472 && STRCMP(p_bsdir, "current") != 0
2473 && mch_isdir(p_bsdir))
2474 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002475 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002476 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2477 && buf != NULL && buf->b_ffname != NULL)
2478 {
2479 if (dflt == NULL || *dflt == NUL)
2480 dflt = gettail(curbuf->b_ffname);
2481 tofree = vim_strsave(curbuf->b_ffname);
2482 if (tofree != NULL)
2483 {
2484 initdir = tofree;
2485 *gettail(initdir) = NUL;
2486 }
2487 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002488 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002489 else if (*p_bsdir == 'l')
2490 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002491 // When 'browsedir is "current", use current directory. This is the
2492 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002493 }
2494
2495# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002496 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002497 {
2498 if (filter == NULL
2499# ifdef FEAT_EVAL
2500 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2501 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2502# endif
2503 )
2504 filter = BROWSE_FILTER_DEFAULT;
2505 if (flags & BROWSE_DIR)
2506 {
2507# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002508 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002509 fname = gui_mch_browsedir(title, initdir);
2510# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002511 // Generic solution for selecting a directory: select a file and
2512 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002513 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2514# endif
2515# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002516 // Win32 adds a dummy file name, others return an arbitrary file
2517 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002518 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2519 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002520 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002521 char_u *tail = gettail_sep(fname);
2522
2523 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002524 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002525 *tail = NUL;
2526 }
2527# endif
2528 }
2529 else
2530 fname = gui_mch_browse(flags & BROWSE_SAVE,
2531 title, dflt, ext, initdir, (char_u *)_(filter));
2532
Bram Moolenaar26262f82019-09-04 20:59:15 +02002533 // We hang around in the dialog for a while, the user might do some
2534 // things to our files. The Win32 dialog allows deleting or renaming
2535 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002536 need_check_timestamps = TRUE;
2537 did_check_timestamps = FALSE;
2538 }
2539 else
2540# endif
2541 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002542 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002543 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002544 fname = NULL;
2545 }
2546
Bram Moolenaar26262f82019-09-04 20:59:15 +02002547 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002548 if (fname != NULL)
2549 {
2550 vim_free(last_dir);
2551 last_dir = vim_strsave(fname);
2552 if (last_dir != NULL && !(flags & BROWSE_DIR))
2553 {
2554 *gettail(last_dir) = NUL;
2555 if (*last_dir == NUL)
2556 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002557 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002558 vim_free(last_dir);
2559 last_dir = alloc(MAXPATHL);
2560 if (last_dir != NULL)
2561 mch_dirname(last_dir, MAXPATHL);
2562 }
2563 }
2564 }
2565
2566 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002567 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002568
2569 return fname;
2570}
2571#endif
2572
2573#if defined(FEAT_EVAL) || defined(PROTO)
2574
2575/*
2576 * "browse(save, title, initdir, default)" function
2577 */
2578 void
2579f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2580{
2581# ifdef FEAT_BROWSE
2582 int save;
2583 char_u *title;
2584 char_u *initdir;
2585 char_u *defname;
2586 char_u buf[NUMBUFLEN];
2587 char_u buf2[NUMBUFLEN];
2588 int error = FALSE;
2589
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002590 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002591 && (check_for_bool_arg(argvars, 0) == FAIL
2592 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002593 || check_for_string_arg(argvars, 2) == FAIL
2594 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002595 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002596
Bram Moolenaar5a049842022-10-08 12:52:09 +01002597 save = (int)tv_get_bool_chk(&argvars[0], &error);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002598 title = tv_get_string_chk(&argvars[1]);
2599 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2600 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2601
2602 if (error || title == NULL || initdir == NULL || defname == NULL)
2603 rettv->vval.v_string = NULL;
2604 else
2605 rettv->vval.v_string =
2606 do_browse(save ? BROWSE_SAVE : 0,
2607 title, defname, NULL, initdir, NULL, curbuf);
2608# else
2609 rettv->vval.v_string = NULL;
2610# endif
2611 rettv->v_type = VAR_STRING;
2612}
2613
2614/*
2615 * "browsedir(title, initdir)" function
2616 */
2617 void
2618f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2619{
2620# ifdef FEAT_BROWSE
2621 char_u *title;
2622 char_u *initdir;
2623 char_u buf[NUMBUFLEN];
2624
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002625 if (in_vim9script()
2626 && (check_for_string_arg(argvars, 0) == FAIL
2627 || check_for_string_arg(argvars, 1) == FAIL))
2628 return;
2629
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002630 title = tv_get_string_chk(&argvars[0]);
2631 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2632
2633 if (title == NULL || initdir == NULL)
2634 rettv->vval.v_string = NULL;
2635 else
2636 rettv->vval.v_string = do_browse(BROWSE_DIR,
2637 title, NULL, NULL, initdir, NULL, curbuf);
2638# else
2639 rettv->vval.v_string = NULL;
2640# endif
2641 rettv->v_type = VAR_STRING;
2642}
2643
2644#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002645
2646/*
2647 * Replace home directory by "~" in each space or comma separated file name in
2648 * 'src'.
2649 * If anything fails (except when out of space) dst equals src.
2650 */
2651 void
2652home_replace(
2653 buf_T *buf, // when not NULL, check for help files
2654 char_u *src, // input file name
2655 char_u *dst, // where to put the result
2656 int dstlen, // maximum length of the result
2657 int one) // if TRUE, only replace one file name, include
2658 // spaces and commas in the file name.
2659{
2660 size_t dirlen = 0, envlen = 0;
2661 size_t len;
2662 char_u *homedir_env, *homedir_env_orig;
2663 char_u *p;
2664
2665 if (src == NULL)
2666 {
2667 *dst = NUL;
2668 return;
2669 }
2670
2671 /*
2672 * If the file is a help file, remove the path completely.
2673 */
2674 if (buf != NULL && buf->b_help)
2675 {
2676 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2677 return;
2678 }
2679
2680 /*
2681 * We check both the value of the $HOME environment variable and the
2682 * "real" home directory.
2683 */
2684 if (homedir != NULL)
2685 dirlen = STRLEN(homedir);
2686
2687#ifdef VMS
2688 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2689#else
2690 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2691#endif
2692#ifdef MSWIN
2693 if (homedir_env == NULL)
2694 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2695#endif
2696 // Empty is the same as not set.
2697 if (homedir_env != NULL && *homedir_env == NUL)
2698 homedir_env = NULL;
2699
2700 if (homedir_env != NULL && *homedir_env == '~')
2701 {
2702 int usedlen = 0;
2703 int flen;
2704 char_u *fbuf = NULL;
2705
2706 flen = (int)STRLEN(homedir_env);
2707 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2708 &homedir_env, &fbuf, &flen);
2709 flen = (int)STRLEN(homedir_env);
2710 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2711 // Remove the trailing / that is added to a directory.
2712 homedir_env[flen - 1] = NUL;
2713 }
2714
2715 if (homedir_env != NULL)
2716 envlen = STRLEN(homedir_env);
2717
2718 if (!one)
2719 src = skipwhite(src);
2720 while (*src && dstlen > 0)
2721 {
2722 /*
2723 * Here we are at the beginning of a file name.
2724 * First, check to see if the beginning of the file name matches
2725 * $HOME or the "real" home directory. Check that there is a '/'
2726 * after the match (so that if e.g. the file is "/home/pieter/bla",
2727 * and the home directory is "/home/piet", the file does not end up
2728 * as "~er/bla" (which would seem to indicate the file "bla" in user
2729 * er's home directory)).
2730 */
2731 p = homedir;
2732 len = dirlen;
2733 for (;;)
2734 {
2735 if ( len
2736 && fnamencmp(src, p, len) == 0
2737 && (vim_ispathsep(src[len])
2738 || (!one && (src[len] == ',' || src[len] == ' '))
2739 || src[len] == NUL))
2740 {
2741 src += len;
2742 if (--dstlen > 0)
2743 *dst++ = '~';
2744
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002745 // Do not add directory separator into dst, because dst is
2746 // expected to just return the directory name without the
2747 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002748 break;
2749 }
2750 if (p == homedir_env)
2751 break;
2752 p = homedir_env;
2753 len = envlen;
2754 }
2755
2756 // if (!one) skip to separator: space or comma
2757 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2758 *dst++ = *src++;
2759 // skip separator
2760 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2761 *dst++ = *src++;
2762 }
2763 // if (dstlen == 0) out of space, what to do???
2764
2765 *dst = NUL;
2766
2767 if (homedir_env != homedir_env_orig)
2768 vim_free(homedir_env);
2769}
2770
2771/*
2772 * Like home_replace, store the replaced string in allocated memory.
2773 * When something fails, NULL is returned.
2774 */
2775 char_u *
2776home_replace_save(
2777 buf_T *buf, // when not NULL, check for help files
2778 char_u *src) // input file name
2779{
2780 char_u *dst;
2781 unsigned len;
2782
2783 len = 3; // space for "~/" and trailing NUL
2784 if (src != NULL) // just in case
2785 len += (unsigned)STRLEN(src);
2786 dst = alloc(len);
2787 if (dst != NULL)
2788 home_replace(buf, src, dst, len, TRUE);
2789 return dst;
2790}
2791
2792/*
2793 * Compare two file names and return:
2794 * FPC_SAME if they both exist and are the same file.
2795 * FPC_SAMEX if they both don't exist and have the same file name.
2796 * FPC_DIFF if they both exist and are different files.
2797 * FPC_NOTX if they both don't exist.
2798 * FPC_DIFFX if one of them doesn't exist.
2799 * For the first name environment variables are expanded if "expandenv" is
2800 * TRUE.
2801 */
2802 int
2803fullpathcmp(
2804 char_u *s1,
2805 char_u *s2,
2806 int checkname, // when both don't exist, check file names
2807 int expandenv)
2808{
2809#ifdef UNIX
2810 char_u exp1[MAXPATHL];
2811 char_u full1[MAXPATHL];
2812 char_u full2[MAXPATHL];
2813 stat_T st1, st2;
2814 int r1, r2;
2815
2816 if (expandenv)
2817 expand_env(s1, exp1, MAXPATHL);
2818 else
2819 vim_strncpy(exp1, s1, MAXPATHL - 1);
2820 r1 = mch_stat((char *)exp1, &st1);
2821 r2 = mch_stat((char *)s2, &st2);
2822 if (r1 != 0 && r2 != 0)
2823 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002824 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002825 if (checkname)
2826 {
2827 if (fnamecmp(exp1, s2) == 0)
2828 return FPC_SAMEX;
2829 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2830 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2831 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2832 return FPC_SAMEX;
2833 }
2834 return FPC_NOTX;
2835 }
2836 if (r1 != 0 || r2 != 0)
2837 return FPC_DIFFX;
2838 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2839 return FPC_SAME;
2840 return FPC_DIFF;
2841#else
2842 char_u *exp1; // expanded s1
2843 char_u *full1; // full path of s1
2844 char_u *full2; // full path of s2
2845 int retval = FPC_DIFF;
2846 int r1, r2;
2847
2848 // allocate one buffer to store three paths (alloc()/free() is slow!)
2849 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2850 {
2851 full1 = exp1 + MAXPATHL;
2852 full2 = full1 + MAXPATHL;
2853
2854 if (expandenv)
2855 expand_env(s1, exp1, MAXPATHL);
2856 else
2857 vim_strncpy(exp1, s1, MAXPATHL - 1);
2858 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2859 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2860
2861 // If vim_FullName() fails, the file probably doesn't exist.
2862 if (r1 != OK && r2 != OK)
2863 {
2864 if (checkname && fnamecmp(exp1, s2) == 0)
2865 retval = FPC_SAMEX;
2866 else
2867 retval = FPC_NOTX;
2868 }
2869 else if (r1 != OK || r2 != OK)
2870 retval = FPC_DIFFX;
2871 else if (fnamecmp(full1, full2))
2872 retval = FPC_DIFF;
2873 else
2874 retval = FPC_SAME;
2875 vim_free(exp1);
2876 }
2877 return retval;
2878#endif
2879}
2880
2881/*
2882 * Get the tail of a path: the file name.
2883 * When the path ends in a path separator the tail is the NUL after it.
2884 * Fail safe: never returns NULL.
2885 */
2886 char_u *
2887gettail(char_u *fname)
2888{
2889 char_u *p1, *p2;
2890
2891 if (fname == NULL)
2892 return (char_u *)"";
2893 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2894 {
2895 if (vim_ispathsep_nocolon(*p2))
2896 p1 = p2 + 1;
2897 MB_PTR_ADV(p2);
2898 }
2899 return p1;
2900}
2901
2902/*
2903 * Get pointer to tail of "fname", including path separators. Putting a NUL
2904 * here leaves the directory name. Takes care of "c:/" and "//".
2905 * Always returns a valid pointer.
2906 */
2907 char_u *
2908gettail_sep(char_u *fname)
2909{
2910 char_u *p;
2911 char_u *t;
2912
2913 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2914 t = gettail(fname);
2915 while (t > p && after_pathsep(fname, t))
2916 --t;
2917#ifdef VMS
2918 // path separator is part of the path
2919 ++t;
2920#endif
2921 return t;
2922}
2923
2924/*
2925 * get the next path component (just after the next path separator).
2926 */
2927 char_u *
2928getnextcomp(char_u *fname)
2929{
2930 while (*fname && !vim_ispathsep(*fname))
2931 MB_PTR_ADV(fname);
2932 if (*fname)
2933 ++fname;
2934 return fname;
2935}
2936
2937/*
2938 * Get a pointer to one character past the head of a path name.
2939 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2940 * If there is no head, path is returned.
2941 */
2942 char_u *
2943get_past_head(char_u *path)
2944{
2945 char_u *retval;
2946
2947#if defined(MSWIN)
2948 // may skip "c:"
2949 if (isalpha(path[0]) && path[1] == ':')
2950 retval = path + 2;
2951 else
2952 retval = path;
2953#else
2954# if defined(AMIGA)
2955 // may skip "label:"
2956 retval = vim_strchr(path, ':');
2957 if (retval == NULL)
2958 retval = path;
2959# else // Unix
2960 retval = path;
2961# endif
2962#endif
2963
2964 while (vim_ispathsep(*retval))
2965 ++retval;
2966
2967 return retval;
2968}
2969
2970/*
2971 * Return TRUE if 'c' is a path separator.
2972 * Note that for MS-Windows this includes the colon.
2973 */
2974 int
2975vim_ispathsep(int c)
2976{
2977#ifdef UNIX
2978 return (c == '/'); // UNIX has ':' inside file names
2979#else
2980# ifdef BACKSLASH_IN_FILENAME
2981 return (c == ':' || c == '/' || c == '\\');
2982# else
2983# ifdef VMS
2984 // server"user passwd"::device:[full.path.name]fname.extension;version"
2985 return (c == ':' || c == '[' || c == ']' || c == '/'
2986 || c == '<' || c == '>' || c == '"' );
2987# else
2988 return (c == ':' || c == '/');
2989# endif // VMS
2990# endif
2991#endif
2992}
2993
2994/*
2995 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2996 */
2997 int
2998vim_ispathsep_nocolon(int c)
2999{
3000 return vim_ispathsep(c)
3001#ifdef BACKSLASH_IN_FILENAME
3002 && c != ':'
3003#endif
3004 ;
3005}
3006
3007/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02003008 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
3009 * Also returns TRUE if there is no directory name.
3010 * "fname" must be writable!.
3011 */
3012 int
3013dir_of_file_exists(char_u *fname)
3014{
3015 char_u *p;
3016 int c;
3017 int retval;
3018
3019 p = gettail_sep(fname);
3020 if (p == fname)
3021 return TRUE;
3022 c = *p;
3023 *p = NUL;
3024 retval = mch_isdir(fname);
3025 *p = c;
3026 return retval;
3027}
3028
3029/*
3030 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
3031 * and deal with 'fileignorecase'.
3032 */
3033 int
3034vim_fnamecmp(char_u *x, char_u *y)
3035{
3036#ifdef BACKSLASH_IN_FILENAME
3037 return vim_fnamencmp(x, y, MAXPATHL);
3038#else
3039 if (p_fic)
3040 return MB_STRICMP(x, y);
3041 return STRCMP(x, y);
3042#endif
3043}
3044
3045 int
3046vim_fnamencmp(char_u *x, char_u *y, size_t len)
3047{
3048#ifdef BACKSLASH_IN_FILENAME
3049 char_u *px = x;
3050 char_u *py = y;
3051 int cx = NUL;
3052 int cy = NUL;
3053
3054 while (len > 0)
3055 {
3056 cx = PTR2CHAR(px);
3057 cy = PTR2CHAR(py);
3058 if (cx == NUL || cy == NUL
3059 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3060 && !(cx == '/' && cy == '\\')
3061 && !(cx == '\\' && cy == '/')))
3062 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003063 len -= mb_ptr2len(px);
3064 px += mb_ptr2len(px);
3065 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003066 }
3067 if (len == 0)
3068 return 0;
3069 return (cx - cy);
3070#else
3071 if (p_fic)
3072 return MB_STRNICMP(x, y, len);
3073 return STRNCMP(x, y, len);
3074#endif
3075}
3076
3077/*
3078 * Concatenate file names fname1 and fname2 into allocated memory.
3079 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3080 */
3081 char_u *
3082concat_fnames(char_u *fname1, char_u *fname2, int sep)
3083{
3084 char_u *dest;
3085
3086 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003087 if (dest == NULL)
3088 return NULL;
3089
3090 STRCPY(dest, fname1);
3091 if (sep)
3092 add_pathsep(dest);
3093 STRCAT(dest, fname2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003094 return dest;
3095}
3096
3097/*
3098 * Add a path separator to a file name, unless it already ends in a path
3099 * separator.
3100 */
3101 void
3102add_pathsep(char_u *p)
3103{
3104 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3105 STRCAT(p, PATHSEPSTR);
3106}
3107
3108/*
3109 * FullName_save - Make an allocated copy of a full file name.
3110 * Returns NULL when out of memory.
3111 */
3112 char_u *
3113FullName_save(
3114 char_u *fname,
3115 int force) // force expansion, even when it already looks
3116 // like a full path name
3117{
3118 char_u *buf;
3119 char_u *new_fname = NULL;
3120
3121 if (fname == NULL)
3122 return NULL;
3123
3124 buf = alloc(MAXPATHL);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003125 if (buf == NULL)
3126 return NULL;
3127
3128 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3129 new_fname = vim_strsave(buf);
3130 else
3131 new_fname = vim_strsave(fname);
3132 vim_free(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003133 return new_fname;
3134}
3135
3136/*
3137 * return TRUE if "fname" exists.
3138 */
3139 int
3140vim_fexists(char_u *fname)
3141{
3142 stat_T st;
3143
3144 if (mch_stat((char *)fname, &st))
3145 return FALSE;
3146 return TRUE;
3147}
3148
3149/*
3150 * Invoke expand_wildcards() for one pattern.
3151 * Expand items like "%:h" before the expansion.
3152 * Returns OK or FAIL.
3153 */
3154 int
3155expand_wildcards_eval(
3156 char_u **pat, // pointer to input pattern
3157 int *num_file, // resulting number of files
3158 char_u ***file, // array of resulting files
3159 int flags) // EW_DIR, etc.
3160{
3161 int ret = FAIL;
3162 char_u *eval_pat = NULL;
3163 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003164 char *ignored_msg;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003165 int usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003166 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3167 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003168
Bram Moolenaarf5724372022-09-02 19:45:15 +01003169 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003170 {
3171 ++emsg_off;
3172 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003173 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003174 --emsg_off;
3175 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003176 {
3177 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003178 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003179 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003180 }
3181
3182 if (exp_pat != NULL)
3183 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3184
3185 if (eval_pat != NULL)
3186 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003187 if (*num_file == 0 && is_cur_alt_file && star_follows)
3188 {
3189 // Expanding "%" or "#" and the file does not exist: Add the
3190 // pattern anyway (without the star) so that this works for remote
3191 // files and non-file buffer names.
3192 *file = ALLOC_ONE(char_u *);
3193 if (*file != NULL)
3194 {
3195 **file = eval_pat;
3196 eval_pat = NULL;
3197 *num_file = 1;
3198 ret = OK;
3199 }
3200 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003201 vim_free(exp_pat);
3202 vim_free(eval_pat);
3203 }
3204
3205 return ret;
3206}
3207
3208/*
3209 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3210 * 'wildignore'.
3211 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3212 */
3213 int
3214expand_wildcards(
3215 int num_pat, // number of input patterns
3216 char_u **pat, // array of input patterns
3217 int *num_files, // resulting number of files
3218 char_u ***files, // array of resulting files
3219 int flags) // EW_DIR, etc.
3220{
3221 int retval;
3222 int i, j;
3223 char_u *p;
3224 int non_suf_match; // number without matching suffix
3225
3226 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3227
3228 // When keeping all matches, return here
3229 if ((flags & EW_KEEPALL) || retval == FAIL)
3230 return retval;
3231
Bram Moolenaar26262f82019-09-04 20:59:15 +02003232 /*
3233 * Remove names that match 'wildignore'.
3234 */
3235 if (*p_wig)
3236 {
3237 char_u *ffname;
3238
3239 // check all files in (*files)[]
3240 for (i = 0; i < *num_files; ++i)
3241 {
3242 ffname = FullName_save((*files)[i], FALSE);
3243 if (ffname == NULL) // out of memory
3244 break;
3245# ifdef VMS
3246 vms_remove_version(ffname);
3247# endif
3248 if (match_file_list(p_wig, (*files)[i], ffname))
3249 {
3250 // remove this matching file from the list
3251 vim_free((*files)[i]);
3252 for (j = i; j + 1 < *num_files; ++j)
3253 (*files)[j] = (*files)[j + 1];
3254 --*num_files;
3255 --i;
3256 }
3257 vim_free(ffname);
3258 }
3259
3260 // If the number of matches is now zero, we fail.
3261 if (*num_files == 0)
3262 {
3263 VIM_CLEAR(*files);
3264 return FAIL;
3265 }
3266 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003267
3268 /*
3269 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003270 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003271 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003272 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003273 {
3274 non_suf_match = 0;
3275 for (i = 0; i < *num_files; ++i)
3276 {
3277 if (!match_suffix((*files)[i]))
3278 {
3279 /*
3280 * Move the name without matching suffix to the front
3281 * of the list.
3282 */
3283 p = (*files)[i];
3284 for (j = i; j > non_suf_match; --j)
3285 (*files)[j] = (*files)[j - 1];
3286 (*files)[non_suf_match++] = p;
3287 }
3288 }
3289 }
3290
3291 return retval;
3292}
3293
3294/*
3295 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3296 */
3297 int
3298match_suffix(char_u *fname)
3299{
3300 int fnamelen, setsuflen;
3301 char_u *setsuf;
3302#define MAXSUFLEN 30 // maximum length of a file suffix
3303 char_u suf_buf[MAXSUFLEN];
3304
3305 fnamelen = (int)STRLEN(fname);
3306 setsuflen = 0;
3307 for (setsuf = p_su; *setsuf; )
3308 {
3309 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3310 if (setsuflen == 0)
3311 {
3312 char_u *tail = gettail(fname);
3313
3314 // empty entry: match name without a '.'
3315 if (vim_strchr(tail, '.') == NULL)
3316 {
3317 setsuflen = 1;
3318 break;
3319 }
3320 }
3321 else
3322 {
3323 if (fnamelen >= setsuflen
3324 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3325 (size_t)setsuflen) == 0)
3326 break;
3327 setsuflen = 0;
3328 }
3329 }
3330 return (setsuflen != 0);
3331}
3332
3333#ifdef VIM_BACKTICK
3334
3335/*
3336 * Return TRUE if we can expand this backtick thing here.
3337 */
3338 static int
3339vim_backtick(char_u *p)
3340{
3341 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3342}
3343
3344/*
3345 * Expand an item in `backticks` by executing it as a command.
3346 * Currently only works when pat[] starts and ends with a `.
3347 * Returns number of file names found, -1 if an error is encountered.
3348 */
3349 static int
3350expand_backtick(
3351 garray_T *gap,
3352 char_u *pat,
3353 int flags) // EW_* flags
3354{
3355 char_u *p;
3356 char_u *cmd;
3357 char_u *buffer;
3358 int cnt = 0;
3359 int i;
3360
3361 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003362 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003363 if (cmd == NULL)
3364 return -1;
3365
3366#ifdef FEAT_EVAL
3367 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaara4e0b972022-10-01 19:43:52 +01003368 buffer = eval_to_string(cmd + 1, TRUE, FALSE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003369 else
3370#endif
3371 buffer = get_cmd_output(cmd, NULL,
3372 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3373 vim_free(cmd);
3374 if (buffer == NULL)
3375 return -1;
3376
3377 cmd = buffer;
3378 while (*cmd != NUL)
3379 {
3380 cmd = skipwhite(cmd); // skip over white space
3381 p = cmd;
3382 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3383 ++p;
3384 // add an entry if it is not empty
3385 if (p > cmd)
3386 {
3387 i = *p;
3388 *p = NUL;
3389 addfile(gap, cmd, flags);
3390 *p = i;
3391 ++cnt;
3392 }
3393 cmd = p;
3394 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3395 ++cmd;
3396 }
3397
3398 vim_free(buffer);
3399 return cnt;
3400}
3401#endif // VIM_BACKTICK
3402
3403#if defined(MSWIN)
3404/*
3405 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3406 * it's shared between these systems.
3407 */
3408
3409/*
3410 * comparison function for qsort in dos_expandpath()
3411 */
3412 static int
3413pstrcmp(const void *a, const void *b)
3414{
3415 return (pathcmp(*(char **)a, *(char **)b, -1));
3416}
3417
3418/*
3419 * Recursively expand one path component into all matching files and/or
3420 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3421 * Return the number of matches found.
3422 * "path" has backslashes before chars that are not to be expanded, starting
3423 * at "path[wildoff]".
3424 * Return the number of matches found.
3425 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3426 */
3427 static int
3428dos_expandpath(
3429 garray_T *gap,
3430 char_u *path,
3431 int wildoff,
3432 int flags, // EW_* flags
3433 int didstar) // expanded "**" once already
3434{
3435 char_u *buf;
3436 char_u *path_end;
3437 char_u *p, *s, *e;
3438 int start_len = gap->ga_len;
3439 char_u *pat;
3440 regmatch_T regmatch;
3441 int starts_with_dot;
3442 int matches;
3443 int len;
3444 int starstar = FALSE;
3445 static int stardepth = 0; // depth for "**" expansion
3446 HANDLE hFind = INVALID_HANDLE_VALUE;
3447 WIN32_FIND_DATAW wfb;
3448 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3449 char_u *matchname;
3450 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003451 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003452
3453 // Expanding "**" may take a long time, check for CTRL-C.
3454 if (stardepth > 0)
3455 {
3456 ui_breakcheck();
3457 if (got_int)
3458 return 0;
3459 }
3460
3461 // Make room for file name. When doing encoding conversion the actual
3462 // length may be quite a bit longer, thus use the maximum possible length.
3463 buf = alloc(MAXPATHL);
3464 if (buf == NULL)
3465 return 0;
3466
3467 /*
3468 * Find the first part in the path name that contains a wildcard or a ~1.
3469 * Copy it into buf, including the preceding characters.
3470 */
3471 p = buf;
3472 s = buf;
3473 e = NULL;
3474 path_end = path;
3475 while (*path_end != NUL)
3476 {
3477 // May ignore a wildcard that has a backslash before it; it will
3478 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3479 if (path_end >= path + wildoff && rem_backslash(path_end))
3480 *p++ = *path_end++;
3481 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3482 {
3483 if (e != NULL)
3484 break;
3485 s = p + 1;
3486 }
3487 else if (path_end >= path + wildoff
3488 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3489 e = p;
3490 if (has_mbyte)
3491 {
3492 len = (*mb_ptr2len)(path_end);
3493 STRNCPY(p, path_end, len);
3494 p += len;
3495 path_end += len;
3496 }
3497 else
3498 *p++ = *path_end++;
3499 }
3500 e = p;
3501 *e = NUL;
3502
3503 // now we have one wildcard component between s and e
3504 // Remove backslashes between "wildoff" and the start of the wildcard
3505 // component.
3506 for (p = buf + wildoff; p < s; ++p)
3507 if (rem_backslash(p))
3508 {
3509 STRMOVE(p, p + 1);
3510 --e;
3511 --s;
3512 }
3513
3514 // Check for "**" between "s" and "e".
3515 for (p = s; p < e; ++p)
3516 if (p[0] == '*' && p[1] == '*')
3517 starstar = TRUE;
3518
3519 starts_with_dot = *s == '.';
3520 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3521 if (pat == NULL)
3522 {
3523 vim_free(buf);
3524 return 0;
3525 }
3526
3527 // compile the regexp into a program
3528 if (flags & (EW_NOERROR | EW_NOTWILD))
3529 ++emsg_silent;
3530 regmatch.rm_ic = TRUE; // Always ignore case
3531 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3532 if (flags & (EW_NOERROR | EW_NOTWILD))
3533 --emsg_silent;
3534 vim_free(pat);
3535
3536 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3537 {
3538 vim_free(buf);
3539 return 0;
3540 }
3541
3542 // remember the pattern or file name being looked for
3543 matchname = vim_strsave(s);
3544
3545 // If "**" is by itself, this is the first time we encounter it and more
3546 // is following then find matches without any directory.
3547 if (!didstar && stardepth < 100 && starstar && e - s == 2
3548 && *path_end == '/')
3549 {
3550 STRCPY(s, path_end + 1);
3551 ++stardepth;
3552 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3553 --stardepth;
3554 }
3555
3556 // Scan all files in the directory with "dir/ *.*"
3557 STRCPY(s, "*.*");
3558 wn = enc_to_utf16(buf, NULL);
3559 if (wn != NULL)
3560 hFind = FindFirstFileW(wn, &wfb);
3561 ok = (hFind != INVALID_HANDLE_VALUE);
3562
3563 while (ok)
3564 {
3565 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003566
Bram Moolenaar26262f82019-09-04 20:59:15 +02003567 if (p == NULL)
3568 break; // out of memory
3569
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003570 // Do not use the alternate filename when the file name ends in '~',
3571 // because it picks up backup files: short name for "foo.vim~" is
3572 // "foo~1.vim", which matches "*.vim".
3573 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003574 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003575 else
3576 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3577
Bram Moolenaar26262f82019-09-04 20:59:15 +02003578 // Ignore entries starting with a dot, unless when asked for. Accept
3579 // all entries found with "matchname".
3580 if ((p[0] != '.' || starts_with_dot
3581 || ((flags & EW_DODOT)
3582 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3583 && (matchname == NULL
3584 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003585 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003586 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003587 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003588 || ((flags & EW_NOTWILD)
3589 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3590 {
3591 STRCPY(s, p);
3592 len = (int)STRLEN(buf);
3593
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003594 if (starstar && stardepth < 100
3595 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003596 {
3597 // For "**" in the pattern first go deeper in the tree to
3598 // find matches.
3599 STRCPY(buf + len, "/**");
3600 STRCPY(buf + len + 3, path_end);
3601 ++stardepth;
3602 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3603 --stardepth;
3604 }
3605
3606 STRCPY(buf + len, path_end);
3607 if (mch_has_exp_wildcard(path_end))
3608 {
3609 // need to expand another component of the path
3610 // remove backslashes for the remaining components only
3611 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3612 }
3613 else
3614 {
3615 // no more wildcards, check if there is a match
3616 // remove backslashes for the remaining components only
3617 if (*path_end != 0)
3618 backslash_halve(buf + len + 1);
3619 if (mch_getperm(buf) >= 0) // add existing file
3620 addfile(gap, buf, flags);
3621 }
3622 }
3623
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003624 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003625 vim_free(p);
3626 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003627 }
3628
3629 FindClose(hFind);
3630 vim_free(wn);
3631 vim_free(buf);
3632 vim_regfree(regmatch.regprog);
3633 vim_free(matchname);
3634
3635 matches = gap->ga_len - start_len;
3636 if (matches > 0)
3637 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3638 sizeof(char_u *), pstrcmp);
3639 return matches;
3640}
3641
3642 int
3643mch_expandpath(
3644 garray_T *gap,
3645 char_u *path,
3646 int flags) // EW_* flags
3647{
3648 return dos_expandpath(gap, path, 0, flags, FALSE);
3649}
3650#endif // MSWIN
3651
3652#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3653 || defined(PROTO)
3654/*
3655 * Unix style wildcard expansion code.
3656 * It's here because it's used both for Unix and Mac.
3657 */
3658 static int
3659pstrcmp(const void *a, const void *b)
3660{
3661 return (pathcmp(*(char **)a, *(char **)b, -1));
3662}
3663
3664/*
3665 * Recursively expand one path component into all matching files and/or
3666 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3667 * "path" has backslashes before chars that are not to be expanded, starting
3668 * at "path + wildoff".
3669 * Return the number of matches found.
3670 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3671 */
3672 int
3673unix_expandpath(
3674 garray_T *gap,
3675 char_u *path,
3676 int wildoff,
3677 int flags, // EW_* flags
3678 int didstar) // expanded "**" once already
3679{
3680 char_u *buf;
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003681 size_t buflen;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003682 char_u *path_end;
3683 char_u *p, *s, *e;
3684 int start_len = gap->ga_len;
3685 char_u *pat;
3686 regmatch_T regmatch;
3687 int starts_with_dot;
3688 int matches;
3689 int len;
3690 int starstar = FALSE;
3691 static int stardepth = 0; // depth for "**" expansion
3692
3693 DIR *dirp;
3694 struct dirent *dp;
3695
3696 // Expanding "**" may take a long time, check for CTRL-C.
3697 if (stardepth > 0)
3698 {
3699 ui_breakcheck();
3700 if (got_int)
3701 return 0;
3702 }
3703
3704 // make room for file name
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003705 buflen = STRLEN(path) + BASENAMELEN + 5;
3706 buf = alloc(buflen);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003707 if (buf == NULL)
3708 return 0;
3709
3710 /*
3711 * Find the first part in the path name that contains a wildcard.
3712 * When EW_ICASE is set every letter is considered to be a wildcard.
3713 * Copy it into "buf", including the preceding characters.
3714 */
3715 p = buf;
3716 s = buf;
3717 e = NULL;
3718 path_end = path;
3719 while (*path_end != NUL)
3720 {
3721 // May ignore a wildcard that has a backslash before it; it will
3722 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3723 if (path_end >= path + wildoff && rem_backslash(path_end))
3724 *p++ = *path_end++;
3725 else if (*path_end == '/')
3726 {
3727 if (e != NULL)
3728 break;
3729 s = p + 1;
3730 }
3731 else if (path_end >= path + wildoff
3732 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3733 || (!p_fic && (flags & EW_ICASE)
Bram Moolenaar5921aeb2022-02-19 11:20:12 +00003734 && vim_isalpha(PTR2CHAR(path_end)))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003735 e = p;
3736 if (has_mbyte)
3737 {
3738 len = (*mb_ptr2len)(path_end);
3739 STRNCPY(p, path_end, len);
3740 p += len;
3741 path_end += len;
3742 }
3743 else
3744 *p++ = *path_end++;
3745 }
3746 e = p;
3747 *e = NUL;
3748
3749 // Now we have one wildcard component between "s" and "e".
3750 // Remove backslashes between "wildoff" and the start of the wildcard
3751 // component.
3752 for (p = buf + wildoff; p < s; ++p)
3753 if (rem_backslash(p))
3754 {
3755 STRMOVE(p, p + 1);
3756 --e;
3757 --s;
3758 }
3759
3760 // Check for "**" between "s" and "e".
3761 for (p = s; p < e; ++p)
3762 if (p[0] == '*' && p[1] == '*')
3763 starstar = TRUE;
3764
3765 // convert the file pattern to a regexp pattern
3766 starts_with_dot = *s == '.';
3767 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3768 if (pat == NULL)
3769 {
3770 vim_free(buf);
3771 return 0;
3772 }
3773
3774 // compile the regexp into a program
3775 if (flags & EW_ICASE)
3776 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3777 else
3778 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3779 if (flags & (EW_NOERROR | EW_NOTWILD))
3780 ++emsg_silent;
3781 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3782 if (flags & (EW_NOERROR | EW_NOTWILD))
3783 --emsg_silent;
3784 vim_free(pat);
3785
3786 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3787 {
3788 vim_free(buf);
3789 return 0;
3790 }
3791
3792 // If "**" is by itself, this is the first time we encounter it and more
3793 // is following then find matches without any directory.
3794 if (!didstar && stardepth < 100 && starstar && e - s == 2
3795 && *path_end == '/')
3796 {
3797 STRCPY(s, path_end + 1);
3798 ++stardepth;
3799 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3800 --stardepth;
3801 }
3802
3803 // open the directory for scanning
3804 *s = NUL;
3805 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3806
3807 // Find all matching entries
3808 if (dirp != NULL)
3809 {
Bram Moolenaar57e95172022-08-20 19:26:14 +01003810 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003811 {
3812 dp = readdir(dirp);
3813 if (dp == NULL)
3814 break;
3815 if ((dp->d_name[0] != '.' || starts_with_dot
3816 || ((flags & EW_DODOT)
3817 && dp->d_name[1] != NUL
3818 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3819 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3820 (char_u *)dp->d_name, (colnr_T)0))
3821 || ((flags & EW_NOTWILD)
3822 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3823 {
3824 STRCPY(s, dp->d_name);
3825 len = STRLEN(buf);
3826
3827 if (starstar && stardepth < 100)
3828 {
3829 // For "**" in the pattern first go deeper in the tree to
3830 // find matches.
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003831 vim_snprintf((char *)buf + len, buflen - len,
3832 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003833 ++stardepth;
3834 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3835 --stardepth;
3836 }
3837
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003838 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003839 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3840 {
3841 // need to expand another component of the path
3842 // remove backslashes for the remaining components only
3843 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3844 }
3845 else
3846 {
3847 stat_T sb;
3848
3849 // no more wildcards, check if there is a match
3850 // remove backslashes for the remaining components only
3851 if (*path_end != NUL)
3852 backslash_halve(buf + len + 1);
3853 // add existing file or symbolic link
3854 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3855 : mch_getperm(buf) >= 0)
3856 {
3857#ifdef MACOS_CONVERT
3858 size_t precomp_len = STRLEN(buf)+1;
3859 char_u *precomp_buf =
3860 mac_precompose_path(buf, precomp_len, &precomp_len);
3861
3862 if (precomp_buf)
3863 {
3864 mch_memmove(buf, precomp_buf, precomp_len);
3865 vim_free(precomp_buf);
3866 }
3867#endif
3868 addfile(gap, buf, flags);
3869 }
3870 }
3871 }
3872 }
3873
3874 closedir(dirp);
3875 }
3876
3877 vim_free(buf);
3878 vim_regfree(regmatch.regprog);
3879
Bram Moolenaar57e95172022-08-20 19:26:14 +01003880 // When interrupted the matches probably won't be used and sorting can be
3881 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003882 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003883 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003884 qsort(((char_u **)gap->ga_data) + start_len, matches,
3885 sizeof(char_u *), pstrcmp);
3886 return matches;
3887}
3888#endif
3889
3890/*
3891 * Return TRUE if "p" contains what looks like an environment variable.
3892 * Allowing for escaping.
3893 */
3894 static int
3895has_env_var(char_u *p)
3896{
3897 for ( ; *p; MB_PTR_ADV(p))
3898 {
3899 if (*p == '\\' && p[1] != NUL)
3900 ++p;
3901 else if (vim_strchr((char_u *)
3902#if defined(MSWIN)
3903 "$%"
3904#else
3905 "$"
3906#endif
3907 , *p) != NULL)
3908 return TRUE;
3909 }
3910 return FALSE;
3911}
3912
3913#ifdef SPECIAL_WILDCHAR
3914/*
3915 * Return TRUE if "p" contains a special wildcard character, one that Vim
3916 * cannot expand, requires using a shell.
3917 */
3918 static int
3919has_special_wildchar(char_u *p)
3920{
3921 for ( ; *p; MB_PTR_ADV(p))
3922 {
3923 // Disallow line break characters.
3924 if (*p == '\r' || *p == '\n')
3925 break;
3926 // Allow for escaping.
3927 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3928 ++p;
3929 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3930 {
3931 // A { must be followed by a matching }.
3932 if (*p == '{' && vim_strchr(p, '}') == NULL)
3933 continue;
3934 // A quote and backtick must be followed by another one.
3935 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3936 continue;
3937 return TRUE;
3938 }
3939 }
3940 return FALSE;
3941}
3942#endif
3943
3944/*
3945 * Generic wildcard expansion code.
3946 *
3947 * Characters in "pat" that should not be expanded must be preceded with a
3948 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3949 *
3950 * Return FAIL when no single file was found. In this case "num_file" is not
3951 * set, and "file" may contain an error message.
3952 * Return OK when some files found. "num_file" is set to the number of
3953 * matches, "file" to the array of matches. Call FreeWild() later.
3954 */
3955 int
3956gen_expand_wildcards(
3957 int num_pat, // number of input patterns
3958 char_u **pat, // array of input patterns
3959 int *num_file, // resulting number of files
3960 char_u ***file, // array of resulting files
3961 int flags) // EW_* flags
3962{
3963 int i;
3964 garray_T ga;
3965 char_u *p;
3966 static int recursive = FALSE;
3967 int add_pat;
3968 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003969 int did_expand_in_path = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003970
3971 /*
3972 * expand_env() is called to expand things like "~user". If this fails,
3973 * it calls ExpandOne(), which brings us back here. In this case, always
3974 * call the machine specific expansion function, if possible. Otherwise,
3975 * return FAIL.
3976 */
3977 if (recursive)
3978#ifdef SPECIAL_WILDCHAR
3979 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3980#else
3981 return FAIL;
3982#endif
3983
3984#ifdef SPECIAL_WILDCHAR
3985 /*
3986 * If there are any special wildcard characters which we cannot handle
3987 * here, call machine specific function for all the expansion. This
3988 * avoids starting the shell for each argument separately.
3989 * For `=expr` do use the internal function.
3990 */
3991 for (i = 0; i < num_pat; i++)
3992 {
3993 if (has_special_wildchar(pat[i])
3994# ifdef VIM_BACKTICK
3995 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3996# endif
3997 )
3998 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3999 }
4000#endif
4001
4002 recursive = TRUE;
4003
4004 /*
4005 * The matching file names are stored in a growarray. Init it empty.
4006 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00004007 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004008
Bram Moolenaar57e95172022-08-20 19:26:14 +01004009 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02004010 {
4011 add_pat = -1;
4012 p = pat[i];
4013
4014#ifdef VIM_BACKTICK
4015 if (vim_backtick(p))
4016 {
4017 add_pat = expand_backtick(&ga, p, flags);
4018 if (add_pat == -1)
4019 retval = FAIL;
4020 }
4021 else
4022#endif
4023 {
4024 /*
4025 * First expand environment variables, "~/" and "~user/".
4026 */
4027 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
4028 {
4029 p = expand_env_save_opt(p, TRUE);
4030 if (p == NULL)
4031 p = pat[i];
4032#ifdef UNIX
4033 /*
4034 * On Unix, if expand_env() can't expand an environment
4035 * variable, use the shell to do that. Discard previously
4036 * found file names and start all over again.
4037 */
4038 else if (has_env_var(p) || *p == '~')
4039 {
4040 vim_free(p);
4041 ga_clear_strings(&ga);
4042 i = mch_expand_wildcards(num_pat, pat, num_file, file,
4043 flags|EW_KEEPDOLLAR);
4044 recursive = FALSE;
4045 return i;
4046 }
4047#endif
4048 }
4049
4050 /*
LemonBoya3157a42022-04-03 11:58:31 +01004051 * If there are wildcards or case-insensitive expansion is
4052 * required: Expand file names and add each match to the list. If
4053 * there is no match, and EW_NOTFOUND is given, add the pattern.
4054 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4055 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004056 */
LemonBoya3157a42022-04-03 11:58:31 +01004057 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004058 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02004059 if ((flags & EW_PATH)
4060 && !mch_isFullName(p)
4061 && !(p[0] == '.'
4062 && (vim_ispathsep(p[1])
4063 || (p[1] == '.' && vim_ispathsep(p[2]))))
4064 )
4065 {
4066 // :find completion where 'path' is used.
4067 // Recursiveness is OK here.
4068 recursive = FALSE;
4069 add_pat = expand_in_path(&ga, p, flags);
4070 recursive = TRUE;
4071 did_expand_in_path = TRUE;
4072 }
4073 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004074 add_pat = mch_expandpath(&ga, p, flags);
4075 }
4076 }
4077
4078 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4079 {
4080 char_u *t = backslash_halve_save(p);
4081
4082 // When EW_NOTFOUND is used, always add files and dirs. Makes
4083 // "vim c:/" work.
4084 if (flags & EW_NOTFOUND)
4085 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4086 else
4087 addfile(&ga, t, flags);
4088
4089 if (t != p)
4090 vim_free(t);
4091 }
4092
Bram Moolenaar26262f82019-09-04 20:59:15 +02004093 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
4094 uniquefy_paths(&ga, p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004095 if (p != pat[i])
4096 vim_free(p);
4097 }
4098
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004099 // When returning FAIL the array must be freed here.
4100 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004101 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004102
Bram Moolenaar26262f82019-09-04 20:59:15 +02004103 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004104 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4105 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004106
4107 recursive = FALSE;
4108
4109 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4110}
4111
4112/*
4113 * Add a file to a file list. Accepted flags:
4114 * EW_DIR add directories
4115 * EW_FILE add files
4116 * EW_EXEC add executable files
4117 * EW_NOTFOUND add even when it doesn't exist
4118 * EW_ADDSLASH add slash after directory name
4119 * EW_ALLLINKS add symlink also when the referred file does not exist
4120 */
4121 void
4122addfile(
4123 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004124 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004125 int flags)
4126{
4127 char_u *p;
4128 int isdir;
4129 stat_T sb;
4130
4131 // if the file/dir/link doesn't exist, may not add it
4132 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4133 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4134 return;
4135
4136#ifdef FNAME_ILLEGAL
4137 // if the file/dir contains illegal characters, don't add it
4138 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4139 return;
4140#endif
4141
4142 isdir = mch_isdir(f);
4143 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4144 return;
4145
4146 // If the file isn't executable, may not add it. Do accept directories.
4147 // When invoked from expand_shellcmd() do not use $PATH.
4148 if (!isdir && (flags & EW_EXEC)
4149 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4150 return;
4151
4152 // Make room for another item in the file list.
4153 if (ga_grow(gap, 1) == FAIL)
4154 return;
4155
4156 p = alloc(STRLEN(f) + 1 + isdir);
4157 if (p == NULL)
4158 return;
4159
4160 STRCPY(p, f);
4161#ifdef BACKSLASH_IN_FILENAME
4162 slash_adjust(p);
4163#endif
4164 /*
4165 * Append a slash or backslash after directory names if none is present.
4166 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004167 if (isdir && (flags & EW_ADDSLASH))
4168 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004169 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4170}
4171
4172/*
4173 * Free the list of files returned by expand_wildcards() or other expansion
4174 * functions.
4175 */
4176 void
4177FreeWild(int count, char_u **files)
4178{
4179 if (count <= 0 || files == NULL)
4180 return;
4181 while (count--)
4182 vim_free(files[count]);
4183 vim_free(files);
4184}
4185
4186/*
4187 * Compare path "p[]" to "q[]".
4188 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4189 * Return value like strcmp(p, q), but consider path separators.
4190 */
4191 int
4192pathcmp(const char *p, const char *q, int maxlen)
4193{
4194 int i, j;
4195 int c1, c2;
4196 const char *s = NULL;
4197
4198 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4199 {
4200 c1 = PTR2CHAR((char_u *)p + i);
4201 c2 = PTR2CHAR((char_u *)q + j);
4202
4203 // End of "p": check if "q" also ends or just has a slash.
4204 if (c1 == NUL)
4205 {
4206 if (c2 == NUL) // full match
4207 return 0;
4208 s = q;
4209 i = j;
4210 break;
4211 }
4212
4213 // End of "q": check if "p" just has a slash.
4214 if (c2 == NUL)
4215 {
4216 s = p;
4217 break;
4218 }
4219
4220 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4221#ifdef BACKSLASH_IN_FILENAME
4222 // consider '/' and '\\' to be equal
4223 && !((c1 == '/' && c2 == '\\')
4224 || (c1 == '\\' && c2 == '/'))
4225#endif
4226 )
4227 {
4228 if (vim_ispathsep(c1))
4229 return -1;
4230 if (vim_ispathsep(c2))
4231 return 1;
4232 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4233 : c1 - c2; // no match
4234 }
4235
Bram Moolenaar1614a142019-10-06 22:00:13 +02004236 i += mb_ptr2len((char_u *)p + i);
4237 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004238 }
4239 if (s == NULL) // "i" or "j" ran into "maxlen"
4240 return 0;
4241
4242 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004243 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004244 // ignore a trailing slash, but not "//" or ":/"
4245 if (c2 == NUL
4246 && i > 0
4247 && !after_pathsep((char_u *)s, (char_u *)s + i)
4248#ifdef BACKSLASH_IN_FILENAME
4249 && (c1 == '/' || c1 == '\\')
4250#else
4251 && c1 == '/'
4252#endif
4253 )
4254 return 0; // match with trailing slash
4255 if (s == q)
4256 return -1; // no match
4257 return 1;
4258}
4259
4260/*
4261 * Return TRUE if "name" is a full (absolute) path name or URL.
4262 */
4263 int
4264vim_isAbsName(char_u *name)
4265{
4266 return (path_with_url(name) != 0 || mch_isFullName(name));
4267}
4268
4269/*
4270 * Get absolute file name into buffer "buf[len]".
4271 *
4272 * return FAIL for failure, OK otherwise
4273 */
4274 int
4275vim_FullName(
4276 char_u *fname,
4277 char_u *buf,
4278 int len,
4279 int force) // force expansion even when already absolute
4280{
4281 int retval = OK;
4282 int url;
4283
4284 *buf = NUL;
4285 if (fname == NULL)
4286 return FAIL;
4287
4288 url = path_with_url(fname);
4289 if (!url)
4290 retval = mch_FullName(fname, buf, len, force);
4291 if (url || retval == FAIL)
4292 {
4293 // something failed; use the file name (truncate when too long)
4294 vim_strncpy(buf, fname, len - 1);
4295 }
4296#if defined(MSWIN)
4297 slash_adjust(buf);
4298#endif
4299 return retval;
4300}