blob: c72e4285f360e88dbea03bc26f1fbce420222193 [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);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001391 globpath(tv_get_string(&argvars[0]), file, &ga, flags);
1392 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.
1431 * Return OK or FAIL.
1432 */
1433 static int
1434mkdir_recurse(char_u *dir, int prot)
1435{
1436 char_u *p;
1437 char_u *updir;
1438 int r = FAIL;
1439
Bram Moolenaar26262f82019-09-04 20:59:15 +02001440 // Get end of directory name in "dir".
1441 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001442 p = gettail_sep(dir);
1443 if (p <= get_past_head(dir))
1444 return OK;
1445
Bram Moolenaar26262f82019-09-04 20:59:15 +02001446 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001447 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001448 if (updir == NULL)
1449 return FAIL;
1450 if (mch_isdir(updir))
1451 r = OK;
1452 else if (mkdir_recurse(updir, prot) == OK)
1453 r = vim_mkdir_emsg(updir, prot);
1454 vim_free(updir);
1455 return r;
1456}
1457
1458/*
1459 * "mkdir()" function
1460 */
1461 void
1462f_mkdir(typval_T *argvars, typval_T *rettv)
1463{
1464 char_u *dir;
1465 char_u buf[NUMBUFLEN];
1466 int prot = 0755;
1467
1468 rettv->vval.v_number = FAIL;
1469 if (check_restricted() || check_secure())
1470 return;
1471
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001472 if (in_vim9script()
1473 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1474 || check_for_opt_string_arg(argvars, 1) == FAIL
1475 || (argvars[1].v_type != VAR_UNKNOWN
1476 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1477 return;
1478
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001479 dir = tv_get_string_buf(&argvars[0], buf);
1480 if (*dir == NUL)
1481 return;
1482
1483 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001484 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001485 *gettail_sep(dir) = NUL;
1486
1487 if (argvars[1].v_type != VAR_UNKNOWN)
1488 {
1489 if (argvars[2].v_type != VAR_UNKNOWN)
1490 {
1491 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1492 if (prot == -1)
1493 return;
1494 }
1495 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0)
1496 {
1497 if (mch_isdir(dir))
1498 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001499 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001500 rettv->vval.v_number = OK;
1501 return;
1502 }
1503 mkdir_recurse(dir, prot);
1504 }
1505 }
1506 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1507}
1508
1509/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001510 * "pathshorten()" function
1511 */
1512 void
1513f_pathshorten(typval_T *argvars, typval_T *rettv)
1514{
1515 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001516 int trim_len = 1;
1517
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001518 if (in_vim9script()
1519 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001520 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001521 return;
1522
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001523 if (argvars[1].v_type != VAR_UNKNOWN)
1524 {
1525 trim_len = (int)tv_get_number(&argvars[1]);
1526 if (trim_len < 1)
1527 trim_len = 1;
1528 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001529
1530 rettv->v_type = VAR_STRING;
1531 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001532
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001533 if (p == NULL)
1534 rettv->vval.v_string = NULL;
1535 else
1536 {
1537 p = vim_strsave(p);
1538 rettv->vval.v_string = p;
1539 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001540 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001541 }
1542}
1543
1544/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001545 * Common code for readdir_checkitem() and readdirex_checkitem().
1546 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001547 */
1548 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001549checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001550{
1551 typval_T *expr = (typval_T *)context;
1552 typval_T save_val;
1553 typval_T rettv;
1554 typval_T argv[2];
1555 int retval = 0;
1556 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001557
1558 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001559 if (name != NULL)
1560 {
1561 set_vim_var_string(VV_VAL, name, -1);
1562 argv[0].v_type = VAR_STRING;
1563 argv[0].vval.v_string = name;
1564 }
1565 else
1566 {
1567 set_vim_var_dict(VV_VAL, dict);
1568 argv[0].v_type = VAR_DICT;
1569 argv[0].vval.v_dict = dict;
1570 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001571
1572 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1573 goto theend;
1574
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001575 // We want to use -1, but also true/false should be allowed.
1576 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1577 {
1578 rettv.v_type = VAR_NUMBER;
1579 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1580 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001581 retval = tv_get_number_chk(&rettv, &error);
1582 if (error)
1583 retval = -1;
1584 clear_tv(&rettv);
1585
1586theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001587 if (name != NULL)
1588 set_vim_var_string(VV_VAL, NULL, 0);
1589 else
1590 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001591 restore_vimvar(VV_VAL, &save_val);
1592 return retval;
1593}
1594
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001595/*
1596 * Evaluate "expr" (= "context") for readdir().
1597 */
1598 static int
1599readdir_checkitem(void *context, void *item)
1600{
1601 char_u *name = (char_u *)item;
1602
1603 return checkitem_common(context, name, NULL);
1604}
1605
Bram Moolenaard83392a2022-09-01 12:22:46 +01001606/*
1607 * Process the keys in the Dict argument to the readdir() and readdirex()
1608 * functions. Assumes the Dict argument is the 3rd argument.
1609 */
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001610 static int
Bram Moolenaard83392a2022-09-01 12:22:46 +01001611readdirex_dict_arg(typval_T *argvars, int *cmp)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001612{
1613 char_u *compare;
1614
Bram Moolenaard83392a2022-09-01 12:22:46 +01001615 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001616 return FAIL;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001617
Bram Moolenaard83392a2022-09-01 12:22:46 +01001618 if (dict_has_key(argvars[2].vval.v_dict, "sort"))
1619 compare = dict_get_string(argvars[2].vval.v_dict, "sort", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001620 else
1621 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001622 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001623 return FAIL;
1624 }
1625
1626 if (STRCMP(compare, (char_u *) "none") == 0)
1627 *cmp = READDIR_SORT_NONE;
1628 else if (STRCMP(compare, (char_u *) "case") == 0)
1629 *cmp = READDIR_SORT_BYTE;
1630 else if (STRCMP(compare, (char_u *) "icase") == 0)
1631 *cmp = READDIR_SORT_IC;
1632 else if (STRCMP(compare, (char_u *) "collate") == 0)
1633 *cmp = READDIR_SORT_COLLATE;
1634 return OK;
1635}
1636
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001637/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001638 * "readdir()" function
1639 */
1640 void
1641f_readdir(typval_T *argvars, typval_T *rettv)
1642{
1643 typval_T *expr;
1644 int ret;
1645 char_u *path;
1646 char_u *p;
1647 garray_T ga;
1648 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001649 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001650
1651 if (rettv_list_alloc(rettv) == FAIL)
1652 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001653
1654 if (in_vim9script()
1655 && (check_for_string_arg(argvars, 0) == FAIL
1656 || (argvars[1].v_type != VAR_UNKNOWN
1657 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1658 return;
1659
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001660 path = tv_get_string(&argvars[0]);
1661 expr = &argvars[1];
1662
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001663 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001664 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001665 return;
1666
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001667 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001668 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001669 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001670 {
1671 for (i = 0; i < ga.ga_len; i++)
1672 {
1673 p = ((char_u **)ga.ga_data)[i];
1674 list_append_string(rettv->vval.v_list, p, -1);
1675 }
1676 }
1677 ga_clear_strings(&ga);
1678}
1679
1680/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001681 * Evaluate "expr" (= "context") for readdirex().
1682 */
1683 static int
1684readdirex_checkitem(void *context, void *item)
1685{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001686 dict_T *dict = (dict_T*)item;
1687
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001688 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001689}
1690
1691/*
1692 * "readdirex()" function
1693 */
1694 void
1695f_readdirex(typval_T *argvars, typval_T *rettv)
1696{
1697 typval_T *expr;
1698 int ret;
1699 char_u *path;
1700 garray_T ga;
1701 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001702 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001703
1704 if (rettv_list_alloc(rettv) == FAIL)
1705 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001706
1707 if (in_vim9script()
1708 && (check_for_string_arg(argvars, 0) == FAIL
1709 || (argvars[1].v_type != VAR_UNKNOWN
1710 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1711 return;
1712
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001713 path = tv_get_string(&argvars[0]);
1714 expr = &argvars[1];
1715
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001716 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001717 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001718 return;
1719
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001720 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001721 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001722 if (ret == OK)
1723 {
1724 for (i = 0; i < ga.ga_len; i++)
1725 {
1726 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1727 list_append_dict(rettv->vval.v_list, dict);
1728 dict_unref(dict);
1729 }
1730 }
1731 ga_clear(&ga);
1732}
1733
1734/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001735 * "readfile()" function
1736 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001737 static void
1738read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001739{
1740 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001741 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001742 int failed = FALSE;
1743 char_u *fname;
1744 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001745 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001746 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001747 int readlen; // size of last fread()
1748 char_u *prev = NULL; // previously read bytes, if any
1749 long prevlen = 0; // length of data in prev
1750 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001751 long maxline = MAXLNUM;
1752 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001753 char_u *p; // position in buf
1754 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001755
1756 if (argvars[1].v_type != VAR_UNKNOWN)
1757 {
1758 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1759 binary = TRUE;
1760 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1761 blob = TRUE;
1762
1763 if (argvars[2].v_type != VAR_UNKNOWN)
1764 maxline = (long)tv_get_number(&argvars[2]);
1765 }
1766
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001767 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1768 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001769
Bram Moolenaar26262f82019-09-04 20:59:15 +02001770 // Always open the file in binary mode, library functions have a mind of
1771 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001772 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001773
1774 if (mch_isdir(fname))
1775 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001776 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001777 return;
1778 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001779 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1780 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001781 semsg(_(e_cant_open_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001782 return;
1783 }
1784
1785 if (blob)
1786 {
1787 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1788 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001789 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001790 // An empty blob is returned on error.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001791 blob_free(rettv->vval.v_blob);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001792 rettv->vval.v_blob = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001793 }
1794 fclose(fd);
1795 return;
1796 }
1797
1798 while (cnt < maxline || maxline < 0)
1799 {
1800 readlen = (int)fread(buf, 1, io_size, fd);
1801
Bram Moolenaar26262f82019-09-04 20:59:15 +02001802 // This for loop processes what was read, but is also entered at end
1803 // of file so that either:
1804 // - an incomplete line gets written
1805 // - a "binary" file gets an empty line at the end if it ends in a
1806 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001807 for (p = buf, start = buf;
1808 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1809 ++p)
1810 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001811 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001812 {
1813 listitem_T *li;
1814 char_u *s = NULL;
1815 long_u len = p - start;
1816
Bram Moolenaar26262f82019-09-04 20:59:15 +02001817 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001818 if (readlen > 0 && !binary)
1819 {
1820 while (len > 0 && start[len - 1] == '\r')
1821 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001822 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001823 if (len == 0)
1824 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1825 --prevlen;
1826 }
1827 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001828 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001829 else
1830 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001831 // Change "prev" buffer to be the right size. This way
1832 // the bytes are only copied once, and very long lines are
1833 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001834 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1835 {
1836 mch_memmove(s + prevlen, start, len);
1837 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001838 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001839 prevlen = prevsize = 0;
1840 }
1841 }
1842 if (s == NULL)
1843 {
1844 do_outofmem_msg((long_u) prevlen + len + 1);
1845 failed = TRUE;
1846 break;
1847 }
1848
1849 if ((li = listitem_alloc()) == NULL)
1850 {
1851 vim_free(s);
1852 failed = TRUE;
1853 break;
1854 }
1855 li->li_tv.v_type = VAR_STRING;
1856 li->li_tv.v_lock = 0;
1857 li->li_tv.vval.v_string = s;
1858 list_append(rettv->vval.v_list, li);
1859
Bram Moolenaar26262f82019-09-04 20:59:15 +02001860 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001861 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1862 break;
1863 }
1864 else if (*p == NUL)
1865 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001866 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1867 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001868 else if (*p == 0xbf && enc_utf8 && !binary)
1869 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001870 // Find the two bytes before the 0xbf. If p is at buf, or buf
1871 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001872 char_u back1 = p >= buf + 1 ? p[-1]
1873 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1874 char_u back2 = p >= buf + 2 ? p[-2]
1875 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1876 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1877
1878 if (back2 == 0xef && back1 == 0xbb)
1879 {
1880 char_u *dest = p - 2;
1881
Bram Moolenaar26262f82019-09-04 20:59:15 +02001882 // Usually a BOM is at the beginning of a file, and so at
1883 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001884 if (start == dest)
1885 start = p + 1;
1886 else
1887 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001888 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001889 int adjust_prevlen = 0;
1890
1891 if (dest < buf)
1892 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001893 // must be 1 or 2
1894 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001895 dest = buf;
1896 }
1897 if (readlen > p - buf + 1)
1898 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1899 readlen -= 3 - adjust_prevlen;
1900 prevlen -= adjust_prevlen;
1901 p = dest - 1;
1902 }
1903 }
1904 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001905 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001906
1907 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1908 break;
1909 if (start < p)
1910 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001911 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001912 if (p - start + prevlen >= prevsize)
1913 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001914 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001915 char_u *newprev;
1916
Bram Moolenaar26262f82019-09-04 20:59:15 +02001917 // A common use case is ordinary text files and "prev" gets a
1918 // fragment of a line, so the first allocation is made
1919 // small, to avoid repeatedly 'allocing' large and
1920 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001921 if (prevsize == 0)
1922 prevsize = (long)(p - start);
1923 else
1924 {
1925 long grow50pc = (prevsize * 3) / 2;
1926 long growmin = (long)((p - start) * 2 + prevlen);
1927 prevsize = grow50pc > growmin ? grow50pc : growmin;
1928 }
1929 newprev = vim_realloc(prev, prevsize);
1930 if (newprev == NULL)
1931 {
1932 do_outofmem_msg((long_u)prevsize);
1933 failed = TRUE;
1934 break;
1935 }
1936 prev = newprev;
1937 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001938 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001939 mch_memmove(prev + prevlen, start, p - start);
1940 prevlen += (long)(p - start);
1941 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001942 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001943
Bram Moolenaar26262f82019-09-04 20:59:15 +02001944 // For a negative line count use only the lines at the end of the file,
1945 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001946 if (!failed && maxline < 0)
1947 while (cnt > -maxline)
1948 {
1949 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1950 --cnt;
1951 }
1952
1953 if (failed)
1954 {
1955 // an empty list is returned on error
1956 list_free(rettv->vval.v_list);
1957 rettv_list_alloc(rettv);
1958 }
1959
1960 vim_free(prev);
1961 fclose(fd);
1962}
1963
1964/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001965 * "readblob()" function
1966 */
1967 void
1968f_readblob(typval_T *argvars, typval_T *rettv)
1969{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001970 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1971 return;
1972
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001973 read_file_or_blob(argvars, rettv, TRUE);
1974}
1975
1976/*
1977 * "readfile()" function
1978 */
1979 void
1980f_readfile(typval_T *argvars, typval_T *rettv)
1981{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001982 if (in_vim9script()
1983 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1984 || check_for_opt_string_arg(argvars, 1) == FAIL
1985 || (argvars[1].v_type != VAR_UNKNOWN
1986 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1987 return;
1988
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001989 read_file_or_blob(argvars, rettv, FALSE);
1990}
1991
1992/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001993 * "resolve()" function
1994 */
1995 void
1996f_resolve(typval_T *argvars, typval_T *rettv)
1997{
1998 char_u *p;
1999#ifdef HAVE_READLINK
2000 char_u *buf = NULL;
2001#endif
2002
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002003 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2004 return;
2005
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002006 p = tv_get_string(&argvars[0]);
2007#ifdef FEAT_SHORTCUT
2008 {
2009 char_u *v = NULL;
2010
2011 v = mch_resolve_path(p, TRUE);
2012 if (v != NULL)
2013 rettv->vval.v_string = v;
2014 else
2015 rettv->vval.v_string = vim_strsave(p);
2016 }
2017#else
2018# ifdef HAVE_READLINK
2019 {
2020 char_u *cpy;
2021 int len;
2022 char_u *remain = NULL;
2023 char_u *q;
2024 int is_relative_to_current = FALSE;
2025 int has_trailing_pathsep = FALSE;
2026 int limit = 100;
2027
2028 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002029 if (p == NULL)
2030 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002031 if (p[0] == '.' && (vim_ispathsep(p[1])
2032 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2033 is_relative_to_current = TRUE;
2034
2035 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02002036 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002037 {
2038 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002039 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002040 }
2041
2042 q = getnextcomp(p);
2043 if (*q != NUL)
2044 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002045 // Separate the first path component in "p", and keep the
2046 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002047 remain = vim_strsave(q - 1);
2048 q[-1] = NUL;
2049 }
2050
2051 buf = alloc(MAXPATHL + 1);
2052 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01002053 {
2054 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002055 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01002056 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002057
2058 for (;;)
2059 {
2060 for (;;)
2061 {
2062 len = readlink((char *)p, (char *)buf, MAXPATHL);
2063 if (len <= 0)
2064 break;
2065 buf[len] = NUL;
2066
2067 if (limit-- == 0)
2068 {
2069 vim_free(p);
2070 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002071 emsg(_(e_too_many_symbolic_links_cycle));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002072 rettv->vval.v_string = NULL;
2073 goto fail;
2074 }
2075
Bram Moolenaar26262f82019-09-04 20:59:15 +02002076 // Ensure that the result will have a trailing path separator
2077 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002078 if (remain == NULL && has_trailing_pathsep)
2079 add_pathsep(buf);
2080
Bram Moolenaar26262f82019-09-04 20:59:15 +02002081 // Separate the first path component in the link value and
2082 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002083 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2084 if (*q != NUL)
2085 {
2086 if (remain == NULL)
2087 remain = vim_strsave(q - 1);
2088 else
2089 {
2090 cpy = concat_str(q - 1, remain);
2091 if (cpy != NULL)
2092 {
2093 vim_free(remain);
2094 remain = cpy;
2095 }
2096 }
2097 q[-1] = NUL;
2098 }
2099
2100 q = gettail(p);
2101 if (q > p && *q == NUL)
2102 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002103 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002104 q[-1] = NUL;
2105 q = gettail(p);
2106 }
2107 if (q > p && !mch_isFullName(buf))
2108 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002109 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002110 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2111 if (cpy != NULL)
2112 {
2113 STRCPY(cpy, p);
2114 STRCPY(gettail(cpy), buf);
2115 vim_free(p);
2116 p = cpy;
2117 }
2118 }
2119 else
2120 {
2121 vim_free(p);
2122 p = vim_strsave(buf);
2123 }
2124 }
2125
2126 if (remain == NULL)
2127 break;
2128
Bram Moolenaar26262f82019-09-04 20:59:15 +02002129 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002130 q = getnextcomp(remain + 1);
2131 len = q - remain - (*q != NUL);
2132 cpy = vim_strnsave(p, STRLEN(p) + len);
2133 if (cpy != NULL)
2134 {
2135 STRNCAT(cpy, remain, len);
2136 vim_free(p);
2137 p = cpy;
2138 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002139 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002140 if (*q != NUL)
2141 STRMOVE(remain, q - 1);
2142 else
2143 VIM_CLEAR(remain);
2144 }
2145
Bram Moolenaar26262f82019-09-04 20:59:15 +02002146 // If the result is a relative path name, make it explicitly relative to
2147 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002148 if (!vim_ispathsep(*p))
2149 {
2150 if (is_relative_to_current
2151 && *p != NUL
2152 && !(p[0] == '.'
2153 && (p[1] == NUL
2154 || vim_ispathsep(p[1])
2155 || (p[1] == '.'
2156 && (p[2] == NUL
2157 || vim_ispathsep(p[2]))))))
2158 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002159 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002160 cpy = concat_str((char_u *)"./", p);
2161 if (cpy != NULL)
2162 {
2163 vim_free(p);
2164 p = cpy;
2165 }
2166 }
2167 else if (!is_relative_to_current)
2168 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002169 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002170 q = p;
2171 while (q[0] == '.' && vim_ispathsep(q[1]))
2172 q += 2;
2173 if (q > p)
2174 STRMOVE(p, p + 2);
2175 }
2176 }
2177
Bram Moolenaar26262f82019-09-04 20:59:15 +02002178 // Ensure that the result will have no trailing path separator
2179 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002180 if (!has_trailing_pathsep)
2181 {
2182 q = p + STRLEN(p);
2183 if (after_pathsep(p, q))
2184 *gettail_sep(p) = NUL;
2185 }
2186
2187 rettv->vval.v_string = p;
2188 }
2189# else
2190 rettv->vval.v_string = vim_strsave(p);
2191# endif
2192#endif
2193
2194 simplify_filename(rettv->vval.v_string);
2195
2196#ifdef HAVE_READLINK
2197fail:
2198 vim_free(buf);
2199#endif
2200 rettv->v_type = VAR_STRING;
2201}
2202
2203/*
2204 * "tempname()" function
2205 */
2206 void
2207f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2208{
2209 static int x = 'A';
2210
2211 rettv->v_type = VAR_STRING;
2212 rettv->vval.v_string = vim_tempname(x, FALSE);
2213
Bram Moolenaar26262f82019-09-04 20:59:15 +02002214 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2215 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002216 do
2217 {
2218 if (x == 'Z')
2219 x = '0';
2220 else if (x == '9')
2221 x = 'A';
2222 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002223 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002224 } while (x == 'I' || x == 'O');
2225}
2226
2227/*
2228 * "writefile()" function
2229 */
2230 void
2231f_writefile(typval_T *argvars, typval_T *rettv)
2232{
2233 int binary = FALSE;
2234 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002235 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002236#ifdef HAVE_FSYNC
2237 int do_fsync = p_fs;
2238#endif
2239 char_u *fname;
2240 FILE *fd;
2241 int ret = 0;
2242 listitem_T *li;
2243 list_T *list = NULL;
2244 blob_T *blob = NULL;
2245
2246 rettv->vval.v_number = -1;
2247 if (check_secure())
2248 return;
2249
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002250 if (in_vim9script()
2251 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2252 || check_for_string_arg(argvars, 1) == FAIL
2253 || check_for_opt_string_arg(argvars, 2) == FAIL))
2254 return;
2255
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002256 if (argvars[0].v_type == VAR_LIST)
2257 {
2258 list = argvars[0].vval.v_list;
2259 if (list == NULL)
2260 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002261 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002262 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002263 if (tv_get_string_chk(&li->li_tv) == NULL)
2264 return;
2265 }
2266 else if (argvars[0].v_type == VAR_BLOB)
2267 {
2268 blob = argvars[0].vval.v_blob;
2269 if (blob == NULL)
2270 return;
2271 }
2272 else
2273 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002274 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002275 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002276 return;
2277 }
2278
2279 if (argvars[2].v_type != VAR_UNKNOWN)
2280 {
2281 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2282
2283 if (arg2 == NULL)
2284 return;
2285 if (vim_strchr(arg2, 'b') != NULL)
2286 binary = TRUE;
2287 if (vim_strchr(arg2, 'a') != NULL)
2288 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002289 if (vim_strchr(arg2, 'D') != NULL)
2290 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002291#ifdef HAVE_FSYNC
2292 if (vim_strchr(arg2, 's') != NULL)
2293 do_fsync = TRUE;
2294 else if (vim_strchr(arg2, 'S') != NULL)
2295 do_fsync = FALSE;
2296#endif
2297 }
2298
2299 fname = tv_get_string_chk(&argvars[1]);
2300 if (fname == NULL)
2301 return;
2302
Bram Moolenaar806a2732022-09-04 15:40:36 +01002303 if (defer && !in_def_function() && get_current_funccal() == NULL)
2304 {
2305 semsg(_(e_str_not_inside_function), "defer");
2306 return;
2307 }
2308
Bram Moolenaar26262f82019-09-04 20:59:15 +02002309 // Always open the file in binary mode, library functions have a mind of
2310 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002311 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2312 append ? APPENDBIN : WRITEBIN)) == NULL)
2313 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002314 semsg(_(e_cant_create_file_str),
2315 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002316 ret = -1;
2317 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002318 else
2319 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002320 if (defer)
2321 {
2322 typval_T tv;
2323
2324 tv.v_type = VAR_STRING;
2325 tv.v_lock = 0;
2326 tv.vval.v_string = vim_strsave(fname);
2327 if (tv.vval.v_string == NULL
2328 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2329 {
2330 ret = -1;
2331 fclose(fd);
2332 (void)mch_remove(fname);
2333 }
2334 }
2335
2336 if (ret == 0)
2337 {
2338 if (blob)
2339 {
2340 if (write_blob(fd, blob) == FAIL)
2341 ret = -1;
2342 }
2343 else
2344 {
2345 if (write_list(fd, list, binary) == FAIL)
2346 ret = -1;
2347 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002348#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002349 if (ret == 0 && do_fsync)
2350 // Ignore the error, the user wouldn't know what to do about
2351 // it. May happen for a device.
2352 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002353#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002354 fclose(fd);
2355 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002356 }
2357
2358 rettv->vval.v_number = ret;
2359}
2360
2361#endif // FEAT_EVAL
2362
2363#if defined(FEAT_BROWSE) || defined(PROTO)
2364/*
2365 * Generic browse function. Calls gui_mch_browse() when possible.
2366 * Later this may pop-up a non-GUI file selector (external command?).
2367 */
2368 char_u *
2369do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002370 int flags, // BROWSE_SAVE and BROWSE_DIR
2371 char_u *title, // title for the window
2372 char_u *dflt, // default file name (may include directory)
2373 char_u *ext, // extension added
2374 char_u *initdir, // initial directory, NULL for current dir or
2375 // when using path from "dflt"
2376 char_u *filter, // file name filter
2377 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002378{
2379 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002380 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002381 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002382 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002383
Bram Moolenaar26262f82019-09-04 20:59:15 +02002384 // Must turn off browse to avoid that autocommands will get the
2385 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002386 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002387
2388 if (title == NULL || *title == NUL)
2389 {
2390 if (flags & BROWSE_DIR)
2391 title = (char_u *)_("Select Directory dialog");
2392 else if (flags & BROWSE_SAVE)
2393 title = (char_u *)_("Save File dialog");
2394 else
2395 title = (char_u *)_("Open File dialog");
2396 }
2397
Bram Moolenaar26262f82019-09-04 20:59:15 +02002398 // When no directory specified, use default file name, default dir, buffer
2399 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002400 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2401 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002402 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002403 {
2404 initdir = dflt;
2405 dflt = NULL;
2406 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002407 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002408 {
2409 tofree = vim_strsave(dflt);
2410 if (tofree != NULL)
2411 {
2412 initdir = tofree;
2413 *gettail(initdir) = NUL;
2414 dflt = gettail(dflt);
2415 }
2416 }
2417 }
2418
2419 if (initdir == NULL || *initdir == NUL)
2420 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002421 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002422 if (STRCMP(p_bsdir, "last") != 0
2423 && STRCMP(p_bsdir, "buffer") != 0
2424 && STRCMP(p_bsdir, "current") != 0
2425 && mch_isdir(p_bsdir))
2426 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002427 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002428 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2429 && buf != NULL && buf->b_ffname != NULL)
2430 {
2431 if (dflt == NULL || *dflt == NUL)
2432 dflt = gettail(curbuf->b_ffname);
2433 tofree = vim_strsave(curbuf->b_ffname);
2434 if (tofree != NULL)
2435 {
2436 initdir = tofree;
2437 *gettail(initdir) = NUL;
2438 }
2439 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002440 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002441 else if (*p_bsdir == 'l')
2442 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002443 // When 'browsedir is "current", use current directory. This is the
2444 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002445 }
2446
2447# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002448 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002449 {
2450 if (filter == NULL
2451# ifdef FEAT_EVAL
2452 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2453 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2454# endif
2455 )
2456 filter = BROWSE_FILTER_DEFAULT;
2457 if (flags & BROWSE_DIR)
2458 {
2459# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002460 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002461 fname = gui_mch_browsedir(title, initdir);
2462# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002463 // Generic solution for selecting a directory: select a file and
2464 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002465 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2466# endif
2467# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002468 // Win32 adds a dummy file name, others return an arbitrary file
2469 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002470 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2471 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002472 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002473 char_u *tail = gettail_sep(fname);
2474
2475 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002476 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002477 *tail = NUL;
2478 }
2479# endif
2480 }
2481 else
2482 fname = gui_mch_browse(flags & BROWSE_SAVE,
2483 title, dflt, ext, initdir, (char_u *)_(filter));
2484
Bram Moolenaar26262f82019-09-04 20:59:15 +02002485 // We hang around in the dialog for a while, the user might do some
2486 // things to our files. The Win32 dialog allows deleting or renaming
2487 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002488 need_check_timestamps = TRUE;
2489 did_check_timestamps = FALSE;
2490 }
2491 else
2492# endif
2493 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002494 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002495 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002496 fname = NULL;
2497 }
2498
Bram Moolenaar26262f82019-09-04 20:59:15 +02002499 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002500 if (fname != NULL)
2501 {
2502 vim_free(last_dir);
2503 last_dir = vim_strsave(fname);
2504 if (last_dir != NULL && !(flags & BROWSE_DIR))
2505 {
2506 *gettail(last_dir) = NUL;
2507 if (*last_dir == NUL)
2508 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002509 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002510 vim_free(last_dir);
2511 last_dir = alloc(MAXPATHL);
2512 if (last_dir != NULL)
2513 mch_dirname(last_dir, MAXPATHL);
2514 }
2515 }
2516 }
2517
2518 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002519 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002520
2521 return fname;
2522}
2523#endif
2524
2525#if defined(FEAT_EVAL) || defined(PROTO)
2526
2527/*
2528 * "browse(save, title, initdir, default)" function
2529 */
2530 void
2531f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2532{
2533# ifdef FEAT_BROWSE
2534 int save;
2535 char_u *title;
2536 char_u *initdir;
2537 char_u *defname;
2538 char_u buf[NUMBUFLEN];
2539 char_u buf2[NUMBUFLEN];
2540 int error = FALSE;
2541
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002542 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002543 && (check_for_bool_arg(argvars, 0) == FAIL
2544 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002545 || check_for_string_arg(argvars, 2) == FAIL
2546 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002547 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002548
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002549 save = (int)tv_get_number_chk(&argvars[0], &error);
2550 title = tv_get_string_chk(&argvars[1]);
2551 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2552 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2553
2554 if (error || title == NULL || initdir == NULL || defname == NULL)
2555 rettv->vval.v_string = NULL;
2556 else
2557 rettv->vval.v_string =
2558 do_browse(save ? BROWSE_SAVE : 0,
2559 title, defname, NULL, initdir, NULL, curbuf);
2560# else
2561 rettv->vval.v_string = NULL;
2562# endif
2563 rettv->v_type = VAR_STRING;
2564}
2565
2566/*
2567 * "browsedir(title, initdir)" function
2568 */
2569 void
2570f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2571{
2572# ifdef FEAT_BROWSE
2573 char_u *title;
2574 char_u *initdir;
2575 char_u buf[NUMBUFLEN];
2576
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002577 if (in_vim9script()
2578 && (check_for_string_arg(argvars, 0) == FAIL
2579 || check_for_string_arg(argvars, 1) == FAIL))
2580 return;
2581
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002582 title = tv_get_string_chk(&argvars[0]);
2583 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2584
2585 if (title == NULL || initdir == NULL)
2586 rettv->vval.v_string = NULL;
2587 else
2588 rettv->vval.v_string = do_browse(BROWSE_DIR,
2589 title, NULL, NULL, initdir, NULL, curbuf);
2590# else
2591 rettv->vval.v_string = NULL;
2592# endif
2593 rettv->v_type = VAR_STRING;
2594}
2595
2596#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002597
2598/*
2599 * Replace home directory by "~" in each space or comma separated file name in
2600 * 'src'.
2601 * If anything fails (except when out of space) dst equals src.
2602 */
2603 void
2604home_replace(
2605 buf_T *buf, // when not NULL, check for help files
2606 char_u *src, // input file name
2607 char_u *dst, // where to put the result
2608 int dstlen, // maximum length of the result
2609 int one) // if TRUE, only replace one file name, include
2610 // spaces and commas in the file name.
2611{
2612 size_t dirlen = 0, envlen = 0;
2613 size_t len;
2614 char_u *homedir_env, *homedir_env_orig;
2615 char_u *p;
2616
2617 if (src == NULL)
2618 {
2619 *dst = NUL;
2620 return;
2621 }
2622
2623 /*
2624 * If the file is a help file, remove the path completely.
2625 */
2626 if (buf != NULL && buf->b_help)
2627 {
2628 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2629 return;
2630 }
2631
2632 /*
2633 * We check both the value of the $HOME environment variable and the
2634 * "real" home directory.
2635 */
2636 if (homedir != NULL)
2637 dirlen = STRLEN(homedir);
2638
2639#ifdef VMS
2640 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2641#else
2642 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2643#endif
2644#ifdef MSWIN
2645 if (homedir_env == NULL)
2646 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2647#endif
2648 // Empty is the same as not set.
2649 if (homedir_env != NULL && *homedir_env == NUL)
2650 homedir_env = NULL;
2651
2652 if (homedir_env != NULL && *homedir_env == '~')
2653 {
2654 int usedlen = 0;
2655 int flen;
2656 char_u *fbuf = NULL;
2657
2658 flen = (int)STRLEN(homedir_env);
2659 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2660 &homedir_env, &fbuf, &flen);
2661 flen = (int)STRLEN(homedir_env);
2662 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2663 // Remove the trailing / that is added to a directory.
2664 homedir_env[flen - 1] = NUL;
2665 }
2666
2667 if (homedir_env != NULL)
2668 envlen = STRLEN(homedir_env);
2669
2670 if (!one)
2671 src = skipwhite(src);
2672 while (*src && dstlen > 0)
2673 {
2674 /*
2675 * Here we are at the beginning of a file name.
2676 * First, check to see if the beginning of the file name matches
2677 * $HOME or the "real" home directory. Check that there is a '/'
2678 * after the match (so that if e.g. the file is "/home/pieter/bla",
2679 * and the home directory is "/home/piet", the file does not end up
2680 * as "~er/bla" (which would seem to indicate the file "bla" in user
2681 * er's home directory)).
2682 */
2683 p = homedir;
2684 len = dirlen;
2685 for (;;)
2686 {
2687 if ( len
2688 && fnamencmp(src, p, len) == 0
2689 && (vim_ispathsep(src[len])
2690 || (!one && (src[len] == ',' || src[len] == ' '))
2691 || src[len] == NUL))
2692 {
2693 src += len;
2694 if (--dstlen > 0)
2695 *dst++ = '~';
2696
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002697 // Do not add directory separator into dst, because dst is
2698 // expected to just return the directory name without the
2699 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002700 break;
2701 }
2702 if (p == homedir_env)
2703 break;
2704 p = homedir_env;
2705 len = envlen;
2706 }
2707
2708 // if (!one) skip to separator: space or comma
2709 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2710 *dst++ = *src++;
2711 // skip separator
2712 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2713 *dst++ = *src++;
2714 }
2715 // if (dstlen == 0) out of space, what to do???
2716
2717 *dst = NUL;
2718
2719 if (homedir_env != homedir_env_orig)
2720 vim_free(homedir_env);
2721}
2722
2723/*
2724 * Like home_replace, store the replaced string in allocated memory.
2725 * When something fails, NULL is returned.
2726 */
2727 char_u *
2728home_replace_save(
2729 buf_T *buf, // when not NULL, check for help files
2730 char_u *src) // input file name
2731{
2732 char_u *dst;
2733 unsigned len;
2734
2735 len = 3; // space for "~/" and trailing NUL
2736 if (src != NULL) // just in case
2737 len += (unsigned)STRLEN(src);
2738 dst = alloc(len);
2739 if (dst != NULL)
2740 home_replace(buf, src, dst, len, TRUE);
2741 return dst;
2742}
2743
2744/*
2745 * Compare two file names and return:
2746 * FPC_SAME if they both exist and are the same file.
2747 * FPC_SAMEX if they both don't exist and have the same file name.
2748 * FPC_DIFF if they both exist and are different files.
2749 * FPC_NOTX if they both don't exist.
2750 * FPC_DIFFX if one of them doesn't exist.
2751 * For the first name environment variables are expanded if "expandenv" is
2752 * TRUE.
2753 */
2754 int
2755fullpathcmp(
2756 char_u *s1,
2757 char_u *s2,
2758 int checkname, // when both don't exist, check file names
2759 int expandenv)
2760{
2761#ifdef UNIX
2762 char_u exp1[MAXPATHL];
2763 char_u full1[MAXPATHL];
2764 char_u full2[MAXPATHL];
2765 stat_T st1, st2;
2766 int r1, r2;
2767
2768 if (expandenv)
2769 expand_env(s1, exp1, MAXPATHL);
2770 else
2771 vim_strncpy(exp1, s1, MAXPATHL - 1);
2772 r1 = mch_stat((char *)exp1, &st1);
2773 r2 = mch_stat((char *)s2, &st2);
2774 if (r1 != 0 && r2 != 0)
2775 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002776 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002777 if (checkname)
2778 {
2779 if (fnamecmp(exp1, s2) == 0)
2780 return FPC_SAMEX;
2781 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2782 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2783 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2784 return FPC_SAMEX;
2785 }
2786 return FPC_NOTX;
2787 }
2788 if (r1 != 0 || r2 != 0)
2789 return FPC_DIFFX;
2790 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2791 return FPC_SAME;
2792 return FPC_DIFF;
2793#else
2794 char_u *exp1; // expanded s1
2795 char_u *full1; // full path of s1
2796 char_u *full2; // full path of s2
2797 int retval = FPC_DIFF;
2798 int r1, r2;
2799
2800 // allocate one buffer to store three paths (alloc()/free() is slow!)
2801 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2802 {
2803 full1 = exp1 + MAXPATHL;
2804 full2 = full1 + MAXPATHL;
2805
2806 if (expandenv)
2807 expand_env(s1, exp1, MAXPATHL);
2808 else
2809 vim_strncpy(exp1, s1, MAXPATHL - 1);
2810 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2811 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2812
2813 // If vim_FullName() fails, the file probably doesn't exist.
2814 if (r1 != OK && r2 != OK)
2815 {
2816 if (checkname && fnamecmp(exp1, s2) == 0)
2817 retval = FPC_SAMEX;
2818 else
2819 retval = FPC_NOTX;
2820 }
2821 else if (r1 != OK || r2 != OK)
2822 retval = FPC_DIFFX;
2823 else if (fnamecmp(full1, full2))
2824 retval = FPC_DIFF;
2825 else
2826 retval = FPC_SAME;
2827 vim_free(exp1);
2828 }
2829 return retval;
2830#endif
2831}
2832
2833/*
2834 * Get the tail of a path: the file name.
2835 * When the path ends in a path separator the tail is the NUL after it.
2836 * Fail safe: never returns NULL.
2837 */
2838 char_u *
2839gettail(char_u *fname)
2840{
2841 char_u *p1, *p2;
2842
2843 if (fname == NULL)
2844 return (char_u *)"";
2845 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2846 {
2847 if (vim_ispathsep_nocolon(*p2))
2848 p1 = p2 + 1;
2849 MB_PTR_ADV(p2);
2850 }
2851 return p1;
2852}
2853
2854/*
2855 * Get pointer to tail of "fname", including path separators. Putting a NUL
2856 * here leaves the directory name. Takes care of "c:/" and "//".
2857 * Always returns a valid pointer.
2858 */
2859 char_u *
2860gettail_sep(char_u *fname)
2861{
2862 char_u *p;
2863 char_u *t;
2864
2865 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2866 t = gettail(fname);
2867 while (t > p && after_pathsep(fname, t))
2868 --t;
2869#ifdef VMS
2870 // path separator is part of the path
2871 ++t;
2872#endif
2873 return t;
2874}
2875
2876/*
2877 * get the next path component (just after the next path separator).
2878 */
2879 char_u *
2880getnextcomp(char_u *fname)
2881{
2882 while (*fname && !vim_ispathsep(*fname))
2883 MB_PTR_ADV(fname);
2884 if (*fname)
2885 ++fname;
2886 return fname;
2887}
2888
2889/*
2890 * Get a pointer to one character past the head of a path name.
2891 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2892 * If there is no head, path is returned.
2893 */
2894 char_u *
2895get_past_head(char_u *path)
2896{
2897 char_u *retval;
2898
2899#if defined(MSWIN)
2900 // may skip "c:"
2901 if (isalpha(path[0]) && path[1] == ':')
2902 retval = path + 2;
2903 else
2904 retval = path;
2905#else
2906# if defined(AMIGA)
2907 // may skip "label:"
2908 retval = vim_strchr(path, ':');
2909 if (retval == NULL)
2910 retval = path;
2911# else // Unix
2912 retval = path;
2913# endif
2914#endif
2915
2916 while (vim_ispathsep(*retval))
2917 ++retval;
2918
2919 return retval;
2920}
2921
2922/*
2923 * Return TRUE if 'c' is a path separator.
2924 * Note that for MS-Windows this includes the colon.
2925 */
2926 int
2927vim_ispathsep(int c)
2928{
2929#ifdef UNIX
2930 return (c == '/'); // UNIX has ':' inside file names
2931#else
2932# ifdef BACKSLASH_IN_FILENAME
2933 return (c == ':' || c == '/' || c == '\\');
2934# else
2935# ifdef VMS
2936 // server"user passwd"::device:[full.path.name]fname.extension;version"
2937 return (c == ':' || c == '[' || c == ']' || c == '/'
2938 || c == '<' || c == '>' || c == '"' );
2939# else
2940 return (c == ':' || c == '/');
2941# endif // VMS
2942# endif
2943#endif
2944}
2945
2946/*
2947 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2948 */
2949 int
2950vim_ispathsep_nocolon(int c)
2951{
2952 return vim_ispathsep(c)
2953#ifdef BACKSLASH_IN_FILENAME
2954 && c != ':'
2955#endif
2956 ;
2957}
2958
2959/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02002960 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2961 * Also returns TRUE if there is no directory name.
2962 * "fname" must be writable!.
2963 */
2964 int
2965dir_of_file_exists(char_u *fname)
2966{
2967 char_u *p;
2968 int c;
2969 int retval;
2970
2971 p = gettail_sep(fname);
2972 if (p == fname)
2973 return TRUE;
2974 c = *p;
2975 *p = NUL;
2976 retval = mch_isdir(fname);
2977 *p = c;
2978 return retval;
2979}
2980
2981/*
2982 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2983 * and deal with 'fileignorecase'.
2984 */
2985 int
2986vim_fnamecmp(char_u *x, char_u *y)
2987{
2988#ifdef BACKSLASH_IN_FILENAME
2989 return vim_fnamencmp(x, y, MAXPATHL);
2990#else
2991 if (p_fic)
2992 return MB_STRICMP(x, y);
2993 return STRCMP(x, y);
2994#endif
2995}
2996
2997 int
2998vim_fnamencmp(char_u *x, char_u *y, size_t len)
2999{
3000#ifdef BACKSLASH_IN_FILENAME
3001 char_u *px = x;
3002 char_u *py = y;
3003 int cx = NUL;
3004 int cy = NUL;
3005
3006 while (len > 0)
3007 {
3008 cx = PTR2CHAR(px);
3009 cy = PTR2CHAR(py);
3010 if (cx == NUL || cy == NUL
3011 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3012 && !(cx == '/' && cy == '\\')
3013 && !(cx == '\\' && cy == '/')))
3014 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003015 len -= mb_ptr2len(px);
3016 px += mb_ptr2len(px);
3017 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003018 }
3019 if (len == 0)
3020 return 0;
3021 return (cx - cy);
3022#else
3023 if (p_fic)
3024 return MB_STRNICMP(x, y, len);
3025 return STRNCMP(x, y, len);
3026#endif
3027}
3028
3029/*
3030 * Concatenate file names fname1 and fname2 into allocated memory.
3031 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3032 */
3033 char_u *
3034concat_fnames(char_u *fname1, char_u *fname2, int sep)
3035{
3036 char_u *dest;
3037
3038 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
3039 if (dest != NULL)
3040 {
3041 STRCPY(dest, fname1);
3042 if (sep)
3043 add_pathsep(dest);
3044 STRCAT(dest, fname2);
3045 }
3046 return dest;
3047}
3048
3049/*
3050 * Add a path separator to a file name, unless it already ends in a path
3051 * separator.
3052 */
3053 void
3054add_pathsep(char_u *p)
3055{
3056 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3057 STRCAT(p, PATHSEPSTR);
3058}
3059
3060/*
3061 * FullName_save - Make an allocated copy of a full file name.
3062 * Returns NULL when out of memory.
3063 */
3064 char_u *
3065FullName_save(
3066 char_u *fname,
3067 int force) // force expansion, even when it already looks
3068 // like a full path name
3069{
3070 char_u *buf;
3071 char_u *new_fname = NULL;
3072
3073 if (fname == NULL)
3074 return NULL;
3075
3076 buf = alloc(MAXPATHL);
3077 if (buf != NULL)
3078 {
3079 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3080 new_fname = vim_strsave(buf);
3081 else
3082 new_fname = vim_strsave(fname);
3083 vim_free(buf);
3084 }
3085 return new_fname;
3086}
3087
3088/*
3089 * return TRUE if "fname" exists.
3090 */
3091 int
3092vim_fexists(char_u *fname)
3093{
3094 stat_T st;
3095
3096 if (mch_stat((char *)fname, &st))
3097 return FALSE;
3098 return TRUE;
3099}
3100
3101/*
3102 * Invoke expand_wildcards() for one pattern.
3103 * Expand items like "%:h" before the expansion.
3104 * Returns OK or FAIL.
3105 */
3106 int
3107expand_wildcards_eval(
3108 char_u **pat, // pointer to input pattern
3109 int *num_file, // resulting number of files
3110 char_u ***file, // array of resulting files
3111 int flags) // EW_DIR, etc.
3112{
3113 int ret = FAIL;
3114 char_u *eval_pat = NULL;
3115 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003116 char *ignored_msg;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003117 int usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003118 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3119 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003120
Bram Moolenaarf5724372022-09-02 19:45:15 +01003121 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003122 {
3123 ++emsg_off;
3124 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003125 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003126 --emsg_off;
3127 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003128 {
3129 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003130 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003131 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003132 }
3133
3134 if (exp_pat != NULL)
3135 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3136
3137 if (eval_pat != NULL)
3138 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003139 if (*num_file == 0 && is_cur_alt_file && star_follows)
3140 {
3141 // Expanding "%" or "#" and the file does not exist: Add the
3142 // pattern anyway (without the star) so that this works for remote
3143 // files and non-file buffer names.
3144 *file = ALLOC_ONE(char_u *);
3145 if (*file != NULL)
3146 {
3147 **file = eval_pat;
3148 eval_pat = NULL;
3149 *num_file = 1;
3150 ret = OK;
3151 }
3152 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003153 vim_free(exp_pat);
3154 vim_free(eval_pat);
3155 }
3156
3157 return ret;
3158}
3159
3160/*
3161 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3162 * 'wildignore'.
3163 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3164 */
3165 int
3166expand_wildcards(
3167 int num_pat, // number of input patterns
3168 char_u **pat, // array of input patterns
3169 int *num_files, // resulting number of files
3170 char_u ***files, // array of resulting files
3171 int flags) // EW_DIR, etc.
3172{
3173 int retval;
3174 int i, j;
3175 char_u *p;
3176 int non_suf_match; // number without matching suffix
3177
3178 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3179
3180 // When keeping all matches, return here
3181 if ((flags & EW_KEEPALL) || retval == FAIL)
3182 return retval;
3183
Bram Moolenaar26262f82019-09-04 20:59:15 +02003184 /*
3185 * Remove names that match 'wildignore'.
3186 */
3187 if (*p_wig)
3188 {
3189 char_u *ffname;
3190
3191 // check all files in (*files)[]
3192 for (i = 0; i < *num_files; ++i)
3193 {
3194 ffname = FullName_save((*files)[i], FALSE);
3195 if (ffname == NULL) // out of memory
3196 break;
3197# ifdef VMS
3198 vms_remove_version(ffname);
3199# endif
3200 if (match_file_list(p_wig, (*files)[i], ffname))
3201 {
3202 // remove this matching file from the list
3203 vim_free((*files)[i]);
3204 for (j = i; j + 1 < *num_files; ++j)
3205 (*files)[j] = (*files)[j + 1];
3206 --*num_files;
3207 --i;
3208 }
3209 vim_free(ffname);
3210 }
3211
3212 // If the number of matches is now zero, we fail.
3213 if (*num_files == 0)
3214 {
3215 VIM_CLEAR(*files);
3216 return FAIL;
3217 }
3218 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003219
3220 /*
3221 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003222 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003223 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003224 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003225 {
3226 non_suf_match = 0;
3227 for (i = 0; i < *num_files; ++i)
3228 {
3229 if (!match_suffix((*files)[i]))
3230 {
3231 /*
3232 * Move the name without matching suffix to the front
3233 * of the list.
3234 */
3235 p = (*files)[i];
3236 for (j = i; j > non_suf_match; --j)
3237 (*files)[j] = (*files)[j - 1];
3238 (*files)[non_suf_match++] = p;
3239 }
3240 }
3241 }
3242
3243 return retval;
3244}
3245
3246/*
3247 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3248 */
3249 int
3250match_suffix(char_u *fname)
3251{
3252 int fnamelen, setsuflen;
3253 char_u *setsuf;
3254#define MAXSUFLEN 30 // maximum length of a file suffix
3255 char_u suf_buf[MAXSUFLEN];
3256
3257 fnamelen = (int)STRLEN(fname);
3258 setsuflen = 0;
3259 for (setsuf = p_su; *setsuf; )
3260 {
3261 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3262 if (setsuflen == 0)
3263 {
3264 char_u *tail = gettail(fname);
3265
3266 // empty entry: match name without a '.'
3267 if (vim_strchr(tail, '.') == NULL)
3268 {
3269 setsuflen = 1;
3270 break;
3271 }
3272 }
3273 else
3274 {
3275 if (fnamelen >= setsuflen
3276 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3277 (size_t)setsuflen) == 0)
3278 break;
3279 setsuflen = 0;
3280 }
3281 }
3282 return (setsuflen != 0);
3283}
3284
3285#ifdef VIM_BACKTICK
3286
3287/*
3288 * Return TRUE if we can expand this backtick thing here.
3289 */
3290 static int
3291vim_backtick(char_u *p)
3292{
3293 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3294}
3295
3296/*
3297 * Expand an item in `backticks` by executing it as a command.
3298 * Currently only works when pat[] starts and ends with a `.
3299 * Returns number of file names found, -1 if an error is encountered.
3300 */
3301 static int
3302expand_backtick(
3303 garray_T *gap,
3304 char_u *pat,
3305 int flags) // EW_* flags
3306{
3307 char_u *p;
3308 char_u *cmd;
3309 char_u *buffer;
3310 int cnt = 0;
3311 int i;
3312
3313 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003314 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003315 if (cmd == NULL)
3316 return -1;
3317
3318#ifdef FEAT_EVAL
3319 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaarb171fb12020-06-24 20:34:03 +02003320 buffer = eval_to_string(cmd + 1, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003321 else
3322#endif
3323 buffer = get_cmd_output(cmd, NULL,
3324 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3325 vim_free(cmd);
3326 if (buffer == NULL)
3327 return -1;
3328
3329 cmd = buffer;
3330 while (*cmd != NUL)
3331 {
3332 cmd = skipwhite(cmd); // skip over white space
3333 p = cmd;
3334 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3335 ++p;
3336 // add an entry if it is not empty
3337 if (p > cmd)
3338 {
3339 i = *p;
3340 *p = NUL;
3341 addfile(gap, cmd, flags);
3342 *p = i;
3343 ++cnt;
3344 }
3345 cmd = p;
3346 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3347 ++cmd;
3348 }
3349
3350 vim_free(buffer);
3351 return cnt;
3352}
3353#endif // VIM_BACKTICK
3354
3355#if defined(MSWIN)
3356/*
3357 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3358 * it's shared between these systems.
3359 */
3360
3361/*
3362 * comparison function for qsort in dos_expandpath()
3363 */
3364 static int
3365pstrcmp(const void *a, const void *b)
3366{
3367 return (pathcmp(*(char **)a, *(char **)b, -1));
3368}
3369
3370/*
3371 * Recursively expand one path component into all matching files and/or
3372 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3373 * Return the number of matches found.
3374 * "path" has backslashes before chars that are not to be expanded, starting
3375 * at "path[wildoff]".
3376 * Return the number of matches found.
3377 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3378 */
3379 static int
3380dos_expandpath(
3381 garray_T *gap,
3382 char_u *path,
3383 int wildoff,
3384 int flags, // EW_* flags
3385 int didstar) // expanded "**" once already
3386{
3387 char_u *buf;
3388 char_u *path_end;
3389 char_u *p, *s, *e;
3390 int start_len = gap->ga_len;
3391 char_u *pat;
3392 regmatch_T regmatch;
3393 int starts_with_dot;
3394 int matches;
3395 int len;
3396 int starstar = FALSE;
3397 static int stardepth = 0; // depth for "**" expansion
3398 HANDLE hFind = INVALID_HANDLE_VALUE;
3399 WIN32_FIND_DATAW wfb;
3400 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3401 char_u *matchname;
3402 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003403 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003404
3405 // Expanding "**" may take a long time, check for CTRL-C.
3406 if (stardepth > 0)
3407 {
3408 ui_breakcheck();
3409 if (got_int)
3410 return 0;
3411 }
3412
3413 // Make room for file name. When doing encoding conversion the actual
3414 // length may be quite a bit longer, thus use the maximum possible length.
3415 buf = alloc(MAXPATHL);
3416 if (buf == NULL)
3417 return 0;
3418
3419 /*
3420 * Find the first part in the path name that contains a wildcard or a ~1.
3421 * Copy it into buf, including the preceding characters.
3422 */
3423 p = buf;
3424 s = buf;
3425 e = NULL;
3426 path_end = path;
3427 while (*path_end != NUL)
3428 {
3429 // May ignore a wildcard that has a backslash before it; it will
3430 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3431 if (path_end >= path + wildoff && rem_backslash(path_end))
3432 *p++ = *path_end++;
3433 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3434 {
3435 if (e != NULL)
3436 break;
3437 s = p + 1;
3438 }
3439 else if (path_end >= path + wildoff
3440 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3441 e = p;
3442 if (has_mbyte)
3443 {
3444 len = (*mb_ptr2len)(path_end);
3445 STRNCPY(p, path_end, len);
3446 p += len;
3447 path_end += len;
3448 }
3449 else
3450 *p++ = *path_end++;
3451 }
3452 e = p;
3453 *e = NUL;
3454
3455 // now we have one wildcard component between s and e
3456 // Remove backslashes between "wildoff" and the start of the wildcard
3457 // component.
3458 for (p = buf + wildoff; p < s; ++p)
3459 if (rem_backslash(p))
3460 {
3461 STRMOVE(p, p + 1);
3462 --e;
3463 --s;
3464 }
3465
3466 // Check for "**" between "s" and "e".
3467 for (p = s; p < e; ++p)
3468 if (p[0] == '*' && p[1] == '*')
3469 starstar = TRUE;
3470
3471 starts_with_dot = *s == '.';
3472 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3473 if (pat == NULL)
3474 {
3475 vim_free(buf);
3476 return 0;
3477 }
3478
3479 // compile the regexp into a program
3480 if (flags & (EW_NOERROR | EW_NOTWILD))
3481 ++emsg_silent;
3482 regmatch.rm_ic = TRUE; // Always ignore case
3483 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3484 if (flags & (EW_NOERROR | EW_NOTWILD))
3485 --emsg_silent;
3486 vim_free(pat);
3487
3488 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3489 {
3490 vim_free(buf);
3491 return 0;
3492 }
3493
3494 // remember the pattern or file name being looked for
3495 matchname = vim_strsave(s);
3496
3497 // If "**" is by itself, this is the first time we encounter it and more
3498 // is following then find matches without any directory.
3499 if (!didstar && stardepth < 100 && starstar && e - s == 2
3500 && *path_end == '/')
3501 {
3502 STRCPY(s, path_end + 1);
3503 ++stardepth;
3504 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3505 --stardepth;
3506 }
3507
3508 // Scan all files in the directory with "dir/ *.*"
3509 STRCPY(s, "*.*");
3510 wn = enc_to_utf16(buf, NULL);
3511 if (wn != NULL)
3512 hFind = FindFirstFileW(wn, &wfb);
3513 ok = (hFind != INVALID_HANDLE_VALUE);
3514
3515 while (ok)
3516 {
3517 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003518
Bram Moolenaar26262f82019-09-04 20:59:15 +02003519 if (p == NULL)
3520 break; // out of memory
3521
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003522 // Do not use the alternate filename when the file name ends in '~',
3523 // because it picks up backup files: short name for "foo.vim~" is
3524 // "foo~1.vim", which matches "*.vim".
3525 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003526 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003527 else
3528 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3529
Bram Moolenaar26262f82019-09-04 20:59:15 +02003530 // Ignore entries starting with a dot, unless when asked for. Accept
3531 // all entries found with "matchname".
3532 if ((p[0] != '.' || starts_with_dot
3533 || ((flags & EW_DODOT)
3534 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3535 && (matchname == NULL
3536 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003537 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003538 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003539 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003540 || ((flags & EW_NOTWILD)
3541 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3542 {
3543 STRCPY(s, p);
3544 len = (int)STRLEN(buf);
3545
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003546 if (starstar && stardepth < 100
3547 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003548 {
3549 // For "**" in the pattern first go deeper in the tree to
3550 // find matches.
3551 STRCPY(buf + len, "/**");
3552 STRCPY(buf + len + 3, path_end);
3553 ++stardepth;
3554 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3555 --stardepth;
3556 }
3557
3558 STRCPY(buf + len, path_end);
3559 if (mch_has_exp_wildcard(path_end))
3560 {
3561 // need to expand another component of the path
3562 // remove backslashes for the remaining components only
3563 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3564 }
3565 else
3566 {
3567 // no more wildcards, check if there is a match
3568 // remove backslashes for the remaining components only
3569 if (*path_end != 0)
3570 backslash_halve(buf + len + 1);
3571 if (mch_getperm(buf) >= 0) // add existing file
3572 addfile(gap, buf, flags);
3573 }
3574 }
3575
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003576 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003577 vim_free(p);
3578 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003579 }
3580
3581 FindClose(hFind);
3582 vim_free(wn);
3583 vim_free(buf);
3584 vim_regfree(regmatch.regprog);
3585 vim_free(matchname);
3586
3587 matches = gap->ga_len - start_len;
3588 if (matches > 0)
3589 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3590 sizeof(char_u *), pstrcmp);
3591 return matches;
3592}
3593
3594 int
3595mch_expandpath(
3596 garray_T *gap,
3597 char_u *path,
3598 int flags) // EW_* flags
3599{
3600 return dos_expandpath(gap, path, 0, flags, FALSE);
3601}
3602#endif // MSWIN
3603
3604#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3605 || defined(PROTO)
3606/*
3607 * Unix style wildcard expansion code.
3608 * It's here because it's used both for Unix and Mac.
3609 */
3610 static int
3611pstrcmp(const void *a, const void *b)
3612{
3613 return (pathcmp(*(char **)a, *(char **)b, -1));
3614}
3615
3616/*
3617 * Recursively expand one path component into all matching files and/or
3618 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3619 * "path" has backslashes before chars that are not to be expanded, starting
3620 * at "path + wildoff".
3621 * Return the number of matches found.
3622 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3623 */
3624 int
3625unix_expandpath(
3626 garray_T *gap,
3627 char_u *path,
3628 int wildoff,
3629 int flags, // EW_* flags
3630 int didstar) // expanded "**" once already
3631{
3632 char_u *buf;
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003633 size_t buflen;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003634 char_u *path_end;
3635 char_u *p, *s, *e;
3636 int start_len = gap->ga_len;
3637 char_u *pat;
3638 regmatch_T regmatch;
3639 int starts_with_dot;
3640 int matches;
3641 int len;
3642 int starstar = FALSE;
3643 static int stardepth = 0; // depth for "**" expansion
3644
3645 DIR *dirp;
3646 struct dirent *dp;
3647
3648 // Expanding "**" may take a long time, check for CTRL-C.
3649 if (stardepth > 0)
3650 {
3651 ui_breakcheck();
3652 if (got_int)
3653 return 0;
3654 }
3655
3656 // make room for file name
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003657 buflen = STRLEN(path) + BASENAMELEN + 5;
3658 buf = alloc(buflen);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003659 if (buf == NULL)
3660 return 0;
3661
3662 /*
3663 * Find the first part in the path name that contains a wildcard.
3664 * When EW_ICASE is set every letter is considered to be a wildcard.
3665 * Copy it into "buf", including the preceding characters.
3666 */
3667 p = buf;
3668 s = buf;
3669 e = NULL;
3670 path_end = path;
3671 while (*path_end != NUL)
3672 {
3673 // May ignore a wildcard that has a backslash before it; it will
3674 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3675 if (path_end >= path + wildoff && rem_backslash(path_end))
3676 *p++ = *path_end++;
3677 else if (*path_end == '/')
3678 {
3679 if (e != NULL)
3680 break;
3681 s = p + 1;
3682 }
3683 else if (path_end >= path + wildoff
3684 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3685 || (!p_fic && (flags & EW_ICASE)
Bram Moolenaar5921aeb2022-02-19 11:20:12 +00003686 && vim_isalpha(PTR2CHAR(path_end)))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003687 e = p;
3688 if (has_mbyte)
3689 {
3690 len = (*mb_ptr2len)(path_end);
3691 STRNCPY(p, path_end, len);
3692 p += len;
3693 path_end += len;
3694 }
3695 else
3696 *p++ = *path_end++;
3697 }
3698 e = p;
3699 *e = NUL;
3700
3701 // Now we have one wildcard component between "s" and "e".
3702 // Remove backslashes between "wildoff" and the start of the wildcard
3703 // component.
3704 for (p = buf + wildoff; p < s; ++p)
3705 if (rem_backslash(p))
3706 {
3707 STRMOVE(p, p + 1);
3708 --e;
3709 --s;
3710 }
3711
3712 // Check for "**" between "s" and "e".
3713 for (p = s; p < e; ++p)
3714 if (p[0] == '*' && p[1] == '*')
3715 starstar = TRUE;
3716
3717 // convert the file pattern to a regexp pattern
3718 starts_with_dot = *s == '.';
3719 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3720 if (pat == NULL)
3721 {
3722 vim_free(buf);
3723 return 0;
3724 }
3725
3726 // compile the regexp into a program
3727 if (flags & EW_ICASE)
3728 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3729 else
3730 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3731 if (flags & (EW_NOERROR | EW_NOTWILD))
3732 ++emsg_silent;
3733 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3734 if (flags & (EW_NOERROR | EW_NOTWILD))
3735 --emsg_silent;
3736 vim_free(pat);
3737
3738 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3739 {
3740 vim_free(buf);
3741 return 0;
3742 }
3743
3744 // If "**" is by itself, this is the first time we encounter it and more
3745 // is following then find matches without any directory.
3746 if (!didstar && stardepth < 100 && starstar && e - s == 2
3747 && *path_end == '/')
3748 {
3749 STRCPY(s, path_end + 1);
3750 ++stardepth;
3751 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3752 --stardepth;
3753 }
3754
3755 // open the directory for scanning
3756 *s = NUL;
3757 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3758
3759 // Find all matching entries
3760 if (dirp != NULL)
3761 {
Bram Moolenaar57e95172022-08-20 19:26:14 +01003762 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003763 {
3764 dp = readdir(dirp);
3765 if (dp == NULL)
3766 break;
3767 if ((dp->d_name[0] != '.' || starts_with_dot
3768 || ((flags & EW_DODOT)
3769 && dp->d_name[1] != NUL
3770 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3771 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3772 (char_u *)dp->d_name, (colnr_T)0))
3773 || ((flags & EW_NOTWILD)
3774 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3775 {
3776 STRCPY(s, dp->d_name);
3777 len = STRLEN(buf);
3778
3779 if (starstar && stardepth < 100)
3780 {
3781 // For "**" in the pattern first go deeper in the tree to
3782 // find matches.
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003783 vim_snprintf((char *)buf + len, buflen - len,
3784 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003785 ++stardepth;
3786 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3787 --stardepth;
3788 }
3789
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003790 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003791 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3792 {
3793 // need to expand another component of the path
3794 // remove backslashes for the remaining components only
3795 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3796 }
3797 else
3798 {
3799 stat_T sb;
3800
3801 // no more wildcards, check if there is a match
3802 // remove backslashes for the remaining components only
3803 if (*path_end != NUL)
3804 backslash_halve(buf + len + 1);
3805 // add existing file or symbolic link
3806 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3807 : mch_getperm(buf) >= 0)
3808 {
3809#ifdef MACOS_CONVERT
3810 size_t precomp_len = STRLEN(buf)+1;
3811 char_u *precomp_buf =
3812 mac_precompose_path(buf, precomp_len, &precomp_len);
3813
3814 if (precomp_buf)
3815 {
3816 mch_memmove(buf, precomp_buf, precomp_len);
3817 vim_free(precomp_buf);
3818 }
3819#endif
3820 addfile(gap, buf, flags);
3821 }
3822 }
3823 }
3824 }
3825
3826 closedir(dirp);
3827 }
3828
3829 vim_free(buf);
3830 vim_regfree(regmatch.regprog);
3831
Bram Moolenaar57e95172022-08-20 19:26:14 +01003832 // When interrupted the matches probably won't be used and sorting can be
3833 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003834 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003835 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003836 qsort(((char_u **)gap->ga_data) + start_len, matches,
3837 sizeof(char_u *), pstrcmp);
3838 return matches;
3839}
3840#endif
3841
3842/*
3843 * Return TRUE if "p" contains what looks like an environment variable.
3844 * Allowing for escaping.
3845 */
3846 static int
3847has_env_var(char_u *p)
3848{
3849 for ( ; *p; MB_PTR_ADV(p))
3850 {
3851 if (*p == '\\' && p[1] != NUL)
3852 ++p;
3853 else if (vim_strchr((char_u *)
3854#if defined(MSWIN)
3855 "$%"
3856#else
3857 "$"
3858#endif
3859 , *p) != NULL)
3860 return TRUE;
3861 }
3862 return FALSE;
3863}
3864
3865#ifdef SPECIAL_WILDCHAR
3866/*
3867 * Return TRUE if "p" contains a special wildcard character, one that Vim
3868 * cannot expand, requires using a shell.
3869 */
3870 static int
3871has_special_wildchar(char_u *p)
3872{
3873 for ( ; *p; MB_PTR_ADV(p))
3874 {
3875 // Disallow line break characters.
3876 if (*p == '\r' || *p == '\n')
3877 break;
3878 // Allow for escaping.
3879 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3880 ++p;
3881 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3882 {
3883 // A { must be followed by a matching }.
3884 if (*p == '{' && vim_strchr(p, '}') == NULL)
3885 continue;
3886 // A quote and backtick must be followed by another one.
3887 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3888 continue;
3889 return TRUE;
3890 }
3891 }
3892 return FALSE;
3893}
3894#endif
3895
3896/*
3897 * Generic wildcard expansion code.
3898 *
3899 * Characters in "pat" that should not be expanded must be preceded with a
3900 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3901 *
3902 * Return FAIL when no single file was found. In this case "num_file" is not
3903 * set, and "file" may contain an error message.
3904 * Return OK when some files found. "num_file" is set to the number of
3905 * matches, "file" to the array of matches. Call FreeWild() later.
3906 */
3907 int
3908gen_expand_wildcards(
3909 int num_pat, // number of input patterns
3910 char_u **pat, // array of input patterns
3911 int *num_file, // resulting number of files
3912 char_u ***file, // array of resulting files
3913 int flags) // EW_* flags
3914{
3915 int i;
3916 garray_T ga;
3917 char_u *p;
3918 static int recursive = FALSE;
3919 int add_pat;
3920 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003921 int did_expand_in_path = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003922
3923 /*
3924 * expand_env() is called to expand things like "~user". If this fails,
3925 * it calls ExpandOne(), which brings us back here. In this case, always
3926 * call the machine specific expansion function, if possible. Otherwise,
3927 * return FAIL.
3928 */
3929 if (recursive)
3930#ifdef SPECIAL_WILDCHAR
3931 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3932#else
3933 return FAIL;
3934#endif
3935
3936#ifdef SPECIAL_WILDCHAR
3937 /*
3938 * If there are any special wildcard characters which we cannot handle
3939 * here, call machine specific function for all the expansion. This
3940 * avoids starting the shell for each argument separately.
3941 * For `=expr` do use the internal function.
3942 */
3943 for (i = 0; i < num_pat; i++)
3944 {
3945 if (has_special_wildchar(pat[i])
3946# ifdef VIM_BACKTICK
3947 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3948# endif
3949 )
3950 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3951 }
3952#endif
3953
3954 recursive = TRUE;
3955
3956 /*
3957 * The matching file names are stored in a growarray. Init it empty.
3958 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00003959 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003960
Bram Moolenaar57e95172022-08-20 19:26:14 +01003961 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003962 {
3963 add_pat = -1;
3964 p = pat[i];
3965
3966#ifdef VIM_BACKTICK
3967 if (vim_backtick(p))
3968 {
3969 add_pat = expand_backtick(&ga, p, flags);
3970 if (add_pat == -1)
3971 retval = FAIL;
3972 }
3973 else
3974#endif
3975 {
3976 /*
3977 * First expand environment variables, "~/" and "~user/".
3978 */
3979 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3980 {
3981 p = expand_env_save_opt(p, TRUE);
3982 if (p == NULL)
3983 p = pat[i];
3984#ifdef UNIX
3985 /*
3986 * On Unix, if expand_env() can't expand an environment
3987 * variable, use the shell to do that. Discard previously
3988 * found file names and start all over again.
3989 */
3990 else if (has_env_var(p) || *p == '~')
3991 {
3992 vim_free(p);
3993 ga_clear_strings(&ga);
3994 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3995 flags|EW_KEEPDOLLAR);
3996 recursive = FALSE;
3997 return i;
3998 }
3999#endif
4000 }
4001
4002 /*
LemonBoya3157a42022-04-03 11:58:31 +01004003 * If there are wildcards or case-insensitive expansion is
4004 * required: Expand file names and add each match to the list. If
4005 * there is no match, and EW_NOTFOUND is given, add the pattern.
4006 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4007 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004008 */
LemonBoya3157a42022-04-03 11:58:31 +01004009 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004010 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02004011 if ((flags & EW_PATH)
4012 && !mch_isFullName(p)
4013 && !(p[0] == '.'
4014 && (vim_ispathsep(p[1])
4015 || (p[1] == '.' && vim_ispathsep(p[2]))))
4016 )
4017 {
4018 // :find completion where 'path' is used.
4019 // Recursiveness is OK here.
4020 recursive = FALSE;
4021 add_pat = expand_in_path(&ga, p, flags);
4022 recursive = TRUE;
4023 did_expand_in_path = TRUE;
4024 }
4025 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004026 add_pat = mch_expandpath(&ga, p, flags);
4027 }
4028 }
4029
4030 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4031 {
4032 char_u *t = backslash_halve_save(p);
4033
4034 // When EW_NOTFOUND is used, always add files and dirs. Makes
4035 // "vim c:/" work.
4036 if (flags & EW_NOTFOUND)
4037 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4038 else
4039 addfile(&ga, t, flags);
4040
4041 if (t != p)
4042 vim_free(t);
4043 }
4044
Bram Moolenaar26262f82019-09-04 20:59:15 +02004045 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
4046 uniquefy_paths(&ga, p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004047 if (p != pat[i])
4048 vim_free(p);
4049 }
4050
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004051 // When returning FAIL the array must be freed here.
4052 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004053 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004054
Bram Moolenaar26262f82019-09-04 20:59:15 +02004055 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004056 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4057 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004058
4059 recursive = FALSE;
4060
4061 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4062}
4063
4064/*
4065 * Add a file to a file list. Accepted flags:
4066 * EW_DIR add directories
4067 * EW_FILE add files
4068 * EW_EXEC add executable files
4069 * EW_NOTFOUND add even when it doesn't exist
4070 * EW_ADDSLASH add slash after directory name
4071 * EW_ALLLINKS add symlink also when the referred file does not exist
4072 */
4073 void
4074addfile(
4075 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004076 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004077 int flags)
4078{
4079 char_u *p;
4080 int isdir;
4081 stat_T sb;
4082
4083 // if the file/dir/link doesn't exist, may not add it
4084 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4085 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4086 return;
4087
4088#ifdef FNAME_ILLEGAL
4089 // if the file/dir contains illegal characters, don't add it
4090 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4091 return;
4092#endif
4093
4094 isdir = mch_isdir(f);
4095 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4096 return;
4097
4098 // If the file isn't executable, may not add it. Do accept directories.
4099 // When invoked from expand_shellcmd() do not use $PATH.
4100 if (!isdir && (flags & EW_EXEC)
4101 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4102 return;
4103
4104 // Make room for another item in the file list.
4105 if (ga_grow(gap, 1) == FAIL)
4106 return;
4107
4108 p = alloc(STRLEN(f) + 1 + isdir);
4109 if (p == NULL)
4110 return;
4111
4112 STRCPY(p, f);
4113#ifdef BACKSLASH_IN_FILENAME
4114 slash_adjust(p);
4115#endif
4116 /*
4117 * Append a slash or backslash after directory names if none is present.
4118 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004119 if (isdir && (flags & EW_ADDSLASH))
4120 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004121 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4122}
4123
4124/*
4125 * Free the list of files returned by expand_wildcards() or other expansion
4126 * functions.
4127 */
4128 void
4129FreeWild(int count, char_u **files)
4130{
4131 if (count <= 0 || files == NULL)
4132 return;
4133 while (count--)
4134 vim_free(files[count]);
4135 vim_free(files);
4136}
4137
4138/*
4139 * Compare path "p[]" to "q[]".
4140 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4141 * Return value like strcmp(p, q), but consider path separators.
4142 */
4143 int
4144pathcmp(const char *p, const char *q, int maxlen)
4145{
4146 int i, j;
4147 int c1, c2;
4148 const char *s = NULL;
4149
4150 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4151 {
4152 c1 = PTR2CHAR((char_u *)p + i);
4153 c2 = PTR2CHAR((char_u *)q + j);
4154
4155 // End of "p": check if "q" also ends or just has a slash.
4156 if (c1 == NUL)
4157 {
4158 if (c2 == NUL) // full match
4159 return 0;
4160 s = q;
4161 i = j;
4162 break;
4163 }
4164
4165 // End of "q": check if "p" just has a slash.
4166 if (c2 == NUL)
4167 {
4168 s = p;
4169 break;
4170 }
4171
4172 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4173#ifdef BACKSLASH_IN_FILENAME
4174 // consider '/' and '\\' to be equal
4175 && !((c1 == '/' && c2 == '\\')
4176 || (c1 == '\\' && c2 == '/'))
4177#endif
4178 )
4179 {
4180 if (vim_ispathsep(c1))
4181 return -1;
4182 if (vim_ispathsep(c2))
4183 return 1;
4184 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4185 : c1 - c2; // no match
4186 }
4187
Bram Moolenaar1614a142019-10-06 22:00:13 +02004188 i += mb_ptr2len((char_u *)p + i);
4189 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004190 }
4191 if (s == NULL) // "i" or "j" ran into "maxlen"
4192 return 0;
4193
4194 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004195 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004196 // ignore a trailing slash, but not "//" or ":/"
4197 if (c2 == NUL
4198 && i > 0
4199 && !after_pathsep((char_u *)s, (char_u *)s + i)
4200#ifdef BACKSLASH_IN_FILENAME
4201 && (c1 == '/' || c1 == '\\')
4202#else
4203 && c1 == '/'
4204#endif
4205 )
4206 return 0; // match with trailing slash
4207 if (s == q)
4208 return -1; // no match
4209 return 1;
4210}
4211
4212/*
4213 * Return TRUE if "name" is a full (absolute) path name or URL.
4214 */
4215 int
4216vim_isAbsName(char_u *name)
4217{
4218 return (path_with_url(name) != 0 || mch_isFullName(name));
4219}
4220
4221/*
4222 * Get absolute file name into buffer "buf[len]".
4223 *
4224 * return FAIL for failure, OK otherwise
4225 */
4226 int
4227vim_FullName(
4228 char_u *fname,
4229 char_u *buf,
4230 int len,
4231 int force) // force expansion even when already absolute
4232{
4233 int retval = OK;
4234 int url;
4235
4236 *buf = NUL;
4237 if (fname == NULL)
4238 return FAIL;
4239
4240 url = path_with_url(fname);
4241 if (!url)
4242 retval = mch_FullName(fname, buf, len, force);
4243 if (url || retval == FAIL)
4244 {
4245 // something failed; use the file name (truncate when too long)
4246 vim_strncpy(buf, fname, len - 1);
4247 }
4248#if defined(MSWIN)
4249 slash_adjust(buf);
4250#endif
4251 return retval;
4252}